PageSourceSearch

https://gradzen.com/assets/index-DNYOfx3x.js

js gradzen.com collected 2026-10-05 04:25:19 UTC 1,398,577 bytes, 736 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/SocialFeed-ZU-nwGdt.js","assets/vendor-query-B0-uRJqS.js","assets/vendor-react-CW1TH9gT.js","assets/vendor-radix-Mcgp0sn6.js","assets/ProjectComposer-YhKYbJfi.js","assets/calendar-C0l7avJc.js","assets/startOfMonth-D3d0T_NF.js","assets/addMonths-DNA65W5C.js","assets/chevron-left-5Swp4geq.js","assets/marketplace-project-KNpUGG09.js","assets/building-AfoHeiOF.js","assets/map-pin-3OMqck86.js","assets/calendar-CQsWeZn5.js","assets/info-CpXHFYBR.js","assets/credit-card-BCZk9E6z.js","assets/PostCard-DRf6ZQHU.js","assets/dropdown-menu-BmDtUFEd.js","assets/circle-DwPTKuEx.js","assets/SponsoredBadge-C2vN-b5Y.js","assets/SharePostModal-D2n3cbX7.js","assets/ReplySection-DJVTOSdT.js","assets/ellipsis-DTojkzh2.js","assets/trash-2-DmYLl9RK.js","assets/tabs-CqKbtoGh.js","assets/ShareToMessengerModal-TOrBuEra.js","assets/radio-group-CCTEA6-A.js","assets/ban-xpLX11NN.js","assets/file-warning-DNNoMjz7.js","assets/dollar-sign-BoI2Hlw4.js","assets/link-2-8CYAbZSg.js","assets/repeat-2-CvGDScJx.js","assets/thumbs-up-PP03EI_u.js","assets/forward-CNiM3Ayh.js","assets/ConnectionDegreeBadge-DqLI6XJu.js","assets/ProjectCard-DZG3ASjK.js","assets/useProfileGate-BlE9Oerx.js","assets/ShareProjectModal-jwzGsYIg.js","assets/share-2-bNphh22o.js","assets/isPast-BV_Yf4IA.js","assets/AlgorithmDebugContext-CsJa6kAZ.js","assets/useSavedItems-CWHh4Cbi.js","assets/useJobBoosts-B6qCYIFe.js","assets/rocket--AfadcpS.js","assets/target-CHsW75gD.js","assets/usePages-CE30qFMf.js","assets/pencil-BBrucd4V.js","assets/bookmark-DSYiKHrJ.js","assets/arrow-right-PwQ7hYFq.js","assets/end-of-content-CD6I2noE.js","assets/useSocialFeed-DDRiEE7O.js","assets/SponsoredJobsSidebar-C2WsaLSd.js","assets/AlgorithmDebugPanel-Ctz7_qBz.js","assets/bug-B-7UQ-4Y.js","assets/trending-down-CGvkXeoc.js","assets/PageCard-B7cPVFRm.js","assets/user-plus-BZf6Kug9.js","assets/useConnectionDegrees-CeyGd-UX.js","assets/useInView-BvsWfo_g.js","assets/progress-BMiFjTTr.js","assets/vendor-charts-BGFylbhW.js","assets/Reels-DAyEXCdz.js","assets/useReels-CGXlG-de.js","assets/copyright-VBxod89a.js","assets/heart-fg3AfMfF.js","assets/link-DhVTX4-q.js","assets/film-64DWZNNv.js","assets/upload-Dg5mH6VJ.js","assets/Dashboard-BNaOI6f7.js","assets/confetti.module-B5JVzsfH.js","assets/JobCard-CQ0PhCSC.js","assets/ApplicationTracker-C3TYoHUg.js","assets/html2canvas.esm-CBrSDip1.js","assets/qr-code-D059EimY.js","assets/FormattedJobText-DFIn0oBq.js","assets/useBilling-C8fQ9O7a.js","assets/list-BgMgea-5.js","assets/date-picker-BxIbrY3W.js","assets/phone-JEGQ4arE.js","assets/RepublishJobModal-BVgJRl_3.js","assets/offlineCache-DhQX4A0L.js","assets/ApplyWithCVDrawer-CrUPUFdH.js","assets/MyNetwork-BteNVmKD.js","assets/MutualConnectionsDisplay-BVmhYyrx.js","assets/SignedImage-Bi4ZIC_V.js","assets/usePageFollowing-gHRbr_6X.js","assets/user-minus-eLkBTl73.js","assets/Courses-G4zYTDmd.js","assets/EnrolledCourseCard-3sq-h93p.js","assets/archive-BZRGu_IA.js","assets/snowflake-BkasW-QC.js","assets/arrow-up-eIH6DXRH.js","assets/wand-sparkles-asliMLKO.js","assets/arrow-up-right-BiTkmscT.js","assets/banknote-CzXQ-JlM.js","assets/blend-CZ6bt9oO.js","assets/message-square-off-QcuPc8_T.js","assets/MentorshipListingCard-CJgfwB0R.js","assets/mentorship-BUpBxnlw.js","assets/clock-3-BHiDN7Tt.js","assets/calculator-DLWtB98M.js","assets/calendar-plus-BkWpX2KJ.js","assets/camera-D97Q77bP.js","assets/sticky-note-92zCfrpi.js","assets/circle-arrow-right-BdoVxsII.js","assets/circle-pause-CVv8F9bv.js","assets/circle-play-fwJ4LiFk.js","assets/clipboard-check-k0nykPkg.js","assets/coins-Dp8WUnI4.js","assets/panels-top-left-CF7mRZ0u.js","assets/crown-CUQRe0nd.js","assets/dot-CPC7qUPR.js","assets/file-spreadsheet-DU6t-0F-.js","assets/youtube-CVWbYVbm.js","assets/file-Cz2mJUY4.js","assets/file-x-_OSD_AvB.js","assets/filter-DqHyzIVn.js","assets/folder-open-DT16V_Xj.js","assets/gift-aNI2Itej.js","assets/grip-vertical-BhNClwSb.js","assets/hard-drive-CLRQgNP0.js","assets/import-DKWKdm-E.js","assets/key-round-B2iblrqo.js","assets/key-Bxu-8MDg.js","assets/languages-nlWs0Ywb.js","assets/layers-DrqNmwQ_.js","assets/layout-grid-mhw0eBIH.js","assets/lightbulb-D9vXXm_s.js","assets/linkedin-yp3EC7z7.js","assets/list-checks-C-F9izAn.js","assets/lock-open-BfjbDUat.js","assets/log-in-CbvbMYOr.js","assets/undo-2-B70_J6R2.js","assets/medal-D0sLNIkK.js","assets/milestone-8KDP1A4C.js","assets/mouse-pointer-click-CE6gkucd.js","assets/mouse-pointer-BO4oZ1c1.js","assets/net
1work-B39U0alB.js","assets/party-popper-Yrqdy4ZE.js","assets/shuffle-BvO83GXP.js","assets/pen-DQ_QIxus.js","assets/percent-DO3z5hVK.js","assets/presentation-B8bWQ6XD.js","assets/save-DXXHO8x1.js","assets/settings-2-n4qygFaQ.js","assets/shield-check-Da6lFrYV.js","assets/tag-CNWHe2As.js","assets/toggle-right-CyJJxSNW.js","assets/video-D0sof9uI.js","assets/zap-BjuBetcO.js","assets/zoom-in-DoUXMJD8.js","assets/zoom-out-B9tMOgp9.js","assets/jspdf.es.min-MthMC4YB.js","assets/useCourses-D5ZAGXN-.js","assets/mentorshipService-BLLMMSUQ.js","assets/MentorshipListingComposer-SJiGutXR.js","assets/MobileMenu-BXWOBUOQ.js","assets/JobAnalytics-C-VyCni3.js","assets/table-ALWKH3Dv.js","assets/AptitudeTests-BE2ljUNm.js","assets/LearningCenter-Cg9e6b86.js","assets/Profile-C3xP_qzj.js","assets/education-utils-BQxgZn2U.js","assets/image-utils-BAugGQ2Y.js","assets/section-order-utils-CCNBt37Y.js","assets/cv-themes-BnQm0mYj.js","assets/ProfileViewMode-D9lTX8aq.js","assets/ImageCropModal-CFoHl8EP.js","assets/parseISO-CirCBpB0.js","assets/VerifiedSkillBadge-DxNJyvZJ.js","assets/skill-verification-utils-_KtcHHhI.js","assets/Messenger-yqI0Jz-Q.js","assets/AppliedJobs-CWxbHjgD.js","assets/JobDetail-DfEO-WCi.js","assets/BillingSummary-DbSLbKy3.js","assets/PaymentSubmissionHistory-DAf1yw_3.js","assets/differenceInDays-BSTdRLxJ.js","assets/PaymentSettings-B6J7Pd8C.js","assets/Invoices-JHXpEZ1s.js","assets/pdf-utils-DOvC-Lk1.js","assets/Transactions-tvOqtdNG.js","assets/BrowseProjects-YzFHJteO.js","assets/MyProjects-CFOeczPy.js","assets/MyCourses-FzknNj7L.js","assets/SearchResults-DhxgGN33.js","assets/JobDetailsModal-CczJXWqE.js","assets/AccountSettings-Qem27ryN.js","assets/useIdentityVerification-BrhAn2Qw.js","assets/SecuritySettings-sNpBDMJy.js","assets/PipelineOverview-qFScsTqe.js","assets/HiddenJobs-DAelIQT8.js","assets/BlockedUsers-DK3WQPjk.js","assets/ActivityLog-DwIrHkUf.js","assets/subMonths-Cv4DWEhn.js","assets/useActivityLog-BUN-NII4.js","assets/AccountDeletion-Bnh71sDD.js","assets/RequestVerification-B3z2ZAnD.js","assets/AvailableTests-wAAUOx7k.js","assets/PersonalityGameLanding-C-NmgL_d.js","assets/PersonalityResults-BWSnxO2v.js","assets/TestSubmission-CC2WddVq.js","assets/CreateAptitudeTest-Bp_3yJSe.js","assets/QuestionImageUpload-4no_inee.js","assets/PipelineJobs-DF4i2Uc_.js","assets/ActivityLog-DveGrEyN.js","assets/BoostCampaigns-i8N2GdFk.js","assets/CreateBoost-CS49hnXy.js","assets/MyReports-DrqQKDat.js","assets/ReportDetail-BvRc1Wwg.js","assets/image-preview-CpQnmv_W.js","assets/CourseDetail-Cq7kP4T7.js","assets/stale-lesson-recovery-IvSeZ9wW.js","assets/SpendProgressBar-DnWTcu52.js","assets/useFinalExam-BNvOuULV.js","assets/useCertificates-dA6lxquJ.js","assets/CourseWatch-B45U_m6R.js","assets/useAssignments-B5NCrMxu.js","assets/useQuizzes-BA441dLJ.js","assets/PostDetail-D_w8BcD9.js","assets/ProjectDetail-82L50UxW.js","assets/UserActivity-DPYRPbJb.js","assets/PublicProfile-7EclJQr1.js","assets/ProfileDispatcher-C7tQgw2z.js","assets/EnableHRAccess-BxYQCePu.js","assets/Applicants-B9CeaZag.js","assets/CandidateProfile-Dodty7S4.js","assets/AdminOverview-1lE2SYer.js","assets/DualLayout-Cj3Hqufw.js","assets/AdminUsers-26t8tN7y.js","assets/AdminJobs-4fmOvpmI.js","assets/useAdminJobDebugScores-DZxqrElX.js","assets/AdminApplications-DhOk0KlE.js","assets/CourseManagement-BuY28AYE.js","assets/video-utils-DJluAgwy.js","assets/ExpertDashboard-DdMDTies.js","assets/TrainerDashboard-BkXx-MR-.js","assets/TrainerCourses-CzYGizht.js","assets/TrainerEarnings-DmomXfzX.js","assets/AlgorithmDebug-CuH3bqWP.js","assets/AptitudeCategories-C2brYh-E.js","assets/AptitudeQuestions-CAvOfhEn.js","assets/PersonalityGameSettings-Ch-bBoGH.js","assets/PersonalityTraitSections-BjON4Lsa.js","assets/PersonalityTraitQuestions-CgcpEjqG.js","assets/PersonalityGameOverview-DmzZOk9I.js","assets/chart-xwxoqcqQ.js","assets/AdminSecuritySettings-D9BlDgSM.js","assets/BrandSettings-CxMHCmai.js","assets/FooterSettings-DC0hT0WE.js","assets/LegalSettings-COqb77v3.js","assets/CertificateSettings-B4t60f7h.js","assets/MaintenanceMode-CAWeKOb-.js","assets/DatabaseBackup-CMY1mEFQ.js","assets/AISettings-DheFLKm0.js","assets/FeedAlgorithmSettings-Ci_jjvnK.js","assets/CrossLearningDashboard-OgcvbAek.js","assets/AdminReports-CUyboH12.js","assets/ReportedJobs-DRZSpqFl.js","assets/AdminAppeals-BcmDuS8b.js","assets/AdminAppealDetail-WP3TBmMs.js","assets/ContentModeration-CZ0a_agO.js","assets/UsernameSettings-BiakSltG.js","assets/VerifiedUsers-UaMeWBFf.js","assets/VerifiedPages-D1EeOxo_.js","assets/BroadcastNotifications-BOkLsv_L.js","assets/ProjectDisputes-rronfLe3.js","assets/ProjectDisputeDetail-DkABke9F.js","assets/MarketplaceProjects-ChhLmP1Q.js","assets/MentorshipModeration-BNbkavg4.js","assets/AdReview-lcCDDbXU.js","assets/AdminAnalytics-DzcgrZc9.js","assets/SavedItems-Bxbh2hEo.js","assets/BoostAnalytics-BW-4WLYv.js","assets/BoostDisputes-B0PNV7Ky.js","assets/useAdDisputes-BtpXVnBT.js","assets/AdDisputes-BMlDP_Dv.js","assets/DocsAds-BdHJR5QA.js","assets/DocsAdsAnalytics-jhaDcXnl.js","assets/DocsMarketplaceEscrow-h9IMLbxW.js","assets/DocsLearningRevenue-CbzEE7CS.js","assets/DocsProfileMatch-DrKUbsok.js","assets/DocsTotalRevenue-B__X4URw.js","assets/WalletAdmin-CbYIGBij.js","assets/WalletTransactions-Dmcd9PV5.js","assets/WalletInvoices-DNHc1Iga.js","assets/RegionalPricing-DFeoqrQl.js","assets/RevenueOverview-CCwuIDzm.js","assets/IdentityVerifications-6c4URMKx.js","assets/PaymentProviderSettings-BosIYRKc.js","assets/CloudStorageSettings-XbOQbmRL.js","assets/PaymentVerification-D4WGt834.js","assets/PaymentMethodSettings-VnVWp1O-.js","assets/WithdrawalRequests-BeK3uOlO.js","assets/EscrowManagement-DgfRuuc7.js","assets/MentorshipDetail-O9MQZ4xl.js","assets/MentorshipManage-Bn5-TMBW.js","assets/TakeQuiz-Du_VYwcU.js","assets/QuestionRenderers-DVrUDOiN.js","assets/QuizResults-BKXf9DVV.js","assets/TakeFinalExam-CcO9Tupk.js","assets/FinalExamResults-B2grBRLf.js","assets/CourseLessons-tg53g2ge.js","assets/useInstructorCertificates-C20N57HD.js","assets/CourseCategories-DCynrieg.js","assets/TrainerRoyalties-B2eR1Bi5.js","assets/TrainerApplications-CIh3B2qe.js","assets/SignupSuccess-BDyUM5mf.js","assets/ResendVerification-Bclpq6NZ.js","assets/VerifyEmail-B7bBK4Rt.js","assets/input-otp-Br5gb7Oh.js","assets/ForgotPassword-BW4nkqXw.js","assets/ResetPassword-CKSoSe16.js","assets/SharedCV-acPfWURF.js","assets/CVBuilder-BYi6bmat.js","assets/SharedCVPage-CneQdgPH.js","assets/CVThemes-BLrY6dvL.js","assets/CVThemeBuilder-DSaTQEht.js","assets/CustomQuestions-BljjlDdO.js","assets/SectionQuestions-C7lOn7dM.js","assets/TestResults-B_IcikT8.js","assets/StageAdvancement-fpp4m2rY.js","assets/FGDSetup-DNqKCk3a.js","assets/InterviewBoardSetup-BnK-AdCe.js","assets/TakeTest-BNVh8HTB.js","assets/TestResultsView-6JrCBGqR.js","assets/TakePersonalityGame-CtaNHGol.js","assets/PersonalityGameResults-Cs5XRLKd.js","assets/TermsOfService-CC8KYLgK.js","assets/PrivacyPolicy-COQBal_h.js","assets/AccountLocked-CvJgZuvA.js","assets/CommunityGuidelines-tBX2u6Id.js","assets/UserJourney-hhPBa87C.js","assets/CertificateVerify-pf2PaX8X.js","assets/BecomeTeacher-CPa2DBiv.js","assets/CreatePage-BVDzHRPp.js","assets/PageProfile-Y6RNxOQI.js","assets/usePageAnalytics-Dynd4boE.js","assets/DiscoverPages-BIlawh6i.js","assets/PageSettings-DydVm4-z.js","assets/PageAnalyticsTab-BdeUcoAP.js","assets/PageAnalytics-ReRVFCCK.js"])))=>i.map(i=>d[i]);
2var a_=Object.defineProperty;var wh=s=>{throw TypeError(s)};var o_=(s,e,t)=>e in s?a_(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var qa=(s,e,t)=>o_(s,typeof e!="symbol"?e+"":e,t),Eh=(s,e,t)=>e.has(s)||wh("Cannot "+t);var Vi=(s,e,t)=>(Eh(s,e,"read from private field"),t?t.call(s):e.get(s)),Vl=(s,e,t)=>e.has(s)?wh("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(s):e.set(s,t),Sh=(s,e,t,r)=>(Eh(s,e,"write to private field"),r?r.call(s,t):e.set(s,t),t);import{r as g,j as a,Q as l_,I as c_,R as J,u as Wt,b as Da,d as Kc,k as d_,e as u_}from"./vendor-query-B0-uRJqS.js";import{r as yl,u as qt,B as h_,P as bt,a as Oa,b as Ln,c as Et,d as Us,e as mg,V as pg,R as f_,f as cn,g as m_,h as xi,i as p_,j as g_,C as gg,k as x_,l as y_,T as v_,_ as b_,m as vl,S as Pi,O as Di,n as bl,o as Oi,p as Ma,q as Mi,D as Fi,s as _l,t as __,v as su,w as ru,x as w_,
2y as xg,z as E_,A as S_,E as yg,F as nu,G as vg,W as T_,H as A_,I as bg,J as k_,K as R_,L as _g,M as j_,N as I_,Q as wg,U as C_,X as Eg,Y as N_,Z as L_,$ as Sg,a0 as Tg,a1 as Ag,a2 as kg}from"./vendor-radix-Mcgp0sn6.js";import{c as Rg}from"./vendor-charts-BGFylbhW.js";import{u as br,a as hs,N as da,b as me,L as er,O as P_,B as D_,R as O_,c as V,d as M_}from"./vendor-react-CW1TH9gT.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))r(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function t(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(n){if(n.ep)return;n.ep=!0;const i=t(n);fetch(n.href,i)}})();var jg,Th=yl;jg=Th.createRoot,Th.hydrateRoot;function Do(){}function F_(s){var t;let e;if((t=s.then(r=>(e=r,r),Do))==null||t.catch(Do),e!==void 0)return{data:e}}function Ig(s){return s}function $_(s){return{mutationKey:s.options.mutationKey,state:s.state,...s.options.scope&&{scope:s.options.scope},...s.meta&&{meta:s.meta}}}function U_(s,e,t){const r=()=>{var i;const n=(i=s.promise)==null?void 0:i.then(e).catch(o=>t(o)?Promise.reject(new Error("redacted")):Promise.reject(o));return n==null||n.catch(Do),n};return{dehydratedAt:Date.now(),state:{...s.state,...s.state.data!==void 0&&{data:e(s.state.data)}},queryKey:s.queryKey,queryHash:s.queryHash,...s.state.status==="pending"&&{promise:r()},...s.meta&&{meta:s.meta}}}function B_(s){return s.state.isPaused}function V_(s){return s.state.status==="success"}function G_(s){return!0}function z_(s,e={}){var d,c,u,h;const t=e.shouldDehydrateMutation??((d=s.getDefaultOptions().dehydrate)==null?void 0:d.shouldDehydrateMutation)??B_,r=s.getMutationCache().getAll().flatMap(f=>t(f)?[$_(f)]:[]),n=e.shouldDehydrateQuery??((c=s.getDefaultOptions().dehydrate)==null?void 0:c.shouldDehydrateQuery)??V_,i=e.shouldRedactErrors??((u=s.getDefaultOptions().dehydrate)==null?void 0:u.shouldRedactErrors)??G_,o=e.serializeData??((h=s.getDefaultOptions().dehydrate)==null?void 0:h.serializeData)??Ig,l=s.getQueryCache().getAll().flatMap(f=>n(f)?[U_(f,o,i)]:[]);return{mutations:r,queries:l}}function q_(s,e,t){var d,c;if(typeof e!="object"||e===null)return;const r=s.getMutationCache(),n=s.getQueryCache(),i=((d=t==null?void 0:t.defaultOptions)==null?void 0:d.deserializeData)??((c=s.getDefaultOptions().hydrate)==null?void 0:c.deserializeData)??Ig,o=e.mutations||[],l=e.queries||[];o.forEach(({state:u,...h})=>{var f,m;r.build(s,{...(f=s.getDefaultOptions().hydrate)==null?void 0:f.mutations,...(m=t==null?void 0:t.defaultOptions)==null?void 0:m.mutations,...h},u)}),l.forEach(({queryKey:u,state:h,queryHash:f,meta:m,promise:p,dehydratedAt:x})=>{var A,S;const y=p?F_(p):void 0,v=h.data===void 0?y==null?void 0:y.data:h.data,_=v===void 0?v:i(v);let b=n.get(f);const w=(b==null?void 0:b.state.status)==="pending",T=(b==null?void 0:b.state.fetchStatus)==="fetching";if(b){const I=y&&x!==void 0&&x>b.state.dataUpdatedAt;if(h.dataUpdatedAt>b.state.dataUpdatedAt||I){const{fetchStatus:j,...R}=h;b.setState({...R,data:_})}}else b=n.build(s,{...(A=s.getDefaultOptions().hydrate)==null?void 0:A.queries,...(S=t==null?void 0:t.defaultOptions)==null?void 0:S.queries,queryKey:u,queryHash:f,meta:m},{...h,data:_,fetchStatus:"idle",status:_!==void 0?"success":h.status});p&&!w&&!T&&(x===void 0||x>b.state.dataUpdatedAt)&&b.fetch(void 0,{initialPromise:Promise.resolve(p).then(i)}).catch(Do)})}var H_=["added","removed","updated"];function Ah(s){return H_.includes(s)}async function K_({queryClient:s,persister:e,maxAge:t=1e3*60*60*24,buster:r="",hydrateOptions:n}){try{const i=await e.restoreClient();if(i)if(i.timestamp){const o=Date.now()-i.timestamp>t,l=i.buster!==r;if(o||l)return e.removeClient();q_(s,i.clientState,n)}else return e.removeClient()}catch(i){throw await e.removeClient(),i}}async function kh({queryClient:s,persister:e,buster:t="",dehydrateOptions:r}){const n={buster:t,timestamp:Date.now(),clientState:z_(s,r)};await e.persistClient(n)}function W_(s){const e=s.queryClient.getQueryCache().subscribe(r=>{Ah(r.type)&&kh(s)}),t=s.queryClient.getMutationCache().subscribe(r=>{Ah(r.type)&&kh(s)});return()=>{e(),t()}}var Y_=({children:s,persistOptions:e,onSuccess:t,onError:r,...n})=>{const[i,o]=g.useState(!0),l=g.useRef({persistOptions:e,onSuccess:t,onError:r}),d=g.useRef(!1);return g.useEffect(()=>{l.current={persistOptions:e,onSuccess:t,onError:r}}),g.useEffect(()=>{const c={...l.current.persistOptions,queryClient:n.client};return d.current||(d.current=!0,K_(c).then(()=>{var u,h;
2return(h=(u=l.current).onSuccess)==null?void 0:h.call(u)}).catch(()=>{var u,h;return(h=(u=l.current).onError)==null?void 0:h.call(u)}).finally(()=>{o(!1)})),i?void 0:W_(c)},[n.client,i]),a.jsx(l_,{...n,children:a.jsx(c_,{value:i,children:s})})},X_={setTimeout:(s,e)=>setTimeout(s,e),clearTimeout:s=>clearTimeout(s),setInterval:(s,e)=>setInterval(s,e),clearInterval:s=>clearInterval(s)},Xr,tu,fg,Q_=(fg=class{constructor(){Vl(this,Xr,X_);Vl(this,tu,!1)}setTimeoutProvider(s){Sh(this,Xr,s)}setTimeout(s,e){return Vi(this,Xr).setTimeout(s,e)}clearTimeout(s){Vi(this,Xr).clearTimeout(s)}setInterval(s,e){return Vi(this,Xr).setInterval(s,e)}clearInterval(s){Vi(this,Xr).clearInterval(s)}},Xr=new WeakMap,tu=new WeakMap,fg),J_=new Q_;function Gl(){}function Z_({storage:s,key:e="REACT_QUERY_OFFLINE_CACHE",throttleTime:t=1e3,serialize:r=JSON.stringify,deserialize:n=JSON.parse,retry:i}){if(s){const o=l=>{try{s.setItem(e,r(l));return}catch(d){return d}};return{persistClient:ew(l=>{let d=l,c=o(d),u=0;for(;c&&d;)u++,d=i==null?void 0:i({persistedClient:d,error:c,errorCount:u}),d&&(c=o(d))},t),restoreClient:()=>{const l=s.getItem(e);if(l)return n(l)},removeClient:()=>{s.removeItem(e)}}}return{persistClient:Gl,restoreClient:Gl,removeClient:Gl}}function ew(s,e=100){let t=null,r;return function(...n){r=n,t===null&&(t=J_.setTimeout(()=>{s(...r),t=null},e))}}const tw="modulepreload",sw=function(s){return"/"+s},Rh={},M=function(e,t,r){let n=Promise.resolve();if(t&&t.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));n=Promise.allSettled(t.map(d=>{if(d=sw(d),d in Rh)return;Rh[d]=!0;const c=d.endsWith(".css"),u=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const h=document.createElement("link");if(h.rel=c?"stylesheet":tw,c||(h.as="script"),h.crossOrigin="",h.href=d,l&&h.setAttribute("nonce",l),document.head.appendChild(h),c)return new Promise((f,m)=>{h.addEventListener("load",f),h.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return n.then(o=>{for(const l of o||[])l.status==="rejected"&&i(l.reason);return e().catch(i)})},rw=1,nw=1e6;let zl=0;function iw(){return zl=(zl+1)%Number.MAX_SAFE_INTEGER,zl.toString()}const ql=new Map,jh=s=>{if(ql.has(s))return;const e=setTimeout(()=>{ql.delete(s),ta({type:"REMOVE_TOAST",toastId:s})},nw);ql.set(s,e)},aw=(s,e)=>{switch(e.type){case"ADD_TOAST":return{...s,toasts:[e.toast,...s.toasts].slice(0,rw)};case"UPDATE_TOAST":return{...s,toasts:s.toasts.map(t=>t.id===e.toast.id?{...t,...e.toast}:t)};case"DISMISS_TOAST":{const{toastId:t}=e;return t?jh(t):s.toasts.forEach(r=>{jh(r.id)}),{...s,toasts:s.toasts.map(r=>r.id===t||t===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return e.toastId===void 0?{...s,toasts:[]}:{...s,toasts:s.toasts.filter(t=>t.id!==e.toastId)}}},bo=[];let _o={toasts:[]};function ta(s){_o=aw(_o,s),bo.forEach(e=>{e(_o)})}function ow({...s}){const e=iw(),t=n=>ta({type:"UPDATE_TOAST",toast:{...n,id:e}}),r=()=>ta({type:"DISMISS_TOAST",toastId:e});return ta({type:"ADD_TOAST",toast:{...s,id:e,open:!0,onOpenChange:n=>{n||r()}}}),{id:e,dismiss:r,update:t}}function lw(){const[s,e]=g.useState(_o);return g.useEffect(()=>(bo.push(e),()=>{const t=bo.indexOf(e);t>-1&&bo.splice(t,1)}),[s]),{...s,toast:ow,dismiss:t=>ta({type:"DISMISS_TOAST",toastId:t})}}var iu="ToastProvider",[au,cw,dw]=mg("Toast"),[Cg]=cn("Toast",[dw]),[uw,wl]=Cg(iu),Ng=s=>{const{__scopeToast:e,label:t="Notification",duration:r=5e3,swipeDirection:n="right",swipeThreshold:i=50,children:o}=s,[l,d]=g.useState(null),[c,u]=g.useState(0),h=g.useRef(!1),f=g.useRef(!1);return t.trim()||console.error(`Invalid prop \`label\` supplied to \`${iu}\`. Expected non-empty \`string\`.`),a.jsx(au.Provider,{scope:e,children:a.jsx(u
2w,{scope:e,label:t,duration:r,swipeDirection:n,swipeThreshold:i,toastCount:c,viewport:l,onViewportChange:d,onToastAdd:g.useCallback(()=>u(m=>m+1),[]),onToastRemove:g.useCallback(()=>u(m=>m-1),[]),isFocusedToastEscapeKeyDownRef:h,isClosePausedRef:f,children:o})})};Ng.displayName=iu;var Lg="ToastViewport",hw=["F8"],Wc="toast.viewportPause",Yc="toast.viewportResume",Pg=g.forwardRef((s,e)=>{const{__scopeToast:t,hotkey:r=hw,label:n="Notifications ({hotkey})",...i}=s,o=wl(Lg,t),l=cw(t),d=g.useRef(null),c=g.useRef(null),u=g.useRef(null),h=g.useRef(null),f=qt(e,h,o.onViewportChange),m=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),p=o.toastCount>0;g.useEffect(()=>{const y=v=>{var b;r.length!==0&&r.every(w=>v[w]||v.code===w)&&((b=h.current)==null||b.focus())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[r]),g.useEffect(()=>{const y=d.current,v=h.current;if(p&&y&&v){const _=()=>{if(!o.isClosePausedRef.current){const A=new CustomEvent(Wc);v.dispatchEvent(A),o.isClosePausedRef.current=!0}},b=()=>{if(o.isClosePausedRef.current){const A=new CustomEvent(Yc);v.dispatchEvent(A),o.isClosePausedRef.current=!1}},w=A=>{!y.contains(A.relatedTarget)&&b()},T=()=>{y.contains(document.activeElement)||b()};return y.addEventListener("focusin",_),y.addEventListener("focusout",w),y.addEventListener("pointermove",_),y.addEventListener("pointerleave",T),window.addEventListener("blur",_),window.addEventListener("focus",b),()=>{y.removeEventListener("focusin",_),y.removeEventListener("focusout",w),y.removeEventListener("pointermove",_),y.removeEventListener("pointerleave",T),window.removeEventListener("blur",_),window.removeEventListener("focus",b)}}},[p,o.isClosePausedRef]);const x=g.useCallback(({tabbingDirection:y})=>{const _=l().map(b=>{const w=b.ref.current,T=[w,...Tw(w)];return y==="forwards"?T:T.reverse()});return(y==="forwards"?_.reverse():_).flat()},[l]);return g.useEffect(()=>{const y=h.current;if(y){const v=_=>{var T,A,S;const b=_.altKey||_.ctrlKey||_.metaKey;if(_.key==="Tab"&&!b){const I=document.activeElement,j=_.shiftKey;if(_.target===y&&j){(T=c.current)==null||T.focus();return}const D=x({tabbingDirection:j?"backwards":"forwards"}),Y=D.findIndex(q=>q===I);Hl(D.slice(Y+1))?_.preventDefault():j?(A=c.current)==null||A.focus():(S=u.current)==null||S.focus()}};return y.addEventListener("keydown",v),()=>y.removeEventListener("keydown",v)}},[l,x]),a.jsxs(h_,{ref:d,role:"region","aria-label":n.replace("{hotkey}",m),tabIndex:-1,style:{pointerEvents:p?void 0:"none"},children:[p&&a.jsx(Xc,{ref:c,onFocusFromOutsideViewport:()=>{const y=x({tabbingDirection:"forwards"});Hl(y)}}),a.jsx(au.Slot,{scope:t,children:a.jsx(bt.ol,{tabIndex:-1,...i,ref:f})}),p&&a.jsx(Xc,{ref:u,onFocusFromOutsideViewport:()=>{const y=x({tabbingDirection:"backwards"});Hl(y)}})]})});Pg.displayName=Lg;var Dg="ToastFocusProxy",Xc=g.forwardRef((s,e)=>{const{__scopeToast:t,onFocusFromOutsideViewport:r,...n}=s,i=wl(Dg,t);return a.jsx(pg,{"aria-hidden":!0,tabIndex:0,...n,ref:e,style:{position:"fixed"},onFocus:o=>{var c;const l=o.relatedTarget;!((c=i.viewport)!=null&&c.contains(l))&&r()}})});Xc.displayName=Dg;var Fa="Toast",fw="toast.swipeStart",mw="toast.swipeMove",pw="toast.swipeCancel",gw="toast.swipeEnd",Og=g.forwardRef((s,e)=>{const{forceMount:t,open:r,defaultOpen:n,onOpenChange:i,...o}=s,[l,d]=Oa({prop:r,defaultProp:n??!0,onChange:i,caller:Fa});return a.jsx(Ln,{present:t||l,children:a.jsx(vw,{open:l,...o,ref:e,onClose:()=>d(!1),onPause:Us(s.onPause),onResume:Us(s.onResume),onSwipeStart:Et(s.onSwipeStart,c=>{c.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:Et(s.onSwipeMove,c=>{const{x:u,y:h}=c.detail.delta;c.currentTarget.setAttribute("data-swipe","move"),c.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${u}px`),c.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${h}px`)}),onSwipeCancel:Et(s.onSwipeCancel,c=>{c.currentTarget.setAttribute("data-swipe","cancel"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),c.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:Et(s.onSwipeEnd,c=>{const{x:u,y:h}=c.detail.delta;c.currentTarget.setAttribute("data-swipe","end"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),c.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${u}px`),c.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${h}px`),d(!1)})})})});Og.displayName=Fa;var[xw,yw]=Cg(Fa,{onClose(){}}),vw=g.forwardRef((s,e)=>{const{__scopeToast:t,type:r="foreground",duration:n,open:i,onClose:o,onEscapeKeyDown:l,onPause:d,onResume:c,onSwipeStart:u,onSwipeMove:h,onSwipeCancel:f,onSwipeEnd:m,...p}=s,x=wl(Fa,t),[y,v]=g.useState(null),_=qt(e,q=>v(q)),b=g.useRef(null),w=g.useRef(null),T=n||x.duration,A=g.useRef(0),S=g.useRef(T),I=g.useRef(0),{onToastAdd:j,onToastRemove:R}=x,k=Us(()=>{var X;(y==null?void 0:y.contains(document.activeElement))&&((X=x.viewport)==null||X.focus()),o()}),D=g.useCallback(q=>
2{!q||q===1/0||(window.clearTimeout(I.current),A.current=new Date().getTime(),I.current=window.setTimeout(k,q))},[k]);g.useEffect(()=>{const q=x.viewport;if(q){const X=()=>{D(S.current),c==null||c()},F=()=>{const P=new Date().getTime()-A.current;S.current=S.current-P,window.clearTimeout(I.current),d==null||d()};return q.addEventListener(Wc,F),q.addEventListener(Yc,X),()=>{q.removeEventListener(Wc,F),q.removeEventListener(Yc,X)}}},[x.viewport,T,d,c,D]),g.useEffect(()=>{i&&!x.isClosePausedRef.current&&D(T)},[i,T,x.isClosePausedRef,D]),g.useEffect(()=>(j(),()=>R()),[j,R]);const Y=g.useMemo(()=>y?Gg(y):null,[y]);return x.viewport?a.jsxs(a.Fragment,{children:[Y&&a.jsx(bw,{__scopeToast:t,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0,children:Y}),a.jsx(xw,{scope:t,onClose:k,children:yl.createPortal(a.jsx(au.ItemSlot,{scope:t,children:a.jsx(f_,{asChild:!0,onEscapeKeyDown:Et(l,()=>{x.isFocusedToastEscapeKeyDownRef.current||k(),x.isFocusedToastEscapeKeyDownRef.current=!1}),children:a.jsx(bt.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":x.swipeDirection,...p,ref:_,style:{userSelect:"none",touchAction:"none",...s.style},onKeyDown:Et(s.onKeyDown,q=>{q.key==="Escape"&&(l==null||l(q.nativeEvent),q.nativeEvent.defaultPrevented||(x.isFocusedToastEscapeKeyDownRef.current=!0,k()))}),onPointerDown:Et(s.onPointerDown,q=>{q.button===0&&(b.current={x:q.clientX,y:q.clientY})}),onPointerMove:Et(s.onPointerMove,q=>{if(!b.current)return;const X=q.clientX-b.current.x,F=q.clientY-b.current.y,P=!!w.current,N=["left","right"].includes(x.swipeDirection),O=["left","up"].includes(x.swipeDirection)?Math.min:Math.max,$=N?O(0,X):0,B=N?0:O(0,F),U=q.pointerType==="touch"?10:2,K={x:$,y:B},ee={originalEvent:q,delta:K};P?(w.current=K,Ha(mw,h,ee,{discrete:!1})):Ih(K,x.swipeDirection,U)?(w.current=K,Ha(fw,u,ee,{discrete:!1}),q.target.setPointerCapture(q.pointerId)):(Math.abs(X)>U||Math.abs(F)>U)&&(b.current=null)}),onPointerUp:Et(s.onPointerUp,q=>{const X=w.current,F=q.target;if(F.hasPointerCapture(q.pointerId)&&F.releasePointerCapture(q.pointerId),w.current=null,b.current=null,X){const P=q.currentTarget,N={originalEvent:q,delta:X};Ih(X,x.swipeDirection,x.swipeThreshold)?Ha(gw,m,N,{discrete:!0}):Ha(pw,f,N,{discrete:!0}),P.addEventListener("click",O=>O.preventDefault(),{once:!0})}})})})}),x.viewport)})]}):null}),bw=s=>{const{__scopeToast:e,children:t,...r}=s,n=wl(Fa,e),[i,o]=g.useState(!1),[l,d]=g.useState(!1);return Ew(()=>o(!0)),g.useEffect(()=>{const c=window.setTimeout(()=>d(!0),1e3);return()=>window.clearTimeout(c)},[]),l?null:a.jsx(m_,{asChild:!0,children:a.jsx(pg,{...r,children:i&&a.jsxs(a.Fragment,{children:[n.label," ",t]})})})},_w="ToastTitle",Mg=g.forwardRef((s,e)=>{const{__scopeToast:t,...r}=s;return a.jsx(bt.div,{...r,ref:e})});Mg.displayName=_w;var ww="ToastDescription",Fg=g.forwardRef((s,e)=>{const{__scopeToast:t,...r}=s;return a.jsx(bt.div,{...r,ref:e})});Fg.displayName=ww;var $g="ToastAction",Ug=g.forwardRef((s,e)=>{const{altText:t,...r}=s;return t.trim()?a.jsx(Vg,{altText:t,asChild:!0,children:a.jsx(ou,{...r,ref:e})}):(console.error(`Invalid prop \`altText\` supplied to \`${$g}\`. Expected non-empty \`string\`.`),null)});Ug.displayName=$g;var Bg="ToastClose",ou=g.forwardRef((s,e)=>{const{__scopeToast:t,...r}=s,n=yw(Bg,t);return a.jsx(Vg,{asChild:!0,children:a.jsx(bt.button,{type:"button",...r,ref:e,onClick:Et(s.onClick,n.onClose)})})});ou.displayName=Bg;var Vg=g.forwardRef((s,e)=>{const{__scopeToast:t,altText:r,...n}=s;return a.jsx(bt.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...n,ref:e})});function Gg(s){const e=[];return Array.from(s.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&e.push(r.textContent),Sw(r)){const n=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!n)if(i){const o=r.dataset.radixToastAnnounceAlt;o&&e.push(o)}else e.push(...Gg(r))}}),e}function Ha(s,e,t,{discrete:r}){const n=t.originalEvent.currentTarget,i=new CustomEvent(s,{bubbles:!0,cancelable:!0,detail:t});e&&n.addEventListener(s,e,{once:!0}),r?p_(n,i):n.dispatchEvent(i)}var Ih=(s,e,t=0)=>{const r=Math.abs(s.x),n=Math.abs(s.y),i=r>n;return e==="left"||e==="right"?i&&r>t:!i&&n>t};function Ew(s=()=>{}){const e=Us(s);xi(()=>{let t=0,r=0;return t=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(e)),()=>{window.cancelAnimationFrame(t),window.cancelAnimationFrame(r)}},[e])}function Sw(s){return s.nodeType===s.ELEMENT_NODE}function Tw(s){const e=[],t=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const n=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||n?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;t.nextNode();)e.push(t.currentNode);return e}function Hl(s){const e=document.activeElement;return s.some(t=>t===e?!0:(t.focus(),document.activeElement!==e))}var Aw=Ng,zg=Pg,qg=Og,Hg=Mg,Kg=Fg,Wg=Ug,Yg=ou;const Ch=s=>typeof s=="boolean"?`${s}`:s===0?"0":s,Nh=Rg,Pn=(s,e)=>t=>{var r;if((e==null?void 0:e.variants)==null)return Nh(s,t==null?void 0:t.class,t==null?void 0:t.className);const{variants:n,defaultVariants:i}=e,o=Object.keys(n).map(c=>{const u=t==null?void 0:t[c],h=i==null?void 0:i[c];if(u===null)return null;const f=Ch(u)||Ch(h);return n[c][f]}),l=t&&Object.entries(t).reduce((c,u)=>{let[h,f]=u;return f===void 0||(c[h]=f),c},{}),d=e==null||(r=e.compoundVariants)===null||r===void 0?void 0:r.reduce((c,u)=>{let{class:h,className:f,...m}=u;return Object.entries(m).every(p=>{let[x,y]=p;return Array.isArray(y)?y.includes({...i,...l}[x]):{...i,...l}[x]===y})?[...c,h,f]:c},[]);return Nh(s,o,d,t==null?void 0:t.class,t==null?void 0:t.className)};/**
3 * @license lucide-react v0.462.0 - ISC
4 *
5 * This source code is licensed under the ISC license.
6 * See the LICENSE file in the root directory of this source tree.
7 */const kw=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Xg=(...s)=>s.filter((e,t,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===t).join(" ").trim();/**
8 * @license lucide-react v0.462.0 - ISC
9 *
10 * This source code is licensed under the ISC license.
11 * See the LICENSE file in the root directory of this source tree.
12 */var Rw={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
13 * @license lucide-react v0.462.0 - ISC
14 *
15 * This source code is licensed under the ISC license.
16 * See the LICENSE file in the root directory of this source tree.
17 */const jw=g.forwardRef(({color:s="currentColor",size:e=24,strokeWidth:t=2,absoluteStrokeWidth:r,className:n="",children:i,iconNode:o,...l},d)=>g.createElement("svg",{ref:d,...Rw,width:e,height:e,stroke:s,strokeWidth:r?Number(t)*24/Number(e):t,className:Xg("lucide",n),...l},[...o.map(([c,u])=>g.createElement(c,u)),...Array.isArray(i)?i:[i]]));/**
18 * @license lucide-react v0.462.0 - ISC
19 *
20 * This source code is licensed under the ISC license.
21 * See the LICENSE file in the root directory of this source tree.
22 */const ae=(s,e)=>{const t=g.forwardRef(({className:r,...n},i)=>g.createElement(jw,{ref:i,iconNode:e,className:Xg(`lucide-${kw(s)}`,r),...n}));return t.displayName=`${s}`,t};/**
23 * @license lucide-react v0.462.0 - ISC
24 *
25 * This source code is licensed under the ISC license.
26 * See the LICENSE file in the root directory of this source tree.
27 */const Lh=ae("Activity",[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l
27-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]);/**
28 * @license lucide-react v0.462.0 - ISC
29 *
30 * This source code is licensed under the ISC license.
31 * See the LICENSE file in the root directory of this source tree.
32 */const Ph=ae("ArrowLeftRight",[["path",{d:"M8 3 4 7l4 4",key:"9rb6wj"}],["path",{d:"M4 7h16",key:"6tx8e3"}],["path",{d:"m16 21 4-4-4-4",key:"siv7j2"}],["path",{d:"M20 17H4",key:"h6l3hr"}]]);/**
33 * @license lucide-react v0.462.0 - ISC
34 *
35 * This source code is licensed under the ISC license.
36 * See the LICENSE file in the root directory of this source tree.
37 */const yi=ae("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/**
38 * @license lucide-react v0.462.0 - ISC
39 *
40 * This source code is licensed under the ISC license.
41 * See the LICENSE file in the root directory of this source tree.
42 */const Qg=ae("AtSign",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8",key:"7n84p3"}]]);/**
43 * @license lucide-react v0.462.0 - ISC
44 *
45 * This source code is licensed under the ISC license.
46 * See the LICENSE file in the root directory of this source tree.
47 */const Iw=ae("Award",[["path",{d:"m15.477 12.89 1.515 8.526a.5.5 0 0 1-.81.47l-3.58-2.687a1 1 0 0 0-1.197 0l-3.586 2.686a.5.5 0 0 1-.81-.469l1.514-8.526",key:"1yiouv"}],["circle",{cx:"12",cy:"8",r:"6",key:"1vp47v"}]]);/**
48 * @license lucide-react v0.462.0 - ISC
49 *
50 * This source code is licensed under the ISC license.
51 * See the LICENSE file in the root directory of this source tree.
52 */const Oo=ae("BadgeCheck",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/**
53 * @license lucide-react v0.462.0 - ISC
54 *
55 * This source code is licensed under the ISC license.
56 * See the LICENSE file in the root directory of this source tree.
57 */const Qc=ae("Bell",[["path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9",key:"1qo2s2"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}]]);/**
58 * @license lucide-react v0.462.0 - ISC
59 *
60 * This source code is licensed under the ISC license.
61 * See the LICENSE file in the root directory of this source tree.
62 */const Jg=ae("BookMarked",[["path",{d:"M10 2v8l3-3 3 3V2",key:"sqw3rj"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]]);/**
63 * @license lucide-react v0.462.0 - ISC
64 *
65 * This source code is licensed under the ISC license.
66 * See the LICENSE file in the root directory of this source tree.
67 */const Mn=ae("BookOpen",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]]);/**
68 * @license lucide-react v0.462.0 - ISC
69 *
70 * This source code is licensed under the ISC license.
71 * See the LICENSE file in the root directory of this source tree.
72 */const si=ae("Brain",[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z",key:"ep3f8r"}],["path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4",key:"1p4c4q"}],["path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375",key:"tmeiqw"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M19.938 10.5a4 4 0 0 1 .585.396",key:"1qfode"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M19.967 17.484A4 4 0 0 1 18 18",key:"159ez6"}]]);/**
73 * @license lucide-react v0.462.0 - ISC
74 *
75 * This source code is licensed under the ISC license.
76 * See the LICENSE file in the root directory of this source tree.
77 */const Es=ae("Briefcase",[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]]);/**
78 * @license lucide-react v0.462.0 - ISC
79 *
80 * This source code is licensed under the ISC license.
81 * See the LICENSE file in the root directory of this source tree.
82 */const wo=ae("Building2",[["path",{d:"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z",key:"1b4qmf"}],["path",{d:"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"i71pzd"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2",key:"10jefs"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"M10 10h4",key:"tcdvrf"}
82],["path",{d:"M10 14h4",key:"kelpxr"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/**
83 * @license lucide-react v0.462.0 - ISC
84 *
85 * This source code is licensed under the ISC license.
86 * See the LICENSE file in the root directory of this source tree.
87 */const Cr=ae("ChartColumn",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]]);/**
88 * @license lucide-react v0.462.0 - ISC
89 *
90 * This source code is licensed under the ISC license.
91 * See the LICENSE file in the root directory of this source tree.
92 */const Cw=ae("ChartPie",[["path",{d:"M21 12c.552 0 1.005-.449.95-.998a10 10 0 0 0-8.953-8.951c-.55-.055-.998.398-.998.95v8a1 1 0 0 0 1 1z",key:"pzmjnu"}],["path",{d:"M21.21 15.89A10 10 0 1 1 8 2.83",key:"k2fpak"}]]);/**
93 * @license lucide-react v0.462.0 - ISC
94 *
95 * This source code is licensed under the ISC license.
96 * See the LICENSE file in the root directory of this source tree.
97 */const Dh=ae("CheckCheck",[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]]);/**
98 * @license lucide-react v0.462.0 - ISC
99 *
100 * This source code is licensed under the ISC license.
101 * See the LICENSE file in the root directory of this source tree.
102 */const vi=ae("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/**
103 * @license lucide-react v0.462.0 - ISC
104 *
105 * This source code is licensed under the ISC license.
106 * See the LICENSE file in the root directory of this source tree.
107 */const ri=ae("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/**
108 * @license lucide-react v0.462.0 - ISC
109 *
110 * This source code is licensed under the ISC license.
111 * See the LICENSE file in the root directory of this source tree.
112 */const us=ae("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/**
113 * @license lucide-react v0.462.0 - ISC
114 *
115 * This source code is licensed under the ISC license.
116 * See the LICENSE file in the root directory of this source tree.
117 */const Nw=ae("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/**
118 * @license lucide-react v0.462.0 - ISC
119 *
120 * This source code is licensed under the ISC license.
121 * See the LICENSE file in the root directory of this source tree.
122 */const lu=ae("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/**
123 * @license lucide-react v0.462.0 - ISC
124 *
125 * This source code is licensed under the ISC license.
126 * See the LICENSE file in the root directory of this source tree.
127 */const bi=ae("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/**
128 * @license lucide-react v0.462.0 - ISC
129 *
130 * This source code is licensed under the ISC license.
131 * See the LICENSE file in the root directory of this source tree.
132 */const sr=ae("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/**
133 * @license lucide-react v0.462.0 - ISC
134 *
135 * This source code is licensed under the ISC license.
136 * See the LICENSE file in the root directory of this source tree.
137 */const Lw=ae("CircleHelp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
138 * @license lucide-react v0.462.0 - ISC
139 *
140 * This source code is licensed under the ISC license.
141 * See the LICENSE file in the root directory of this source tree.
142 */const Pw=ae("CirclePlus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);/**
143 * @license lucide-react v0.462.0 - ISC
144 *
145 * This source code is licensed under the ISC license.
146 * See the LICENSE file in the root directory of this source tree.
147 */const cu=ae("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
148 * @license lucide-react v0.462.0 - ISC
149 *
150 * This source code is licensed under the ISC license.
151 * See the LICENSE file in the root directory of this source tree.
152 */const Mo=ae("Clapperboard",[["path",{d:"M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3Z",key:"1tn4o7"}],["path",{d:"m6.2 5.3 3.1 3.9",key:"iuk76l"}],["path",{d:"m12.4 3.4 3.1 4",key:"6hsd6n"}],["path",{d:"M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z",key:"ltgou9"}]]);/**
153 * @license lucide-react v0.462.0 - ISC
154 *
155 * This source code is licensed under the ISC license.
156 * See the LICENSE file in the root directory of this source tree.
157 */const $a=ae("ClipboardList",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);/**
158 * @license lucide-react v0.462.0 - ISC
159 *
160 * This source code is licensed under the ISC license.
161 * See the LICENSE file in the root directory of this source tree.
162 */const Dw=ae("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/**
163 * @license lucide-react v0.462.0 - ISC
164 *
165 * This source code is licensed under the ISC license.
166 * See the LICENSE file in the root directory of this source tree.
167 */const Ow=ae("Cloud",[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]]);/**
168 * @license lucide-react v0.462.0 - ISC
169 *
170 * This source code is licensed under the ISC license.
171 * See the LICENSE file in the root directory of this source tree.
172 */const Oh=ae("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/**
173 * @license lucide-react v0.462.0 - ISC
174 *
175 * This source code is licensed under the ISC license.
176 * See the LICENSE file in the root directory of this source tree.
177 */const du=ae("Construction",[["rect",{x:"2",y:"6",width:"20",height:"8",rx:"1",key:"1estib"}],["path",{d:"M17 14v7",key:"7m2elx"}],["path",{d:"M7 14v7",key:"1cm7wv"}],["path",{d:"M17 3v3",key:"1v4jwn"}],["path",{d:"M7 3v3",key:"7o6guu"}],["path",{d:"M10 14 2.3 6.3",key:"1023jk"}],["path",{d:"m14 6 7.7 7.7",key:"1s8pl2"}],["path",{d:"m8 6 8 8",key:"hl96qh"}]]);/**
178 * @license lucide-react v0.462.0 - ISC
179 *
180 * This source code is licensed under the ISC license.
181 * See the LICENSE file in the root directory of this source tree.
182 */const Mh=ae("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/**
183 * @license lucide-react v0.462.0 - ISC
184 *
185 * This source code is licensed under the ISC license.
186 * See the LICENSE file in the root directory of this source tree.
187 */const Zg=ae("Database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]);/**
188 * @license lucide-react v0.462.0 - ISC
189 *
190 * This source code is licensed under the ISC license.
191 * See the LICENSE file in the root directory of this source tree.
192 */const Mw=ae("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/**
193 * @license lucide-react v0.462.0 - ISC
194 *
195 * This source code is licensed under the ISC license.
196 * See the LICENSE file in the root directory of this source tree.
197 */const Fw=ae("EllipsisVertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);/**
198 * @license lucide-react v0.462.0 - ISC
199 *
200 * This source code is licensed under the ISC license.
201 * See the LICENSE file in the root directory of this source tree.
202 */const sa=ae("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/**
203 * @license lucide-react v0.462.0 - ISC
204 *
205 * This source code is licensed under the ISC license.
206 * See the LICENSE file in the root directory of this source tree.
207 */const Jc=ae("EyeOff",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/**
208 * @license lucide-react v0.462.0 - ISC
209 *
210 * This source code is licensed under the ISC license.
211 * See the LICENSE file in the root directory of this source tree.
212 */const Fh=ae("Eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/**
213 * @license lucide-react v0.462.0 - ISC
214 *
215 * This source code is licensed under the ISC license.
216 * See the LICENSE file in the root directory of this source tree.
217 */const $w=ae("FileCheck",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m9 15 2 2 4-4",key:"1grp1n"}]]);/**
218 * @license lucide-react v0.462.0 - ISC
219 *
220 * This source code is licensed under the ISC license.
221 * See the LICENSE file in the root directory of this source tree.
222 */const $h=ae("FilePen",[["path",{d:"M12.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v9.5",key:"1couwa"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M13.378 15.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1y4qbx"}]]);/**
223 * @license lucide-react v0.462.0 - ISC
224 *
225 * This source code is licensed under the ISC license.
226 * See the LICENSE file in the root directory of this source tree.
227 */const Dn=ae("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);/**
228 * @license lucide-react v0.462.0 - ISC
229 *
230 * This source code is licensed under the ISC license.
231 * See the LICENSE file in the root directory of this source tree.
232 */const Fo=ae("Flag",[["path",{d:"M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z",key:"i9b6wo"}],["line",{x1:"4",x2:"4",y1:"22",y2:"15",key:"1cm3nv"}]]);/**
233 * @license lucide-react v0.462.0 - ISC
234 *
235 * This source code is licensed under the ISC license.
236 * See the LICENSE file in the root directory of this source tree.
237 */const Kl=ae("FolderKanban",[["path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z",key:"1fr9dc"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M12 10v2",key:"hh53o1"}],["path",{d:"M16 10v6",key:"1d6xys"}]]);/**
238 * @license lucide-react v0.462.0 - ISC
239 *
240 * This source code is licensed under the ISC license.
241 * See the LICENSE file in the root directory of this source tree.
242 */const Uw=ae("Gamepad2",[["line",{x1:"6",x2:"10",y1:"11",y2:"11",key:"1gktln"}],["line",{x1:"8",x2:"8",y1:"9",y2:"13",key:"qnk9ow"}],["line",{x1:"15",x2:"15.01",y1:"12",y2:"12",key:"krot7o"}],["line",{x1:"18",x2:"18.01",y1:"10",y2:"10",key:"1lcuu1"}],["path",{d:"M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z",key:"mfqc10"}]]);/**
243 * @license lucide-react v0.462.0 - ISC
244 *
245 * This source code is licensed under the ISC license.
246 * See the LICENSE file in the root directory of this source tree.
247 */const Uh=ae("Gavel",[["path",{d:"m14.5 12.5-8 8a2.119 2.119 0 1 1-3-3l8-8",key:"15492f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m9 7 8 8",key:"5jnvq1"}],["path",{d:"m21 11-8-8",key:"z4y7zo"}]]);/**
248 * @license lucide-react v0.462.0 - ISC
249 *
250 * This source code is licensed under the ISC license.
251 * See the LICENSE file in the root directory of this source tree.
252 */const Bw=ae("GitBranch",[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]]);/**
253 * @license lucide-react v0.462.0 - ISC
254 *
255 * This source code is licensed under the ISC license.
256 * See the LICENSE file in the root directory of this source tree.
257 */const ra=ae("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);/**
258 * @license lucide-react v0.462.0 - ISC
259 *
260 * This source code is licensed under the ISC license.
261 * See the LICENSE file in the root directory of this source tree.
262 */const Nr=ae("GraduationCap",[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]]);/**
263 * @license lucide-react v0.462.0 - ISC
264 *
265 * This source code is licensed under the ISC license.
266 * See the LICENSE file in the root directory of this source tree.
267 */const Bh=ae("Headphones",[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3",key:"1xhozi"}]]);/**
268 * @license lucide-react v0.462.0 - ISC
269 *
270 * This source code is licensed under the ISC license.
271 * See the LICENSE file in the root directory of this source tree.
272 */const e0=ae("History",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/**
273 * @license lucide-react v0.462.0 - ISC
274 *
275 * This source code is licensed under the ISC license.
276 * See the LICENSE file in the root directory of this source tree.
277 */const ua=ae("House",[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"1d0kgt"}]]);/**
278 * @license lucide-react v0.462.0 - ISC
279 *
280 * This source code is licensed under the ISC license.
281 * See the LICENSE file in the root directory of this source tree.
282 */const Vw=ae("IdCard",[["path",{d:"M16 10h2",key:"8sgtl7"}],["path",{d:"M16 14h2",key:"epxaof"}],["path",{d:"M6.17 15a3 3 0 0 1 5.66 0",key:"n6f512"}],["circle",{cx:"9",cy:"11",r:"2",key:"yxgjnd"}],["rect",{x:"2",y:"5",width:"20",height:"14",rx:"2",key:"qneu4z"}]]);/**
283 * @license lucide-react v0.462.0 - ISC
284 *
285 * This source code is licensed under the ISC license.
286 * See the LICENSE file in the root directory of this source tree.
287 */const Gw=ae("ImageOff",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M10.41 10.41a2 2 0 1 1-2.83-2.83",key:"1bzlo9"}],["line",{x1:"13.5",x2:"6",y1:"13.5",y2:"21",key:"1q0aeu"}],["line",{x1:"18",x2:"21",y1:"12",y2:"15",key:"5mozeu"}],["path",{d:"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",key:"mmje98"}],["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}]]);/**
288 * @license lucide-react v0.462.0 - ISC
289 *
290 * This source code is licensed under the ISC license.
291 * See the LICENSE file in the root directory of this source tree.
292 */const zw=ae("ImagePlus",[["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5",key:"1ue2ih"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]);/**
293 * @license lucide-react v0.462.0 - ISC
294 *
295 * This source code is licensed under the ISC license.
296 * See the LICENSE file in the root directory of this source tree.
297 */const Zc=ae("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/**
298 * @license lucide-react v0.462.0 - ISC
299 *
300 * This source code is licensed under the ISC license.
301 * See the LICENSE file in the root directory of this source tree.
302 */const qw=ae("Inbox",[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]]);/**
303 * @license lucide-react v0.462.0 - ISC
304 *
305 * This source code is licensed under the ISC license.
306 * See the LICENSE file in the root directory of this source tree.
307 */const Dr=ae("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/**
308 * @license lucide-react v0.462.0 - ISC
309 *
310 * This source code is licensed under the ISC license.
311 * See the LICENSE file in the root directory of this source tree.
312 */const ts=ae("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
313 * @license lucide-react v0.462.0 - ISC
314 *
315 * This source code is licensed under the ISC license.
316 * See the LICENSE file in the root directory of this source tree.
317 */const $o=ae("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/**
318 * @license lucide-react v0.462.0 - ISC
319 *
320 * This source code is licensed under the ISC license.
321 * See the LICENSE file in the root directory of this source tree.
322 */const Hw=ae("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/**
323 * @license lucide-react v0.462.0 - ISC
324 *
325 * This source code is licensed under the ISC license.
326 * See the LICENSE file in the root directory of this source tree.
327 */const Vh=ae("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/**
328 * @license lucide-react v0.462.0 - ISC
329 *
330 * This source code is licensed under the ISC license.
331 * See the LICENSE file in the root directory of this source tree.
332 */const t0=ae("Maximize",[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]]);/**
333 * @license lucide-react v0.462.0 - ISC
334 *
335 * This source code is licensed under the ISC license.
336 * See the LICENSE file in the root directory of this source tree.
337 */const Xn=ae("Megaphone",[["path",{d:"m3 11 18-5v12L3 14v-3z",key:"n962bs"}],["path",{d:"M11.6 16.8a3 3 0 1 1-5.8-1.6",key:"1yl0tm"}]]);/**
338 * @license lucide-react v0.462.0 - ISC
339 *
340 * This source code is licensed under the ISC license.
341 * See the LICENSE file in the root directory of this source tree.
342 */const Tn=ae("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/**
343 * @license lucide-react v0.462.0 - ISC
344 *
345 * This source code is licensed under the ISC license.
346 * See the LICENSE file in the root directory of this source tree.
347 */const Gh=ae("MessageSquareWarning",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M12 7v2",key:"stiyo7"}],["path",{d:"M12 13h.01",key:"y0uutt"}]]);/**
348 * @license lucide-react v0.462.0 - ISC
349 *
350 * This source code is licensed under the ISC license.
351 * See the LICENSE file in the root directory of this source tree.
352 */const ed=ae("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/**
353 * @license lucide-react v0.462.0 - ISC
354 *
355 * This source code is licensed under the ISC license.
356 * See the LICENSE file in the root directory of this source tree.
357 */const Kw=ae("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);/**
358 * @license lucide-react v0.462.0 - ISC
359 *
360 * This source code is licensed under the ISC license.
361 * See the LICENSE file in the root directory of this source tree.
362 */const Ww=ae("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
363 * @license lucide-react v0.462.0 - ISC
364 *
365 * This source code is licensed under the ISC license.
366 * See the LICENSE file in the root directory of this source tree.
367 */const na=ae("Package",[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["path",{d:"m3.3 7 7.703 4.734a2 2 0 0 0 1.994 0L20.7 7",key:"yx3hmr"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]]);/**
368 * @license lucide-react v0.462.0 - ISC
369 *
370 * This source code is licensed under the ISC license.
371 * See the LICENSE file in the root directory of this source tree.
372 */const zh=ae("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/**
373 * @license lucide-react v0.462.0 - ISC
374 *
375 * This source code is licensed under the ISC license.
376 * See the LICENSE file in the root directory of this source tree.
377 */const Yw=ae("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);/**
378 * @license lucide-react v0.462.0 - ISC
379 *
380 * This source code is licensed under the ISC license.
381 * See the LICENSE file in the root directory of this source tree.
382 */const Xw=ae("Paperclip",[["path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48",key:"1u3ebp"}]]);/**
383 * @license lucide-react v0.462.0 - ISC
384 *
385 * This source code is licensed under the ISC license.
386 * See the LICENSE file in the root directory of this source tree.
387 */const Qw=ae("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]]);/**
388 * @license lucide-react v0.462.0 - ISC
389 *
390 * This source code is licensed under the ISC license.
391 * See the LICENSE file in the root directory of this source tree.
392 */const qh=ae("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/**
393 * @license lucide-react v0.462.0 - ISC
394 *
395 * This source code is licensed under the ISC license.
396 * See the LICENSE file in the root directory of this source tree.
397 */const Qr=ae("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/**
398 * @license lucide-react v0.462.0 - ISC
399 *
400 * This source code is licensed under the ISC license.
401 * See the LICENSE file in the root directory of this source tree.
402 */const Hh=ae("ReceiptText",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M14 8H8",key:"1l3xfs"}],["path",{d:"M16 12H8",key:"1fr5h0"}
402],["path",{d:"M13 16H8",key:"wsln4y"}]]);/**
403 * @license lucide-react v0.462.0 - ISC
404 *
405 * This source code is licensed under the ISC license.
406 * See the LICENSE file in the root directory of this source tree.
407 */const Wl=ae("Receipt",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8",key:"1h4pet"}],["path",{d:"M12 17.5v-11",key:"1jc1ny"}]]);/**
408 * @license lucide-react v0.462.0 - ISC
409 *
410 * This source code is licensed under the ISC license.
411 * See the LICENSE file in the root directory of this source tree.
412 */const ha=ae("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/**
413 * @license lucide-react v0.462.0 - ISC
414 *
415 * This source code is licensed under the ISC license.
416 * See the LICENSE file in the root directory of this source tree.
417 */const Kh=ae("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
418 * @license lucide-react v0.462.0 - ISC
419 *
420 * This source code is licensed under the ISC license.
421 * See the LICENSE file in the root directory of this source tree.
422 */const Wh=ae("Scale",[["path",{d:"m16 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"7g6ntu"}],["path",{d:"m2 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"ijws7r"}],["path",{d:"M7 21h10",key:"1b0cd5"}],["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 7h2c2 0 5-1 7-2 2 1 5 2 7 2h2",key:"3gwbw2"}]]);/**
423 * @license lucide-react v0.462.0 - ISC
424 *
425 * This source code is licensed under the ISC license.
426 * See the LICENSE file in the root directory of this source tree.
427 */const Jw=ae("SearchX",[["path",{d:"m13.5 8.5-5 5",key:"1cs55j"}],["path",{d:"m8.5 8.5 5 5",key:"a8mexj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/**
428 * @license lucide-react v0.462.0 - ISC
429 *
430 * This source code is licensed under the ISC license.
431 * See the LICENSE file in the root directory of this source tree.
432 */const Ds=ae("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/**
433 * @license lucide-react v0.462.0 - ISC
434 *
435 * This source code is licensed under the ISC license.
436 * See the LICENSE file in the root directory of this source tree.
437 */const Zw=ae("SendHorizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]);/**
438 * @license lucide-react v0.462.0 - ISC
439 *
440 * This source code is licensed under the ISC license.
441 * See the LICENSE file in the root directory of this source tree.
442 */const s0=ae("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);/**
443 * @license lucide-react v0.462.0 - ISC
444 *
445 * This source code is licensed under the ISC license.
446 * See the LICENSE file in the root directory of this source tree.
447 */const bn=ae("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/**
448 * @license lucide-react v0.462.0 - ISC
449 *
450 * This source code is licensed under the ISC license.
451 * See the LICENSE file in the root directory of this source tree.
452 */const eE=ae("ShieldAlert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",ke
452y:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);/**
453 * @license lucide-react v0.462.0 - ISC
454 *
455 * This source code is licensed under the ISC license.
456 * See the LICENSE file in the root directory of this source tree.
457 */const kr=ae("Shield",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]]);/**
458 * @license lucide-react v0.462.0 - ISC
459 *
460 * This source code is licensed under the ISC license.
461 * See the LICENSE file in the root directory of this source tree.
462 */const Yh=ae("Smartphone",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]]);/**
463 * @license lucide-react v0.462.0 - ISC
464 *
465 * This source code is licensed under the ISC license.
466 * See the LICENSE file in the root directory of this source tree.
467 */const tE=ae("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]);/**
468 * @license lucide-react v0.462.0 - ISC
469 *
470 * This source code is licensed under the ISC license.
471 * See the LICENSE file in the root directory of this source tree.
472 */const Eo=ae("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]);/**
473 * @license lucide-react v0.462.0 - ISC
474 *
475 * This source code is licensed under the ISC license.
476 * See the LICENSE file in the root directory of this source tree.
477 */const r0=ae("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]);/**
478 * @license lucide-react v0.462.0 - ISC
479 *
480 * This source code is licensed under the ISC license.
481 * See the LICENSE file in the root directory of this source tree.
482 */const sE=ae("Star",[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]);/**
483 * @license lucide-react v0.462.0 - ISC
484 *
485 * This source code is licensed under the ISC license.
486 * See the LICENSE file in the root directory of this source tree.
487 */const rE=ae("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/**
488 * @license lucide-react v0.462.0 - ISC
489 *
490 * This source code is licensed under the ISC license.
491 * See the LICENSE file in the root directory of this source tree.
492 */const nE=ae("Timer",[["line",{x1:"10",x2:"14",y1:"2",y2:"2",key:"14vaq8"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11",key:"17fdiu"}],["circle",{cx:"12",cy:"14",r:"8",key:"1e1u0o"}]]);/**
493 * @license lucide-react v0.462.0 - ISC
494 *
495 * This source code is licensed under the ISC license.
496 * See the LICENSE file in the root directory of this source tree.
497 */const ni=ae("TrendingUp",[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]]);/**
498 * @license lucide-react v0.462.0 - ISC
499 *
500 * This source code is licensed under the ISC license.
501 * See the LICENSE file in the root directory of this source tree.
502 */const Lr=ae("TriangleAlert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
503 * @license lucide-react v0.462.0 - ISC
504 *
505 * This source code is licensed under the ISC license.
506 * See the LICENSE file in the root directory of this source tree.
507 */const iE=ae("Trophy",[["path",{d:"M6 9H4.5a2.5 2.5 0 0 1 0-5H6",key:"17hqa7"}],["path",{d:"M18 9h1.5a2.5 2.5 0 0 0 0-5H18",key:"lmptdp"}],["path",{d:"M4 22h16",key:"57wxv0"}
507],["path",{d:"M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22",key:"1nw9bq"}],["path",{d:"M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22",key:"1np0yb"}],["path",{d:"M18 2H6v7a6 6 0 0 0 12 0V2Z",key:"u46fv3"}]]);/**
508 * @license lucide-react v0.462.0 - ISC
509 *
510 * This source code is licensed under the ISC license.
511 * See the LICENSE file in the root directory of this source tree.
512 */const Uo=ae("UserCheck",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["polyline",{points:"16 11 18 13 22 9",key:"1pwet4"}]]);/**
513 * @license lucide-react v0.462.0 - ISC
514 *
515 * This source code is licensed under the ISC license.
516 * See the LICENSE file in the root directory of this source tree.
517 */const aE=ae("UserCog",[["circle",{cx:"18",cy:"15",r:"3",key:"gjjjvw"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M10 15H6a4 4 0 0 0-4 4v2",key:"1nfge6"}],["path",{d:"m21.7 16.4-.9-.3",key:"12j9ji"}],["path",{d:"m15.2 13.9-.9-.3",key:"1fdjdi"}],["path",{d:"m16.6 18.7.3-.9",key:"heedtr"}],["path",{d:"m19.1 12.2.3-.9",key:"1af3ki"}],["path",{d:"m19.6 18.7-.4-1",key:"1x9vze"}],["path",{d:"m16.8 12.3-.4-1",key:"vqeiwj"}],["path",{d:"m14.3 16.6 1-.4",key:"1qlj63"}],["path",{d:"m20.7 13.8 1-.4",key:"1v5t8k"}]]);/**
518 * @license lucide-react v0.462.0 - ISC
519 *
520 * This source code is licensed under the ISC license.
521 * See the LICENSE file in the root directory of this source tree.
522 */const oE=ae("UserX",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"17",x2:"22",y1:"8",y2:"13",key:"3nzzx3"}],["line",{x1:"22",x2:"17",y1:"8",y2:"13",key:"1swrse"}]]);/**
523 * @license lucide-react v0.462.0 - ISC
524 *
525 * This source code is licensed under the ISC license.
526 * See the LICENSE file in the root directory of this source tree.
527 */const lE=ae("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/**
528 * @license lucide-react v0.462.0 - ISC
529 *
530 * This source code is licensed under the ISC license.
531 * See the LICENSE file in the root directory of this source tree.
532 */const Xh=ae("UsersRound",[["path",{d:"M18 21a8 8 0 0 0-16 0",key:"3ypg7q"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M22 20c0-3.37-2-6.5-4-8a5 5 0 0 0-.45-8.3",key:"10s06x"}]]);/**
533 * @license lucide-react v0.462.0 - ISC
534 *
535 * This source code is licensed under the ISC license.
536 * See the LICENSE file in the root directory of this source tree.
537 */const Ss=ae("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/**
538 * @license lucide-react v0.462.0 - ISC
539 *
540 * This source code is licensed under the ISC license.
541 * See the LICENSE file in the root directory of this source tree.
542 */const cE=ae("Volume1",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}]]);/**
543 * @license lucide-react v0.462.0 - ISC
544 *
545 * This source code is licensed under the ISC license.
546 * See the LICENSE file in the root directory of this source tree.
547 */const dE=ae("Volume2",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]]);/**
548 * @license lucide-react v0.462.0 - ISC
549 *
550 * This source code is licensed under the ISC license.
551 * See the LICENSE file in the root directory of this source tree.
552 */const uE=ae("VolumeX",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]]);/**
553 * @license lucide-react v0.462.0 - ISC
554 *
555 * This source code is licensed under the ISC license.
556 * See the LICENSE file in the root directory of this source tree.
557 */const zr=ae("Wallet",[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",key:"18etb6"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4",key:"xoc0q4"}]]);/**
558 * @license lucide-react v0.462.0 - ISC
559 *
560 * This source code is licensed under the ISC license.
561 * See the LICENSE file in the root directory of this source tree.
562 */const n0=ae("WifiOff",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}
vendor: 6,304 bytes, lines 562-567
562],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/**
563 * @license lucide-react v0.462.0 - ISC
564 *
565 * This source code is licensed under the ISC license.
566 * See the LICENSE file in the root directory of this source tree.
567 */const Fs=ae("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),uu="-",hE=s=>{const e=mE(s),{conflictingClassGroups:t,conflictingClassGroupModifiers:r}=s;return{getClassGroupId:o=>{const l=o.split(uu);return l[0]===""&&l.length!==1&&l.shift(),i0(l,e)||fE(o)},getConflictingClassGroupIds:(o,l)=>{const d=t[o]||[];return l&&r[o]?[...d,...r[o]]:d}}},i0=(s,e)=>{var o;if(s.length===0)return e.classGroupId;const t=s[0],r=e.nextPart.get(t),n=r?i0(s.slice(1),r):void 0;if(n)return n;if(e.validators.length===0)return;const i=s.join(uu);return(o=e.validators.find(({validator:l})=>l(i)))==null?void 0:o.classGroupId},Qh=/^\[(.+)\]$/,fE=s=>{if(Qh.test(s)){const e=Qh.exec(s)[1],t=e==null?void 0:e.substring(0,e.indexOf(":"));if(t)return"arbitrary.."+t}},mE=s=>{const{theme:e,prefix:t}=s,r={nextPart:new Map,validators:[]};return gE(Object.entries(s.classGroups),t).forEach(([i,o])=>{td(o,r,i,e)}),r},td=(s,e,t,r)=>{s.forEach(n=>{if(typeof n=="string"){const i=n===""?e:Jh(e,n);i.classGroupId=t;return}if(typeof n=="function"){if(pE(n)){td(n(r),e,t,r);return}e.validators.push({validator:n,classGroupId:t});return}Object.entries(n).forEach(([i,o])=>{td(o,Jh(e,i),t,r)})})},Jh=(s,e)=>{let t=s;return e.split(uu).forEach(r=>{t.nextPart.has(r)||t.nextPart.set(r,{nextPart:new Map,validators:[]}),t=t.nextPart.get(r)}),t},pE=s=>s.isThemeGetter,gE=(s,e)=>e?s.map(([t,r])=>{const n=r.map(i=>typeof i=="string"?e+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([o,l])=>[e+o,l])):i);return[t,n]}):s,xE=s=>{if(s<1)return{get:()=>{},set:()=>{}};let e=0,t=new Map,r=new Map;const n=(i,o)=>{t.set(i,o),e++,e>s&&(e=0,r=t,t=new Map)};return{get(i){let o=t.get(i);if(o!==void 0)return o;if((o=r.get(i))!==void 0)return n(i,o),o},set(i,o){t.has(i)?t.set(i,o):n(i,o)}}},a0="!",yE=s=>{const{separator:e,experimentalParseClassName:t}=s,r=e.length===1,n=e[0],i=e.length,o=l=>{const d=[];let c=0,u=0,h;for(let y=0;y<l.length;y++){let v=l[y];if(c===0){if(v===n&&(r||l.slice(y,y+i)===e)){d.push(l.slice(u,y)),u=y+i;continue}if(v==="/"){h=y;continue}}v==="["?c++:v==="]"&&c--}const f=d.length===0?l:l.substring(u),m=f.startsWith(a0),p=m?f.substring(1):f,x=h&&h>u?h-u:void 0;return{modifiers:d,hasImportantModifier:m,baseClassName:p,maybePostfixModifierPosition:x}};return t?l=>t({className:l,parseClassName:o}):o},vE=s=>{if(s.length<=1)return s;const e=[];let t=[];return s.forEach(r=>{r[0]==="["?(e.push(...t.sort(),r),t=[]):t.push(r)}),e.push(...t.sort()),e},bE=s=>({cache:xE(s.cacheSize),parseClassName:yE(s),...hE(s)}),_E=/\s+/,wE=(s,e)=>{const{parseClassName:t,getClassGroupId:r,getConflictingClassGroupIds:n}=e,i=[],o=s.trim().split(_E);let l="";for(let d=o.length-1;d>=0;d-=1){const c=o[d],{modifiers:u,hasImportantModifier:h,baseClassName:f,maybePostfixModifierPosition:m}=t(c);let p=!!m,x=r(p?f.substring(0,m):f);if(!x){if(!p){l=c+(l.length>0?" "+l:l);continue}if(x=r(f),!x){l=c+(l.length>0?" "+l:l);continue}p=!1}const y=vE(u).join(":"),v=h?y+a0:y,_=v+x;if(i.includes(_))continue;i.push(_);const b=n(x,p);for(let w=0;w<b.length;++w){const T=b[w];i.push(v+T)}l=c+(l.length>0?" "+l:l)}return l};function EE(){let s=0,e,t,r="";for(;s<arguments.length;)(e=arguments[s++])&&(t=o0(e))&&(r&&(r+=" "),r+=t);return r}const o0=s=>{if(typeof s=="string")return s;let e,t="";for(let r=0;r<s.length;r++)s[r]&&(e=o0(s[r]))&&(t&&(t+=" "),t+=e);return t};function SE(s,...e){let t,r,n,i=o;function o(d){const c=e.reduce((u,h)=>h(u),s());return t=bE(c),r=t.cache.get,n=t.cache.set,i=l,l(d)}function l(d){const c=r(d);if(c)return c;const u=wE(d,t);return n(d,u),u}return function(){return i(EE.apply(null,arguments))}}const Nt=s=>{const e=t=>t[s]||[];return e.isThemeGetter=!0,e},l0=/^\[(?:([a-z-]+):)?(.+)\]$/i,TE=/^\d+\/\d+$/,AE=new Set(["px","full","screen"]),kE=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,RE=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,jE=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,IE=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,CE=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Sr=s=>ci(s)||AE.has(s)||TE.test(s),$r=s=>$i(s,"length",$E),ci=s=>!!s&&!Number.isNaN(Number(s)),Yl=s=>$i(s,"number",ci),Gi=s=>!!s&&Number.isInteger(Number(s)),NE=s=>s.endsWith("%")&&ci(s.slice(0,-1)),Ye=s=>l0.test(s),Ur=s=>kE.test(s),LE=new Set(["length","size","percentage"]),PE=s=>$i(s,LE,c0),DE=s=>$i(s,"position",c0),OE=new Set(["image","url"]),ME=s=>$i(s,OE,BE),FE=s=>$i(s,"",UE),zi=()=>!0,$i=(s,e,t)=>{const r=l0.exec(s);return r?r[1]?typeof e=="string"?r[1]===e:e.has(r[1]):t(r[2]):!1},$E=s=>RE.test(s)&&!jE.test(s),c0=()=>!1,UE=s=>IE.test(s),BE=s=>CE.test(s),VE=()=>{const s=Nt("colors"),e=Nt("spacing"),t=Nt("blur"),r=Nt("brightness"),n=Nt("borderColor"),i=Nt("borderRadius"),o=Nt("borderSpacing"),l=Nt("borderWidth"),d=Nt("contrast"),c=Nt("grayscale"),u=Nt("hueRotate"),h=Nt("invert"),f=Nt("gap"),m=Nt("gradientColorStops"),p=Nt("gradientColorStopPositions"),x=Nt("inset"),y=Nt("margin"),v=Nt("opacity"),_=Nt("padding"),b=Nt("saturate"),w=Nt("scale"),T=Nt("sepia"),A=Nt("skew"),S=Nt("space"),I=Nt("translate"),j=()=>["auto","contain","none"],R=()=>["auto","hidden","clip","visible","scroll"],k=()=>["auto",Ye,e],D=()=>[Ye,e],Y=()=>["",Sr,$r],q=()=>["auto",ci,Ye],X=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],F=()=>["solid","dashed","dotted","double","none"],P=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],N=()=>["start","end","center","between","around","evenly","stretch"],O=()=>["","0",Ye],$=()=>["auto","avoid","all","avoid-page","page","left","right","column"],B=()=>[ci,Ye];return{cacheSize:500,separator:":",theme:{colors:[zi],spacing:[Sr,$r],blur:["none","",Ur,Ye],brightness:B(),borderColor:[s],borderRadius:["n
567one","","full",Ur,Ye],borderSpacing:D(),borderWidth:Y(),contrast:B(),grayscale:O(),hueRotate:B(),invert:O(),gap:D(),gradientColorStops:[s],gradientColorStopPositions:[NE,$r],inset:k(),margin:k(),opacity:B(),padding:D(),saturate:B(),scale:B(),sepia:O(),skew:B(),space:D(),translate:D()},classGroups:{aspect:[{aspect:["auto","square","video",Ye]}],container:["container"],columns:[{columns:[Ur]}],"break-after":[{"break-after":$()}],"break-before":[{"break-before":$()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...X(),Ye]}],overflow:[{overflow:R()}],"overflow-x":[{"overflow-x":R()}],"overflow-y":[{"overflow-y":R()}],overscroll:[{overscroll:j()}],"overscroll-x":[{"overscroll-x":j()}],"overscroll-y":[{"overscroll-y":j()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[x]}],"inset-x":[{"inset-x":[x]}],"inset-y":[{"inset-y":[x]}],start:[{start:[x]}],end:[{end:[x]}],top:[{top:[x]}],right:[{right:[x]}],bottom:[{bottom:[x]}],left:[{left:[x]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Gi,Ye]}],basis:[{basis:k()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Ye]}],grow:[{grow:O()}],shrink:[{shrink:O()}],order:[{order:["first","last","none",Gi,Ye]}],"grid-cols":[{"grid-cols":[zi]}],"col-start-end":[{col:["auto",{span:["full",Gi,Ye]},Ye]}],"col-start":[{"col-start":q()}],"col-end":[{"col-end":q()}],"grid-rows":[{"grid-rows":[zi]}],"row-start-end":[{row:["auto",{span:[Gi,Ye]},Ye]}],"row-start":[{"row-start":q()}],"row-end":[{"row-end":q()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Ye]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Ye]}],gap:[{gap:[f]}],"gap-x":[{"gap-x":[f]}],"gap-y":[{"gap-y":[f]}],"justify-content":[{justify:["normal",...N()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...N(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...N(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[_]}],px:[{px:[_]}],py:[{py:[_]}],ps:[{ps:[_]}],pe:[{pe:[_]}],pt:[{pt:[_]}],pr:[{pr:[_]}],pb:[{pb:[_]}],pl:[{pl:[_]}],m:[{m:[y]}],mx:[{mx:[y]}],my:[{my:[y]}],ms:[{ms:[y]}],me:[{me:[y]}],mt:[{mt:[y]}],mr:[{mr:[y]}],mb:[{mb:[y]}],ml:[{ml:[y]}],"space-x":[{"space-x":[S]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[S]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Ye,e]}],"min-w":[{"min-w":[Ye,e,"min","max","fit"]}],"max-w":[{"max-w":[Ye,e,"none","full","min","max","fit","prose",{screen:[Ur]},Ur]}],h:[{h:[Ye,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Ye,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Ye,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Ye,e,"auto","min","max","fit"]}],"font-size":[{text:["base",Ur,$r]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Yl]}],"font-family":[{font:[zi]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Ye]}],"line-clamp":[{"line-clamp":["none",ci,Yl]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Sr,Ye]}],"list-image":[{"list-image":["none",Ye]}],"list-style-type":[{list:["none","disc","decimal",Ye]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[s]}],"placeholder-opacity":[{"placeholder-opacity":[v]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[s]}],"text-opacity":[{"text-opacity":[v]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...F(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Sr,$r]}],"underline-offset":[{"underline-offset":["auto",Sr,Ye]}],"text-decoration-color":[{decoration:[s]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:D()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Ye]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Ye]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[v]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...X(),DE]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",PE]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},ME]}],"bg-color":[{bg:[s]}],"gradient-from-pos":[{from:[p]}
vendor: 5,180 bytes, line 567
567],"gradient-via-pos":[{via:[p]}],"gradient-to-pos":[{to:[p]}],"gradient-from":[{from:[m]}],"gradient-via":[{via:[m]}],"gradient-to":[{to:[m]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[v]}],"border-style":[{border:[...F(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[v]}],"divide-style":[{divide:F()}],"border-color":[{border:[n]}],"border-color-x":[{"border-x":[n]}],"border-color-y":[{"border-y":[n]}],"border-color-s":[{"border-s":[n]}],"border-color-e":[{"border-e":[n]}],"border-color-t":[{"border-t":[n]}],"border-color-r":[{"border-r":[n]}],"border-color-b":[{"border-b":[n]}],"border-color-l":[{"border-l":[n]}],"divide-color":[{divide:[n]}],"outline-style":[{outline:["",...F()]}],"outline-offset":[{"outline-offset":[Sr,Ye]}],"outline-w":[{outline:[Sr,$r]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:Y()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[v]}],"ring-offset-w":[{"ring-offset":[Sr,$r]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",Ur,FE]}],"shadow-color":[{shadow:[zi]}],opacity:[{opacity:[v]}],"mix-blend":[{"mix-blend":[...P(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":P()}],filter:[{filter:["","none"]}],blur:[{blur:[t]}],brightness:[{brightness:[r]}],contrast:[{contrast:[d]}],"drop-shadow":[{"drop-shadow":["","none",Ur,Ye]}],grayscale:[{grayscale:[c]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[h]}],saturate:[{saturate:[b]}],sepia:[{sepia:[T]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[t]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[d]}],"backdrop-grayscale":[{"backdrop-grayscale":[c]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[u]}],"backdrop-invert":[{"backdrop-invert":[h]}],"backdrop-opacity":[{"backdrop-opacity":[v]}],"backdrop-saturate":[{"backdrop-saturate":[b]}],"backdrop-sepia":[{"backdrop-sepia":[T]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[o]}],"border-spacing-x":[{"border-spacing-x":[o]}],"border-spacing-y":[{"border-spacing-y":[o]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Ye]}],duration:[{duration:B()}],ease:[{ease:["linear","in","out","in-out",Ye]}],delay:[{delay:B()}],animate:[{animate:["none","spin","ping","pulse","bounce",Ye]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[w]}],"scale-x":[{"scale-x":[w]}],"scale-y":[{"scale-y":[w]}],rotate:[{rotate:[Gi,Ye]}],"translate-x":[{"translate-x":[I]}],"translate-y":[{"translate-y":[I]}],"skew-x":[{"skew-x":[A]}],"skew-y":[{"skew-y":[A]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Ye]}],accent:[{accent:["auto",s]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Ye]}],"caret-color":[{caret:[s]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":D()}],"scroll-mx":[{"scroll-mx":D()}],"scroll-my":[{"scroll-my":D()}],"scroll-ms":[{"scroll-ms":D()}],"scroll-me":[{"scroll-me":D()}],"scroll-mt":[{"scroll-mt":D()}],"scroll-mr":[{"scroll-mr":D()}],"scroll-mb":[{"scroll-mb":D()}],"scroll-ml":[{"scroll-ml":D()}],"scroll-p":[{"scroll-p":D()}],"scroll-px":[{"scroll-px":D()}],"scroll-py":[{"scroll-py":D()}],"scroll-ps":[{"scroll-ps":D()}],"scroll-pe":[{"scroll-pe":D()}],"scroll-pt":[{"scroll-pt":D()}],"scroll-pr":[{"scroll-pr":D()}],"scroll-pb":[{"scroll-pb":D()}],"scroll-pl":[{"scroll-pl":D()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}
567],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Ye]}],fill:[{fill:[s,"none"]}],"stroke-w":[{stroke:[Sr,$r,Yl]}],stroke:[{stroke:[s,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},GE=SE(VE);function C(...s){return GE(Rg(s))}function B4(s){if(!s)return"";const e=s.trim();return e?e.startsWith("http://")||e.startsWith("https://")?e:`https://${e}`:""}function sn(s){return!s||!s.trim()?"?":s.trim().split(" ").filter(Boolean).map(e=>e[0]).join("").toUpperCase().slice(0,2)}function _i(s){if(s==="male")return"/default-avatar-male.svg";if(s==="female")return"/default-avatar-female.svg"}const zE=Aw,d0=g.forwardRef(({className:s,...e},t)=>a.jsx(zg,{ref:t,className:C("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",s),...e}));d0.displayName=zg.displayName;const qE=Pn("group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),u0=g.forwardRef(({className:s,variant:e,...t},r)=>a.jsx(qg,{ref:r,className:C(qE({variant:e}),s),...t}));u0.displayName=qg.displayName;const HE=g.forwardRef(({className:s,...e},t)=>a.jsx(Wg,{ref:t,className:C("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors group-[.destructive]:border-muted/40 hover:bg-secondary group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 group-[.destructive]:focus:ring-destructive disabled:pointer-events-none disabled:opacity-50",s),...e}));
567HE.displayName=Wg.displayName;const h0=g.forwardRef(({className:s,...e},t)=>a.jsx(Yg,{ref:t,className:C("absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity group-hover:opacity-100 group-[.destructive]:text-red-300 hover:text-foreground group-[.destructive]:hover:text-red-50 focus:opacity-100 focus:outline-none focus:ring-2 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",s),"toast-close":"",...e,children:a.jsx(Fs,{className:"h-4 w-4"})}));h0.displayName=Yg.displayName;const f0=g.forwardRef(({className:s,...e},t)=>a.jsx(Hg,{ref:t,className:C("text-sm font-semibold",s),...e}));f0.displayName=Hg.displayName;const m0=g.forwardRef(({className:s,...e},t)=>a.jsx(Kg,{ref:t,className:C("text-sm opacity-90",s),...e}));m0.displayName=Kg.displayName;function KE(){const{toasts:s}=lw();return a.jsxs(zE,{children:[s.map(function({id:e,title:t,description:r,action:n,...i}){return a.jsxs(u0,{...i,children:[a.jsxs("div",{className:"grid gap-1",children:[t&&a.jsx(f0,{children:t}),r&&a.jsx(m0,{children:r})]}),n,a.jsx(h0,{})]},e)}),a.jsx(d0,{})]})}var Bo=["light","dark"],hu="(prefers-color-scheme: dark)",WE=typeof window>"u",fu=g.createContext(void 0),YE={setTheme:s=>{},themes:[]},p0=()=>{var s;return(s=g.useContext(fu))!=null?s:YE},XE=s=>g.useContext(fu)?s.children:g.createElement(JE,{...s}),QE=["light","dark"],JE=({forcedTheme:s,disableTransitionOnChange:e=!1,enableSystem:t=!0,enableColorScheme:r=!0,storageKey:n="theme",themes:i=QE,defaultTheme:o=t?"system":"light",attribute:l="data-theme",value:d,children:c,nonce:u})=>{let[h,f]=g.useState(()=>Zh(n,o)),[m,p]=g.useState(()=>Zh(n)),x=d?Object.values(d):i,y=g.useCallback(w=>{let T=w;if(!T)return;w==="system"&&t&&(T=ef());let A=d?d[T]:T,S=e?eS():null,I=document.documentElement;if(l==="class"?(I.classList.remove(...x),A&&I.classList.add(A)):A?I.setAttribute(l,A):I.removeAttribute(l),r){let j=Bo.includes(o)?o:null,R=Bo.includes(T)?T:j;I.style.colorScheme=R}S==null||S()},[]),v=g.useCallback(w=>{let T=typeof w=="function"?w(w):w;f(T);try{localStorage.setItem(n,T)}catch{}},[s]),_=g.useCallback(w=>{let T=ef(w);p(T),h==="system"&&t&&!s&&y("system")},[h,s]);g.useEffect(()=>{let w=window.matchMedia(hu);return w.addListener(_),_(w),()=>w.removeListener(_)},[_]),g.useEffect(()=>{let w=T=>{if(T.key!==n)return;let A=T.newValue||o;v(A)};return window.addEventListener("storage",w),()=>window.removeEventListener("storage",w)},[v]),g.useEffect(()=>{y(s??h)},[s,h]);let b=g.useMemo(()=>({theme:h,setTheme:v,forcedTheme:s,resolvedTheme:h==="system"?m:h,themes:t?[...i,"system"]:i,systemTheme:t?m:void 0}),[h,v,s,m,t,i]);return g.createElement(fu.Provider,{value:b},g.createElement(ZE,{forcedTheme:s,disableTransitionOnChange:e,enableSystem:t,enableColorScheme:r,storageKey:n,themes:i,defaultTheme:o,attribute:l,value:d,children:c,attrs:x,nonce:u}),c)},ZE=g.memo(({forcedTheme:s,storageKey:e,attribute:t,enableSystem:r,enableColorScheme:n,defaultTheme:i,value:o,attrs:l,nonce:d})=>{let c=i==="system",u=t==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${l.map(p=>`'${p}'`).join(",")})`};`:`var d=document.documentElement,n='${t}',s='setAttribute';`,h=n?Bo.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",f=(p,x=!1,y=!0)=>{let v=o?o[p]:p,_=x?p+"|| ''":`'${v}'`,b="";return n&&y&&!x&&Bo.includes(p)&&(b+=`d.style.colorScheme = '${p}';`),t==="class"?x||v?b+=`c.add(${_})`:b+="null":v&&(b+=`d[s](n,${_})`),b},m=s?`!function(){${u}${f(s)}}()`:r?`!function(){try{${u}var e=localStorage.getItem('${e}');if('system'===e||(!e&&${c})){var t='${hu}',m=window.matchMedia(t);if(m.media!==t||m.matches){${f("dark")}}else{${f("light")}}}else if(e){${o?`var x=${JSON.stringify(o)};`:""}${f(o?"x[e]":"e",!0)}}${c?"":"else{"+f(i,!1,!1)+"}"}${h}}catch(e){}}()`:`!function(){try{${u}var e=localStorage.getItem('${e}');if(e){${o?`var x=${JSON.stringify(o)};`:""}${f(o?"x[e]":"e",!0)}}else{${f(i,!1,!1)};}${h}}catch(t){}}();`;return g.createElement("script",{nonce:d,dangerouslySetInnerHTML:{__html:m}})}),Zh=(s,e)=>{if(WE)return;let t;try{t=localStorage.getItem(s)||void 0}catch{}return t||e},eS=()=>{let s=document.createElement("style");return s.appendChild(document.createTextNode("*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}")),document.head.appendChild(s),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(s)},1)}},ef=s=>
567(s||(s=window.matchMedia(hu)),s.matches?"dark":"light"),tS=s=>{switch(s){case"success":return nS;case"info":return aS;case"warning":return iS;case"error":return oS;default:return null}},sS=Array(12).fill(0),rS=({visible:s,className:e})=>J.createElement("div",{className:["sonner-loading-wrapper",e].filter(Boolean).join(" "),"data-visible":s},J.createElement("div",{className:"sonner-spinner"},sS.map((t,r)=>J.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),nS=J.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},J.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),iS=J.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},J.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),aS=J.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},J.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),oS=J.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},J.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),lS=J.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},J.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),J.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),cS=()=>{let[s,e]=J.useState(document.hidden);return J.useEffect(()=>{let t=()=>{e(document.hidden)};return document.addEventListener("visibilitychange",t),()=>window.removeEventListener("visibilitychange",t)},[]),s},sd=1,dS=class{constructor(){this.subscribe=s=>(this.subscribers.push(s),()=>{let e=this.subscribers.indexOf(s);this.subscribers.splice(e,1)}),this.publish=s=>{this.subscribers.forEach(e=>e(s))},this.addToast=s=>{this.publish(s),this.toasts=[...this.toasts,s]},this.create=s=>{var e;let{message:t,...r}=s,n=typeof(s==null?void 0:s.id)=="number"||((e=s.id)==null?void 0:e.length)>0?s.id:sd++,i=this.toasts.find(l=>l.id===n),o=s.dismissible===void 0?!0:s.dismissible;return this.dismissedToasts.has(n)&&this.dismissedToasts.delete(n),i?this.toasts=this.toasts.map(l=>l.id===n?(this.publish({...l,...s,id:n,title:t}),{...l,...s,id:n,dismissible:o,title:t}):l):this.addToast({title:t,...r,dismissible:o,id:n}),n},this.dismiss=s=>(this.dismissedToasts.add(s),s||this.toasts.forEach(e=>{this.subscribers.forEach(t=>t({id:e.id,dismiss:!0}))}),this.subscribers.forEach(e=>e({id:s,dismiss:!0})),s),this.message=(s,e)=>this.create({...e,message:s}),this.error=(s,e)=>this.create({...e,message:s,type:"error"}),this.success=(s,e)=>this.create({...e,type:"success",message:s}),this.info=(s,e)=>this.create({...e,type:"info",message:s}),this.warning=(s,e)=>this.create({...e,type:"warning",message:s}),this.loading=(s,e)=>this.create({...e,type:"loading",message:s}),this.promise=(s,e)=>{if(!e)return;let t;e.loading!==void 0&&(t=this.create({...e,promise:s,type:"loading",message:e.loading,description:typeof e.description!="function"?e.description:void 0}));let r=s instanceof Promise?s:s(),n=t!==void 0,i,o=r.then(async d=>{if(i=["resolve",d],J.isValidElement(d))n=!1,this.create({id:t,type:"default",message:d});else if(hS(d)&&!d.ok){n=!1;let c=typeof e.error=="function"?await e.error(`HTTP error! status: ${d.status}`):e.error,u=typeof e.description=="function"?await e.description(`HTTP error! status: ${d.status}`):e.description;this.create({id:t,type:"error",message:c,description:u})}else if(e.success!==void 0){n=!1;let c=typeof e.success=="function"?await e.success(d):e.success,u=typeof e.description=="function"?await e.description(d):e.description;this.create({id:t,type:"success",message:c,description:u})}}).catch(async d=>{if(i=["reject",d],e.error!==void 0){n=!1;let c=typeof e.error=="function"?await e.error(d):e.error,u=typeof e.description=="function"?await e.description(d):e.description;this.create({id:t,type:"error",message:c,description:u})}}).finally(()=>{var d;
567n&&(this.dismiss(t),t=void 0),(d=e.finally)==null||d.call(e)}),l=()=>new Promise((d,c)=>o.then(()=>i[0]==="reject"?c(i[1]):d(i[1])).catch(c));return typeof t!="string"&&typeof t!="number"?{unwrap:l}:Object.assign(t,{unwrap:l})},this.custom=(s,e)=>{let t=(e==null?void 0:e.id)||sd++;return this.create({jsx:s(t),id:t,...e}),t},this.getActiveToasts=()=>this.toasts.filter(s=>!this.dismissedToasts.has(s.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},bs=new dS,uS=(s,e)=>{let t=(e==null?void 0:e.id)||sd++;return bs.addToast({title:s,...e,id:t}),t},hS=s=>s&&typeof s=="object"&&"ok"in s&&typeof s.ok=="boolean"&&"status"in s&&typeof s.status=="number",fS=uS,mS=()=>bs.toasts,pS=()=>bs.getActiveToasts(),Ae=Object.assign(fS,{success:bs.success,info:bs.info,warning:bs.warning,error:bs.error,custom:bs.custom,message:bs.message,promise:bs.promise,dismiss:bs.dismiss,loading:bs.loading},{getHistory:mS,getToasts:pS});function gS(s,{insertAt:e}={}){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",e==="top"&&t.firstChild?t.insertBefore(r,t.firstChild):t.appendChild(r),r.styleSheet?r.styleSheet.cssText=s:r.appendChild(document.createTextNode(s))}gS(`:where(html[dir="ltr"]),:where([data-sonner-toaster][dir="ltr"]){--toast-icon-margin-start: -3px;--toast-icon-margin-end: 4px;--toast-svg-margin-start: -1px;--toast-svg-margin-end: 0px;--toast-button-margin-start: auto;--toast-button-margin-end: 0;--toast-close-button-start: 0;--toast-close-button-end: unset;--toast-close-button-transform: translate(-35%, -35%)}:where(html[dir="rtl"]),:where([data-sonner-toaster][dir="rtl"]){--toast-icon-margin-start: 4px;--toast-icon-margin-end: -3px;--toast-svg-margin-start: 0px;--toast-svg-margin-end: -1px;--toast-button-margin-start: 0;--toast-button-margin-end: auto;--toast-close-button-start: unset;--toast-close-button-end: 0;--toast-close-button-transform: translate(35%, -35%)}:where([data-sonner-toaster]){position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1: hsl(0, 0%, 99%);--gray2: hsl(0, 0%, 97.3%);--gray3: hsl(0, 0%, 95.1%);--gray4: hsl(0, 0%, 93%);--gray5: hsl(0, 0%, 90.9%);--gray6: hsl(0, 0%, 88.7%);--gray7: hsl(0, 0%, 85.8%);--gray8: hsl(0, 0%, 78%);--gray9: hsl(0, 0%, 56.1%);--gray10: hsl(0, 0%, 52.3%);--gray11: hsl(0, 0%, 43.5%);--gray12: hsl(0, 0%, 9%);--border-radius: 8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:none;z-index:999999999;transition:transform .4s ease}:where([data-sonner-toaster][data-lifted="true"]){transform:translateY(-10px)}@media (hover: none) and (pointer: coarse){:where([data-sonner-toaster][data-lifted="true"]){transform:none}}:where([data-sonner-toaster][data-x-position="right"]){right:var(--offset-right)}:where([data-sonner-toaster][data-x-position="left"]){left:var(--offset-left)}:where([data-sonner-toaster][data-x-position="center"]){left:50%;transform:translate(-50%)}:where([data-sonner-toaster][data-y-position="top"]){top:var(--offset-top)}:where([data-sonner-toaster][data-y-position="bottom"]){bottom:var(--offset-bottom)}:where([data-sonner-toast]){--y: translateY(100%);--lift-amount: calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);filter:blur(0);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:none;overflow-wrap:anywhere}:where([data-sonner-toast][data-styled="true"]){padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px #0000001a;width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}:where([data-sonner-toast]:focus-visible){box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast][data-y-position="top"]){top:0;--y: translateY(-100%);--lift: 1;--lift-amount: calc(1 * var(--gap))}:where([data-sonner-toast][data-y-position="bottom"]){bottom:0;--y: translateY(100%);--lift: -1;--lift-amount: calc(var(--lift) * var(--gap))}:where([data-sonner-toast]) :where([data-description]){font-weight:400;line-height:1.4;color:inherit}:where([data-sonner-toast]) :where([data-title]){font-weight:500;line-height:1.5;color:inherit}:where([data-sonner-toast]) :where([data-icon]){display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}:where([data-sonner-toast][data-promise="true"]) :where([data-icon])>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}:where([data-sonner-toast]) :where([data-icon])>*{flex-shrink:0}:where([data-sonner-toast]) :where([data-icon]) svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}:where([data-sonner-toast]) :where([data-content]){display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;cursor:pointer;outline:none;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}:where([data-sonner-toast]) :where([data-button]):focus-visible{box-shadow:0 0 0 2px #0006}:where([data-sonner-toast]) :where([data-button]):first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}:where([data-sonner-toast]) :where([data-cancel]){color:var(--normal-text);background:rgba(0,0,0,.08)}:where([data-sonner-toast][data-theme="dark"]) :where([data-cancel]){background:rgba(255,255,255,.3)}:where([data-sonner-toast]) :where([data-close-button]){position:absolute;
567left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast] [data-close-button]{background:var(--gray1)}:where([data-sonner-toast]) :where([data-close-button]):focus-visible{box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast]) :where([data-disabled="true"]){cursor:not-allowed}:where([data-sonner-toast]):hover :where([data-close-button]):hover{background:var(--gray2);border-color:var(--gray5)}:where([data-sonner-toast][data-swiping="true"]):before{content:"";position:absolute;left:-50%;right:-50%;height:100%;z-index:-1}:where([data-sonner-toast][data-y-position="top"][data-swiping="true"]):before{bottom:50%;transform:scaleY(3) translateY(50%)}:where([data-sonner-toast][data-y-position="bottom"][data-swiping="true"]):before{top:50%;transform:scaleY(3) translateY(-50%)}:where([data-sonner-toast][data-swiping="false"][data-removed="true"]):before{content:"";position:absolute;inset:0;transform:scaleY(2)}:where([data-sonner-toast]):after{content:"";position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}:where([data-sonner-toast][data-mounted="true"]){--y: translateY(0);opacity:1}:where([data-sonner-toast][data-expanded="false"][data-front="false"]){--scale: var(--toasts-before) * .05 + 1;--y: translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}:where([data-sonner-toast])>*{transition:opacity .4s}:where([data-sonner-toast][data-expanded="false"][data-front="false"][data-styled="true"])>*{opacity:0}
567:where([data-sonner-toast][data-visible="false"]){opacity:0;pointer-events:none}:where([data-sonner-toast][data-mounted="true"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}:where([data-sonner-toast][data-removed="true"][data-front="true"][data-swipe-out="false"]){--y: translateY(calc(var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="false"]){--y: translateY(40%);opacity:0;transition:transform .5s,opacity .2s}:where([data-sonner-toast][data-removed="true"][data-front="false"]):before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y, 0px)) translate(var(--swipe-amount-x, 0px));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width: 600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-theme=light]{--normal-bg: #fff;--normal-border: var(--gray4);--normal-text: var(--gray12);--success-bg: hsl(143, 85%, 96%);--success-border: hsl(145, 92%, 91%);--success-text: hsl(140, 100%, 27%);--info-bg: hsl(208, 100%, 97%);--info-border: hsl(221, 91%, 91%);--info-text: hsl(210, 92%, 45%);--warning-bg: hsl(49, 100%, 97%);--warning-border: hsl(49, 91%, 91%);--warning-text: hsl(31, 92%, 45%);--error-bg: hsl(359, 100%, 97%);--error-border: hsl(359, 100%, 94%);--error-text: hsl(360, 100%, 45%)}[data-sonner-toaster][data-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg: #000;--normal-border: hsl(0, 0%, 20%);--normal-text: var(--gray1)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg: #fff;--normal-border: var(--gray3);--normal-text: var(--gray12)}[data-sonner-toaster][data-theme=dark]{--normal-bg: #000;--normal-bg-hover: hsl(0, 0%, 12%);--normal-border: hsl(0, 0%, 20%);--normal-border-hover: hsl(0, 0%, 25%);--normal-text: var(--gray1);--success-bg: hsl(150, 100%, 6%);--success-border: hsl(147, 100%, 12%);--success-text: hsl(150, 86%, 65%);--info-bg: hsl(215, 100%, 6%);--info-border: hsl(223, 100%, 12%);--info-text: hsl(216, 87%, 65%);--warning-bg: hsl(64, 100%, 6%);--warning-border: hsl(60, 100%, 12%);--warning-text: hsl(46, 87%, 65%);--error-bg: hsl(358, 76%, 10%);--error-border: hsl(357, 89%, 16%);
567--error-text: hsl(358, 100%, 81%)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success],[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info],[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning],[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error],[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size: 16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:nth-child(1){animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}to{opacity:.15}}@media (prefers-reduced-motion){[data-sonner-toast],[data-sonner-toast]>*,.sonner-loading-bar{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}
568`);function Ka(s){return s.label!==void 0}var xS=3,yS="32px",vS="16px",tf=4e3,bS=356,_S=14,wS=20,ES=200;function Ys(...s){return s.filter(Boolean).join(" ")}function SS(s){let[e,t]=s.split("-"),r=[];return e&&r.push(e),t&&r.push(t),r}var TS=s=>{var e,t,r,n,i,o,l,d,c,u,h;let{invert:f,toast:m,unstyled:p,interacting:x,setHeights:y,visibleToasts:v,heights:_,index:b,toasts:w,expanded:T,removeToast:A,defaultRichColors:S,closeButton:I,style:j,cancelButtonStyle:R,actionButtonStyle:k,className:D="",descriptionClassName:Y="",duration:q,position:X,gap:F,loadingIcon:P,expandByDefault:N,classNames:O,icons:$,closeButtonAriaLabel:B="Close toast",pauseWhenPageIsHidden:U}=s,[K,ee]=J.useState(null),[ce,Q]=J.useState(null),[re,ve]=J.useState(!1),[Ce,Pe]=J.useState(!1),[Me,le]=J.useState(!1),[oe,He]=J.useState(!1),[ct,se]=J.useState(!1),[Be,Ke]=J.useState(0),[Ee,fe]=J.useState(0),et=J.useRef(m.duration||q||tf),rt=J.useRef(null),We=J.useRef(null),dt=b===0,pe=b+1<=v,ge=m.type,be=m.dismissible!==!1,ie=m.className||"",Qe=m.descriptionClassName||"",Ve=J.useMemo(()=>_.findIndex(Ie=>Ie.toastId===m.id)||0,[_,m.id]),It=J.useMemo(()=>{var Ie;return(Ie=m.closeButton)!=null?Ie:I},[m.closeButton,I]),At=J.useMemo(()=>m.duration||q||tf,[m.duration,q]),Yt=J.useRef(0),W=J.useRef(0),Se=J.useRef(0),it=J.useRef(null),[Ct,Ne]=X.split("-"),Ge=J.useMemo(()=>_.reduce((Ie,$e,lt)=>lt>=Ve?Ie:Ie+$e.height,0),[_,Ve]),ht=cS(),at=m.invert||f,Xe=ge==="loading";W.current=J.useMemo(()=>Ve*F+Ge,[Ve,Ge]),J.useEffect(()=>{et.current=At},[At]),J.useEffect(()=>{ve(!0)},[]),J.useEffect(()=>{let Ie=We.current;if(Ie){let $e=Ie.getBoundingClientRect().height;return fe($e),y(lt=>[{toastId:m.id,height:$e,position:m.position},...lt]),()=>y(lt=>lt.filter(Ut=>Ut.toastId!==m.id))}},[y,m.id]),J.useLayoutEffect(()=>{if(!re)return;let Ie=We.current,$e=Ie.style.height;Ie.style.height="auto";let lt=Ie.getBoundingClientRect().height;Ie.style.height=$e,fe(lt),y(Ut=>Ut.find(Lt=>Lt.toastId===m.id)?Ut.map(Lt=>Lt.toastId===m.id?{...Lt,height:lt}:Lt):[{toastId:m.id,height:lt,position:m.position},...Ut])},[re,m.title,m.description,y,m.id]);let Pt=J.useCallback(()=>{Pe(!0),Ke(W.current),y(Ie=>Ie.filter($e=>$e.toastId!==m.id)),setTimeout(()=>{A(m)},ES)},[m,A,y,W]);J.useEffect(()=>{if(m.promise&&ge==="loading"||m.duration===1/0||m.type==="loading")return;let Ie;return T||x||U&&ht?(()=>{if(Se.current<Yt.current){let $e=new Date().getTime()-Yt.current;et.current=et.current-$e}
568Se.current=new Date().getTime()})():et.current!==1/0&&(Yt.current=new Date().getTime(),Ie=setTimeout(()=>{var $e;($e=m.onAutoClose)==null||$e.call(m,m),Pt()},et.current)),()=>clearTimeout(Ie)},[T,x,m,ge,U,ht,Pt]),J.useEffect(()=>{m.delete&&Pt()},[Pt,m.delete]);function Xt(){var Ie,$e,lt;return $!=null&&$.loading?J.createElement("div",{className:Ys(O==null?void 0:O.loader,(Ie=m==null?void 0:m.classNames)==null?void 0:Ie.loader,"sonner-loader"),"data-visible":ge==="loading"},$.loading):P?J.createElement("div",{className:Ys(O==null?void 0:O.loader,($e=m==null?void 0:m.classNames)==null?void 0:$e.loader,"sonner-loader"),"data-visible":ge==="loading"},P):J.createElement(rS,{className:Ys(O==null?void 0:O.loader,(lt=m==null?void 0:m.classNames)==null?void 0:lt.loader),visible:ge==="loading"})}return J.createElement("li",{tabIndex:0,ref:We,className:Ys(D,ie,O==null?void 0:O.toast,(e=m==null?void 0:m.classNames)==null?void 0:e.toast,O==null?void 0:O.default,O==null?void 0:O[ge],(t=m==null?void 0:m.classNames)==null?void 0:t[ge]),"data-sonner-toast":"","data-rich-colors":(r=m.richColors)!=null?r:S,"data-styled":!(m.jsx||m.unstyled||p),"data-mounted":re,"data-
568promise":!!m.promise,"data-swiped":ct,"data-removed":Ce,"data-visible":pe,"data-y-position":Ct,"data-x-position":Ne,"data-index":b,"data-front":dt,"data-swiping":Me,"data-dismissible":be,"data-type":ge,"data-invert":at,"data-swipe-out":oe,"data-swipe-direction":ce,"data-expanded":!!(T||N&&re),style:{"--index":b,"--toasts-before":b,"--z-index":w.length-b,"--offset":`${Ce?Be:W.current}px`,"--initial-height":N?"auto":`${Ee}px`,...j,...m.style},onDragEnd:()=>{le(!1),ee(null),it.current=null},onPointerDown:Ie=>{Xe||!be||(rt.current=new Date,Ke(W.current),Ie.target.setPointerCapture(Ie.pointerId),Ie.target.tagName!=="BUTTON"&&(le(!0),it.current={x:Ie.clientX,y:Ie.clientY}))},onPointerUp:()=>{var Ie,$e,lt,Ut;if(oe||!be)return;it.current=null;let Lt=Number(((Ie=We.current)==null?void 0:Ie.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),fs=Number((($e=We.current)==null?void 0:$e.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Ts=new Date().getTime()-((lt=rt.current)==null?void 0:lt.getTime()),As=K==="x"?Lt:fs,ir=Math.abs(As)/Ts;if(Math.abs(As)>=wS||ir>.11){Ke(W.current),(Ut=m.onDismiss)==null||Ut.call(m,m),Q(K==="x"?Lt>0?"right":"left":fs>0?"down":"up"),Pt(),He(!0),se(!1);return}le(!1),ee(null)},onPointerMove:Ie=>{var $e,lt,Ut,Lt;if(!it.current||!be||(($e=window.getSelection())==null?void 0:$e.toString().length)>0)return;let fs=Ie.clientY-it.current.y,Ts=Ie.clientX-it.current.x,As=(lt=s.swipeDirections)!=null?lt:SS(X);!K&&(Math.abs(Ts)>1||Math.abs(fs)>1)&&ee(Math.abs(Ts)>Math.abs(fs)?"x":"y");let ir={x:0,y:0};K==="y"?(As.includes("top")||As.includes("bottom"))&&(As.includes("top")&&fs<0||As.includes("bottom")&&fs>0)&&(ir.y=fs):K==="x"&&(As.includes("left")||As.includes("right"))&&(As.includes("left")&&Ts<0||As.includes("right")&&Ts>0)&&(ir.x=Ts),(Math.abs(ir.x)>0||Math.abs(ir.y)>0)&&se(!0),(Ut=We.current)==null||Ut.style.setProperty("--swipe-amount-x",`${ir.x}px`),(Lt=We.current)==null||Lt.style.setProperty("--swipe-amount-y",`${ir.y}px`)}},It&&!m.jsx?J.createElement("button",{"aria-label":B,"data-disabled":Xe,"data-close-button":!0,onClick:Xe||!be?()=>{}:()=>{var Ie;Pt(),(Ie=m.onDismiss)==null||Ie.call(m,m)},className:Ys(O==null?void 0:O.closeButton,(n=m==null?void 0:m.classNames)==null?void 0:n.closeButton)},(i=$==null?void 0:$.close)!=null?i:lS):null,m.jsx||g.isValidElement(m.title)?m.jsx?m.jsx:typeof m.title=="function"?m.title():m.title:J.createElement(J.Fragment,null,ge||m.icon||m.promise?J.createElement("div",{"data-icon":"",className:Ys(O==null?void 0:O.icon,(o=m==null?void 0:m.classNames)==null?void 0:o.icon)},m.promise||m.type==="loading"&&!m.icon?m.icon||Xt():null,m.type!=="loading"?m.
568icon||($==null?void 0:$[ge])||tS(ge):null):null,J.createElement("div",{"data-content":"",className:Ys(O==null?void 0:O.content,(l=m==null?void 0:m.classNames)==null?void 0:l.content)},J.createElement("div",{"data-title":"",className:Ys(O==null?void 0:O.title,(d=m==null?void 0:m.classNames)==null?void 0:d.title)},typeof m.title=="function"?m.title():m.title),m.description?J.createElement("div",{"data-description":"",className:Ys(Y,Qe,O==null?void 0:O.description,(c=m==null?void 0:m.classNames)==null?void 0:c.description)},typeof m.description=="function"?m.description():m.description):null),g.isValidElement(m.cancel)?m.cancel:m.cancel&&Ka(m.cancel)?J.createElement("button",{"data-button":!0,"data-cancel":!0,style:m.cancelButtonStyle||R,onClick:Ie=>{var $e,lt;Ka(m.cancel)&&be&&((lt=($e=m.cancel).onClick)==null||lt.call($e,Ie),Pt())},className:Ys(O==null?void 0:O.cancelButton,(u=m==null?void 0:m.classNames)==null?void 0:u.cancelButton)},m.cancel.label):null,g.isValidElement(m.action)?m.action:m.action&&Ka(m.action)?J.createElement("button",{"data-button":!0,"data-action":!0,style:m.actionButtonStyle||k,onClick:Ie=>{var $e,lt;Ka(m.action)&&((lt=($e=m.action).onClick)==null||lt.call($e,Ie),!Ie.defaultPrevented&&Pt())},className:Ys(O==null?void 0:O.actionButton,(h=m==null?void 0:m.classNames)==null?void 0:h.actionButton)},m.action.label):null))};function sf(){if(typeof window>"u"||typeof document>"u")return"ltr";let s=document.documentElement.getAttribute("dir");return s==="auto"||!s?window.getComputedStyle(document.documentElement).direction:s}function AS(s,e){let t={};return[s,e].forEach((r,n)=>{let i=n===1,o=i?"--mobile-offset":"--offset",l=i?vS:yS;function d(c){["top","right","bottom","left"].forEach(u=>{t[`${o}-${u}`]=typeof c=="number"?`${c}px`:c})}typeof r=="number"||typeof r=="string"?d(r):typeof r=="object"?["top","right","bottom","left"].forEach(c=>{r[c]===void 0?t[`${o}-${c}`]=l:t[`${o}-${c}`]=typeof r[c]=="number"?`${r[c]}px`:r[c]}):d(l)}),t}var kS=g.forwardRef(function(s,e){let{invert:t,position:r="bottom-right",hotkey:n=["altKey","KeyT"],expand:i,closeButton:o,className:l,offset:d,mobileOffset:c,theme:u="light",richColors:h,duration:f,style:m,visibleToasts:p=xS,toastOptions:x,dir:y=sf(),gap:v=_S,loadingIcon:_,icons:b,containerAriaLabel:w="Notifications",pauseWhenPageIsHidden:T}=s,[A,S]=J.useState([]),I=J.useMemo(()=>Array.from(new Set([r].concat(A.filter(U=>U.position).map(U=>U.position)))),[A,r]),[j,R]=J.useState([]),[k,D]=J.useState(!1),[Y,q]=J.useState(!1),[X,F]=J.useState(u!=="system"?u:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),P=J.useRef(null),N=n.join("+").replace(/Key/g,"").replace(/Digit/g,""),O=J.useRef(null),$=J.useRef(!1),B=J.useCallback(U=>{S(K=>{var ee;return(ee=K.find(ce=>ce.id===U.id))!=null&&ee.delete||bs.dismiss(U.id),K.filter(({id:ce})=>ce!==U.id)})},[]);return J.useEffect(()=>bs.subscribe(U=>{if(U.dismiss){S(K=>K.map(ee=>ee.id===U.id?{...ee,delete:!0}:ee));return}setTimeout(()=>{g_.flushSync(()=>{S(K=>{let ee=K.findIndex(ce=>ce.id===U.id);return ee!==-1?[...K.slice(0,ee),{...K[ee],...U},...K.slice(ee+1)]:[U,...K]})})})}),[]),J.useEffect(()=>{if(u!=="system"){F(u);return}if(u==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?F("dark"):F("light")),typeof window>"u")return;let U=window.matchMedia("(prefers-color-scheme: dark)");try{U.addEventListener("change",({matches:K})=>{F(K?"dark":"light")})}catch{U.addListener(({matches:ee})=>{try{F(ee?"dark":"light")}catch(ce){console.error(ce)}})}},[u]),J.useEffect(()=>{A.length<=1&&D(!1)},[A]),J.useEffect(()=>{let U=K=>{var ee,ce;n.every(Q=>K[Q]||K.code===Q)&&(D(!0),(ee=P.current)==null||ee.focus()),K.code==="Escape"&&(document.activeElement===P.current||(ce=P.current)!=null&&ce.contains(document.activeElement))&&D(!1)};return document.addEventListener("keydown",U),()=>document.removeEventListener("keydown",U)},[n]),J.useEffect(()=>{if(P.current)return()=>{O.current&&(O.current.focus({preventScroll:!0}),O.current=null,$.current=!1)}},[P.current]),J.createElement("section",{ref:e,"aria-label":`${w} ${N}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},I.map((U,K)=>{var ee;let[ce,Q]=U.split("-");return A.length?J.createElement("ol",{key:U,dir:y==="auto"?sf():y,tabIndex:-1,ref:P,className:l,"data-sonner-toaster":!0,"data-theme":X,"data-y-position":ce,"data-lifted":k&&A.length>1&&!i,"data-x-position":Q,style:{"--front-toast-height":`${((ee=j[0])==null?void 0:ee.height)||0}px`,"--width":`${bS}px`,"--gap":`${v}px`,...m,...AS(d,c)},onBlur:re=>{$.current&&!re.currentTarget.contains(re.relatedTarget)&&($.current=!1,O.current&&(O.current.focus({preventScroll:!0}),O.current=null))},onFocus:re=>{re.target instanceof HTMLElement&&re.target.dataset.dismissible==="false"||$.current||($.current=!0,O.current=re.relatedTarget)},onMouseEnter:()=>D(!0),onMouseMove:()=>D(!0),onMouseLeave:()=>{Y||D(!1)},onDragEnd:()=>D(!1),onPointerDown:re=>{re.target instanceof HTMLElement&&re.target.dataset.dismissible==="false"||q(!0)},onPointerUp:()=>q(!1)},A.filter(re=>!re.position&&K===0||re.position===U).map((re,ve)=>{var Ce,Pe;return J.createElement(TS,{key:re.id,icons:b,index:ve,toast:re,defaultRichColors:h,duration:(Ce=x==null?void 0:x.duration)!=null?Ce:f,className:x==null?void 0:x.className,descriptionClassName:x==null?void 0:x.descriptionClassName,invert:t,visibleToasts:p,closeButton:(Pe=x==null?void 0:x.closeButton)!=null?Pe:o,interacting:Y,position:U,style:x==null?void 0:x.style,unstyled:x==null?void 0:x.unstyled,classNames:x==null?void 0:x.classNames,cancelButtonStyle:x==null?void 0:x.cancelButtonStyle,actionButtonStyle:x==null?void 0:x.actionButtonStyle,removeToast:B,toasts:A.filter(Me=>Me.position==re.position),heights:j.filter(Me=>Me.position==re.position),setHeights:R,expandByDefault:i,gap:v,loadingIcon:_,expanded:k,pauseWhenPageIsHidden:T,swipeDirections:s.swipeDirections})})):null}))});const RS=({...s})=>{const{theme:e="system"}=p0();return a.jsx(kS,{theme:e,className:"toaster group",toastOptions:{classNames:{toast:"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground"}},...s})},Vo=x_,Go=y_,zo=v_,fa=g.forwardRef(({className:s,sideOffset:e=4,...t},r)=>
568a.jsx(gg,{ref:r,sideOffset:e,className:C("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...t}));fa.displayName=gg.displayName;const jS=s=>s?(...e)=>s(...e):(...e)=>fetch(...e);class mu extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class IS extends mu{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class rf extends mu{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class nf extends mu{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var rd;(function(s){s.Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2"})(rd||(rd={}));class CS{constructor(e,{headers:t={},customFetch:r,region:n=rd.Any}={}){this.url=e,this.headers=t,this.region=n,this.fetch=jS(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return b_(this,arguments,void 0,function*(t,r={}){var n;let i,o;try{const{headers:l,method:d,body:c,signal:u,timeout:h}=r;let f={},{region:m}=r;m||(m=this.region);const p=new URL(`${this.url}/${t}`);m&&m!=="any"&&(f["x-region"]=m,p.searchParams.set("forceFunctionRegion",m));let x;c&&(l&&!Object.prototype.hasOwnProperty.call(l,"Content-Type")||!l)?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",x=c):typeof c=="string"?(f["Content-Type"]="text/plain",x=c):typeof FormData<"u"&&c instanceof FormData?x=c:(f["Content-Type"]="application/json",x=JSON.stringify(c)):c&&typeof c!="string"&&!(typeof Blob<"u"&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<"u"&&c instanceof FormData)?x=JSON.stringify(c):x=c;let y=u;h&&(o=new AbortController,i=setTimeout(()=>o.abort(),h),u?(y=o.signal,u.addEventListener("abort",()=>o.abort())):y=o.signal);const v=yield this.fetch(p.toString(),{method:d||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),l),body:x,signal:y}).catch(T=>{throw new IS(T)}),_=v.headers.get("x-relay-error");if(_&&_==="true")throw new rf(v);if(!v.ok)throw new nf(v);let b=((n=v.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),w;return b==="application/json"?w=yield v.json():b==="application/octet-stream"||b==="application/pdf"?w=yield v.blob():b==="text/event-stream"?w=v:b==="multipart/form-data"?w=yield v.formData():w=yield v.text(),{data:w,error:null,response:v}}catch(l){return{data:null,error:l,response:l instanceof nf||l instanceof rf?l.context:void 0}}finally{i&&clearTimeout(i)}})}}var NS=class extends Error{constructor(s){super(s.message),this.name="PostgrestError",this.details=s.details,this.hint=s.hint,this.co
568de=s.code}},LS=class{constructor(s){var e,t;this.shouldThrowOnError=!1,this.method=s.method,this.url=s.url,this.headers=new Headers(s.headers),this.schema=s.schema,this.body=s.body,this.shouldThrowOnError=(e=s.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=s.signal,this.isMaybeSingle=(t=s.isMaybeSingle)!==null&&t!==void 0?t:!1,s.fetch?this.fetch=s.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(s,e){return this.headers=new Headers(this.headers),this.headers.set(s,e),this}then(s,e){var t=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const r=this.fetch;let n=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{let o=null,l=null,d=null,c=i.status,u=i.statusText;if(i.ok){var h,f;if(t.method!=="HEAD"){var m;const v=await i.text();v===""||(t.headers.get("Accept")==="text/csv"||t.headers.get("Accept")&&(!((m=t.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text"))?l=v:l=JSON.parse(v))}const x=(h=t.headers.get("Prefer"))===null||h===void 0?void 0:h.match(/count=(exact|planned|estimated)/),y=(f=i.headers.get("content-range"))===null||f===void 0?void 0:f.split("/");x&&y&&y.length>1&&(d=parseInt(y[1])),t.isMaybeSingle&&t.method==="GET"&&Array.isArray(l)&&(l.length>1?(o={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,d=null,c=406,u="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{var p;const x=await i.text();try{o=JSON.parse(x),Array.isArray(o)&&i.status===404&&(l=[],o=null,c=200,u="OK")}catch{i.status===404&&x===""?(c=204,u="No Content"):o={message:x}}if(o&&t.isMaybeSingle&&(!(o==null||(p=o.details)===null||p===void 0)&&p.includes("0 rows"))&&(o=null,c=200,u="OK"),o&&t.shouldThrowOnError)throw new NS(o)}return{error:o,data:l,count:d,status:c,statusText:u}});return this.shouldThrowOnError||(n=n.catch(i=>{var o;let l="";const d=i==null?void 0:i.cause;if(d){var c,u,h,f;const p=(c=d==null?void 0:d.message)!==null&&c!==void 0?c:"",x=(u=d==null?void 0:d.code)!==null&&u!==void 0?u:"";l=`${(h=i==null?void 0:i.name)!==null&&h!==void 0?h:"FetchError"}: ${i==null?void 0:i.message}`,l+=`
569
570Caused by: ${(f=d==null?void 0:d.name)!==null&&f!==void 0?f:"Error"}: ${p}`,x&&(l+=` (${x})`),d!=null&&d.stack&&(l+=`
571${d.stack}`)}else{var m;l=(m=i==null?void 0:i.stack)!==null&&m!==void 0?m:""}return{error:{message:`${(o=i==null?void 0:i.name)!==null&&o!==void 0?o:"FetchError"}: ${i==null?void 0:i.message}`,details:l,hint:"",code:""},data:null,count:null,status:0,statusText:""}})),n.then(s,e)}returns(){return this}overrideTypes(){return this}},PS=class extends LS{select(s){let e=!1;const t=(s??"*").split("").map(r=>/\s/.test(r)&&!e?"":(r==='"'&&(e=!e),r)).join("");return this.url.searchParams.set("select",t),this.headers.append("Prefer","return=representation"),this}order(s,{ascending:e=!0,nullsFirst:t,foreignTable:r,referencedTable:n=r}={}){const i=n?`${n}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${s}.${e?"asc":"desc"}${t===void 0?"":t?".nullsfirst":".nullslast"}`),this}limit(s,{foreignTable:e,referencedTable:t=e}={}){const r=typeof t>"u"?"limit":`${t}.limit`;return this.url.searchParams.set(r,`${s}`),this}range(s,e,{foreignTable:t,referencedTable:r=t}={}){const n=typeof r>"u"?"offset":`${r}.offset`,i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${s}`),this.url.searchParams.set(i,`${e-s+1}`),this}abortSignal(s){return this.signal=s,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}
571explain({analyze:s=!1,verbose:e=!1,settings:t=!1,buffers:r=!1,wal:n=!1,format:i="text"}={}){var o;const l=[s?"analyze":null,e?"verbose":null,t?"settings":null,r?"buffers":null,n?"wal":null].filter(Boolean).join("|"),d=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${d}"; options=${l};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(s){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${s}`),this}};const af=new RegExp("[,()]");var Qn=class extends PS{eq(s,e){return this.url.searchParams.append(s,`eq.${e}`),this}neq(s,e){return this.url.searchParams.append(s,`neq.${e}`),this}gt(s,e){return this.url.searchParams.append(s,`gt.${e}`),this}gte(s,e){return this.url.searchParams.append(s,`gte.${e}`),this}lt(s,e){return this.url.searchParams.append(s,`lt.${e}`),this}lte(s,e){return this.url.searchParams.append(s,`lte.${e}`),this}like(s,e){return this.url.searchParams.append(s,`like.${e}`),this}likeAllOf(s,e){return this.url.searchParams.append(s,`like(all).{${e.join(",")}}`),this}likeAnyOf(s,e){return this.url.searchParams.append(s,`like(any).{${e.join(",")}}`),this}ilike(s,e){return this.url.searchParams.append(s,`ilike.${e}`),this}ilikeAllOf(s,e){return this.url.searchParams.append(s,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(s,e){return this.url.searchParams.append(s,`ilike(any).{${e.join(",")}}`),this}regexMatch(s,e){return this.url.searchParams.append(s,`match.${e}`),this}regexIMatch(s,e){return this.url.searchParams.append(s,`imatch.${e}`),this}is(s,e){return this.url.searchParams.append(s,`is.${e}`),this}isDistinct(s,e){return this.url.searchParams.append(s,`isdistinct.${e}`),this}in(s,e){const t=Array.from(new Set(e)).map(r=>typeof r=="string"&&af.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(s,`in.(${t})`),this}notIn(s,e){const t=Array.from(new Set(e)).map(r=>typeof r=="string"&&af.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(s,`not.in.(${t})`),this}contains(s,e){return typeof e=="string"?this.url.searchParams.append(s,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(s,`cs.{${e.join(",")}}`):this.url.searchParams.append(s,`cs.${JSON.stringify(e)}`),this}containedBy(s,e){return typeof e=="string"?this.url.searchParams.append(s,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(s,`cd.{${e.join(",")}}`):this.url.searchParams.append(s,`cd.${JSON.stringify(e)}`),this}rangeGt(s,e){return this.url.searchParams.append(s,`sr.${e}`),this}rangeGte(s,e){return this.url.searchParams.append(s,`nxl.${e}`),this}rangeLt(s,e){return this.url.searchParams.append(s,`sl.${e}`),this}rangeLte(s,e){return this.url.searchParams.append(s,`nxr.${e}`),this}rangeAdjacent(s,e){return this.url.searchParams.append(s,`adj.${e}`),this}overlaps(s,e){return typeof e=="string"?this.url.searchParams.append(s,`ov.${e}`):this.url.searchParams.append(s,`ov.{${e.join(",")}}`),this}textSearch(s,e,{config:t,type:r}={}){let n="";r==="plain"?n="pl":r==="phrase"?n="ph":r==="websearch"&&(n="w");const i=t===void 0?"":`(${t})`;return this.url.searchParams.append(s,`${n}fts${i}.${e}`),this}match(s){return Object.entries(s).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(s,e,t){return this.url.searchParams.append(s,`not.${e}.${t}`),this}or(s,{foreignTable:e,referencedTable:t=e}={}){const r=t?`${t}.or`:"or";return this.url.searchParams.append(r,`(${s})`),this}filter(s,e,t){return this.url.searchParams.append(s,`${e}.${t}`),this}},DS=class{constructor(s,{headers:e={},schema:t,fetch:r}){this.url=s,this.headers=new Headers(e),this.schema=t,this.fetch=r}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(s,e){const{head:t=!1,count:r}=e??{},n=t?"HEAD":"GET";let i=!1;const o=(s??"*").split("").map(c=>/\s/.test(c)&&!i?"":(c==='"'&&(i=!i),c)).join(""),{url:l,headers:d}=this.cloneRequestState();return l.searchParams.set("select",o),r&&d.append("Prefer",`count=${r}`),new Qn({method:n,url:l,headers:d,schema:this.schema,fetch:this.fetch})}insert(s,{count:e,defaultToNull:t=!0}={}){var r;const n="POST",{url:i,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),t||o.append("Prefer","missing=default"),Array.isArray(s)){const l=s.reduce((d,c)=>d.concat(Object.keys(c)),[]);if(l.length>0){const d=[...new Set(l)].map(c=>`"${c}"`);i.searchParams.set("columns",d.join(","))}}return new Qn({method:n,url:i,headers:o,schema:this.schema,body:s,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch})}
571upsert(s,{onConflict:e,ignoreDuplicates:t=!1,count:r,defaultToNull:n=!0}={}){var i;const o="POST",{url:l,headers:d}=this.cloneRequestState();if(d.append("Prefer",`resolution=${t?"ignore":"merge"}-duplicates`),e!==void 0&&l.searchParams.set("on_conflict",e),r&&d.append("Prefer",`count=${r}`),n||d.append("Prefer","missing=default"),Array.isArray(s)){const c=s.reduce((u,h)=>u.concat(Object.keys(h)),[]);if(c.length>0){const u=[...new Set(c)].map(h=>`"${h}"`);l.searchParams.set("columns",u.join(","))}}return new Qn({method:o,url:l,headers:d,schema:this.schema,body:s,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch})}update(s,{count:e}={}){var t;const r="PATCH",{url:n,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new Qn({method:r,url:n,headers:i,schema:this.schema,body:s,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch})}delete({count:s}={}){var e;const t="DELETE",{url:r,headers:n}=this.cloneRequestState();return s&&n.append("Prefer",`count=${s}`),new Qn({method:t,url:r,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch})}},OS=class g0{constructor(e,{headers:t={},schema:r,fetch:n}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.fetch=n}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new DS(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new g0(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:n=!1,count:i}={}){var o;let l;const d=new URL(`${this.url}/rpc/${e}`);let c;const u=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(u)),h=r&&Object.values(t).some(u);h?(l="POST",c=t):r||n?(l=r?"HEAD":"GET",Object.entries(t).filter(([m,p])=>p!==void 0).map(([m,p])=>[m,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([m,p])=>{d.searchParams.append(m,p)})):(l="POST",c=t);const f=new Headers(this.headers);return h?f.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&f.set("Prefer",`count=${i}`),new Qn({method:l,url:d,headers:f,schema:this.schemaName,body:c,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}};class MS{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const t=globalThis.process;if(t){const r=t.versions;if(r&&r.node){const n=r.node,i=parseInt(n.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
572import ws from "ws"
573new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`
574
575Suggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){const r=this.getWebSocketConstructor();return new r(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const FS="2.90.1",$S=`realtime-js/${FS}`,x0="1.0.0",US="2.0.0",of=x0,nd=1e4,BS=1e3,VS=100;var qr;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(qr||(qr={}));var Qt;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(Qt||(Qt={}));var tr;(function(s){s.close="phx_close",s.error="phx_error",s.join="phx_join",s.reply="phx_reply",s.leave="phx_leave",s.access_token="access_token"})(tr||(tr={}));var id;(function(s){s.websocket="websocket"})(id||(id={}));var _n;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(_n||(_n={}));class GS{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return t(this._binaryEncodeUserBroadcastPush(e));let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer((t=e.payload)===null||t===void 0?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r;const n=(r=(t=e.payload)===null||t===void 0?void 0:t.payload)!==null&&r!==void 0?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var t,r;const n=(r=(t=e.payload)===null||t===void 0?void 0:t.payload)!==null&&r!==void 0?r:{},o=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,t,r){var n,i;const o=e.topic,l=(n=e.ref)!==null&&n!==void 0?n:"",d=(i=e.join_ref)!==null&&i!==void 0?i:"",c=e.payload.event,u=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},h=Object.keys(u).length===0?"":JSON.stringify(u);if(d.length>255)throw new Error(`joinRef length ${d.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`ref length ${l.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(h.length>255)throw new Error(`metadata length ${h.length} exceeds maximum of 255`);const f=this.USER_BROADCAST_PUSH_META_LENGTH+d.length+l.length+o.length+c.length+h.length,m=new ArrayBuffer(this.HEADER_LENGTH+f);let p=new DataView(m),x=0;p.setUint8(x++,this.KINDS.userBroadcastPush),p.setUint8(x++,d.length),p.setUint8(x++,l.length),p.setUint8(x++,o.length),p.setUint8(x++,c.length),p.setUint8(x++,h.length),p.setUint8(x++,t),Array.from(d,v=>p.setUint8(x++,v.charCodeAt(0))),Array.from(l,v=>p.setUint8(x++,v.charCodeAt(0))),Array.from(o,v=>p.setUint8(x++,v.charCodeAt(0))),Array.from(c,v=>p.setUint8(x++,v.charCodeAt(0))),Array.from(h,v=>p.setUint8(x++,v.charCodeAt(0)));var y=new Uint8Array(m.byteLength+r.byteLength);return y.set(new Uint8Array(m),0),y.set(new Uint8Array(r),m.byteLength),y.buffer}decode(e,t){if(this._isArrayBuffer(e)){let r=this._binaryDecode(e);return t(r)}if(typeof e=="string"){const r=JSON.parse(e),[n,i,o,l,d]=r;return t({join_ref:n,ref:i,topic:o,event:l,payload:d})}return t({})}_binaryDecode(e){const t=new DataView(e),r=t.getUint8(0),n=new TextDecoder;switch(r){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,t,n)}}_decodeUserBroadcast(e,t,r){const n=t.getUint8(1),i=t.getUint8(2),o=t.getUint8(3),l=t.getUint8(4);let d=this.HEADER_LENGTH+4;const c=r.decode(e.slice(d,d+n));d=d+n;const u=r.decode(e.slice(d,d+i));d=d+i;const h=r.decode(e.slice(d,d+o));d=d+o;const f=e.slice(d,e.byteLength),m=l===this.JSON_ENCODING?JSON.parse(r.decode(f)):f,p={type:this.BROADCAST_EVENT,event:u,payload:m};return o>0&&(p.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||((t=e==null?void 0:e.constructor)===null||t===void 0?void 0:t.name)==="ArrayBuffer"}_pick(e,t){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([r])=>t.includes(r)))}}class y0{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var jt;(function(s){s.abstime="abstime",s.bool="bool",s.date="date",s.daterange="daterange",s.float4="float4",s.float8="float8",s.int2="int2",s.int4="int4",s.int4range="int4range",s.int8="int8",s.int8range="int8range",s.json="json",s.jsonb="jsonb",s.money="money",s.numeric="numeric",s.oid="oid",s.reltime="reltime",s.text="text",s.time="time",s.timestamp="timestamp",s.timestamptz="timestamptz",s.timetz="timetz",s.tsrange="tsrange",s.tstzrange="tstzrange"})(jt||(jt={}));const lf=(s,e,t={})=>{var r;const n=(r=t.skipTypes)!==null&&r!==void 0?r:[];return e?Object.keys(e).reduce((i,o)=>(i[o]=zS(o,s,e,n),i),{}):{}},zS=(s,e,t,r)=>{const n=e.find(l=>
575l.name===s),i=n==null?void 0:n.type,o=t[s];return i&&!r.includes(i)?v0(i,o):ad(o)},v0=(s,e)=>{if(s.charAt(0)==="_"){const t=s.slice(1,s.length);return WS(e,t)}switch(s){case jt.bool:return qS(e);case jt.float4:case jt.float8:case jt.int2:case jt.int4:case jt.int8:case jt.numeric:case jt.oid:return HS(e);case jt.json:case jt.jsonb:return KS(e);case jt.timestamp:return YS(e);case jt.abstime:case jt.date:case jt.daterange:case jt.int4range:case jt.int8range:case jt.money:case jt.reltime:case jt.text:case jt.time:case jt.timestamptz:case jt.timetz:case jt.tsrange:case jt.tstzrange:return ad(e);default:return ad(e)}},ad=s=>s,qS=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},HS=s=>{if(typeof s=="string"){const e=parseFloat(s);if(!Number.isNaN(e))return e}return s},KS=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch{return s}return s},WS=(s,e)=>{if(typeof s!="string")return s;const t=s.length-1,r=s[t];if(s[0]==="{"&&r==="}"){let i;const o=s.slice(1,t);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(l=>v0(e,l))}return s},YS=s=>typeof s=="string"?s.replace(" ","T"):s,b0=s=>{const e=new URL(s);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};class Xl{constructor(e,t,r={},n=nd){this.channel=e,this.event=t,this.payload=r,this.timeout=n,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var cf;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(cf||(cf={}));class ia{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(t==null?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},n=>{const{onJoin:i,onLeave:o,onSync:l}=this.caller;this.joinRef=this.channel._joinRef(),this.state=ia.syncState(this.state,n,i,o),this.pendingDiffs.forEach(d=>{this.state=ia.syncDiff(this.state,d,i,o)}),this.pendingDiffs=[],l()}),this.channel._on(r.diff,{},n=>{const{onJoin:i,onLeave:o,onSync:l}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=ia.syncDiff(this.state,n,i,o),l())}),this.onJoin((n,i,o)=>{this.channel._trigger("presence",{event:"join",key:n,currentPresences:i,newPresences:o})}),this.onLeave((n,i,o)=>{this.channel._trigger("presence",{event:"leave",key:n,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,n){const i=this.cloneDeep(e),o=this.transformState(t),l={},d={};return this.map(i,(c,u)=>{o[c]||(d[c]=u)}),this.map(o,(c,u)=>{const h=i[c];if(h){const f=u.map(y=>y.presence_ref),m=h.map(y=>y.presence_ref),p=u.filter(y=>m.indexOf(y.presence_ref)<0),x=h.filter(y=>f.indexOf(y.presence_ref)<0);p.length>0&&(l[c]=p),x.length>0&&(d[c]=x)}else l[c]=u}),this.syncDiff(i,{joins:l,leaves:d}
575,r,n)}static syncDiff(e,t,r,n){const{joins:i,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),n||(n=()=>{}),this.map(i,(l,d)=>{var c;const u=(c=e[l])!==null&&c!==void 0?c:[];if(e[l]=this.cloneDeep(d),u.length>0){const h=e[l].map(m=>m.presence_ref),f=u.filter(m=>h.indexOf(m.presence_ref)<0);e[l].unshift(...f)}r(l,u,d)}),this.map(o,(l,d)=>{let c=e[l];if(!c)return;const u=d.map(h=>h.presence_ref);c=c.filter(h=>u.indexOf(h.presence_ref)<0),e[l]=c,n(l,c,d),c.length===0&&delete e[l]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{const n=e[r];return"metas"in n?t[r]=n.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):t[r]=n,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var df;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(df||(df={}));var aa;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(aa||(aa={}));var Rr;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(Rr||(Rr={}));class ii{constructor(e,t={config:{}},r){var n,i;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=Qt.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new Xl(this,tr.join,this.params,this.timeout),this.rejoinTimer=new y0(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Qt.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(o=>o.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=Qt.closed,this.socket._remove(this)}),this._onError(o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=Qt.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Qt.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=Qt.errored,this.rejoinTimer.scheduleTimeout())}),this._on(tr.reply,{},(o,l)=>{this._trigger(this._replyEventName(l),o)}),this.presence=new ia(this),this.broadcastEndpointURL=b0(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((i=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||i===void 0)&&i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var r,n,i;if(this.socket.isConnected()||this.socket.connect(),this.state==Qt.closed){const{config:{broadcast:o,presence:l,private:d}}=this.params,c=(n=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(m=>m.filter))!==null&&n!==void 0?n:[],u=!!this.bindings[aa.PRESENCE]&&this.bindings[aa.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,h={},f={broadcast:o,presence:Object.assign(Object.assign({},l),{enabled:u}),postgres_changes:c,private:d};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(m=>e==null?void 0:e(Rr.CHANNEL_ERROR,m)),this._onClose(()=>e==null?void 0:e(Rr.CLOSED)),this.updateJoinPayload(Object.assign({config:f},h)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:m})=>{var p;if(this.socket._isManualToken()||this.socket.setAuth(),m===void 0){e==null||e(Rr.SUBSCRIBED);return}else{const x=this.bindings.postgres_changes,y=(p=x==null?void 0:x.length)!==null&&p!==void 0?p:0,v=[];for(let _=0;_<y;_++){const b=x[_],{filter:{event:w,schema:T,table:A,filter:S}}=b,I=m&&m[_];if(I&&I.event===w&&ii.isFilterValueEqual(I.schema,T)&&ii.isFilterValueEqual(I.table,A)&&ii.isFilterValueEqual(I.filter,S))v.push(Object.assign(Object.assign({},b),{id:I.id}));else{this.unsubscribe(),this.state=Qt.errored,e==null||e(Rr.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=v,e&&e(Rr.SUBSCRIBED);return}}).receive("error",m=>{this.state=Qt.errored,e==null||e(Rr.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(m).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(Rr.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this.state===Qt.joined&&e===aa.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,t,r)}async httpSend(e,t,r={}){var n;if(t==null)return Promise.reject("Payload is required for httpSend()");const i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);const o={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},l=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);if(l.status===202)return{success:!0};let d=l.statusText;
575try{const c=await l.json();d=c.error||c.message||d}catch{}return Promise.reject(new Error(d))}async send(e,t={}){var r,n;if(!this._canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:i,payload:o}=e,l={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(l.Authorization=`Bearer ${this.socket.accessTokenValue}`);const d={method:"POST",headers:l,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,private:this.private}]})};try{const c=await this._fetchWithTimeout(this.broadcastEndpointURL,d,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((n=c.body)===null||n===void 0?void 0:n.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,l,d;const c=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((d=(l=(o=this.params)===null||o===void 0?void 0:o.config)===null||l===void 0?void 0:l.broadcast)===null||d===void 0)&&d.ack)&&i("ok"),c.receive("ok",()=>i("ok")),c.receive("error",()=>i("error")),c.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=Qt.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(tr.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(n=>{r=new Xl(this,tr.leave,{},e),r.receive("ok",()=>{t(),n("ok")}).receive("timeout",()=>{t(),n("timed out")}).receive("error",()=>{n("error")}),r.send(),this._canPush()||r.trigger("ok",{})}).finally(()=>{r==null||r.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Qt.closed,this.bindings={}}async _fetchWithTimeout(e,t,r){const n=new AbortController,i=setTimeout(()=>n.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:n.signal}));return clearTimeout(i),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let n=new Xl(this,e,t,r);return this._canPush()?n.send():this._addToPushBuffer(n),n}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>VS){const t=this.pushBuffer.shift();t&&(t.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${t.event}`,t.payload))}}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var n,i;const o=e.toLocaleLowerCase(),{close:l,error:d,leave:c,join:u}=tr;if(r&&[l,d,c,u].indexOf(o)>=0&&r!==this._joinRef())return;let f=this._onMessage(o,t,r);if(t&&!f)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(n=this.bindings.postgres_changes)===null||n===void 0||n.filter(m=>{var p,x,y;return((p=m.filter)===null||p===void 0?void 0:p.event)==="*"||((y=(x=m.filter)===null||x===void 0?void 0:x.event)===null||y===void 0?void 0:y.toLocaleLowerCase())===o}).map(m=>m.callback(f,r)):(i=this.bindings[o])===null||i===void 0||i.filter(m=>{var p,x,y,v,_,b,w,T;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in m){const A=m.id,S=(p=m.filter)===null||p===void 0?void 0:p.event;return A&&((x=t.ids)===null||x===void 0?void 0:x.includes(A))&&(S==="*"||(S==null?void 0:S.toLocaleLowerCase())===((y=t.data)===null||y===void 0?void 0:y.type.toLocaleLowerCase()))&&(!(!((v=m.filter)===null||v===void 0)&&v.table)||m.filter.table===((_=t.data)===null||_===void 0?void 0:_.table))}else{const A=(w=(b=m==null?void 0:m.filter)===null||b===void 0?void 0:b.event)===null||w===void 0?void 0:w.toLocaleLowerCase();return A==="*"||A===((T=t==null?void 0:t.event)===null||T===void 0?void 0:T.toLocaleLowerCase())}else return m.type.toLocaleLowerCase()===o}).map(m=>{if(typeof f=="object"&&"ids"in f){const p=f.data,{schema:x,table:y,commit_timestamp:v,type:_,errors:b}=p;f=Object.assign(Object.assign({},{schema:x,table:y,commit_timestamp:v,eventType:_,new:{},old:{},errors:b}),this._getPayloadRecords(p))}m.callback(f,r)}
575)}_isClosed(){return this.state===Qt.closed}_isJoined(){return this.state===Qt.joined}_isJoining(){return this.state===Qt.joining}_isLeaving(){return this.state===Qt.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){const n=e.toLocaleLowerCase(),i={type:n,filter:t,callback:r};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this}_off(e,t){const r=e.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(n=>{var i;return!(((i=n.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===r&&ii.isEqual(n.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}static isFilterValueEqual(e,t){return(e??void 0)===(t??void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(tr.close,{},e)}_onError(e){this._on(tr.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Qt.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=lf(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=lf(e.columns,e.old_record)),t}}const Ql=()=>{},Wa={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},XS=[1e3,2e3,5e3,1e4],QS=1e4,JS=`
576  addEventListener("message", (e) => {
577    if (e.data.event === "start") {
578      setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
579    }
580  });`;class ZS{constructor(e,t){var r;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=nd,this.transport=null,this.heartbeatIntervalMs=Wa.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Ql,this.ref=0,this.reconnectTimer=null,this.vsn=of,this.logger=Ql,this.conn=null,this.sendBuffer=[],this.serializer=new GS,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=n=>n?(...i)=>n(...i):(...i)=>fetch(...i),!(!((r=t==null?void 0:t.params)===null||r===void 0)&&r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${id.websocket}`,this.httpEndpoint=b0(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(t==null?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=MS.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;throw t.includes("Node.js")?new Error(`${t}
581
582To use Realtime in Node.js, you need to provide a WebSocket implementation:
583
584Option 1: Use Node.js 22+ which has native WebSocket support
585Option 2: Install and provide the "ws" package:
586
587  npm install ws
588
589  import ws from "ws"
590  const client = new RealtimeClient(url, {
591    ...options,
592    transport: ws
593  })`):new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const r=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(r),this._setConnectionState("disconnected")},typeof this.conn.close=="function"&&(e?this.conn.close(e,t??""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case qr.connecting:return _n.Connecting;case qr.open:return _n.Open;case qr.closing:return _n.Closing;default:return _n.Closed}}
593isConnected(){return this.connectionState()===_n.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,t={config:{}}){const r=`realtime:${e}`,n=this.getChannels().find(i=>i.topic===r);if(n)return n;{const i=new ii(`realtime:${e}`,t,this);return this.channels.push(i),i}}push(e){const{topic:t,event:r,payload:n,ref:i}=e,o=()=>{this.encode(e,l=>{var d;(d=this.conn)===null||d===void 0||d.send(l)})};this.log("push",`${t} ${r} (${i})`,n),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(BS,"heartbeat timeout"),setTimeout(()=>{var t;this.isConnected()||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout()},Wa.HEARTBEAT_TIMEOUT_FALLBACK);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(r=>r.topic===e&&(r._isJoined()||r._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,t=>{if(t.topic==="phoenix"&&t.event==="phx_reply"&&t.ref&&t.ref===this.pendingHeartbeatRef){const c=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback(t.payload.status==="ok"?"ok":"error",c)}catch(u){this.log("error","error in heartbeat callback",u)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}const{topic:r,event:n,payload:i,ref:o}=t,l=o?`(${o})`:"",d=i.status||"";this.log("receive",`${d} ${r} ${n} ${l}`.trim(),i),this.channels.filter(c=>c._isMember(r)).forEach(c=>c._trigger(n,i,o)),this._triggerStateCallbacks("message",t)})}_clearTimer(e){var t;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((t=this.reconnectTimer)===null||t===void 0||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e),this.conn.readyState===qr.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===qr.open||this.conn.readyState===qr.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(t=>{this.log("error","error waiting for auth on connect",t),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=t=>{this.log("worker","worker error",t.message),this._terminateWorker()},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}
593_triggerChanError(){this.channels.forEach(e=>e._trigger(tr.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;const r=e.match(/\?/)?"&":"?",n=new URLSearchParams(t);return`${e}${r}${n}`}_workerObjectUrl(e){let t;if(e)t=e;else{const r=new Blob([JS],{type:"application/javascript"});t=URL.createObjectURL(r)}return t}_setConnectionState(e,t=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t,r=!1;if(e)t=e,r=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(n){this.log("error","Error fetching access token from callback",n),t=this.accessTokenValue}else t=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(n=>{const i={access_token:t,version:$S};t&&n.updateJoinPayload(i),n.joinedOnce&&n._isJoined()&&n._push(tr.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(t=>{this.log("error",`Error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(r=>{try{r(t)}catch(n){this.log("error",`error in ${e} callback`,n)}})}catch(r){this.log("error",`error triggering ${e} callbacks`,r)}}_setupReconnectionTimer(){this.reconnectTimer=new y0(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Wa.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var t,r,n,i,o,l,d,c,u,h,f,m;switch(this.transport=(t=e==null?void 0:e.transport)!==null&&t!==void 0?t:null,this.timeout=(r=e==null?void 0:e.timeout)!==null&&r!==void 0?r:nd,this.heartbeatIntervalMs=(n=e==null?void 0:e.heartbeatIntervalMs)!==null&&n!==void 0?n:Wa.HEARTBEAT_INTERVAL,this.worker=(i=e==null?void 0:e.worker)!==null&&i!==void 0?i:!1,this.accessToken=(o=e==null?void 0:e.accessToken)!==null&&o!==void 0?o:null,this.heartbeatCallback=(l=e==null?void 0:e.heartbeatCallback)!==null&&l!==void 0?l:Ql,this.vsn=(d=e==null?void 0:e.vsn)!==null&&d!==void 0?d:of,e!=null&&e.params&&(this.params=e.params),e!=null&&e.logger&&(this.logger=e.logger),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(c=e==null?void 0:e.reconnectAfterMs)!==null&&c!==void 0?c:p=>XS[p-1]||QS,this.vsn){case x0:this.encode=(u=e==null?void 0:e.encode)!==null&&u!==void 0?u:(p,x)=>x(JSON.stringify(p)),this.decode=(h=e==null?void 0:e.decode)!==null&&h!==void 0?h:(p,x)=>x(JSON.parse(p));break;case US:this.encode=(f=e==null?void 0:e.encode)!==null&&f!==void 0?f:this.serializer.encode.bind(this.serializer),this.decode=(m=e==null?void 0:e.decode)!==null&&m!==void 0?m:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl}}}var ma=class extends Error{constructor(s,e){var t;super(s),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&((t=e.icebergType)==null?void 0:t.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function eT(s,e,t){const r=new URL(e,s);if(t)for(const[n,i]of Object.entries(t))i!==void 0&&r.searchParams.set(n,i);return r.toString()}async function tT(s){return!s||s.type==="none"?{}:s.type==="bearer"?{Authorization:`Bearer ${s.token}`}:s.type==="header"?{[s.name]:s.value}:s.type==="custom"?await s.getHeaders():{}}function sT(s){const e=s.fetchImpl??globalThis.fetch;return{async request({method:t,path:r,query:n,body:i,headers:o}){const l=eT(s.baseUrl,r,n),d=await tT(s.auth),c=await e(l,{method:t,headers:{...i?{"Content-Type":"application/json"}:{},...d,...o},body:i?JSON.stringify(i):void 0}),u=await c.text(),h=(c.headers.get("content-type")||"").includes("application/json"),f=h&&u?JSON.parse(u):u;if(!c.ok){const m=h?f:void 0,p=m==null?void 0:m.error;throw new ma((p==null?void 0:p.message)??`Request failed with status ${c.status}`,{status:c.status,icebergType:p==null?void 0:p.type,icebergCode:p==null?void 0:p.code,details:m})}return{status:c.status,headers:c.headers,data:f}}}}function Ya(s){return s.join("�")}var rT=class{constructor(s,e=""){this.client=s,this.prefix=e}async listNamespaces(s){const e=s?{parent:Ya(s.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(r=>({namespace:r}))}async createNamespace(s,e){const t={namespace:s.namespace,properties:e==null?void 0:e.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:t})).data}async dropNamespace(s){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Ya(s.namespace)}`})}async loadNamespaceMetadata(s){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ya(s.namespace)}`})).data.properties}}async namespaceExists(s){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Ya(s.namespace)}`}),!0}catch(e){if(e instanceof ma&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(s,e){try{return await this.createNamespace(s,e)}catch(t){if(t instanceof ma&&t.status===409)return;throw t}}};function Fn(s){return s.join("�")}var nT=class{constructor(s,e="",t){this.client=s,this.prefix=e,this.accessDelegation=t}async listTables(s){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Fn(s.namespace)}/tables`})).data.identifiers}async createTable(s,e){const t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Fn(s.namespace)}/tables`,body:e,headers:t})).data.metadata}async updateTable(s,e){const t=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Fn(s.namespace)}/tables/${s.name}`,body:e});return{"metadata-location":t.data["metadata-location"],metadata:t.data.metadata}}async dropTable(s,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Fn(s.namespace)}/tables/${s.name}`,query:{purgeRequested:String((e==null?void 0:e.purge)??!1)}})}async loadTable(s){const e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Fn(s.namespace)}/tables/${s.name}`,headers:e})).data.metadata}async tableExists(s){const e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Fn(s.namespace)}/tables/${s.name}`,headers:e}),!0}catch(t){if(t instanceof ma&&t.status===404)return!1;throw t}}async createTableIfNotExists(s,e){try{return await this.createTable(s,e)}catch(t){if(t instanceof ma&&t.status===409)return await this.loadTable({namespace:s.namespace,name:e.name});throw t}}},iT=class{constructor(s){var r;let e="v1";s.catalogName&&(e+=`/${s.catalogName}`);const t=s.baseUrl.endsWith("/")?s.baseUrl:`${s.baseUrl}/`;this.client=sT({baseUrl:t,auth:s.auth,fetchImpl:s.fetch}),this.accessDelegation=(r=s.accessDelegation)==null?void 0:r.join(","),this.namespaceOps=new rT(this.client,e),this.tableOps=new nT(this.client,e,this.accessDelegation)}async listNamespaces(s){return this.namespaceOps.listNamespaces(s)}async createNamespace(s,e){return this.namespaceOps.createNamespace(s,e)}async dropNamespace(s){await this.namespaceOps.dropNamespace(s)}async loadNamespaceMetadata(s){return this.namespaceOps.loadNamespaceMetadata(s)}async listTables(s){return this.tableOps.listTables(s)}
593async createTable(s,e){return this.tableOps.createTable(s,e)}async updateTable(s,e){return this.tableOps.updateTable(s,e)}async dropTable(s,e){await this.tableOps.dropTable(s,e)}async loadTable(s){return this.tableOps.loadTable(s)}async namespaceExists(s){return this.namespaceOps.namespaceExists(s)}async tableExists(s){return this.tableOps.tableExists(s)}async createNamespaceIfNotExists(s,e){return this.namespaceOps.createNamespaceIfNotExists(s,e)}async createTableIfNotExists(s,e){return this.tableOps.createTableIfNotExists(s,e)}},El=class extends Error{constructor(s){super(s),this.__isStorageError=!0,this.name="StorageError"}};function Ot(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}var aT=class extends El{constructor(s,e,t){super(s),this.name="StorageApiError",this.status=e,this.statusCode=t}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},od=class extends El{constructor(s,e){super(s),this.name="StorageUnknownError",this.originalError=e}};const pu=s=>s?(...e)=>s(...e):(...e)=>fetch(...e),oT=()=>Response,ld=s=>{if(Array.isArray(s))return s.map(t=>ld(t));if(typeof s=="function"||s!==Object(s))return s;const e={};return Object.entries(s).forEach(([t,r])=>{const n=t.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[n]=ld(r)}),e},lT=s=>{if(typeof s!="object"||s===null)return!1;const e=Object.getPrototypeOf(s);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in s)&&!(Symbol.iterator in s)},cT=s=>!s||typeof s!="string"||s.length===0||s.length>100||s.trim()!==s||s.includes("/")||s.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(s);function pa(s){"@babel/helpers - typeof";return pa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},pa(s)}function dT(s,e){if(pa(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var r=t.call(s,e);if(pa(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(s)}function uT(s){var e=dT(s,"string");return pa(e)=="symbol"?e:e+""}function hT(s,e,t){return(e=uT(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function uf(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);e&&(r=r.filter(function(n){return Object.getOwnPropertyDescriptor(s,n).enumerable})),t.push.apply(t,r)}return t}function Oe(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?uf(Object(t),!0).forEach(function(r){hT(s,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):uf(Object(t)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(t,r))})}return s}const Jl=s=>{var e;return s.msg||s.message||s.error_description||(typeof s.error=="string"?s.error:(e=s.error)===null||e===void 0?void 0:e.message)||JSON.stringify(s)},fT=async(s,e,t)=>{s instanceof await oT()&&!(t!=null&&t.noResolveJson)?s.json().then(r=>{const n=s.status||500,i=(r==null?void 0:r.statusCode)||n+"";e(new aT(Jl(r),n,i))}).catch(r=>{e(new od(Jl(r),r))}):e(new od(Jl(s),s))},mT=(s,e,t,r)=>{const n={method:s,headers:(e==null?void 0:e.headers)||{}};return s==="GET"||!r?n:(lT(r)?(n.headers=Oe({"Content-Type":"application/json"},e==null?void 0:e.headers),n.body=JSON.stringify(r)):n.body=r,e!=null&&e.duplex&&(n.duplex=e.duplex),Oe(Oe({},n),t))};async function Ua(s,e,t,r,n,i){return new Promise((o,l)=>{s(t,mT(e,r,n,i)).then(d=>{if(!d.ok)throw d;return r!=null&&r.noResolveJson?d:d.json()}).then(d=>o(d)).catch(d=>fT(d,l,r))})}async function ga(s,e,t,r){return Ua(s,"GET",e,t,r)}async function Zs(s,e,t,r,n){return Ua(s,"POST",e,r,n,t)}async function cd(s,e,t,r,n){return Ua(s,"PUT",e,r,n,t)}async function pT(s,e,t,r){return Ua(s,"HEAD",e,Oe(Oe({},t),{},{noResolveJson:!0}),r)}async function gu(s,e,t,r,n){return Ua(s,"DELETE",e,r,n,t)}var gT=class{constructor(s,e){this.downloadFn=s,this.shouldThrowOnError=e}then(s,e){return this.execute().then(s,e)}async execute(){var s=this;try{return{data:(await s.downloadFn()).body,error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(Ot(e))return{data:null,error:e};throw e}}};let _0;_0=Symbol.toStringTag;var xT=class{constructor(s,e){this.downloadFn=s,this.shouldThrowOnError=e,this[_0]="BlobDownloadBuilder",this.promise=null}asStream(){return new gT(this.downloadFn,this.shouldThrowOnError)}then(s,e){return this.getPromise().then(s,e)}catch(s){return this.getPromise().catch(s)}finally(s){return this.getPromise().finally(s)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var s=this;try{return{data:await(await s.downloadFn()).blob(),error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(Ot(e))return{data:null,error:e};throw e}}};const yT={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},hf={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var vT=class{constructor(s,e={},t,r){this.shouldThrowOnError=!1,this.url=s,this.headers=e,this.bucketId=t,this.fetch=pu(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async uploadOrUpdate(s,e,t,r){var n=this;try{let i;const o=Oe(Oe({},hf),r);let l=Oe(Oe({},n.headers),s==="POST"&&{"x-upsert":String(o.upsert)});const d=o.metadata;typeof Blob<"u"&&t instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),d&&i.append("metadata",n.encodeMetadata(d)),i.append("",t)):typeof FormData<"u"&&t instanceof FormData?(i=t,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),d&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(d))):(i=t,l["cache-control"]=`max-age=${o.cacheControl}`,l["content-type"]=o.contentType,d&&(l["x-metadata"]=n.toBase64(n.encodeMetadata(d))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!o.duplex&&(o.duplex="half")),r!=null&&r.headers&&(l=Oe(Oe({},l),r.headers));const c=n._removeEmptyFolders(e),u=n._getFinalPath(c),h=await(s=="PUT"?cd:Zs)(n.fetch,`${n.url}/object/${u}`,i,Oe({headers:l},o!=null&&o.duplex?{duplex:o.duplex}:{}));return{data:{path:c,id:h.Id,fullPath:h.Key},error:null}}catch(i){if(n.shouldThrowOnError)throw i;if(Ot(i))return{data:null,error:i};throw i}}async upload(s,e,t){return this.uploadOrUpdate("POST",s,e,t)}async uploadToSignedUrl(s,e,t,r){var n=this;const i=n._removeEmptyFolders(s),o=n._getFinalPath(i),l=new URL(n.url+`/object/upload/sign/${o}`);l.searchParams.set("token",e);try{let d;const c=Oe({upsert:hf.upsert},r),u=Oe(Oe({},n.headers),{"x-upsert":String(c.upsert)});return typeof Blob<"u"&&t instanceof Blob?(d=new FormData,d.append("cacheControl",c.cacheControl),d.append("",t)):typeof FormData<"u"&&t instanceof FormData?(d=t,d.append("cacheControl",c.cacheControl)):(d=t,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType),{data:{path:i,fullPath:(await cd(n.fetch,l.toString(),d,{headers:u})).Key},error:null}}catch(d){if(n.shouldThrowOnError)throw d;if(Ot(d))return{data:null,error:d};throw d}}async createSignedUploadUrl(s,e){var t=this;try{let r=t._getFinalPath(s);const n=Oe({},t.headers);e!=null&&e.upsert&&(n["x-upsert"]="true");const i=await Zs(t.fetch,`${t.url}/object/upload/sign/${r}`,{},{headers:n}),o=new URL(t.url+i.url),l=o.searchParams.get("token");if(!l)throw new El("No token returned by API");return{data:{signedUrl:o.toString(),path:s,token:l},error:null}}catch(r){if(t.shouldThrowOnError)throw r;if(Ot(r))return{data:null,error:r};throw r}}async update(s,e,t){return this.uploadOrUpdate("PUT",s,e,t)}async move(s,e,t){var r=this;try{return{data:await Zs(r.fetch,`${r.url}/object/move`,{bucketId:r.bucketId,sourceKey:s,destinationKey:e,destinationBucket:t==null?void 0:t.destinationBucket},{headers:r.headers}),error:null}}catch(n){if(r.shouldThrowOnError)throw n;if(Ot(n))return{data:null,error:n};throw n}}async copy(s,e,t){var r=this;try{return{data:{path:(await Zs(r.fetch,`${r.url}/object/copy`,{bucketId:r.bucketId,sourceKey:s,destinationKey:e,destinationBucket:t==null?void 0:t.destinationBucket},{headers:r.headers})).Key},error:null}}catch(n){if(r.shouldThrowOnError)throw n;if(Ot(n))return{data:null,error:n};throw n}}async createSignedUrl(s,e,t){var r=this;try{let n=r._getFinalPath(s),i=await Zs(r.fetch,`${r.url}/object/sign/${n}
593`,Oe({expiresIn:e},t!=null&&t.transform?{transform:t.transform}:{}),{headers:r.headers});const o=t!=null&&t.download?`&download=${t.download===!0?"":t.download}`:"";return i={signedUrl:encodeURI(`${r.url}${i.signedURL}${o}`)},{data:i,error:null}}catch(n){if(r.shouldThrowOnError)throw n;if(Ot(n))return{data:null,error:n};throw n}}async createSignedUrls(s,e,t){var r=this;try{const n=await Zs(r.fetch,`${r.url}/object/sign/${r.bucketId}`,{expiresIn:e,paths:s},{headers:r.headers}),i=t!=null&&t.download?`&download=${t.download===!0?"":t.download}`:"";return{data:n.map(o=>Oe(Oe({},o),{},{signedUrl:o.signedURL?encodeURI(`${r.url}${o.signedURL}${i}`):null})),error:null}}catch(n){if(r.shouldThrowOnError)throw n;if(Ot(n))return{data:null,error:n};throw n}}download(s,e){const t=typeof(e==null?void 0:e.transform)<"u"?"render/image/authenticated":"object",r=this.transformOptsToQueryString((e==null?void 0:e.transform)||{}),n=r?`?${r}`:"",i=this._getFinalPath(s),o=()=>ga(this.fetch,`${this.url}/${t}/${i}${n}`,{headers:this.headers,noResolveJson:!0});return new xT(o,this.shouldThrowOnError)}async info(s){var e=this;const t=e._getFinalPath(s);try{return{data:ld(await ga(e.fetch,`${e.url}/object/info/${t}`,{headers:e.headers})),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(Ot(r))return{data:null,error:r};throw r}}async exists(s){var e=this;const t=e._getFinalPath(s);try{return await pT(e.fetch,`${e.url}/object/${t}`,{headers:e.headers}),{data:!0,error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(Ot(r)&&r instanceof od){const n=r.originalError;if([400,404].includes(n==null?void 0:n.status))return{data:!1,error:r}}throw r}}getPublicUrl(s,e){const t=this._getFinalPath(s),r=[],n=e!=null&&e.download?`download=${e.download===!0?"":e.download}`:"";n!==""&&r.push(n);const i=typeof(e==null?void 0:e.transform)<"u"?"render/image":"object",o=this.transformOptsToQueryString((e==null?void 0:e.transform)||{});o!==""&&r.push(o);let l=r.join("&");return l!==""&&(l=`?${l}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${t}${l}`)}}}async remove(s){var e=this;try{return{data:await gu(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:s},{headers:e.headers}),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ot(t))return{data:null,error:t};throw t}}async list(s,e,t){var r=this;try{const n=Oe(Oe(Oe({},yT),e),{},{prefix:s||""});return{data:await Zs(r.fetch,`${r.url}/object/list/${r.bucketId}`,n,{headers:r.headers},t),error:null}}catch(n){if(r.shouldThrowOnError)throw n;if(Ot(n))return{data:null,error:n};throw n}}async listV2(s,e){var t=this;try{const r=Oe({},s);return{data:await Zs(t.fetch,`${t.url}/object/list-v2/${t.bucketId}`,r,{headers:t.headers},e),error:null}}catch(r){if(t.shouldThrowOnError)throw r;if(Ot(r))return{data:null,error:r};throw r}}encodeMetadata(s){return JSON.stringify(s)}toBase64(s){return typeof Buffer<"u"?Buffer.from(s).toString("base64"):btoa(s)}_getFinalPath(s){return`${this.bucketId}/${s.replace(/^\/+/,"")}`}_removeEmptyFolders(s){return s.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(s){const e=[];return s.width&&e.push(`width=${s.width}`),s.height&&e.push(`height=${s.height}`),s.resize&&e.push(`resize=${s.resize}`),s.format&&e.push(`format=${s.format}`),s.quality&&e.push(`quality=${s.quality}`),e.join("&")}};const w0="2.90.1",E0={"X-Client-Info":`storage-js/${w0}`};var bT=class{constructor(s,e={},t,r){this.shouldThrowOnError=!1;const n=new URL(s);r!=null&&r.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase.")),this.url=n.href.replace(/\/$/,""),this.headers=Oe(Oe({},E0),e),this.fetch=pu(t)}throwOnError(){return this.shouldThrowOnError=!0,this}async listBuckets(s){var e=this;try{const t=e.listBucketOptionsToQueryString(s);return{data:await ga(e.fetch,`${e.url}/bucket${t}`,{headers:e.headers}),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ot(t))return{data:null,error:t};throw t}}async getBucket(s){var e=this;try{return{data:await ga(e.fetch,`${e.url}/bucket/${s}`,{headers:e.headers}),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ot(t))return{data:null,error:t};throw t}}async createBucket(s,e={public:!1}){var t=this;try{return{data:await Zs(t.fetch,`${t.url}/bucket`,{id:s,name:s,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:t.headers}),error:null}}catch(r){if(t.shouldThrowOnError)throw r;if(Ot(r))return{data:null,error:r};throw r}}async updateBucket(s,e){var t=this;try{return{data:await cd(t.fetch,`${t.url}/bucket/${s}`,{id:s,name:s,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:t.headers}),error:null}}catch(r){if(t.shouldThrowOnError)throw r;if(Ot(r))return{data:null,error:r};throw r}}async emptyBucket(s){var e=this;try{return{data:await Zs(e.fetch,`${e.url}/bucket/${s}/empty`,{},{headers:e.headers}),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ot(t))return{data:null,error:t};throw t}}async deleteBucket(s){var e=this;try{return{data:await gu(e.fetch,`${e.url}/bucket/${s}`,{},{headers:e.headers}),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ot(t))return{data:null,error:t};throw t}}listBucketOptionsToQueryString(s){const e={};return s&&("limit"in s&&(e.limit=String(s.limit)),"offset"in s&&(e.offset=String(s.offset)),s.search&&(e.search=s.search),s.sortColumn&&(e.sortColumn=s.sortColumn),s.sortOrder&&(e.sortOrder=s.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},_T=class{constructor(s,e={},t){this.shouldThrowOnError=!1,this.url=s.replace(/\/$/,""),this.headers=Oe(Oe({},E0),e),this.fetch=pu(t)}throwOnError(){return this.shouldThrowOnError=!0,this}async createBucket(s){var e=this;try{return{data:await Zs(e.fetch,`${e.url}/bucket`,{name:s},{headers:e.headers}),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ot(t))return{data:null,error:t};throw t}}async listBuckets(s){var e=this;try{const t=new URLSearchParams;(s==null?void 0:s.limit)!==void 0&&t.set("limit",s.limit.toString()),(s==null?void 0:s.offset)!==void 0&&t.set("offset",s.offset.toString()),s!=null&&s.sortColumn&&t.set("sortColumn",s.sortColumn),s!=null&&s.sortOrder&&t.set("sortOrder",s.sortOrder),s!=null&&s.search&&t.set("search",s.search);const r=t.toString(),n=r?`${e.url}/bucket?${r}`:`${e.url}/bucket`;return{data:await ga(e.fetch,n,{headers:e.headers}),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ot(t))return{data:null,error:t};throw t}}async deleteBucket(s){var e=this;try{return{data:await gu(e.fetch,`${e.url}/bucket/${s}`,{},{headers:e.headers}),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ot(t))return{data:null,error:t};throw t}}from(s){var e=this;if(!cT(s))throw new El("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const t=new iT({baseUrl:this.url,catalogName:s,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}
593),r=this.shouldThrowOnError;return new Proxy(t,{get(n,i){const o=n[i];return typeof o!="function"?o:async(...l)=>{try{return{data:await o.apply(n,l),error:null}}catch(d){if(r)throw d;return{data:null,error:d}}}}})}};const xu={"X-Client-Info":`storage-js/${w0}`,"Content-Type":"application/json"};var S0=class extends Error{constructor(s){super(s),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}};function Ls(s){return typeof s=="object"&&s!==null&&"__isStorageVectorsError"in s}var Zl=class extends S0{constructor(s,e,t){super(s),this.name="StorageVectorsApiError",this.status=e,this.statusCode=t}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},wT=class extends S0{constructor(s,e){super(s),this.name="StorageVectorsUnknownError",this.originalError=e}};const yu=s=>s?(...e)=>s(...e):(...e)=>fetch(...e),ET=s=>{if(typeof s!="object"||s===null)return!1;const e=Object.getPrototypeOf(s);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in s)&&!(Symbol.iterator in s)},ff=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),ST=async(s,e,t)=>{if(s&&typeof s=="object"&&"status"in s&&"ok"in s&&typeof s.status=="number"&&!(t!=null&&t.noResolveJson)){const r=s.status||500,n=s;if(typeof n.json=="function")n.json().then(i=>{const o=(i==null?void 0:i.statusCode)||(i==null?void 0:i.code)||r+"";e(new Zl(ff(i),r,o))}).catch(()=>{const i=r+"";e(new Zl(n.statusText||`HTTP ${r} error`,r,i))});else{const i=r+"";e(new Zl(n.statusText||`HTTP ${r} error`,r,i))}}else e(new wT(ff(s),s))},TT=(s,e,t,r)=>{const n={method:s,headers:(e==null?void 0:e.headers)||{}};return r?(ET(r)?(n.headers=Oe({"Content-Type":"application/json"},e==null?void 0:e.headers),n.body=JSON.stringify(r)):n.body=r,Oe(Oe({},n),t)):n};async function AT(s,e,t,r,n,i){return new Promise((o,l)=>{s(t,TT(e,r,n,i)).then(d=>{if(!d.ok)throw d;if(r!=null&&r.noResolveJson)return d;const c=d.headers.get("content-type");return!c||!c.includes("application/json")?{}:d.json()}).then(d=>o(d)).catch(d=>ST(d,l,r))})}async function Ps(s,e,t,r,n){return AT(s,"POST",e,r,n,t)}var kT=class{constructor(s,e={},t){this.shouldThrowOnError=!1,this.url=s.replace(/\/$/,""),this.headers=Oe(Oe({},xu),e),this.fetch=yu(t)}throwOnError(){return this.shouldThrowOnError=!0,this}async createIndex(s){var e=this;try{return{data:await Ps(e.fetch,`${e.url}/CreateIndex`,s,{headers:e.headers})||{},error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ls(t))return{data:null,error:t};throw t}}async getIndex(s,e){var t=this;try{return{data:await Ps(t.fetch,`${t.url}/GetIndex`,{vectorBucketName:s,indexName:e},{headers:t.headers}),error:null}}catch(r){if(t.shouldThrowOnError)throw r;if(Ls(r))return{data:null,error:r};throw r}}async listIndexes(s){var e=this;try{return{data:await Ps(e.fetch,`${e.url}/ListIndexes`,s,{headers:e.headers}),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ls(t))return{data:null,error:t};throw t}}async deleteIndex(s,e){var t=this;try{return{data:await Ps(t.fetch,`${t.url}/DeleteIndex`,{vectorBucketName:s,indexName:e},{headers:t.headers})||{},error:null}}catch(r){if(t.shouldThrowOnError)throw r;if(Ls(r))return{data:null,error:r};throw r}}},RT=class{constructor(s,e={},t){this.shouldThrowOnError=!1,this.url=s.replace(/\/$/,""),this.headers=Oe(Oe({},xu),e),this.fetch=yu(t)}throwOnError(){return this.shouldThrowOnError=!0,this}async putVectors(s){var e=this;try{if(s.vectors.length<1||s.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return{data:await Ps(e.fetch,`${e.url}/PutVectors`,s,{headers:e.headers})||{},error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ls(t))return{data:null,error:t};throw t}}async getVectors(s){var e=this;try{return{data:await Ps(e.fetch,`${e.url}/GetVectors`,s,{headers:e.headers}),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ls(t))return{data:null,error:t};throw t}}async listVectors(s){var e=this;try{if(s.segmentCount!==void 0){if(s.segmentCount<1||s.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");
593if(s.segmentIndex!==void 0&&(s.segmentIndex<0||s.segmentIndex>=s.segmentCount))throw new Error(`segmentIndex must be between 0 and ${s.segmentCount-1}`)}return{data:await Ps(e.fetch,`${e.url}/ListVectors`,s,{headers:e.headers}),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ls(t))return{data:null,error:t};throw t}}async queryVectors(s){var e=this;try{return{data:await Ps(e.fetch,`${e.url}/QueryVectors`,s,{headers:e.headers}),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ls(t))return{data:null,error:t};throw t}}async deleteVectors(s){var e=this;try{if(s.keys.length<1||s.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return{data:await Ps(e.fetch,`${e.url}/DeleteVectors`,s,{headers:e.headers})||{},error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ls(t))return{data:null,error:t};throw t}}},jT=class{constructor(s,e={},t){this.shouldThrowOnError=!1,this.url=s.replace(/\/$/,""),this.headers=Oe(Oe({},xu),e),this.fetch=yu(t)}throwOnError(){return this.shouldThrowOnError=!0,this}async createBucket(s){var e=this;try{return{data:await Ps(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:s},{headers:e.headers})||{},error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ls(t))return{data:null,error:t};throw t}}async getBucket(s){var e=this;try{return{data:await Ps(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:s},{headers:e.headers}),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ls(t))return{data:null,error:t};throw t}}async listBuckets(s={}){var e=this;try{return{data:await Ps(e.fetch,`${e.url}/ListVectorBuckets`,s,{headers:e.headers}),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ls(t))return{data:null,error:t};throw t}}async deleteBucket(s){var e=this;try{return{data:await Ps(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:s},{headers:e.headers})||{},error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ls(t))return{data:null,error:t};throw t}}},IT=class extends jT{constructor(s,e={}){super(s,e.headers||{},e.fetch)}from(s){return new CT(this.url,this.headers,s,this.fetch)}async createBucket(s){var e=()=>super.createBucket,t=this;return e().call(t,s)}async getBucket(s){var e=()=>super.getBucket,t=this;return e().call(t,s)}async listBuckets(s={}){var e=()=>super.listBuckets,t=this;return e().call(t,s)}async deleteBucket(s){var e=()=>super.deleteBucket,t=this;return e().call(t,s)}},CT=class extends kT{constructor(s,e,t,r){super(s,e,r),this.vectorBucketName=t}async createIndex(s){var e=()=>super.createIndex,t=this;return e().call(t,Oe(Oe({},s),{},{vectorBucketName:t.vectorBucketName}))}async listIndexes(s={}){var e=()=>super.listIndexes,t=this;return e().call(t,Oe(Oe({},s),{},{vectorBucketName:t.vectorBucketName}))}async getIndex(s){var e=()=>super.getIndex,t=this;return e().call(t,t.vectorBucketName,s)}async deleteIndex(s){var e=()=>super.deleteIndex,t=this;return e().call(t,t.vectorBucketName,s)}index(s){return new NT(this.url,this.headers,this.vectorBucketName,s,this.fetch)}},NT=class extends RT{constructor(s,e,t,r,n){super(s,e,n),this.vectorBucketName=t,this.indexName=r}async putVectors(s){var e=()=>super.putVectors,t=this;return e().call(t,Oe(Oe({},s),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async getVectors(s){var e=()=>super.getVectors,t=this;return e().call(t,Oe(Oe({},s),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async listVectors(s={}){var e=()=>super.listVectors,t=this;return e().call(t,Oe(Oe({},s),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async queryVectors(s){var e=()=>super.queryVectors,t=this;return e().call(t,Oe(Oe({},s),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async deleteVectors(s){var e=()=>super.deleteVectors,t=this;return e().call(t,Oe(Oe({},s),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}},LT=class extends bT{constructor(s,e={},t,r){super(s,e,t,r)}from(s){return new vT(this.url,this.headers,s,this.fetch)}get vectors(){return new IT(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new _T(this.url+"/iceberg",this.headers,this.fetch)}};const T0="2.90.1",Jn=30*1e3,dd=3,ec=dd*Jn,PT="http://localhost:9999",DT="supabase.auth.token",OT={"X-Client-Info":`gotrue-js/${T0}`},ud="X-Supabase-Api-Version",A0={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},MT=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,FT=10*60*1e3;
593class xa extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function Le(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class $T extends xa{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}function UT(s){return Le(s)&&s.name==="AuthApiError"}class wn extends xa{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class Mr extends xa{constructor(e,t,r,n){super(e,r,n),this.name=t,this.status=r}}class Rs extends Mr{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function BT(s){return Le(s)&&s.name==="AuthSessionMissingError"}class $n extends Mr{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Xa extends Mr{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Qa extends Mr{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function VT(s){return Le(s)&&s.name==="AuthImplicitGrantRedirectError"}class mf extends Mr{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class GT extends Mr{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class hd extends Mr{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function tc(s){return Le(s)&&s.name==="AuthRetryableFetchError"}class pf extends Mr{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}class fd extends Mr{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const qo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),gf=` 	
594\r=`.split(""),zT=(()=>{const s=new Array(128);for(let e=0;e<s.length;e+=1)s[e]=-1;for(let e=0;e<gf.length;e+=1)s[gf[e].charCodeAt(0)]=-2;for(let e=0;e<qo.length;e+=1)s[qo[e].charCodeAt(0)]=e;return s})();function xf(s,e,t){if(s!==null)for(e.queue=e.queue<<8|s,e.queuedBits+=8;e.queuedBits>=6;){const r=e.queue>>e.queuedBits-6&63;t(qo[r]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const r=e.queue>>e.queuedBits-6&63;t(qo[r]),e.queuedBits-=6}}function k0(s,e,t){const r=zT[s];if(r>-1)for(e.queue=e.queue<<6|r,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(s)}"`)}}function yf(s){const e=[],t=o=>{e.push(String.fromCodePoint(o))},r={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=o=>{KT(o,r,t)};for(let o=0;o<s.length;o+=1)k0(s.charCodeAt(o),n,i);return e.join("")}function qT(s,e){if(s<=127){e(s);return}else if(s<=2047){e(192|s>>6),e(128|s&63);return}else if(s<=65535){e(224|s>>12),e(128|s>>6&63),e(128|s&63);return}else if(s<=1114111){e(240|s>>18),e(128|s>>12&63),e(128|s>>6&63),e(128|s&63);return}throw new Error(`Unrecognized Unicode codepoint: ${s.toString(16)}`)}function HT(s,e){for(let t=0;t<s.length;t+=1){let r=s.charCodeAt(t);if(r>55295&&r<=56319){const n=(r-55296)*1024&65535;r=(s.charCodeAt(t+1)-56320&65535|n)+65536,t+=1}qT(r,e)}}function KT(s,e,t){if(e.utf8seq===0){if(s<=127){t(s);return}for(let r=1;r<6;r+=1)if(!(s>>7-r&1)){e.utf8seq=r;break}if(e.utf8seq===2)e.codepoint=s&31;else if(e.utf8seq===3)e.codepoint=s&15;else if(e.utf8seq===4)e.codepoint=s&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(s<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|s&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function di(s){const e=[],t={queue:0,queuedBits:0},r=n=>{e.push(n)};for(let n=0;n<s.length;n+=1)k0(s.charCodeAt(n),t,r);return new Uint8Array(e)}function WT(s){const e=[];return HT(s,t=>e.push(t)),new Uint8Array(e)}function En(s){const e=[],t={queue:0,queuedBits:0},r=n=>{e.push(n)};
594return s.forEach(n=>xf(n,t,r)),xf(null,t,r),e.join("")}function YT(s){return Math.round(Date.now()/1e3)+s}function XT(){return Symbol("auth-callback")}const as=()=>typeof window<"u"&&typeof document<"u",un={tested:!1,writable:!1},R0=()=>{if(!as())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(un.tested)return un.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),un.tested=!0,un.writable=!0}catch{un.tested=!0,un.writable=!1}return un.writable};function QT(s){const e={},t=new URL(s);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((n,i)=>{e[i]=n})}catch{}return t.searchParams.forEach((r,n)=>{e[n]=r}),e}const j0=s=>s?(...e)=>s(...e):(...e)=>fetch(...e),JT=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",Zn=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},hn=async(s,e)=>{const t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},is=async(s,e)=>{await s.removeItem(e)};class Sl{constructor(){this.promise=new Sl.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}Sl.promiseConstructor=Promise;function sc(s){const e=s.split(".");if(e.length!==3)throw new fd("Invalid JWT structure");for(let r=0;r<e.length;r++)if(!MT.test(e[r]))throw new fd("JWT not in base64url format");return{header:JSON.parse(yf(e[0])),payload:JSON.parse(yf(e[1])),signature:di(e[2]),raw:{header:e[0],payload:e[1]}}}async function ZT(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function e1(s,e){return new Promise((r,n)=>{(async()=>{for(let i=0;i<1/0;i++)try{const o=await s(i);if(!e(i,null,o)){r(o);return}}catch(o){if(!e(i,o)){n(o);return}}})()})}function t1(s){return("0"+s.toString(16)).substr(-2)}function s1(){const e=new Uint32Array(56);if(typeof crypto>"u"){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length;let n="";for(let i=0;i<56;i++)n+=t.charAt(Math.floor(Math.random()*r));return n}return crypto.getRandomValues(e),Array.from(e,t1).join("")}async function r1(s){const t=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",t),n=new Uint8Array(r);return Array.from(n).map(i=>String.fromCharCode(i)).join("")}async function n1(s){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),s;const t=await r1(s);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Un(s,e,t=!1){const r=s1();let n=r;t&&(n+="/PASSWORD_RECOVERY"),await Zn(s,`${e}-code-verifier`,n);const i=await n1(r);return[i,r===i?"plain":"s256"]}const i1=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function a1(s){const e=s.headers.get(ud);if(!e||!e.match(i1))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function o1(s){if(!s)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(s<=e)throw new Error("JWT has expired")}function l1(s){switch(s){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const c1=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Bn(s){if(!c1.test(s))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function rc(){const s={};return new Proxy(s,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return!0;if(typeof t=="symbol"){const r=t.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function d1(s,e){return new Proxy(s,{get:(t,r,n)=>{if(r==="__isInsecureUserWarningProxy")return!0;
594if(typeof r=="symbol"){const i=r.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(t,r,n)}return!e.value&&typeof r=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(t,r,n)}})}function vf(s){return JSON.parse(JSON.stringify(s))}const xn=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),u1=[502,503,504];async function bf(s){var e;if(!JT(s))throw new hd(xn(s),0);if(u1.includes(s.status))throw new hd(xn(s),s.status);let t;try{t=await s.json()}catch(i){throw new wn(xn(i),i)}let r;const n=a1(s);if(n&&n.getTime()>=A0["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new pf(xn(t),s.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(r==="session_not_found")throw new Rs}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new pf(xn(t),s.status,t.weak_password.reasons);throw new $T(xn(t),s.status||500,r)}const h1=(s,e,t,r)=>{const n={method:s,headers:(e==null?void 0:e.headers)||{}};return s==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),n.body=JSON.stringify(r),Object.assign(Object.assign({},n),t))};async function De(s,e,t,r){var n;const i=Object.assign({},r==null?void 0:r.headers);i[ud]||(i[ud]=A0["2024-01-01"].name),r!=null&&r.jwt&&(i.Authorization=`Bearer ${r.jwt}`);const o=(n=r==null?void 0:r.query)!==null&&n!==void 0?n:{};r!=null&&r.redirectTo&&(o.redirect_to=r.redirectTo);const l=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",d=await f1(s,e,t+l,{headers:i,noResolveJson:r==null?void 0:r.noResolveJson},{},r==null?void 0:r.body);return r!=null&&r.xform?r==null?void 0:r.xform(d):{data:Object.assign({},d),error:null}}async function f1(s,e,t,r,n,i){const o=h1(e,r,n,i);let l;try{l=await s(t,Object.assign({},o))}catch(d){throw console.error(d),new hd(xn(d),0)}if(l.ok||await bf(l),r!=null&&r.noResolveJson)return l;try{return await l.json()}catch(d){await bf(d)}}function Qs(s){var e;let t=null;g1(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=YT(s.expires_in)));const r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function _f(s){const e=Qs(s);return!e.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=s.weak_password),e}function Yr(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function m1(s){return{data:s,error:null}}function p1(s){const{action_link:e,email_otp:t,hashed_token:r,redirect_to:n,verification_type:i}=s,o=vl(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:e,email_otp:t,hashed_token:r,redirect_to:n,verification_type:i},d=Object.assign({},o);return{data:{properties:l,user:d},error:null}}function wf(s){return s}function g1(s){return s.access_token&&s.refresh_token&&s.expires_in}const nc=["global","local","others"];class x1{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=j0(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)}}async signOut(e,t=nc[0]){if(nc.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${nc.join(", ")}`);try{return await De(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(Le(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await De(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Yr})}catch(r){if(Le(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{const{options:t}=e,r=vl(e,["options"]),n=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(n.new_email=r==null?void 0:r.newEmail,delete n.newEmail),await De(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:p1,redirectTo:t==null?void 0:t.redirectTo})}catch(t){if(Le(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await De(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Yr})}catch(t){if(Le(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,n,i,o,l,d;try{const c={nextPage:null,lastPage:0,total:0},u=await De(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e==null?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(n=e==null?void 0:e.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:wf});if(u.error)throw u.error;const h=await u.json(),f=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(d=(l=u.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&d!==void 0?d:[];return m.length>0&&(m.forEach(p=>{const x=parseInt(p.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(p.split(";")[1].split("=")[1]);c[`${y}Page`]=x}),c.total=parseInt(f)),{data:Object.assign(Object.assign({},h),c),error:null}}catch(c){if(Le(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){Bn(e);try{return await De(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Yr})}catch(t){if(Le(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){Bn(e);try{return await De(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Yr})}catch(r){if(Le(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){Bn(e);
594try{return await De(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Yr})}catch(r){if(Le(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){Bn(e.userId);try{const{data:t,error:r}=await De(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:t,error:r}}catch(t){if(Le(t))return{data:null,error:t};throw t}}async _deleteFactor(e){Bn(e.userId),Bn(e.id);try{return{data:await De(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(Le(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,r,n,i,o,l,d;try{const c={nextPage:null,lastPage:0,total:0},u=await De(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e==null?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(n=e==null?void 0:e.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:wf});if(u.error)throw u.error;const h=await u.json(),f=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(d=(l=u.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&d!==void 0?d:[];return m.length>0&&(m.forEach(p=>{const x=parseInt(p.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(p.split(";")[1].split("=")[1]);c[`${y}Page`]=x}),c.total=parseInt(f)),{data:Object.assign(Object.assign({},h),c),error:null}}catch(c){if(Le(c))return{data:{clients:[]},error:c};throw c}}async _createOAuthClient(e){try{return await De(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(Le(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await De(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(Le(t))return{data:null,error:t};throw t}}async _updateOAuthClient(e,t){try{return await De(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(Le(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(e){try{return await De(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(Le(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await De(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(Le(t))return{data:null,error:t};throw t}}}function Ef(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}const Vn={debug:!!(globalThis&&R0()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class I0 extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class y1 extends I0{}async function v1(s,e,t){Vn.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);const r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),Vn.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(s,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async n=>{if(n){Vn.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,n.name);try{return await t()}finally{Vn.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,n.name)}}else{if(e===0)throw Vn.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new y1(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(Vn.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null,"  "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}}))}function b1(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function C0(s){if(!/^0x[a-fA-F0-9]{40}$/.test(s))throw new Error(`@supabase/auth-js: Address "${s}
594" is invalid.`);return s.toLowerCase()}function _1(s){return parseInt(s,16)}function w1(s){const e=new TextEncoder().encode(s);return"0x"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}function E1(s){var e;const{chainId:t,domain:r,expirationTime:n,issuedAt:i=new Date,nonce:o,notBefore:l,requestId:d,resources:c,scheme:u,uri:h,version:f}=s;{if(!Number.isInteger(t))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!h)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(f!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${f}`);if(!((e=s.statement)===null||e===void 0)&&e.includes(`
595`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${s.statement}`)}const m=C0(s.address),p=u?`${u}://${r}`:r,x=s.statement?`${s.statement}
596`:"",y=`${p} wants you to sign in with your Ethereum account:
597${m}
598
599${x}`;let v=`URI: ${h}
600Version: ${f}
601Chain ID: ${t}${o?`
602Nonce: ${o}`:""}
603Issued At: ${i.toISOString()}`;if(n&&(v+=`
604Expiration Time: ${n.toISOString()}`),l&&(v+=`
605Not Before: ${l.toISOString()}`),d&&(v+=`
606Request ID: ${d}`),c){let _=`
607Resources:`;for(const b of c){if(!b||typeof b!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${b}`);_+=`
608- ${b}`}v+=_}return`${y}
609${v}`}class Ht extends Error{constructor({message:e,code:t,cause:r,name:n}){var i;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=n??(r instanceof Error?r.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=t}}class Ho extends Ht{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function S1({error:s,options:e}){var t,r,n;const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(s.name==="AbortError"){if(e.signal instanceof AbortSignal)return new Ht({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:s})}else if(s.name==="ConstraintError"){if(((t=i.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new Ht({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:s});if(e.mediation==="conditional"&&((r=i.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new Ht({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:s});if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new Ht({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:s})}else{if(s.name==="InvalidStateError")return new Ht({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:s});if(s.name==="NotAllowedError")return new Ht({message:s.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:s});if(s.name==="NotSupportedError")return i.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new Ht({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:s}):new Ht({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:s});if(s.name==="SecurityError"){const o=window.location.hostname;if(N0(o)){if(i.rp.id!==o)return new Ht({message:`The RP ID "${i.rp.id}
609" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:s})}else return new Ht({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:s})}else if(s.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new Ht({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:s})}else if(s.name==="UnknownError")return new Ht({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:s})}return new Ht({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:s})}function T1({error:s,options:e}){const{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(s.name==="AbortError"){if(e.signal instanceof AbortSignal)return new Ht({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:s})}else{if(s.name==="NotAllowedError")return new Ht({message:s.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:s});if(s.name==="SecurityError"){const r=window.location.hostname;if(N0(r)){if(t.rpId!==r)return new Ht({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:s})}else return new Ht({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:s})}else if(s.name==="UnknownError")return new Ht({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:s})}return new Ht({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:s})}class A1{createNewAbortSignal(){if(this.controller){const t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const k1=new A1;function R1(s){if(!s)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(s);const{challenge:e,user:t,excludeCredentials:r}=s,n=vl(s,["challenge","user","excludeCredentials"]),i=di(e).buffer,o=Object.assign(Object.assign({},t),{id:di(t.id).buffer}),l=Object.assign(Object.assign({},n),{challenge:i,user:o});if(r&&r.length>0){l.excludeCredentials=new Array(r.length);for(let d=0;d<r.length;d++){const c=r[d];l.excludeCredentials[d]=Object.assign(Object.assign({},c),{id:di(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return l}function j1(s){if(!s)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(s);const{challenge:e,allowCredentials:t}=s,r=vl(s,["challenge","allowCredentials"]),n=di(e).buffer,i=Object.assign(Object.assign({},r),{challenge:n});if(t&&t.length>0){i.allowCredentials=new Array(t.length);for(let o=0;o<t.length;o++){const l=t[o];i.allowCredentials[o]=Object.assign(Object.assign({},l),{id:di(l.id).buffer,type:l.type||"public-key",transports:l.transports})}}return i}function I1(s){var e;if("toJSON"in s&&typeof s.toJSON=="function")return s.toJSON();const t=s;return{id:s.id,rawId:s.id,response:{attestationObject:En(new Uint8Array(s.response.attestationObject)),clientDataJSON:En(new Uint8Array(s.response.clientDataJSON))},type:"public-key",clientExtensionResults:s.getClientExtensionResults(),authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function C1(s){var e;if("toJSON"in s&&typeof s.toJSON=="function")return s.toJSON();const t=s,r=s.getClientExtensionResults(),n=s.response;return{id:s.id,rawId:s.id,response:{authenticatorData:En(new Uint8Array(n.authenticatorData)),clientDataJSON:En(new Uint8Array(n.clientDataJSON)),signature:En(new Uint8Array(n.signature)),userHandle:n.userHandle?En(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function N0(s){return s==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(s)}function Sf(){var s,e;return!!(as()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((s=navigator==null?void 0:navigator.credentials)===null||s===void 0?void 0:s.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function N1(s){try{const e=await navigator.credentials.create(s);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ho("Browser returned unexpected credential type",e)}:{data:null,error:new Ho("Empty credential response",e)}}catch(e){return{data:null,error:S1({error:e,options:s})}}}async function L1(s){try{const e=await navigator.credentials.get(s);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ho("Browser returned unexpected credential type",e)}:{data:null,error:new Ho("Empty credential response",e)}}catch(e){return{data:null,error:T1({error:e,options:s})}}}const P1={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},D1={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Ko(...s){const e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),t=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),r={};for(const n of s)if(n)for(const i in n){const o=n[i];if(o!==void 0)if(Array.isArray(o))r[i]=o;else if(t(o))r[i]=o;else if(e(o)){const l=r[i];e(l)?r[i]=Ko(l,o):r[i]=Ko(o)}else r[i]=o}return r}function O1(s,e){return Ko(P1,s,e||{})}function M1(s,e){return Ko(D1,s,e||{})}class F1{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:n},i){try{const{data:o,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!o)return{data:null,error:l};const d=n??k1.createNewAbortSignal();if(o.webauthn.type==="create"){const{user:c}=o.webauthn.credential_options.publicKey;c.name||(c.name=`${c.id}:${r}`),c.displayName||(c.displayName=c.name)}switch(o.webauthn.type){case"create":{const c=O1(o.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:u,error:h}=await N1({publicKey:c,signal:d});return u?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:u}},error:null}:{data:null,error:h}}case"request":{const c=M1(o.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:u,error:h}=await L1(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:c,signal:d}));return u?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:u}},error:null}:{data:null,error:h}}}}catch(o){return Le(o)?{data:null,error:o}:{data:null,error:new wn("Unexpected error in challenge",o)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!t)return{data:null,error:new xa("rpId is required for WebAuthn authentication")};try{if(!Sf())return{data:null,error:new wn("Browser does not support WebAuthn",null)};const{data:o,error:l}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:n},{request:i});if(!o)return{data:null,error:l};const{webauthn:d}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:d.type,rpId:t,rpOrigins:r,credential_response:d.credential_response}})}catch(o){return Le(o)?{data:null,error:o}:{data:null,error:new wn("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!t)return{data:null,error:new xa("rpId is required for WebAuthn registration")};try{if(!Sf())return{data:null,error:new wn("Browser does not support WebAuthn",null)};const{data:o,error:l}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(u=>{var h;
609return(h=u.data)===null||h===void 0?void 0:h.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.status!=="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u==null?void 0:u.id}):void 0),{data:null,error:l};const{data:d,error:c}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:n},{create:i});return d?this._verify({factorId:o.id,challengeId:d.challengeId,webauthn:{rpId:t,rpOrigins:r,type:d.webauthn.type,credential_response:d.webauthn.credential_response}}):{data:null,error:c}}catch(o){return Le(o)?{data:null,error:o}:{data:null,error:new wn("Unexpected error in register",o)}}}}b1();const $1={url:PT,storageKey:DT,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:OT,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4};async function Tf(s,e,t){return await t()}const Gn={};class ya{get jwks(){var e,t;return(t=(e=Gn[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){Gn[this.storageKey]=Object.assign(Object.assign({},Gn[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=Gn[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Gn[this.storageKey]=Object.assign(Object.assign({},Gn[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},$1),e);if(this.storageKey=i.storageKey,this.instanceID=(t=ya.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,ya.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&as()){const o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new x1({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=j0(i.fetch),this.lock=i.lock||Tf,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock?this.lock=i.lock:this.persistSession&&as()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=v1:this.lock=Tf,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new F1(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:R0()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Ef(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=Ef(this.memoryStorage)),as()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),await this._notifyAllSubscribers(o.data.event,o.data.session,!1)})}this.initialize()}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${T0}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let t={},r="none";if(as()&&(t=QT(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),as()&&this.detectSessionInUrl&&r!=="none"){const{data:n,error:i}=await this._getSessionFromURL(t,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),VT(i)){const d=(e=i.details)===null||e===void 0?void 0:e.code;
609if(d==="identity_already_exists"||d==="identity_not_found"||d==="single_identity_not_deletable")return{error:i}}return{error:i}}const{session:o,redirectType:l}=n;return this._debug("#_initialize()","detected session in URL",o,"redirect type",l),await this._saveSession(o),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return Le(t)?this._returnResult({error:t}):this._returnResult({error:new wn("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,n;try{const i=await De(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e==null?void 0:e.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(n=e==null?void 0:e.options)===null||n===void 0?void 0:n.captchaToken}},xform:Qs}),{data:o,error:l}=i;if(l||!o)return this._returnResult({data:{user:null,session:null},error:l});const d=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",d)),this._returnResult({data:{user:c,session:d},error:null})}catch(i){if(Le(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var t,r,n;try{let i;if("email"in e){const{email:u,password:h,options:f}=e;let m=null,p=null;this.flowType==="pkce"&&([m,p]=await Un(this.storage,this.storageKey)),i=await De(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f==null?void 0:f.emailRedirectTo,body:{email:u,password:h,data:(t=f==null?void 0:f.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},code_challenge:m,code_challenge_method:p},xform:Qs})}else if("phone"in e){const{phone:u,password:h,options:f}=e;i=await De(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:h,data:(r=f==null?void 0:f.data)!==null&&r!==void 0?r:{},channel:(n=f==null?void 0:f.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken}},xform:Qs})}else throw new Xa("You must provide either an email or phone number and a password");const{data:o,error:l}=i;if(l||!o)return await is(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:l});const d=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",d)),this._returnResult({data:{user:c,session:d},error:null})}catch(i){if(await is(this.storage,`${this.storageKey}-code-verifier`),Le(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let t;if("email"in e){const{email:i,password:o,options:l}=e;t=await De(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:_f})}else if("phone"in e){const{phone:i,password:o,options:l}=e;t=await De(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:_f})}else throw new Xa("You must provide either an email or phone number and a password");const{data:r,error:n}=t;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!r||!r.session||!r.user){const i=new $n;return this._returnResult({data:{user:null,session:null},error:i})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:n})}catch(t){if(Le(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,r,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,n,i,o,l,d,c,u,h,f;let m,p;if("message"in e)m=e.message,p=e.signature;else{const{chain:x,wallet:y,statement:v,options:_}=e;let b;if(as())if(typeof y=="object")b=y;else{const j=window;if("ethereum"in j&&typeof j.ethereum=="object"&&"request"in j.ethereum&&typeof j.ethereum.request=="function")b=j.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof y!="object"||!(_!=null&&_.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");b=y}const w=new URL((t=_==null?void 0:_.url)!==null&&t!==void 0?t:window.location.href),T=await b.request({method:"eth_requestAccounts"}).then(j=>j).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!T||T.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const A=C0(T[0]);let S=(r=_==null?void 0:_.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!S){const j=await b.request({method:"eth_chainId"});S=_1(j)}const I={domain:w.host,address:A,statement:v,uri:w.href,version:"1",chainId:S,nonce:(n=_==null?void 0:_.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(o=(i=_==null?void 0:_.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(l=_==null?void 0:_.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(d=_==null?void 0:_.signInWithEthereum)===null||d===void 0?void 0:d.notBefore,requestId:(c=_==null?void 0:_.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(u=_==null?void 0:_.signInWithEthereum)===null||u===void 0?void 0:u.resources};m=E1(I),p=await b.request({method:"personal_sign",params:[w1(m),A]})}try{const{data:x,error:y}=await De(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:m,signature:p}
609,!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:Qs});if(y)throw y;if(!x||!x.session||!x.user){const v=new $n;return this._returnResult({data:{user:null,session:null},error:v})}return x.session&&(await this._saveSession(x.session),await this._notifyAllSubscribers("SIGNED_IN",x.session)),this._returnResult({data:Object.assign({},x),error:y})}catch(x){if(Le(x))return this._returnResult({data:{user:null,session:null},error:x});throw x}}async signInWithSolana(e){var t,r,n,i,o,l,d,c,u,h,f,m;let p,x;if("message"in e)p=e.message,x=e.signature;else{const{chain:y,wallet:v,statement:_,options:b}=e;let w;if(as())if(typeof v=="object")w=v;else{const A=window;if("solana"in A&&typeof A.solana=="object"&&("signIn"in A.solana&&typeof A.solana.signIn=="function"||"signMessage"in A.solana&&typeof A.solana.signMessage=="function"))w=A.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof v!="object"||!(b!=null&&b.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=v}const T=new URL((t=b==null?void 0:b.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in w&&w.signIn){const A=await w.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},b==null?void 0:b.signInWithSolana),{version:"1",domain:T.host,uri:T.href}),_?{statement:_}:null));let S;if(Array.isArray(A)&&A[0]&&typeof A[0]=="object")S=A[0];else if(A&&typeof A=="object"&&"signedMessage"in A&&"signature"in A)S=A;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in S&&"signature"in S&&(typeof S.signedMessage=="string"||S.signedMessage instanceof Uint8Array)&&S.signature instanceof Uint8Array)p=typeof S.signedMessage=="string"?S.signedMessage:new TextDecoder().decode(S.signedMessage),x=S.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in w)||typeof w.signMessage!="function"||!("publicKey"in w)||typeof w!="object"||!w.publicKey||!("toBase58"in w.publicKey)||typeof w.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${T.host} wants you to sign in with your Solana account:`,w.publicKey.toBase58(),..._?["",_,""]:[""],"Version: 1",`URI: ${T.href}`,`Issued At: ${(n=(r=b==null?void 0:b.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=b==null?void 0:b.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${b.signInWithSolana.notBefore}`]:[],...!((o=b==null?void 0:b.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${b.signInWithSolana.expirationTime}`]:[],...!((l=b==null?void 0:b.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${b.signInWithSolana.chainId}`]:[],...!((d=b==null?void 0:b.signInWithSolana)===null||d===void 0)&&d.nonce?[`Nonce: ${b.signInWithSolana.nonce}`]:[],...!((c=b==null?void 0:b.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${b.signInWithSolana.requestId}`]:[],...!((h=(u=b==null?void 0:b.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||h===void 0)&&h.length?["Resources",...b.signInWithSolana.resources.map(S=>`- ${S}`)]:[]].join(`
610`);const A=await w.signMessage(new TextEncoder().encode(p),"utf8");if(!A||!(A instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");x=A}}try{const{data:y,error:v}=await De(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:En(x)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(m=e.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:Qs});if(v)throw v;if(!y||!y.session||!y.user){const _=new $n;return this._returnResult({data:{user:null,session:null},error:_})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:v})}catch(y){if(Le(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async _exchangeCodeForSession(e){const t=await hn(this.storage,`${this.storageKey}-code-verifier`),[r,n]=(t??"").split("/");try{if(!r&&this.flowType==="pkce")throw new GT;const{data:i,error:o}=await De(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:Qs});if(await is(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){const l=new $n;return this._returnResult({data:{user:null,session:null,redirectType:null},error:l})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:n??null}),error:o})}catch(i){if(await is(this.storage,`${this.storageKey}-code-verifier`),Le(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{const{options:t,provider:r,token:n,access_token:i,nonce:o}=e,l=await De(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:n,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:Qs}),{data:d,error:c}=l;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!d||!d.session||!d.user){const u=new $n;return this._returnResult({data:{user:null,session:null},error:u})}return d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("SIGNED_IN",d.session)),this._returnResult({data:d,error:c})}catch(t){if(Le(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,r,n,i,o;try{if("email"in e){const{email:l,options:d}=e;let c=null,u=null;this.flowType==="pkce"&&([c,u]=await Un(this.storage,this.storageKey));const{error:h}=await De(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(t=d==null?void 0:d.data)!==null&&t!==void 0?t:{},create_user:(r=d==null?void 0:d.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:d==null?void 0:d.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:h})}if("phone"in e){const{phone:l,options:d}=e,{data:c,error:u}=await De(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(n=d==null?void 0:d.data)!==null&&n!==void 0?n:{},create_user:(i=d==null?void 0:d.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken},channel:(o=d==null?void 0:d.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:u})}throw new Xa("You must provide either an email or phone number.")}catch(l){if(await is(this.storage,`${this.storageKey}-code-verifier`),Le(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}}async verifyOtp(e){var t,r;try{let n,i;"options"in e&&(n=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(r=e.options)===null||r===void 0?void 0:r.captchaToken);const{data:o,error:l}=await De(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:Qs});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");const d=o.session,c=o.user;return d!=null&&d.access_token&&(await this._saveSession(d),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",d)),this._returnResult({data:{user:c,session:d},error:null})}catch(n){if(Le(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var t,r,n,i,o;try{let l=null,d=null;this.flowType==="pkce"&&([l,d]=await Un(this.storage,this.storageKey));const c=await De(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((n=e==null?void 0:e.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:d}),headers:this.headers,xform:m1});return!((i=c.data)===null||i===void 0)&&i.url&&as()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(l){if(await is(this.storage,`${this.storageKey}-code-verifier`),Le(l))return this._returnResult({data:null,error:l});throw l}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new Rs;const{error:n}=await De(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(Le(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:r,type:n,options:i}=e,{error:o}=await De(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){const{phone:r,type:n,options:i}=e,{data:o,error:l}=await De(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:l})}throw new Xa("You must provide either an email or phone number and a type")}catch(t){if(Le(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const t=await hn(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not val
610id"),await this._removeSession())),!e)return{data:{session:null},error:null};const r=e.expires_at?e.expires_at*1e3-Date.now()<ec:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){const o=await hn(this.userStorage,this.storageKey+"-user");o!=null&&o.user?e.user=o.user:e.user=rc()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const o={value:this.suppressGetSessionWarning};e.user=d1(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await De(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Yr}):await this._useSession(async t=>{var r,n,i;const{data:o,error:l}=t;if(l)throw l;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Rs}:await De(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=o.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:Yr})})}catch(t){if(Le(t))return BT(t)&&(await this._removeSession(),await is(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:t});throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{const{data:n,error:i}=r;if(i)throw i;if(!n.session)throw new Rs;const o=n.session;let l=null,d=null;this.flowType==="pkce"&&e.email!=null&&([l,d]=await Un(this.storage,this.storageKey));const{data:c,error:u}=await De(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t==null?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:l,code_challenge_method:d}),jwt:o.access_token,xform:Yr});if(u)throw u;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(r){if(await is(this.storage,`${this.storageKey}-code-verifier`),Le(r))return this._returnResult({data:{user:null},error:r});throw r}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new Rs;const t=Date.now()/1e3;let r=t,n=!0,i=null;const{payload:o}=sc(e.access_token);if(o.exp&&(r=o.exp,n=r<=t),n){const{data:l,error:d}=await this._callRefreshToken(e.refresh_token);if(d)return this._returnResult({data:{user:null,session:null},error:d});if(!l)return{data:{user:null,session:null},error:null};i=l}else{const{data:l,error:d}=await this._getUser(e.access_token);if(d)throw d;i={access_token:e.access_token,refresh_token:e.refresh_token,user:l.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(Le(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){const{data:o,error:l}=t;if(l)throw l;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!(e!=null&&e.refresh_token))throw new Rs;const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(Le(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){try{if(!as())throw new Qa("No browser detected.");
610if(e.error||e.error_description||e.error_code)throw new Qa(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new mf("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Qa("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new mf("No code detected.");const{data:_,error:b}=await this._exchangeCodeForSession(e.code);if(b)throw b;const w=new URL(window.location.href);return w.searchParams.delete("code"),window.history.replaceState(window.history.state,"",w.toString()),{data:{session:_.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:n,access_token:i,refresh_token:o,expires_in:l,expires_at:d,token_type:c}=e;if(!i||!l||!o||!c)throw new Qa("No session defined in URL");const u=Math.round(Date.now()/1e3),h=parseInt(l);let f=u+h;d&&(f=parseInt(d));const m=f-u;m*1e3<=Jn&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${h}s`);const p=f-h;u-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,f,u):u-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,f,u);const{data:x,error:y}=await this._getUser(i);if(y)throw y;const v={provider_token:r,provider_refresh_token:n,access_token:i,expires_in:h,expires_at:f,refresh_token:o,token_type:c,user:x.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:v,redirectType:e.type},error:null})}catch(r){if(Le(r))return this._returnResult({data:{session:null,redirectType:null},error:r});throw r}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await hn(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;const{data:n,error:i}=t;if(i)return this._returnResult({error:i});const o=(r=n.session)===null||r===void 0?void 0:r.access_token;if(o){const{error:l}=await this.admin.signOut(o,e);if(l&&!(UT(l)&&(l.status===404||l.status===401||l.status===403)))return this._returnResult({error:l})}return e!=="others"&&(await this._removeSession(),await is(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const t=XT(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,n;try{const{data:{session:i},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,t={}){let r=null,n=null;this.flowType==="pkce"&&([r,n]=await Un(this.storage,this.storageKey,!0));try{return await De(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:n,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(i){if(await is(this.storage,`${this.storageKey}-code-verifier`),Le(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{const{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(Le(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{const{data:r,error:n}=await this._useSession(async i=>{var o,l,d,c,u;const{data:h,error:f}=i;if(f)throw f;const m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(l=e.options)===null||l===void 0?void 0:l.scopes,queryParams:(d=e.options)===null||d===void 0?void 0:d.queryParams,skipBrowserRedirect:!0});return await De(this.fetch,"GET",m,{headers:this.headers,jwt:(u=(c=h.session)===null||c===void 0?void 0:c.access_token)!==null&&u!==void 0?u:void 0})});if(n)throw n;return as()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r==null?void 0:r.url),this._returnResult({data:{provider:e.provider,url:r==null?void 0:r.url},error:null})}catch(r){if(Le(r))return this._returnResult({data:{provider:e.provider,url:null},error:r});throw r}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{const{error:n,data:{session:i}}=t;if(n)throw n;const{options:o,provider:l,token:d,access_token:c,nonce:u}=e,h=await De(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i==null?void 0:i.access_token)!==null&&r!==void 0?r:void 0,body:{provider:l,id_token:d,access_token:c,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Qs}),{data:f,error:m}=h;return m?this._returnResult({data:{user:null,session:null},error:m}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new $n}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:m}))}catch(n){if(await is(this.storage,`${this.storageKey}-code-verifier`),Le(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,n;const{data:i,error:o}=t;if(o)throw o;
610return await De(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&n!==void 0?n:void 0})})}catch(t){if(Le(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const r=Date.now();return await e1(async n=>(n>0&&await ZT(200*Math.pow(2,n-1)),this._debug(t,"refreshing attempt",n),await De(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Qs})),(n,i)=>{const o=200*Math.pow(2,n);return i&&tc(i)&&Date.now()+o-r<Jn})}catch(r){if(this._debug(t,"error",r),Le(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),as()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;const r="#_recoverAndRefresh()";this._debug(r,"begin");try{const n=await hn(this.storage,this.storageKey);if(n&&this.userStorage){let o=await hn(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:n.user},await Zn(this.userStorage,this.storageKey+"-user",o)),n.user=(e=o==null?void 0:o.user)!==null&&e!==void 0?e:rc()}else if(n&&!n.user&&!n.user){const o=await hn(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(n.user=o.user,await is(this.storage,this.storageKey+"-user"),await Zn(this.storage,this.storageKey,n)):n.user=rc()}if(this._debug(r,"session from storage",n),!this._isValidSession(n)){this._debug(r,"session is not valid"),n!==null&&await this._removeSession();return}const i=((t=n.expires_at)!==null&&t!==void 0?t:1/0)*1e3-Date.now()<ec;if(this._debug(r,`session has${i?"":" not"} expired with margin of ${ec}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:o}=await this._callRefreshToken(n.refresh_token);o&&(console.error(o),tc(o)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:o,error:l}=await this._getUser(n.access_token);!l&&(o!=null&&o.user)?(n.user=o.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(r,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(r,"error",n),console.error(n);return}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new Rs;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new Sl;const{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new Rs;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const l={data:i.session,error:null};return this.refreshingDeferred.resolve(l),l}catch(i){if(this._debug(n,"error",i),Le(i)){const o={data:null,error:i};return tc(i)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,t,r=!0){const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});const i=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,t)}catch(d){i.push(d)}});if(await Promise.all(o),i.length>0){for(let l=0;l<i.length;l+=1)console.error(i[l]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await is(this.storage,`${this.storageKey}-code-verifier`);const t=Object.assign({},e),r=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!r&&t.user&&await Zn(this.userStorage,this.storageKey+"-user",{user:t.user});const n=Object.assign({},t);delete n.user;const i=vf(n);await Zn(this.storage,this.storageKey,i)}else{const n=vf(t);await Zn(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await is(this.storage,this.storageKey),await is(this.storage,this.storageKey+"-code-verifier"),await is(this.storage,this.storageKey+"-user"),this.userStorage&&await is(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&as()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}
610catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),Jn);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async t=>{const{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((r.expires_at*1e3-e)/Jn);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${Jn}ms, refresh threshold is ${dd} ticks`),n<=dd&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof I0)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!as()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){const n=[`provider=${encodeURIComponent(t)}`];if(r!=null&&r.redirectTo&&n.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r!=null&&r.scopes&&n.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[i,o]=await Un(this.storage,this.storageKey),l=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});n.push(l.toString())}if(r!=null&&r.queryParams){const i=new URLSearchParams(r.queryParams);n.push(i.toString())}return r!=null&&r.skipBrowserRedirect&&n.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;const{data:n,error:i}=t;return i?this._returnResult({data:null,error:i}):await De(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=n==null?void 0:n.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(Le(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,n;const{data:i,error:o}=t;if(o)return this._returnResult({data:null,error:o});const l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:d,error:c}=await De(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&d.type==="totp"&&(!((n=d==null?void 0:d.totp)===null||n===void 0)&&n.qr_code)&&(d.totp.qr_code=`data:image/svg+xml;utf-8,${d.totp.qr_code}`),this._returnResult({data:d,error:null}))})}catch(t){if(Le(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r;const{data:n,error:i}=t;if(i)return this._returnResult({data:null,error:i});const o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?I1(e.webauthn.credential_response):C1(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:d}=await De(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(r=n==null?void 0:n.session)===null||r===void 0?void 0:r.access_token});return d?this._returnResult({data:null,error:d}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:l,error:d}))})}catch(t){if(Le(t))return this._returnResult({data:null,error:t});throw t}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r;const{data:n,error:i}=t;if(i)return this._returnResult({data:null,error:i});const o=await De(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(r=n==null?void 0:n.session)===null||r===void 0?void 0:r.access_token});if(o.error)return o;const{data:l}=o;if(l.type!=="webauthn")return{data:l,error:null};switch(l.webauthn.type){case"create":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:R1(l.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:j1(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(t){if(Le(t))return this._returnResult({data:null,error:t});throw t}})}async _challengeAndVerify(e){const{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;const{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};const n={all:[],phone:[],totp:[],webauthn:[]};for(const i of(e=t==null?void 0:t.factors)!==null&&e!==void 0?e:[])n.all.push(i),i.status==="verified"&&n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(){var e,t;const{data:{session:r},error:n}
610=await this.getSession();if(n)return this._returnResult({data:null,error:n});if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:i}=sc(r.access_token);let o=null;i.aal&&(o=i.aal);let l=o;((t=(e=r.user.factors)===null||e===void 0?void 0:e.filter(u=>u.status==="verified"))!==null&&t!==void 0?t:[]).length>0&&(l="aal2");const c=i.amr||[];return{data:{currentLevel:o,nextLevel:l,currentAuthenticationMethods:c},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{const{data:{session:r},error:n}=t;return n?this._returnResult({data:null,error:n}):r?await De(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new Rs})})}catch(t){if(Le(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new Rs});const o=await De(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&as()&&!(t!=null&&t.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(r){if(Le(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new Rs});const o=await De(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&as()&&!(t!=null&&t.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(r){if(Le(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await De(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new Rs})})}catch(e){if(Le(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{const{data:{session:r},error:n}=t;return n?this._returnResult({data:null,error:n}):r?(await De(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Rs})})}catch(t){if(Le(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(l=>l.kid===e);if(r)return r;const n=Date.now();if(r=this.jwks.keys.find(l=>l.kid===e),r&&this.jwks_cached_at+FT>n)return r;const{data:i,error:o}=await De(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=n,r=i.keys.find(l=>l.kid===e),!r)?null:r}async getClaims(e,t={}){try{let r=e;if(!r){const{data:m,error:p}
610=await this.getSession();if(p||!m.session)return this._returnResult({data:null,error:p});r=m.session.access_token}const{header:n,payload:i,signature:o,raw:{header:l,payload:d}}=sc(r);t!=null&&t.allowExpired||o1(i.exp);const c=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,t!=null&&t.keys?{keys:t.keys}:t==null?void 0:t.jwks);if(!c){const{error:m}=await this.getUser(r);if(m)throw m;return{data:{claims:i,header:n,signature:o},error:null}}const u=l1(n.alg),h=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,h,o,WT(`${l}.${d}`)))throw new fd("Invalid JWT signature");return{data:{claims:i,header:n,signature:o},error:null}}catch(r){if(Le(r))return this._returnResult({data:null,error:r});throw r}}}ya.nextInstanceID={};const U1=ya,B1="2.90.1";let Xi="";typeof Deno<"u"?Xi="deno":typeof document<"u"?Xi="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Xi="react-native":Xi="node";const V1={"X-Client-Info":`supabase-js-${Xi}/${B1}`},G1={headers:V1},z1={schema:"public"},q1={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},H1={};function va(s){"@babel/helpers - typeof";return va=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},va(s)}function K1(s,e){if(va(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var r=t.call(s,e);if(va(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(s)}function W1(s){var e=K1(s,"string");return va(e)=="symbol"?e:e+""}function Y1(s,e,t){return(e=W1(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function Af(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);e&&(r=r.filter(function(n){return Object.getOwnPropertyDescriptor(s,n).enumerable})),t.push.apply(t,r)}return t}function Gt(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Af(Object(t),!0).forEach(function(r){Y1(s,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):Af(Object(t)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(t,r))})}return s}const X1=s=>s?(...e)=>s(...e):(...e)=>fetch(...e),Q1=()=>Headers,J1=(s,e,t)=>{const r=X1(t),n=Q1();return async(i,o)=>{var l;const d=(l=await e())!==null&&l!==void 0?l:s;let c=new n(o==null?void 0:o.headers);return c.has("apikey")||c.set("apikey",s),c.has("Authorization")||c.set("Authorization",`Bearer ${d}`),r(i,Gt(Gt({},o),{},{headers:c}))}};function Z1(s){return s.endsWith("/")?s:s+"/"}function eA(s,e){var t,r;const{db:n,auth:i,realtime:o,global:l}=s,{db:d,auth:c,realtime:u,global:h}=e,f={db:Gt(Gt({},d),n),auth:Gt(Gt({},c),i),realtime:Gt(Gt({},u),o),storage:{},global:Gt(Gt(Gt({},h),l),{},{headers:Gt(Gt({},(t=h==null?void 0:h.headers)!==null&&t!==void 0?t:{}),(r=l==null?void 0:l.headers)!==null&&r!==void 0?r:{})}),accessToken:async()=>""};return s.accessToken?f.accessToken=s.accessToken:delete f.accessToken,f}function tA(s){const e=s==null?void 0:s.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(Z1(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var sA=class extends U1{constructor(s){super(s)}},rA=class{constructor(s,e,t){var r,n;this.supabaseUrl=s,this.supabaseKey=e;const i=tA(s);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const o=`sb-${i.hostname.split(".")[0]}-auth-token`,l={db:z1,realtime:H1,auth:Gt(Gt({},q1),{},{storageKey:o}),global:G1},d=eA(t??{},l);if(this.storageKey=(r=d.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(n=d.global.headers)!==null&&n!==void 0?n:{},d.accessToken)this.accessToken=d.accessToken,this.auth=new Proxy({},{get:(u,h)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(h)} is not possible`)}});else{var c;this.auth=this._initSupabaseAuthClient((c=d.auth)!==null&&c!==void 0?c:{},this.headers,d.global.fetch)}this.fetch=J1(e,this._getAccessToken.bind(this),d.global.fetch),this.realtime=this._initRealtimeClient(Gt({headers:this.headers,accessToken:this._getAccessToken.bind(this)},d.realtime)),this.accessToken&&this.accessToken().then(u=>this.realtime.setAuth(u)).catch(u=>console.warn("Failed to set initial Realtime auth token:",u)),this.rest=new OS(new URL("rest/v1",i).href,{headers:this.headers,schema:d.db.schema,fetch:this.fetch}),this.storage=new LT(this.storageUrl.href,this.headers,this.fetch,t==null?void 0:t.storage),d.accessToken||this._listenForAuthEvents()}get functions(){return new CS(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(s){return this.rest.from(s)}schema(s){return this.rest.schema(s)}rpc(s,e={},t={head:!1,get:!1,count:void 0}){return this.rest.rpc(s,e,t)}channel(s,e={config:{}}){return this.realtime.channel(s,e)}getChannels(){return this.realtime.getChannels()}removeChannel(s){return this.realtime.removeChannel(s)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var s=this,e,t;if(s.accessToken)return await s.accessToken();const{data:r}=await s.auth.getSession();return(e=(t=r.session)===null||t===void 0?void 0:t.access_token)!==null&&e!==void 0?e:s.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:s,persistSession:e,detectSessionInUrl:t,storage:r,userStorage:n,storageKey:i,flowType:o,lock:l,debug:d,throwOnError:c},u,h){const f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new sA({url:this.authUrl.href,headers:Gt(Gt({},f),u),storageKey:i,autoRefreshToken:s,persistSession:e,detectSessionInUrl:t,storage:r,userStorage:n,flowType:o,lock:l,debug:d,throwOnError:c,fetch:h,hasCustomAuthorizationHeader:Object.keys(this.headers).some(m=>m.toLowerCase()==="authorization")})}_initRealtimeClient(s){return new ZS(this.realtimeUrl.href,Gt(Gt({},s),{},{params:Gt(Gt({},{apikey:this.supabaseKey}),s==null?void 0:s.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((s,e)=>{this._handleTokenChanged(s,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(s,e,t){(s==="TOKEN_REFRESHED"||s==="SIGNED_IN")&&this.changedAccessToken!==t?(this.changedAccessToken=t,this.realtime.setAuth(t)):s==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const nA=(s,e,t)=>new rA(s,e,t);
610function iA(){if(typeof window<"u")return!1;const s=globalThis.process;if(!s)return!1;const e=s.version;if(e==null)return!1;const t=e.match(/^v(\d+)\./);return t?parseInt(t[1],10)<=18:!1}iA()&&console.warn("⚠️  Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const aA="https://mgfwdrpalgzacqncgvcx.supabase.co",oA="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im1nZndkcnBhbGd6YWNxbmNndmN4Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3Njc4ODM4NzAsImV4cCI6MjA4MzQ1OTg3MH0.la0LtpnJZZcN7j0JMiiJD03BLf1Zs9jyNy9m5_h4znw",L=nA(aA,oA,{auth:{storage:localStorage,persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!0}}),lA="talentmatch_feed_cache_v2",cA="talentmatch_feed_cache_ts_v2";function dA(){try{localStorage.removeItem(lA),localStorage.removeItem(cA)}catch(s){console.warn("Failed to clear feed cache:",s)}}const md=new Map,Wo=new Map,uA="https://mgfwdrpalgzacqncgvcx.supabase.co/functions/v1/get-media-url",hA="https://mgfwdrpalgzacqncgvcx.supabase.co/functions/v1/media-token",fA="https://mgfwdrpalgzacqncgvcx.supabase.co/storage/v1/object/public";function kf(s){return`${fA}/${s}`}function mA(s){return s.startsWith("http://")||s.startsWith("https://")}async function ba(s,e){var o;const t=`${s}:${e}`,r=Wo.get(t);if(r&&r.expiresAt>Date.now()+3e4)return r.token;const{data:n}=await L.auth.getSession(),i=(o=n==null?void 0:n.session)==null?void 0:o.access_token;if(!i)return null;try{const l=await fetch(hA,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({type:s,id:e})});if(!l.ok)return null;const d=await l.json(),{token:c,expiresIn:u}=d;Wo.set(t,{token:c,expiresAt:Date.now()+u*1e3});try{document.cookie=`media_token=${c}; domain=.gradzen.com; path=/; max-age=${Math.max(u-20,60)}; SameSite=None; Secure`}catch{}return c}catch{return null}}function L0(s,e){const t=`${s}:${e}`,r=Wo.get(t);return r&&r.expiresAt>Date.now()+1e4?r.token:null}function _a(s,e){if(!e||!s)return s;const t=s.includes("?")?"&":"?";return`${s}${t}token=${e}`}async function pA(s,e,t){var o;const{data:r}=await L.auth.getSession(),n=(o=r==null?void 0:r.session)==null?void 0:o.access_token;if(!n)throw new Error("Not authenticated");const i=await fetch(uA,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({type:s,id:e,path:t})});if(!i.ok){const l=await i.json().catch(()=>({error:"Unknown error"}));throw new Error(l.error||`Failed to get signed URL: ${i.status}`)}return i.json()}function P0(s,e,t){const[r,n]=g.useState(null),[i,o]=g.useState(!1),[l,d]=g.useState(null),c=g.useRef(),u=`${s}:${e||""}:${t||""}`,h=t?mA(t):!1,f=g.useCallback(async()=>{if(!e&&!t)return;if(h&&t){n(t),o(!1),d(null);return}const m=md.get(u);if(m&&m.expiresAt>Date.now()+6e4){(s==="reel"||s==="course_video"||s==="chat_attachment")&&await ba(s==="reel"?"reel":s==="course_video"?"course":"chat_attachment",e||"").catch(()=>{}),n(m.url),o(!1),d(null);const p=m.expiresAt-Date.now()-5*6e4;p>0&&(c.current=setTimeout(f,p));return}t&&!h&&!t.endsWith(".m3u8")&&n(kf(t)),o(!0),d(null);try{const p=await pA(s,e||"",t||void 0),x=Date.now()+p.expiresIn*1e3;md.set(u,{url:p.signedUrl,expiresAt:x}),(s==="reel"||s==="course_video"||s==="chat_attachment")&&await ba(s==="reel"?"reel":s==="course_video"?"course":"chat_attachment",e||"").catch(()=>{}),n(p.signedUrl);const y=p.expiresIn*1e3-5*6e4;y>0&&(c.current=setTimeout(f,y))}catch(p){!r&&t&&n(kf(t)),d(p.message)}finally{o(!1)}},[s,e,t,u,h]);return g.useEffect(()=>(f(),()=>{c.current&&clearTimeout(c.current)}),[f]),{signedUrl:r,isLoading:i,error:l,refresh:f}}function gA(){md.clear(),Wo.clear()}function pd(){return a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:a.jsxs("div",{className:"animate-pulse flex flex-col items-center gap-4",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-primary/20"}),a.jsx("div",{className:"h-2 w-24 bg-muted rounded"})]})})}const H=g.forwardRef(({className:s,...e},t)=>a.jsx("div",{ref:t,className:C("animate-pulse rounded-md bg-muted",s),...e}));H.displayName="Skeleton";function xA({hasImage:s}={}){return a.jsxs("div",{className:"bg-card rounded-none p-4 border-x-0 border-t-0 border-b-2 border-b-muted-foreground
610/30 post-card-perf",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx(H,{className:"h-10 w-10 rounded-full flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx(H,{className:"h-4 w-28 mb-1.5"}),a.jsx(H,{className:"h-3 w-36"})]})]}),a.jsxs("div",{className:"space-y-2 mb-4",children:[a.jsx(H,{className:"h-4 w-full"}),a.jsx(H,{className:"h-4 w-[90%]"}),a.jsx(H,{className:"h-4 w-[60%]"})]}),s&&a.jsx(H,{className:"w-full h-[250px] mb-4"}),a.jsxs("div",{className:"flex items-center gap-4 pt-3 border-t",children:[a.jsx(H,{className:"h-8 w-20"}),a.jsx(H,{className:"h-8 w-20"}),a.jsx(H,{className:"h-8 w-20"})]})]})}function yA(){return a.jsxs("div",{className:"bg-card rounded-none p-4 border-x-0 border-t-0 border-b-2 border-b-muted-foreground/30",children:[a.jsxs("div",{className:"flex items-start gap-3 mb-3",children:[a.jsx(H,{className:"h-10 w-10 rounded-lg flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx(H,{className:"h-4 w-40 mb-1.5"}),a.jsx(H,{className:"h-3 w-28"})]})]}),a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(H,{className:"h-5 w-24 rounded-full"}),a.jsx(H,{className:"h-5 w-20 rounded-full"})]}),a.jsx(H,{className:"h-3.5 w-32 mb-3"}),a.jsxs("div",{className:"flex items-center justify-between pt-3 border-t",children:[a.jsx(H,{className:"h-3 w-28"}),a.jsx(H,{className:"h-8 w-20 rounded-md"})]})]})}function gd({className:s}){return a.jsxs("div",{className:`rounded-lg border bg-card p-6 ${s||""}`,children:[a.jsx(H,{className:"h-4 w-1/3 mb-4"}),a.jsx(H,{className:"h-8 w-1/2 mb-2"}),a.jsx(H,{className:"h-3 w-2/3"})]})}function On({count:s=4}){return a.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:Array.from({length:s}).map((e,t)=>a.jsx(gd,{},t))})}function vA(){return a.jsxs("div",{className:"flex items-center gap-4 py-4 border-b",children:[a.jsx(H,{className:"h-10 w-10 rounded-full"}),a.jsxs("div",{className:"flex-1 space-y-2",children:[a.jsx(H,{className:"h-4 w-1/3"}),a.jsx(H,{className:"h-3 w-1/4"})]}),a.jsx(H,{className:"h-6 w-20"}),a.jsx(H,{className:"h-8 w-24"})]})}function _r({rows:s=5}){return a.jsxs("div",{className:"rounded-lg border bg-card",children:[a.jsx("div",{className:"p-4 border-b",children:a.jsx(H,{className:"h-5 w-1/4"})}),a.jsx("div",{className:"p-4",children:Array.from({length:s}).map((e,t)=>a.jsx(vA,{},t))})]})}function bA(){return a.jsxs("div",{className:"space-y-2",children:[a.jsx(H,{className:"h-4 w-24"}),a.jsx(H,{className:"h-10 w-full"})]})}function Pr({fields:s=3}){return a.jsxs("div",{className:"rounded-lg border bg-card p-6 space-y-4",children:[a.jsx(H,{className:"h-5 w-1/3 mb-4"}),Array.from({length:s}).map((e,t)=>a.jsx(bA,{},t))]})}function _A(){return a.jsxs("div",{className:"flex items-center gap-4 p-4 rounded-lg border",children:[a.jsx(H,{className:"h-12 w-12 rounded-full"}),a.jsxs("div",{className:"flex-1 space-y-2",children:[a.jsx(H,{className:"h-4 w-1/3"}),a.jsx(H,{className:"h-3 w-1/2"})]}),a.jsx(H,{className:"h-8 w-20"})]})}function wA({items:s=5}){return a.jsx("div",{className:"space-y-3",children:Array.from({length:s}).map((e,t)=>a.jsx(_A,{},t))})}function ui(){return a.jsxs("div",{className:"rounded-lg border bg-card p-6",children:[a.jsx(H,{className:"h-5 w-1/4 mb-4"}),a.jsx(H,{className:"h-64 w-full"})]})}function D0({tabs:s=4}){return a.jsx("div",{className:"flex gap-2 mb-6",children:Array.from({length:s}).map((e,t)=>a.jsx(H,{className:"h-10 w-24"},t))})}function Rf(){return a.jsxs("div",{className:"max-w-4xl space-y-6",children:[a.jsx(On,{count:3}),a.jsx(ui,{}),a.jsx(_r,{rows:3})]})}function EA(){return a.jsxs("div",{className:"max-w-4xl space-y-6",children:[a.jsx(On,{count:2}),a.jsx(_r,{rows:8})]})}function SA(){return a.jsxs("div",{className:"max-w-4xl space-y-6",children:[a.jsx(On,{count:3}),a.jsx(_r,{rows:6})]})}function TA(){return a.jsxs("div",{className:"max-w-2xl space-y-6",children:[a.jsx(Pr,{fields:2}),a.jsx(Pr,{fields:3}),a.jsx(Pr,{fields:2})]})}function AA(){return a.jsxs("div",{className:"max-w-2xl space-y-6",children:[a.jsx(Pr,{fields:2}),a.jsx(Pr,{fields:1}),a.jsx(Pr,{fields:1})]})}function kA(){return a.jsxs("div",{className:"max-w-2xl space-y-6",children:[a.jsx(Pr,{fields:3}),a.jsx(Pr,{fields:2})]})}function RA(){return a.jsx("div",{className:"max-w-2xl space-y-6",children:a.jsxs("div",{className:"rounded-lg border bg-card p-6",children:[a.jsx(H,{className:"h-6 w-1/3 mb-4"}),a.jsx(H,{className:"h-4 w-full mb-2"}),a.jsx(H,{className:"h-4 w-3/4 mb-6"}),a.jsx(H,{className:"h-10 w-32"})]})})}function jA(){return a.jsx("div",{className:"max-w-2xl space-y-6",children:a.jsx(wA,{items:4})})}function IA(){return a.jsx("div",{className:"max-w-4xl space-y-4",children:Array.from({length:4}).map((s,e)=>a.jsx("div",{className:"rounded-lg border bg-card p-4",children:a.jsxs("div",{className:"flex items-start gap-4",children:[a.jsx(H,{className:"h-12 w-12 rounded"}),a.jsxs("div",{className:"flex-1 space-y-2",children:[a.jsx(H,{className:"h-5 w-1/3"}),a.jsx(H,{className:"h-4 w-1/4"}),a.jsxs("div",{className:"flex gap-2 mt-2",children:[a.jsx(H,{className:"h-6 w-16"}),a.jsx(H,{className:"h-6 w-20"})]})]}),a.jsx(H,{className:"h-8 w-24"})]})},e))})}function CA(){return a.jsxs("div",{className:"max-w-2xl space-y-6",children:[a.jsxs("div",{className:"rounded-lg border bg-card p-6",children:[a.jsx(H,{className:"h-6 w-1/3 mb-4"}),a.jsx(H,{className:"h-4 w-full mb-2"}),a.jsx(H,{className:"h-4 w-2/3 mb-6"})]}),a.jsx(Pr,{fields:4})]})}function NA(){return a.jsxs("div",{className:"space-y-6",children:[a.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:Array.from({length:4}).map((s,e)=>a.jsxs("div",{className:"rounded-lg border bg-card p-4",children:[a.jsx(H,{className:"h-4 w-20 mb-2"}),a.jsx(H,{className:"h-8 w-12"})]},e))}),Array.from({length:3}).map((s,e)=>a.jsx("div",{className:"rounded-lg border bg-card p-4",children:a.jsxs("div",{className:"flex items-start gap-4",children:[a.jsx(H,{className:"h-12 w-12 rounded"}),a.jsxs("div",{className:"flex-1 space-y-2",children:[a.jsx(H,{className:"h-5 w-1/3"}),a.jsx(H,{className:"h-4 w-1/4"}),a.jsx(H,{className:"h-6 w-24 mt-2"})]})]})},e))]})}function LA(){return a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx(H,{className:"h-8 w-48"}),a.jsx(H,{className:"h-10 w-32"})]}),a.jsx(_r,{rows:5})]})}function PA(){return a.jsxs("div",{className:"space-y-6",children:[a.jsx(On,{count:4}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[a.jsx(ui,{}),a.jsx(ui,{})]}),a.jsx(_r,{rows:5})]})}function DA(){return a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx(H,{className:"h-8 w-48"}),a.jsx(H,{className:"h-10 w-32"})]}),a.jsx(D0,{tabs:4}),a.jsx("div",{className:"grid gap-4",children:Array.from({length:4}).map((s,e)=>a.jsx("div",{className:"rounded-lg border bg-card p-4",children:a.jsxs("div",{className:"flex items-start gap-4",children:[a.jsx(H,{className:"h-12 w-12 rounded"}),a.jsxs("div",{className:"flex-1 space-y-2",children:[a.jsx(H,{className:"h-5 w-1/3"}),a.jsx(H,{className:"h-4 w-1/4"}),a.jsxs("div",{className:"flex gap-2 mt-2",children:[a.jsx(H,{className:"h-6 w-16"}),a.jsx(H,{className:"h-6 w-20"})]})]}),a.jsx(H,{className:"h-8 w-24"})]})},e))})]})}function OA(){return a.jsx("div",{className:"space-y-6",children:a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Array.from({length:6}).map((s,e)=>a.jsxs("div",{className:"rounded-lg border bg-card p-6",children:[a.jsx(H,{className:"h-10 w-10 mb-4"}),a.jsx(H,{className:"h-5 w-2/3 mb-2"}),a.jsx(H,{className:"h-4 w-full"}
610),a.jsx(H,{className:"h-4 w-3/4 mt-1"})]},e))})})}function jf(){return a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx(H,{className:"h-8 w-48"}),a.jsx(H,{className:"h-10 w-32"})]}),a.jsx(gd,{}),a.jsx(gd,{})]})}function MA(){return a.jsxs("div",{className:"space-y-6",children:[a.jsx(On,{count:4}),a.jsxs("div",{className:"flex gap-4 mb-4",children:[a.jsx(H,{className:"h-10 flex-1"}),a.jsx(H,{className:"h-10 w-32"})]}),a.jsx(_r,{rows:8})]})}function FA(){return a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"flex gap-4 mb-4",children:[a.jsx(H,{className:"h-10 flex-1"}),a.jsx(H,{className:"h-10 w-32"}),a.jsx(H,{className:"h-10 w-32"})]}),a.jsx(_r,{rows:10})]})}function $A(){return a.jsxs("div",{className:"space-y-6",children:[a.jsx(On,{count:3}),a.jsx(_r,{rows:8})]})}function UA(){return a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx(H,{className:"h-8 w-48"}),a.jsx(H,{className:"h-10 w-32"})]}),a.jsx(_r,{rows:6})]})}function BA(){return a.jsxs("div",{className:"space-y-6",children:[a.jsx(On,{count:4}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[a.jsx(ui,{}),a.jsx(ui,{})]}),a.jsx(ui,{})]})}function VA(){return a.jsxs("div",{className:"space-y-6",children:[a.jsx(D0,{tabs:3}),a.jsx(_r,{rows:6})]})}function GA(){return a.jsxs("div",{className:"flex h-[calc(100dvh-4rem)]",children:[a.jsxs("div",{className:"w-full md:w-80 md:border-r p-4 space-y-1",children:[a.jsx(H,{className:"h-10 w-full rounded-lg mb-4"}),Array.from({length:8}).map((s,e)=>a.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg",children:[a.jsx(H,{className:"h-12 w-12 rounded-full flex-shrink-0"}),a.jsxs("div",{className:"flex-1 space-y-1.5",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx(H,{className:"h-4 w-24"}),a.jsx(H,{className:"h-3 w-10"})]}),a.jsx(H,{className:"h-3 w-3/4"})]})]},e))]}),a.jsxs("div",{className:"hidden md:flex flex-1 flex-col",children:[a.jsxs("div",{className:"p-4 border-b flex items-center gap-3",children:[a.jsx(H,{className:"h-10 w-10 rounded-full"}),a.jsxs("div",{className:"space-y-1.5",children:[a.jsx(H,{className:"h-4 w-32"}),a.jsx(H,{className:"h-3 w-20"})]})]}),a.jsx("div",{className:"flex-1 p-4 space-y-4",children:Array.from({length:5}).map((s,e)=>a.jsx("div",{className:`flex ${e%2===0?"justify-start":"justify-end"}`,children:a.jsx(H,{className:`h-12 ${e%2===0?"w-2/3":"w-1/2"} rounded-lg`})},e))}),a.jsx("div",{className:"p-4 border-t",children:a.jsx(H,{className:"h-12 w-full rounded-lg"})})]})]})}function zA(){return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"px-4 pt-4",children:[a.jsx(H,{className:"h-6 w-36 mb-1"}),a.jsx(H,{className:"h-3.5 w-52"})]}),a.jsxs("div",{className:"flex gap-2 px-4",children:[a.jsx(H,{className:"h-9 w-20 rounded-full"}),a.jsx(H,{className:"h-9 w-24 rounded-full"})]}),a.jsxs("div",{className:"px-4",children:[a.jsx(H,{className:"h-4 w-24 mb-3"}),[1,2].map(s=>a.jsxs("div",{className:"flex items-center gap-3 py-3 border-b",children:[a.jsx(H,{className:"h-12 w-12 rounded-full flex-shrink-0"}),a.jsxs("div",{className:"flex-1 space-y-1.5",children:[a.jsx(H,{className:"h-4 w-28"}),a.jsx(H,{className:"h-3 w-40"})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(H,{className:"h-8 w-8 rounded-full"}),a.jsx(H,{className:"h-8 w-8 rounded-full"})]})]},s))]}),a.jsxs("div",{className:"px-4",children:[a.jsx(H,{className:"h-4 w-40 mb-3"}),a.jsx("div",{className:"grid grid-cols-2 gap-3",children:Array.from({length:4}).map((s,e)=>a.jsxs("div",{className:"rounded-lg border bg-card p-3 flex flex-col items-center gap-2",children:[a.jsx(H,{className:"h-14 w-14 rounded-full"}),a.jsx(H,{className:"h-3.5 w-20"}),a.jsx(H,{className:"h-3 w-24"}),a.jsx(H,{className:"h-8 w-full rounded-full mt-1"})]},e))})]})]})}function qA(){return a.jsxs("div",{className:"space-y-6",children:[a.jsx("div",{className:"rounded-lg border bg-card p-6",children:a.jsxs("div",{className:"flex items-start gap-6",children:[a.jsx(H,{className:"h-24 w-24 rounded-full"}),a.jsxs("div",{className:"flex-1 space-y-3",children:[a.jsx(H,{className:"h-7 w-48"}),a.jsx(H,{className:"h-4 w-64"}),a.jsx(H,{className:"h-4 w-32"}),a.jsxs("div",{className:"flex gap-2 mt-2",children:[a.jsx(H,{className:"h-8 w-24"}),a.jsx(H,{className:"h-8 w-24"})]})]})]})}),a.jsxs("div",{className:"rounded-lg border bg-card p-6",children:[a.jsx(H,{className:"h-5 w-24 mb-4"}),a.jsx(H,{className:"h-4 w-full"}),a.jsx(H,{className:"h-4 w-full mt-2"}
610),a.jsx(H,{className:"h-4 w-3/4 mt-2"})]}),a.jsxs("div",{className:"rounded-lg border bg-card p-6",children:[a.jsx(H,{className:"h-5 w-32 mb-4"}),Array.from({length:2}).map((s,e)=>a.jsxs("div",{className:"flex gap-4 mb-4",children:[a.jsx(H,{className:"h-12 w-12 rounded"}),a.jsxs("div",{className:"flex-1 space-y-2",children:[a.jsx(H,{className:"h-5 w-1/3"}),a.jsx(H,{className:"h-4 w-1/4"}),a.jsx(H,{className:"h-3 w-1/5"})]})]},e))]}),a.jsxs("div",{className:"rounded-lg border bg-card p-6",children:[a.jsx(H,{className:"h-5 w-20 mb-4"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from({length:8}).map((s,e)=>a.jsx(H,{className:"h-8 w-20"},e))})]})]})}function HA(){return a.jsxs("div",{className:"space-y-4 p-4",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(H,{className:"h-16 w-16 rounded-full flex-shrink-0"}),a.jsxs("div",{className:"flex-1 space-y-2",children:[a.jsx(H,{className:"h-5 w-32"}),a.jsx(H,{className:"h-3 w-48"})]}),a.jsx(H,{className:"h-5 w-5 rounded"})]}),a.jsx("div",{className:"grid grid-cols-3 gap-3",children:[1,2,3].map(s=>a.jsxs("div",{className:"flex flex-col items-center gap-2 rounded-lg border bg-card p-4",children:[a.jsx(H,{className:"h-8 w-8 rounded-full"}),a.jsx(H,{className:"h-3 w-12"})]},s))}),[1,2].map(s=>a.jsxs("div",{className:"space-y-1",children:[a.jsx(H,{className:"h-3 w-20 mb-2"}),[1,2,3].map(e=>a.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg",children:[a.jsx(H,{className:"h-5 w-5 rounded"}),a.jsx(H,{className:"h-4 w-28"})]},e))]},s))]})}function KA(){return a.jsxs("div",{children:[a.jsx("div",{className:"flex gap-3 p-4 border-b-2 border-b-muted-foreground/30 bg-card",children:Array.from({length:6}).map((s,e)=>a.jsxs("div",{className:"flex flex-col items-center gap-1.5 flex-shrink-0",children:[a.jsx(H,{className:"h-14 w-14 rounded-full"}),a.jsx(H,{className:"h-2.5 w-10"})]},e))}),a.jsxs("div",{className:"flex items-center gap-3 p-4 border-b-2 border-b-muted-foreground/30 bg-card",children:[a.jsx(H,{className:"h-10 w-10 rounded-full flex-shrink-0"}),a.jsx(H,{className:"h-10 flex-1 rounded-full"})]}),Array.from({length:3}).map((s,e)=>a.jsx(xA,{},e))]})}function WA(){return a.jsxs("div",{children:[a.jsxs("div",{className:"p-4 border-b-2 border-b-muted-foreground/30 bg-card",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[a.jsx(H,{className:"h-10 w-10 rounded-full flex-shrink-0"}),a.jsxs("div",{className:"flex-1 space-y-1.5",children:[a.jsx(H,{className:"h-4 w-40"}),a.jsx(H,{className:"h-3 w-56"})]})]}),a.jsx(H,{className:"h-2 w-full rounded-full"})]}),a.jsx("div",{className:"grid grid-cols-1 gap-0",children:Array.from({length:4}).map((s,e)=>a.jsx(yA,{},e))})]})}function YA(){return a.jsxs("div",{className:"space-y-4",children:[a.jsx("div",{className:"px-4 pt-4",children:a.jsx(H,{className:"h-10 w-full rounded-lg"})}),a.jsxs("div",{className:"px-4",children:[a.jsx(H,{className:"h-4 w-32 mb-3"}),a.jsx("div",{className:"flex gap-3 overflow-hidden",children:[1,2,3].map(s=>a.jsxs("div",{className:"flex-shrink-0 w-56 rounded-lg border bg-card p-3 space-y-2",children:[a.jsx(H,{className:"h-28 w-full rounded-lg"}),a.jsx(H,{className:"h-3.5 w-3/4"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(H,{className:"h-2 flex-1 rounded-full"}),a.jsx(H,{className:"h-3 w-8"})]})]},s))})]}),a.jsx("div",{className:"flex gap-2 px-4 overflow-hidden",children:[1,2,3,4,5].map(s=>a.jsx(H,{className:"h-8 w-20 rounded-full flex-shrink-0"},s))}),a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 px-4",children:Array.from({length:4}).map((s,e)=>a.jsxs("div",{className:"rounded-lg border bg-card p-4",children:[a.jsx(H,{className:"h-36 w-full rounded-lg mb-3"}),a.jsx(H,{className:"h-4 w-3/4 mb-2"}),a.jsx(H,{className:"h-3 w-1/2"})]},e))})]})}function XA(){return a.jsx("div",{className:"flex items-center justify-center py-20",children:a.jsxs("div",{className:"animate-pulse flex flex-col items-center gap-4",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-primary/20"}),a.jsx("div",{className:"h-2 w-24 bg-muted rounded"})]})})}function vu(){const{pathname:s}=br();return s==="/social"?a.jsx(KA,{}):s==="/dashboard"?a.jsx(WA,{}):s==="/my-network"?a.jsx(zA,{}):s==="/messenger"?a.jsx(GA,{}):s==="/menu"?a.jsx(HA,{}):s==="/courses"?a.jsx(YA,{}):s.startsWith("/profile")?a.jsx(qA,{}):s==="/applicant/account"?a.jsx(AA,{}):s==="/applicant/security"?a.jsx(kA,{}):s==="/applicant/pipeline"?a.jsx(NA,{}):s==="/applicant/hidden-jobs"?a.jsx(IA,{}):s==="/applicant/blocked-users"?a.jsx(jA,{}):s==="/applicant/delete-account"?a.jsx(RA,{}):s==="/applicant/request-verification"?a.jsx(CA,{}):s.startsWith("/admin/billing")?a.jsx(MA,{}):s.startsWith("/admin/transactions")?a.jsx(FA,{}):s.startsWith("/admin/invoices")?a.jsx($A,{}):s.startsWith("/admin/regional-pricing")?a.jsx(UA,{}):s.startsWith("/admin/revenue")?a.jsx(BA,{}):s.startsWith("/admin/identity")?a.jsx(VA,{}):s.startsWith("/admin")?a.jsx(jf,{}):s==="/billing/summary"?a.jsx(Rf,{}):s==="/billing/transactions"?a.jsx(EA,{}):s==="/billing/invoices"?a.jsx(SA,{}):s==="/billing/payment-settings"?a.jsx(TA,{}):s.startsWith("/billing")?a.jsx(Rf,{}):s.startsWith("/hr/aptitude")?a.jsx(LA,{}):s.startsWith("/hr/analytics")?a.jsx(PA,{}):s.startsWith("/hr/pipeline")?a.jsx(DA,{}):s.startsWith("/hr/learning")?a.jsx(OA,{}):s.startsWith("/hr")?a.jsx(jf,{}):a.jsx(XA,{})}let xd=!1;function O0(){const{user:s,loading:e}=$t();return e?a.jsx(pd,{}):s?F0||xd?null:(setTimeout(()=>{xd=!0},0),a.jsx(vu,{})):a.jsx(pd,{})}function QA(){xd=!1}const M0=g.createContext(void 0),JA="sb-mgfwdrpalgzacqncgvcx-auth-token";function ZA(){try{const s=localStorage.getItem(JA);if(!s)return{user:null,session:null};const e=JSON.parse(s);return e!=null&&e.access_token&&(e!=null&&e.user)?{user:e.user,session:e}:{user:null,session:null}}catch{return{user:null,session:null}}}let F0=!1;const So=ZA();So.user&&(F0=!0);function ek({children:s}){const[e,t]=g.useState(So.user),[r,n]=g.useState(So.session),[i,o]=g.useState(!So.user),[l,d]=g.useState(!0),[c,u]=g.useState(!1),[h,f]=g.useState(!1),m=g.useRef(null);g.useEffect(()=>{m.current=(e==null?void 0:e.id)??null},[e]);const p=async _=>{d(!0);try{const{data:b,error:w}=await L.from("user_roles").select("role").eq("user_id",_);!w&&b?(u(b.some(T=>T.role==="admin")),f(b.some(T=>T.role==="expert"))):(u(!1),f(!1))}catch{u(!1),f(!1)}finally{d(!1)}};g.useEffect(()=>{const{data:{subscription:_}}=L.auth.onAuthStateChange((b,w)=>{var S;const T=((S=w==null?void 0:w.user)==null?void 0:S.id)??null,A=m.current;if(o(!1),!T){n(null),t(null),u(!1),f(!1),d(!1);return}if(b==="TOKEN_REFRESHED"&&A===T){n(w);return}if(A===T){n(w);return}n(w),t(w.user),u(!1),f(!1),d(!0),setTimeout(()=>{p(T)},0)});return L.auth.getSession().then(({data:{session:b}})=>{n(b),t((b==null?void 0:b.user)??null),o(!1),b!=null&&b.user?(d(!0),p(b.user.id)):d(!1)}),()=>_.unsubscribe()},[]);const x=async(_,b,w)=>{const T=await L.functions.invoke("signup-user",{body:{email:_,password:b,fullName:w||""}}),{data:A,error:S}=T,I=T==null?void 0:T.response;if(S){let j=null;try{const k=S==null?void 0:S.context,D=k&&typeof k.clone=="function"?k:I&&typeof I.clone=="function"?I:null;D&&(j=await D.clone().json())}catch{}const R=(j==null?void 0:j.error)||(A==null?void 0:A.error)||S.message||"Failed to create account";return{error:new Error(R),needsEmailConfirmation:!1,alreadyExists:!!(j!=null&&j.alreadyExists),confirmed:!!(j!=null&&j.confirmed)}}return A!=null&&A.error?{error:new Error(A.error),needsEmailConfirmation:!1,alreadyExists:!!(A!=null&&A.alreadyExists),confirmed:!!(A!=null&&A.confirmed)}:{error:null,needsEmailConfirmation:!0}},y=async(_,b)=>{const{error:w}=await L.auth.signInWithPassword({email:_,password:b});return{error:w}},v=async()=>{try{await L.auth.signOut()}catch(_){console.warn("Sign out error:",_)}
610t(null),n(null),u(!1),f(!1),localStorage.removeItem("tm_rq_cache"),dA(),gA(),QA()};return a.jsx(M0.Provider,{value:{user:e,session:r,loading:i,rolesLoading:l,isAdmin:c,isExpert:h,signUp:x,signIn:y,signOut:v},children:s})}const tk={user:null,session:null,loading:!1,rolesLoading:!1,isAdmin:!1,isExpert:!1,signUp:async()=>({error:new Error("Auth not initialized")}),signIn:async()=>({error:new Error("Auth not initialized")}),signOut:async()=>{}};function $t(){const s=g.useContext(M0);return s===void 0?tk:s}function If(s){return{id:s.id,userId:s.user_id,creditLimit:Number(s.credit_limit),usedAmount:Number(s.used_amount),dueAmount:Number(s.due_amount),balance:Number(s.balance||0),refundableBalance:Number(s.refundable_balance||0),trustScore:s.trust_score,status:s.status,region:s.region,currency:s.currency,displayCurrency:s.display_currency||null,timezone:s.timezone||"UTC",payEarlyEnabled:s.pay_early_enabled,paymentThreshold:Number(s.payment_threshold||500),thresholdIndex:s.threshold_index||0,maxPaymentThreshold:s.max_payment_threshold?Number(s.max_payment_threshold):null,accountScore:s.account_score||50,lastScoreUpdate:s.last_score_update,scoreChangeReason:s.score_change_reason,billingDay:s.billing_day||1,nextBillingDate:s.next_billing_date,lifetimePaid:Number(s.lifetime_paid||0),successfulPayments:s.successful_payments||0,failedPayments:s.failed_payments||0,chargebacks:s.chargebacks||0,lastThresholdChangeAt:s.last_threshold_change_at,thresholdChangeDirection:s.threshold_change_direction,createdAt:s.created_at,updatedAt:s.updated_at}}function Cf(s){return{id:s.id,userId:s.user_id,brand:s.brand,last4:s.last4,isPrimary:s.is_primary,isBackup:s.is_backup,token:s.token,expiresAt:s.expires_at,createdAt:s.created_at}}function Nf(s){return{id:s.id,userId:s.user_id,invoiceNumber:s.invoice_number,amount:Number(s.amount),status:s.status,description:s.description,serviceType:s.service_type,serviceReferenceId:s.service_reference_id,createdAt:s.created_at,paidAt:s.paid_at,paymentMethodId:s.payment_method_id,writeOffDate:s.write_off_date,writeOffReason:s.write_off_reason}}function Lf(s){return{id:s.id,userId:s.user_id,type:s.type,subtype:s.subtype,reference:s.reference,amount:Number(s.amount),createdBy:s.created_by,actorId:s.actor_id,note:s.note,invoiceId:s.invoice_id,serviceContext:s.service_context||"general",metadata:s.metadata,createdAt:s.created_at}}function sk(s){return{id:s.id,userId:s.user_id,previousScore:s.previous_score,newScore:s.new_score,changeAmount:s.change_amount,reason:s.reason,thresholdChanged:s.threshold_changed,oldThreshold:s.old_threshold?Number(s.old_threshold):null,newThreshold:s.new_threshold?Number(s.new_threshold):null,relatedInvoiceId:s.related_invoice_id,createdAt:s.created_at}}function ic(s){return{id:s.id,countryCode:s.country_code,countryName:s.country_name,currency:s.currency,timezone:s.timezone||"UTC",initialThresholdIndex:s.initial_threshold_index,thresholdProgression:s.threshold_progression||[],initialAccountScore:s.initial_account_score??60,jobPostPrice:Number(s.job_post_price),jobBoostPrice:Number(s.job_boost_price),profileMatchPrice:Number(s.profile_match_price),cvHighlightPrice:Number(s.cv_highlight_price),aptitudeTestPrice:Number(s.aptitude_test_price),projectCommissionRate:Number(s.project_commission_rate??20),withdrawalFlatFee:Number(s.withdrawal_flat_fee??0),withdrawalPercentFee:Number(s.withdrawal_percent_fee??0),minimumWithdrawalAmount:Number(s.minimum_withdrawal_amount??500),referralBonusAmount:Number(s.referral_bonus_amount??0),isActive:s.is_active,createdAt:s.created_at,updatedAt:s.updated_at}}function yd(s){return{id:s.id,userId:s.user_id,methodType:s.method_type,methodKey:s.method_key,accountNumber:s.account_number,accountName:s.account_name,bankName:s.bank_name||void 0,branchName:s.branch_name||void 0,routingNumber:s.routing_number||void 0,isPrimary:s.is_primary,isVerified:s.is_verified,createdAt:s.created_at,updatedAt:s.updated_at}}function Pf(s){return{id:s.id,userId:s.user_id,withdrawalMethodId:s.withdrawal_method_id,amount:Number(s.amount),currency:s.currency,flatFee:Number(s.flat_fee),percentFee:Number(s.percent_fee),totalFee:Number(s.total_fee),netAmount:Number(s.net_amount),status:s.status,adminId:s.admin_id||void 0,adminNote:s.admin_note||void 0,transactionReference:s.transaction_reference||void 0,processedAt:s.processed_at||void 0,createdAt:s.created_at,withdrawalMethod:s.withdrawal_methods?yd(s.withdrawal_methods):void 0,profile:s.profiles?{fullName:s.profiles.full_name||"",email:s.profiles.email||"",avatarUrl:s.profiles.avatar_url||""}:void 0}}const Df={async getWallet(s){const{data:e,error:t}=await L.from("user_wallets").select("*").eq("user_id",s).maybeSingle();if(t)throw t;return e?If(e):null},async createWallet(s,e="BD"){const{data:t,error:r}=await L.rpc("create_user_wallet",{p_user_id:s,p_region:e});if(r)throw r;return this.getWallet(s)},async getPaymentMethods(s){const{data:e,error:t}=await L.from("wallet_payment_methods").select("*").eq("user_id",s).order("created_at",{ascending:!1});if(t)throw t;return(e||[]).map(Cf)},async addPaymentMethod(s,e,t){const{count:r}=await L.from("wallet_payment_methods").select("*",{count:"exact",head:!0}).eq("user_id",s),n=(r||0)===0,{data:i,error:o}=await L.from("wallet_payment_methods").insert({user_id:s,brand:e,last4:t,is_primary:n,is_backup:!1}).select().single();if(o)throw o;return Cf(i)},async setPrimaryMethod(s,e){await L.from("wallet_payment_methods").update({is_primary:!1}).eq("user_id",s);const{error:t}=await L.from("wallet_payment_methods").update({is_primary:!0}).eq("id",e);if(t)throw t},async setBackupMethod(s,e){await L.from("wallet_payment_methods").update({is_backup:!1}).eq("user_id",s);const{error:t}=await L.from("wallet_payment_methods").update({is_backup:!0}).eq("id",e);if(t)throw t},async getInvoices(s){const{data:e,error:t}=await L.from("wallet_invoices").select("*").eq("user_id",s).order("created_at",{ascending:!1});if(t)throw t;return(e||[]).map(Nf)},async getLedger(s,e=50,t){let r=L.from("wallet_ledger").select("*").eq("user_id",s).order("created_at",{ascending:!1}).limit(e);t&&(r=r.eq("service_context",t));const{data:n,error:i}=await r;if(i)throw i;return(n||[]).map(Lf)},async getScoreHistory(s,e=20){const{data:t,error:r}=await L.from("wallet_score_history").select("*").eq("user_id",s).order("created_at",{ascending:!1}).limit(e);
610if(r)throw r;return(t||[]).map(sk)},async getBillingCountryConfigs(){const{data:s,error:e}=await L.from("billing_country_config").select("*").eq("is_active",!0).order("country_name");if(e)throw e;return(s||[]).map(ic)},async getCountryConfig(s){const{data:e,error:t}=await L.from("billing_country_config").select("*").eq("country_code",s).eq("is_active",!0).maybeSingle();if(t)throw t;return e?ic(e):null},async payEarly(s,e,t){const{data:r,error:n}=await L.rpc("process_wallet_payment",{p_user_id:s,p_amount:e,p_payment_method_id:t||null});if(n)throw n;return r},async payFromEarnings(s){const{data:e,error:t}=await L.rpc("auto_pay_from_earnings",{p_user_id:s});if(t)throw t;return e},async chargeService(s,e,t,r,n,i="general"){const{data:o,error:l}=await L.rpc("charge_wallet",{p_user_id:s,p_amount:e,p_service_type:t,p_description:r,p_reference_id:n||null,p_service_context:i});if(l)throw l;return o},async updateWalletPreferences(s,e){const t={};e.payEarlyEnabled!==void 0&&(t.pay_early_enabled=e.payEarlyEnabled),e.maxPaymentThreshold!==void 0&&(t.max_payment_threshold=e.maxPaymentThreshold),e.billingDay!==void 0&&(t.billing_day=e.billingDay);const{error:r}=await L.from("user_wallets").update(t).eq("user_id",s);if(r)throw r},async changeRegion(s,e){const t=await this.getCountryConfig(e);if(!t)throw new Error("Country not supported");const r=t.thresholdProgression[0],n=t.thresholdProgression[t.thresholdProgression.length-1],{error:i}=await L.from("user_wallets").update({region:e,currency:t.currency,timezone:t.timezone,payment_threshold:r,threshold_index:0,credit_limit:n}).eq("user_id",s);if(i)throw i},async setDisplayCurrency(s,e){const{error:t}=await L.from("user_wallets").update({display_currency:e}).eq("user_id",s);if(t)throw t},async changeTimezone(s,e){const{error:t}=await L.from("user_wallets").update({timezone:e}).eq("user_id",s);if(t)throw t},async freezeWallet(s){const{error:e}=await L.from("user_wallets").update({status:"frozen"}).eq("user_id",s);if(e)throw e},async unfreezeWallet(s){const{error:e}=await L.from("user_wallets").update({status:"active"}).eq("user_id",s);if(e)throw e},async setCreditLimit(s,e,t="Admin override"){const{data:r}=await L.from("user_wallets").select("credit_limit").eq("user_id",s).single(),n=(r==null?void 0:r.credit_limit)||0,{error:i}=await L.from("user_wallets").update({credit_limit:e}).eq("user_id",s);if(i)throw i;const{error:o}=await L.from("wallet_ledger").insert({user_id:s,type:"adjustment",subtype:"credit_limit_override",reference:`LIMIT-${Date.now()}`,amount:0,created_by:"admin",note:t,service_context:"general",metadata:{old_limit:n,new_limit:e,reason:t}});o&&console.error("Failed to create audit entry:",o)},async adminAdjustScore(s,e,t){const{data:r,error:n}=await L.rpc("admin_adjust_score",{p_user_id:s,p_change:e,p_reason:t});if(n)throw n;return r},async recordChargeback(s,e,t){const{data:r,error:n}=await L.rpc("record_chargeback",{p_user_id:s,p_invoice_id:e,p_admin_note:t||null});if(n)throw n;return r},async getSpendChart(s,e=30){const{data:t,error:r}=await L.rpc("get_wallet_spend_chart",{p_user_id:s,p_days:e});if(r)throw r;return(t||[]).map(n=>({date:n.date,amount:Number(n.amount)}))},async getServicePrice(s,e){const{data:t,error:r}=await L.rpc("get_service_price",{p_user_id:s,p_service_type:e});if(r)throw r;return Number(t)||0},async getAllWallets(s){let e=L.from("user_wallets").select(`
611        *,
612        profiles!user_wallets_user_id_fkey (
613          full_name,
614          email,
615          avatar_url
616        )
617      `).order("created_at",{ascending:!1});s&&(e=e.eq("status",s));const{data:t,error:r}=await e;if(r)throw r;return(t||[]).map(n=>{const i=If(n);return n.profiles&&(i.userName=n.profiles.full_name||void 0,i.userEmail=n.profiles.email||void 0,i.userAvatar=n.profiles.avatar_url||void 0),i})},async getAllInvoices(s){let e=L.from("wallet_invoices").select("*").order("created_at",{ascending:!1});s&&(e=e.eq("status",s));const{data:t,error:r}=await e;if(r)throw r;return(t||[]).map(Nf)},async getAllLedger(s=100){const{data:e,error:t}=await L.from("wallet_ledger").select("*").order("created_at",{ascending:!1}).limit(s);if(t)throw t;return(e||[]).map(Lf)},async getAllCountryConfigs(){const{data:s,error:e}=await L.from("billing_country_config").select("*").order("country_name");if(e)throw e;return(s||[]).map(ic)},async updateCountryConfig(s,e){const t={updated_at:new Date().toISOString()};e.thresholdProgression!==void 0&&(t.threshold_progression=e.thresholdProgression),e.initialThresholdIndex!==void 0&&(t.initial_threshold_index=e.initialThresholdIndex),e.initialAccountScore!==void 0&&(t.initial_account_score=e.initialAccountScore),e.jobPostPrice!==void 0&&(t.job_post_price=e.jobPostPrice),e.jobBoostPrice!==void 0&&(t.job_boost_price=e.jobBoostPrice),e.profileMatchPrice!==void 0&&(t.profile_match_price=e.profileMatchPrice),e.cvHighlightPrice!==void 0&&(t.cv_highlight_price=e.cvHighlightPrice),e.projectCommissionRate!==void 0&&(t.project_commission_rate=e.projectCommissionRate),e.aptitudeTestPrice!==void 0&&(t.aptitude_test_price=e.aptitudeTestPrice),e.withdrawalFlatFee!==void 0&&(t.withdrawal_flat_fee=e.withdrawalFlatFee),e.withdrawalPercentFee!==void 0&&(t.withdrawal_percent_fee=e.withdrawalPercentFee),e.minimumWithdrawalAmount!==void 0&&(t.minimum_withdrawal_amount=e.minimumWithdrawalAmount),e.referralBonusAmount!==void 0&&(t.referral_bonus_amount=e.referralBonusAmount),e.isActive!==void 0&&(t.is_active=e.isActive);const{error:r}=await L.from("billing_country_config").update(t).eq("id",s);if(r)throw r},async syncWalletThresholds(s){const{data:e,error:t}=await L.rpc("sync_wallet_thresholds_for_region",{p_country_code:s});if(t)throw console.error("Failed to sync wallet thresholds:",t),t;return e||0},async writeOffInvoice(s,e){const{error:t}=await L.from("wallet_invoices").update({status:"written_off",write_off_date:new Date().toISOString(),write_off_reason:e}).eq("id",s);if(t)throw t},async getInvoiceAging(){const{data:s,error:e}=await L.rpc("get_invoice_aging");if(e)throw e;return(s||[]).map(t=>({ageBucket:t.age_bucket,totalAmount:Number(t.total_amount),invoiceCount:Number(t.invoice_count)}))},async getPendingEarnings(s){const{data:e,error:t}=await L.from("user_wallets").select("region").eq("user_id",s).single(),r=(e==null?void 0:e.region)||"BD",{data:n,error:i}=await L.from("billing_country_config").select("project_commission_rate").eq("country_code",r).single(),o=(n==null?void 0:n.project_commission_rate)??20,{data:l,error:d}=await L.from("project_applications").select("project_id").eq("applicant_id",s).in("status",["confirmed","work_completed","delivered"]);if(d)throw d;if(!l||l.length===0)return[];const c=l.map(v=>v.project_id),{data:u,error:h}=await L.from("project_escrow").select(`
618        id,
619        project_id,
620        amount,
621        pre_paid_completion_amount,
622        currency,
623        status,
624        dispute_deadline,
625        available_at,
626        created_at,
627        marketplace_projects!project_escrow_project_id_fkey (title)
628      `).in("project_id",c).in("status",["held","pending_dispute_window","disputed","pending_release"]);if(h)throw h;const{data:f}=await L.from("marketplace_projects").select("id, agreed_amount").in("id",c),m=new Map((f||[]).map(v=>[v.id,Number(v.agreed_amount)])),p=(u||[]).map(v=>{var A;const b=m.get(v.project_id)||Number(v.amount)+Number(v.pre_paid_completion_amount||0),w=Math.round(b*(o/100)
628*100)/100,T=b-w;return{id:v.id,projectId:v.project_id,projectTitle:((A=v.marketplace_projects)==null?void 0:A.title)||"Unknown Project",amount:b,grossAmount:b,commissionRate:o,commissionAmount:w,netAmount:T,currency:v.currency,status:v.status,disputeDeadline:v.dispute_deadline,availableAt:v.available_at,createdAt:v.created_at}}),{data:x}=await L.from("mentorship_escrow").select(`
629        id, booking_id, amount, currency, status, available_at, created_at,
630        mentorship_bookings!mentorship_escrow_booking_id_fkey ( listing_id ),
631        mentorship_listings:mentorship_bookings!mentorship_escrow_booking_id_fkey ( listing_id )
632      `).eq("payee_id",s).in("status",["held","pending_release"]);let y=[];if(x&&x.length>0){const v=x.map(S=>S.booking_id),{data:_}=await L.from("mentorship_bookings").select("id, listing_id").in("id",v),b=[...new Set((_||[]).map(S=>S.listing_id))],{data:w}=await L.from("mentorship_listings").select("id, title").in("id",b),T=new Map((_||[]).map(S=>[S.id,S.listing_id])),A=new Map((w||[]).map(S=>[S.id,S.title]));y=x.map(S=>{const I=Number(S.amount),j=Math.round(I*(o/100)*100)/100,R=I-j,k=T.get(S.booking_id);return{id:S.id,projectId:S.booking_id,projectTitle:`Mentorship: ${A.get(k)||"Session"}`,amount:I,grossAmount:I,commissionRate:o,commissionAmount:j,netAmount:R,currency:S.currency,status:S.status,disputeDeadline:null,availableAt:S.available_at,createdAt:S.created_at}})}return[...p,...y]},async getCompletedEarnings(s){const{data:e}=await L.from("user_wallets").select("region").eq("user_id",s).single(),t=(e==null?void 0:e.region)||"BD",{data:r}=await L.from("billing_country_config").select("project_commission_rate").eq("country_code",t).single(),n=(r==null?void 0:r.project_commission_rate)??20,{data:i,error:o}=await L.from("project_escrow").select(`
633        id,
634        project_id,
635        amount,
636        pre_paid_completion_amount,
637        currency,
638        released_at,
639        created_at,
640        marketplace_projects!project_escrow_project_id_fkey (id, title, agreed_amount)
641      `).eq("payee_id",s).eq("status","released_to_freelancer").order("released_at",{ascending:!1});if(o)throw o;const l=(i||[]).map(u=>{var p,x;const h=(p=u.marketplace_projects)!=null&&p.agreed_amount?Number(u.marketplace_projects.agreed_amount):Number(u.amount)+Number(u.pre_paid_completion_amount||0),f=Math.round(h*(n/100)*100)/100,m=h-f;return{id:u.id,projectId:u.project_id,projectTitle:((x=u.marketplace_projects)==null?void 0:x.title)||"Unknown Project",grossAmount:h,commissionRate:n,commissionAmount:f,netAmount:m,currency:u.currency,releasedAt:u.released_at,createdAt:u.created_at}}),{data:d}=await L.from("mentorship_escrow").select("id, booking_id, amount, currency, released_at, created_at").eq("payee_id",s).eq("status","released").order("released_at",{ascending:!1});let c=[];if(d&&d.length>0){const u=d.map(y=>y.booking_id),{data:h}=await L.from("mentorship_bookings").select("id, listing_id").in("id",u),f=[...new Set((h||[]).map(y=>y.listing_id))],{data:m}=await L.from("mentorship_listings").select("id, title").in("id",f),p=new Map((h||[]).map(y=>[y.id,y.listing_id])),x=new Map((m||[]).map(y=>[y.id,y.title]));c=d.map(y=>{const v=Number(y.amount),_=Math.round(v*(n/100)*100)/100,b=v-_,w=p.get(y.booking_id);return{id:y.id,projectId:y.booking_id,projectTitle:`Mentorship: ${x.get(w)||"Session"}`,grossAmount:v,commissionRate:n,commissionAmount:_,netAmount:b,currency:y.currency,releasedAt:y.released_at,createdAt:y.created_at}})}return[...l,...c]},async getWithdrawalMethods(s){const{data:e,error:t}=await L.from("withdrawal_methods").select("*").eq("user_id",s).order("is_primary",{ascending:!1}).order("created_at",{ascending:!1});if(t)throw t;return(e||[]).map(yd)},async addWithdrawalMethod(s,e){const{count:t}=await L.from("withdrawal_methods").select("*",{count:"exact",head:!0}).eq("user_id",s),r=(t||0)===0,{data:n,error:i}=await L.from("withdrawal_methods").insert({user_id:s,method_type:e.methodType,method_key:e.methodKey,account_number:e.accountNumber,account_name:e.accountName,bank_name:e.bankName||null,branch_name:e.branchName||null,routing_number:e.routingNumber||null,is_primary:r,is_verified:!1}).select().single();if(i)throw i;return yd(n)},async updateWithdrawalMethod(s,e){const t={};e.accountNumber!==void 0&&(t.account_number=e.accountNumber),e.accountName!==void 0&&(t.account_name=e.accountName),e.bankName!==void 0&&(t.bank_name=e.bankName),e.branchName!==void 0&&(t.branch_name=e.branchName),e.routingNumber!==void 0&&(t.routing_number=e.routingNumber);const{error:r}=await L.from("withdrawal_methods").update(t).eq("id",s);if(r)throw r},async deleteWithdrawalMethod(s){const{error:e}=await L.from("withdrawal_methods").delete().eq("id",s);if(e)throw e},async setPrimaryWithdrawalMethod(s,e){await L.from("withdrawal_methods").update({is_primary:!1}).eq("user_id",s);const{error:t}=await L.from("withdrawal_methods").update({is_primary:!0}).eq("id",e);if(t)throw t},async getWithdrawalRequests(s){const{data:e,error:t}=await L.from("withdrawal_requests").select(`
642        *,
643        withdrawal_methods (*)
644      `).eq("user_id",s).order("created_at",{ascending:!1});if(t)throw t;return(e||[]).map(Pf)},async requestWithdrawal(s,e,t){const{data:r,error:n}=await L.rpc("create_withdrawal_request",{p_user_id:s,p_method_id:e,p_amount:t});if(n)throw n;const i=r;return i.success?{success:!0,requestId:i.request_id,feeBreakdown:{flatFee:i.flat_fee,percentFee:i.percent_fee,totalFee:i.total_fee,netAmount:i.net_amount}}:{success:!1,error:i.error}},async cancelWithdrawal(s,e){const{data:t,error:r}=await L.rpc("cancel_withdrawal",{p_request_id:s,p_user_id:e});if(r)throw r;return t},async getAllWithdrawalRequests(s){let e=L.from("withdrawal_requests").select(`
645        *,
646        withdrawal_methods (*)
647      `).order("created_at",{ascending:!1});s&&(e=e.eq("status",s));const{data:t,error:r}=await e;if(r)throw r;const n=[...new Set((t||[]).map(o=>
647o.user_id))];let i=new Map;if(n.length>0){const{data:o}=await L.rpc("get_profiles_admin",{p_user_ids:n});i=new Map((o||[]).map(l=>[l.user_id,{full_name:l.full_name,email:l.email,avatar_url:l.avatar_url}]))}return(t||[]).map(o=>({...o,profiles:i.get(o.user_id)||null})).map(Pf)},async processWithdrawal(s,e,t,r){const{data:n,error:i}=await L.rpc("process_withdrawal",{p_request_id:s,p_admin_id:e,p_action:t,p_transaction_reference:r.transactionReference||null,p_admin_note:r.adminNote||null});if(i)throw i;return n},async verifyWithdrawalMethod(s){const{error:e}=await L.from("withdrawal_methods").update({is_verified:!0}).eq("id",s);if(e)throw e}},rk={currentMode:"job_seeker",hasHRAccess:!1,isCollaboratorOnly:!1,hrCompanyName:null,hrCompanyLogo:null,hrCompanyVerified:!1,isLoading:!0,switchMode:async()=>{},enableHRAccess:async()=>{}},$0=g.createContext(rk);function nk({children:s}){const[e,t]=g.useState(null),[r,n]=g.useState("job_seeker"),[i,o]=g.useState(!1),[l,d]=g.useState(!1),[c,u]=g.useState(null),[h,f]=g.useState(null),[m,p]=g.useState(!1),[x,y]=g.useState(!0);g.useEffect(()=>{const{data:{subscription:w}}=L.auth.onAuthStateChange((T,A)=>{var S;T==="TOKEN_REFRESHED"&&((S=A==null?void 0:A.user)==null?void 0:S.id)===(e==null?void 0:e.id)||t((A==null?void 0:A.user)??null)});return L.auth.getSession().then(({data:{session:T}})=>{t((T==null?void 0:T.user)??null)}),()=>w.unsubscribe()},[e==null?void 0:e.id]),g.useEffect(()=>{e?v():(n("job_seeker"),o(!1),d(!1),u(null),f(null),p(!1),y(!1))},[e]);const v=async()=>{if(e){y(!0);try{const[w,T]=await Promise.all([L.from("profiles").select("current_mode, has_hr_access, hr_company_name, hr_company_logo, hr_company_verified, role").eq("user_id",e.id).single(),L.from("job_collaborators").select("id").eq("user_id",e.id).limit(1)]);if(w.error)throw w.error;const A=w.data,S=T.data&&T.data.length>0||!1;if(A){const I=A.has_hr_access||A.role==="hr";o(I||S),d(!I&&S),n(A.current_mode||"job_seeker"),u(A.hr_company_name),f(A.hr_company_logo),p(A.hr_company_verified||!1)}}catch(w){console.error("Error fetching mode data:",w)}finally{y(!1)}}},_=async w=>{console.warn("switchMode is deprecated. Use sidebar HR Overview instead.")},b=async(w,T)=>{if(e)try{const{error:A}=await L.from("profiles").update({has_hr_access:!0,hr_enabled_at:new Date().toISOString(),hr_company_name:w,hr_company_logo:T||null,current_mode:"hr"}).eq("user_id",e.id);if(A)throw A;try{await Df.getWallet(e.id)||await Df.createWallet(e.id,"BD")}catch(S){console.error("Error creating wallet:",S)}o(!0),u(w),f(T||null),n("hr")}catch(A){throw console.error("Error enabling HR access:",A),A}};return a.jsx($0.Provider,{value:{currentMode:r,hasHRAccess:i,isCollaboratorOnly:l,hrCompanyName:c,hrCompanyLogo:h,hrCompanyVerified:m,isLoading:x,switchMode:_,enableHRAccess:b},children:s})}function U0(){return g.useContext($0)}const B0=g.createContext(void 0);function ik({children:s}){const{user:e}=$t(),[t,r]=g.useState(null),{data:n=[],isLoading:i,refetch:o}=Wt({queryKey:["user-pages",e==null?void 0:e.id],queryFn:async()=>{if(!(e!=null&&e.id))return[];const{data:c,error:u}=await L.from("page_roles").select("page_id, role, pages:page_id(id, name, slug, logo_url, category, has_hr_access, is_verified, verification_type)").eq("user_id",e.id);if(u)throw u;return(c||[]).map(h=>h.pages).filter(Boolean)},enabled:!!(e!=null&&e.id),staleTime:1e3*60*5}),l=g.useCallback(c=>{r(c)},[]),d=g.useCallback(()=>{r(null)},[]);return a.jsx(B0.Provider,{value:{activePage:t,switchToPage:l,switchToPersonal:d,isPageMode:!!t,userPages:n,userPagesLoading:i,refetchPages:o},children:s})}function bu(){const s=g.useContext(B0);return s||{activePage:null,switchToPage:()=>{},switchToPersonal:()=>{},isPageMode:!1,userPages:[],userPagesLoading:!1,refetchPages:()=>{}}}const _u=Pn("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),ye=g.forwardRef(({className:s,variant:e,size:t,asChild:r=!1,...n},i)=>{const o=r?Pi:"button";return a.jsx(o,{className:C(_u({variant:e,size:t,className:s})),ref:i,...n})});ye.displayName="Button";const ak=({message:s})=>{const e=()=>{window.location.reload()};return a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:a.jsxs("div",{className:"max-w-md w-full text-center space-y-6",children:[a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:a.jsx("div",{className:"w-32 h-32 bg-primary/10 rounded-full animate-pulse"})}),a.jsx(du,{className:"h-20 w-20 mx-auto text-primary relative z-10"})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("h1",{className:"text-3xl font-bold text-foreground",children:"Under Maintenance"}),a.jsx("p",{className:"text-muted-foreground text-lg",children:s||"We're currently performing scheduled maintenance. Please check back soon."})]}),a.jsx("div",{className:"pt-4",children:a.jsxs(ye,{variant:"outline",onClick:e,className:"gap-2",children:[a.jsx(ha,{className:"h-4 w-4"}),"Check Again"]})}),a.jsx("p",{className:"text-xs text-muted-foreground pt-8",children:"We ap
647ologize for any inconvenience. Our team is working hard to bring the site back online."})]})})},ok=["/auth","/signup-success","/terms","/privacy","/social","/reels","/courses","/profile","/u","/page"],lk=({children:s})=>{const{user:e,loading:t,rolesLoading:r,isAdmin:n,isExpert:i}=$t(),o=br(),[l,d]=g.useState(!1),[c,u]=g.useState(""),{data:h,isLoading:f}=Wt({queryKey:["maintenance-mode-check"],queryFn:async()=>{const{data:m,error:p}=await L.from("site_settings").select("setting_value").eq("setting_key","maintenance_mode").maybeSingle();return p?(console.error("Error fetching maintenance settings:",p),null):(m==null?void 0:m.setting_value)??null},refetchInterval:5*60*1e3,staleTime:4*60*1e3});return g.useEffect(()=>{if(!h){d(!1);return}const m=h,p=new Date;let x=m.enabled;if(m.scheduled_start&&m.scheduled_end){const y=new Date(m.scheduled_start),v=new Date(m.scheduled_end);p>=y&&p<=v&&(x=!0)}d(x),u(m.message||"")},[h]),t||f?a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:a.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})}):l?ok.some(x=>o.pathname===x||o.pathname.startsWith(x+"/"))?a.jsx(a.Fragment,{children:s}):((h==null?void 0:h.allow_admin_access)??!0)&&!r&&(n||i)?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed top-0 left-0 right-0 z-[100] bg-destructive text-destructive-foreground py-2 px-4 text-center text-sm font-medium shadow-lg",children:"🔧 Maintenance mode is active. Regular users cannot access the site."}),a.jsx("div",{className:"mt-10",children:s})]}):a.jsx(ak,{message:c}):a.jsx(a.Fragment,{children:s})};function Te({children:s}){const{user:e,loading:t,rolesLoading:r,isAdmin:n}=$t(),i=hs(),o=t||r;return g.useEffect(()=>{!o&&(!e||!n)&&i("/social")},[o,e,n,i]),o?a.jsx("div",{className:"flex items-center justify-center h-screen",children:a.jsx(ts,{className:"h-8 w-8 animate-spin text-primary"})}):!e||!n?null:a.jsx(a.Fragment,{children:s})}function ds({children:s,requiredPermission:e}){const{user:t,loading:r,rolesLoading:n,isExpert:i,isAdmin:o}=$t(),l=hs(),{data:d=[],isLoading:c}=Wt({queryKey:["expert-permissions",t==null?void 0:t.id],queryFn:async()=>{if(!(t!=null&&t.id))return[];const{data:h,error:f}=await L.from("expert_permissions").select("permission_key").eq("user_id",t.id);if(f)throw f;return(h==null?void 0:h.map(m=>m.permission_key))||[]},enabled:!!(t!=null&&t.id)&&!n&&i}),u=r||n||i&&c;return g.useEffect(()=>{if(!u){if(!t){l("/");return}if(o)return;if(!i){l("/social");return}if(e&&!d.includes(e)){const h=e.split(".")[0];d.some(m=>m.startsWith(`${h}.`))||l("/expert")}}},[u,t,i,o,d,e,l]),u?a.jsx("div",{className:"flex items-center justify-center h-screen",children:a.jsx(ts,{className:"h-8 w-8 animate-spin text-primary"})}):!t||!i&&!o?null:a.jsx(a.Fragment,{children:s})}function ac({children:s}){const{user:e,loading:t}=$t(),{data:r,isLoading:n}=Wt({queryKey:["user-is-trainer",e==null?void 0:e.id],queryFn:async()=>{const{data:i,error:o}=await L.from("user_roles").select("role").eq("user_id",e.id).eq("role","trainer").maybeSingle();if(o)throw o;return!!i},enabled:!!(e!=null&&e.id),staleTime:1e3*60*5});return t||n?a.jsx(O0,{}):e?r?a.jsx(a.Fragment,{children:s}):a.jsx(da,{to:"/dashboard",replace:!0}):a.jsx(da,{to:"/auth",replace:!0})}function ck(s){const e=s.message||"";return e.includes("Failed to fetch dynamically imported module")||e.includes("Loading chunk")||e.includes("Loading CSS chunk")||e.includes("Importing a module script failed")||e.includes("dynamically imported module")||s.name==="ChunkLoadError"}class dk extends g.Component{constructor(t){super(t);qa(this,"handleRetry",()=>{this.setState({hasError:!1,isChunkError:!1})});qa(this,"handleReload",()=>{window.location.reload()});this.state={hasError:!1,isChunkError:!1}}static getDerivedStateFromError(t){return{hasError:!0,isChunkError:ck(t)}}componentDidCatch(t,r){var n;console.error("[LazyErrorBoundary]",t.message,(n=r.componentStack)==null?void 0:n.slice(0,200))}render(){return this.state.hasError?a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:a.jsxs("div",{className:"text-center max-w-md 
647space-y-4",children:[a.jsx(Lr,{className:"h-12 w-12 text-muted-foreground mx-auto"}),a.jsx("h2",{className:"text-lg font-semibold text-foreground",children:this.state.isChunkError?"Page failed to load":"Something went wrong"}),a.jsx("p",{className:"text-sm text-muted-foreground",children:this.state.isChunkError?"A network issue prevented this page from loading. Please try again.":"An unexpected error occurred. Please try again."}),a.jsxs("div",{className:"flex gap-3 justify-center",children:[a.jsxs(ye,{onClick:this.handleRetry,variant:"default",children:[a.jsx(ha,{className:"h-4 w-4 mr-2"}),"Try Again"]}),a.jsx(ye,{onClick:this.handleReload,variant:"outline",children:"Reload Page"})]})]})}):this.props.children}}class uk extends g.Component{constructor(t){super(t);qa(this,"handleRetry",()=>{this.setState({hasError:!1,error:null,retryCount:0})});this.state={hasError:!1,error:null,retryCount:0}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){var n;console.error("[RouteErrorBoundary]",t.message,(n=r.componentStack)==null?void 0:n.slice(0,300))}componentDidUpdate(t,r){this.state.hasError&&!r.hasError&&this.state.retryCount<1&&this.setState(n=>({hasError:!1,error:null,retryCount:n.retryCount+1}))}render(){return this.state.hasError?a.jsx("div",{className:"flex items-center justify-center p-8 min-h-[300px]",children:a.jsxs("div",{className:"text-center max-w-sm space-y-3",children:[a.jsx(Lr,{className:"h-10 w-10 text-muted-foreground mx-auto"}),a.jsx("h3",{className:"text-base font-semibold text-foreground",children:"This page encountered an error"}),a.jsx("p",{className:"text-sm text-muted-foreground",children:"Something went wrong loading this view. You can try again or navigate elsewhere."}),a.jsxs(ye,{onClick:this.handleRetry,variant:"default",size:"sm",children:[a.jsx(ha,{className:"h-4 w-4 mr-2"}),"Try Again"]})]})}):this.props.children}}const hk={sm:"h-3.5 w-3.5",md:"h-4 w-4",lg:"h-5 w-5"};function wa({isVerified:s,verificationType:e="notable",size:t="sm",className:r,showTooltip:n=!0}){if(!s)return null;const i=e==="notable"?"Verified Notable Account":"Verified Account",o=a.jsx(Oo,{className:C("text-[#1DA1F2] fill-[#1DA1F2]/10 inline-block shrink-0",hk[t],r)});return n?a.jsxs(Go,{children:[a.jsx(zo,{asChild:!0,children:a.jsx("span",{className:"inline-flex items-center",children:o})}),a.jsx(fa,{children:a.jsx("p",{className:"text-xs font-medium",children:i})})]}):o}const fk="https://media.gradzen.com";function Of(s,e){if(!e)return s;const t=s.lastIndexOf(".");return t===-1?s:`${s.substring(0,t)}_${e}.jpg`}function pr(s,e){if(s)return s.startsWith("http://")||s.startsWith("https://")?Of(s,e==null?void 0:e.variant):`${fk}/${Of(s,e==null?void 0:e.variant)}`}const V4=Object.freeze(Object.defineProperty({__proto__:null,cdnUrl:pr},Symbol.toStringTag,{value:"Module"}));var V0={exports:{}},G0={};/**
648 * @license React
649 * use-sync-external-store-shim.production.js
650 *
651 * Copyright (c) Meta Platforms, Inc. and affiliates.
652 *
653 * This source code is licensed under the MIT license found in the
654 * LICENSE file in the root directory of this source tree.
655 */var wi=g;function mk(s,e){return s===e&&(s!==0||1/s===1/e)||s!==s&&e!==e}var pk=typeof Object.is=="function"?Object.is:mk,gk=wi.useState,xk=wi.useEffect,yk=wi.useLayoutEffect,vk=wi.useDebugValue;function bk(s,e){var t=e(),r=gk({inst:{value:t,getSnapshot:e}}),n=r[0].inst,i=r[1];return yk(function(){n.value=t,n.getSnapshot=e,oc(n)&&i({inst:n})},[s,t,e]),xk(function(){return oc(n)&&i({inst:n}),s(function(){oc(n)&&i({inst:n})})},[s]),vk(t),t}function oc(s){var e=s.getSnapshot;s=s.value;try{var t=e();return!pk(s,t)}catch{return!0}}function _k(s,e){return e()}var wk=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?_k:bk;G0.useSyncExternalStore=wi.useSyncExternalStore!==void 0?wi.useSyncExternalStore:wk;V0.exports=G0;var Ek=V0.exports;function Sk(){return Ek.useSyncExternalStore(Tk,()=>!0,()=>!1)}function Tk(){return()=>{}}var wu="Avatar",[Ak]=cn(wu),[kk,z0]=Ak(wu),q0=g.forwardRef((s,e)=>{const{__scopeAvatar:t,...r}=s,[n,i]=g.useState("idle");return a.jsx(kk,{scope:t,imageLoadingStatus:n,onImageLoadingStatusChange:i,children:a.jsx(bt.span,{...r,ref:e})})});q0.displayName=wu;var H0="AvatarImage",K0=g.forwardRef((s,e)=>{const{__scopeAvatar:t,src:r,onLoadingStatusChange:n=()=>{},...i}=s,o=z0(H0,t),l=Rk(r,i),d=Us(c=>{n(c),o.onImageLoadingStatusChange(c)});return xi(()=>{l!=="idle"&&d(l)},[l,d]),l==="loaded"?a.jsx(bt.img,{...i,ref:e,src:r}):null});K0.displayName=H0;var W0="AvatarFallback",Y0=g.forwardRef((s,e)=>{const{__scopeAvatar:t,delayMs:r,...n}=s,i=z0(W0,t),[o,l]=g.useState(r===void 0);return g.useEffect(()=>{if(r!==void 0){const d=window.setTimeout(()=>l(!0),r);return()=>window.clearTimeout(d)}},[r]),o&&i.imageLoadingStatus!=="loaded"?a.jsx(bt.span,{...n,ref:e}):null});Y0.displayName=W0;function Mf(s,e){return s?e?(s.src!==e&&(s.src=e),s.complete&&s.naturalWi
655dth>0?"loaded":"loading"):"error":"idle"}function Rk(s,{referrerPolicy:e,crossOrigin:t}){const r=Sk(),n=g.useRef(null),i=r?(n.current||(n.current=new window.Image),n.current):null,[o,l]=g.useState(()=>Mf(i,s));return xi(()=>{l(Mf(i,s))},[i,s]),xi(()=>{const d=h=>()=>{l(h)};if(!i)return;const c=d("loaded"),u=d("error");return i.addEventListener("load",c),i.addEventListener("error",u),e&&(i.referrerPolicy=e),typeof t=="string"&&(i.crossOrigin=t),()=>{i.removeEventListener("load",c),i.removeEventListener("error",u)}},[i,t,e]),o}var X0=q0,Q0=K0,J0=Y0;const Bs=g.forwardRef(({className:s,...e},t)=>a.jsx(X0,{ref:t,className:C("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...e}));Bs.displayName=X0.displayName;const Vs=g.forwardRef(({className:s,...e},t)=>a.jsx(Q0,{ref:t,className:C("aspect-square h-full w-full",s),...e}));Vs.displayName=Q0.displayName;const Gs=g.forwardRef(({className:s,...e},t)=>a.jsx(J0,{ref:t,delayMs:600,className:C("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...e}));Gs.displayName=J0.displayName;function jk({variant:s="sidebar"}){const{activePage:e,switchToPage:t,switchToPersonal:r,userPages:n,userPagesLoading:i}=bu(),o=hs();return i||n.length===0?s==="mobile"?a.jsxs("div",{className:"mb-4",children:[a.jsx("h3",{className:"px-4 mb-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Pages"}),a.jsxs("div",{className:"bg-card rounded-xl border border-border overflow-hidden",children:[a.jsxs("button",{onClick:()=>o("/page/create"),className:"flex items-center gap-3 px-4 py-3.5 w-full transition-colors active:bg-accent border-b border-border",children:[a.jsx(Qr,{className:"h-5 w-5 text-primary"}),a.jsx("span",{className:"flex-1 text-left text-sm font-medium text-foreground",children:"Create Page"}),a.jsx(us,{className:"h-4 w-4 text-muted-foreground"})]}),a.jsxs("button",{onClick:()=>o("/pages/discover"),className:"flex items-center gap-3 px-4 py-3.5 w-full transition-colors active:bg-accent",children:[a.jsx(Ds,{className:"h-5 w-5 text-muted-foreground"}),a.jsx("span",{className:"flex-1 text-left text-sm font-medium text-foreground",children:"Discover Pages"}),a.jsx(us,{className:"h-4 w-4 text-muted-foreground"})]})]})]}):a.jsxs("div",{className:"px-3 py-2 space-y-1",children:[a.jsxs("button",{onClick:()=>o("/page/create"),className:"flex items-center gap-2 w-full rounded-lg px-3 py-2 text-sm text-muted-foreground hover:bg-accent hover:text-accent-foreground transition-colors",children:[a.jsx(Qr,{className:"h-4 w-4"}),a.jsx("span",{children:"Create Page"})]}),a.jsxs("button",{onClick:()=>o("/pages/discover"),className:"flex items-center gap-2 w-full rounded-lg px-3 py-2 text-sm text-muted-foreground hover:bg-accent hover:text-accent-foreground transition-colors",children:[a.jsx(Ds,{className:"h-4 w-4"}),a.jsx("span",{children:"Discover Pages"})]})]}):s==="mobile"?a.jsxs("div",{className:"mb-4",children:[a.jsx("h3",{className:"px-4 mb-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Pages"}),a.jsxs("div",{className:"bg-card rounded-xl border border-border overflow-hidden",children:[e&&a.jsxs("button",{onClick:r,className:"flex items-center gap-3 px-4 py-3.5 w-full border-b border-border transition-colors active:bg-accent",children:[a.jsx(Ph,{className:"h-5 w-5 text-primary"}),a.jsx("span",{className:"flex-1 text-left text-sm font-medium text-foreground",children:"Switch to Personal Profile"})]}),n.map((l,d)=>a.jsx(Ff,{page:l,isActive:(e==null?void 0:e.id)===l.id,onClick:()=>{(e==null?void 0:e.id)===l.id?o(`/page/${l.slug}`):t(l)},showBorder:d<n.length-1||!0,variant:"mobile"},l.id)),a.jsxs("button",{onClick:()=>o("/page/create"),className:"flex items-center gap-3 px-4 py-3.5 w-full transition-colors active:bg-accent border-t border-border",children:[a.jsx(Qr,{className:"h-5 w-5 text-primary"}),a.jsx("span",{className:"flex-1 text-left text-sm font-medium text-foreground",children:"Create New Page"}),a.jsx(us,{className:"h-4 w-4 text-muted-foreground"})]}),a.jsxs("button",{onClick:()=>o("/pages/discover"),className:"flex items-center gap-3 px-4 py-3.5 w-full transition-colors active:bg-accent border-t border-border",children:[a.jsx(Ds,{className:"h-5 w-5 text-muted-foreground"}),a.jsx("span",{className:"flex-1 text-left text-sm font-medium text-foreground",children:"Discover Pages"}),a.jsx(us,{className:"h-4 w-4 text-muted-foreground"})]})]})]}):a.jsxs("div",{className:"space-y-1 px-3",children:[e&&a.jsxs("button",{onClick:r,className:"flex items-center gap-2 w-full rounded-lg px-3 py-2 text-sm text-muted-foreground hover:bg-accent hover:text-accent-foreground transition-colors",children:[a.jsx(Ph,{className:"h-4 w-4"}),a.jsx("span",{children:"Switch to Personal"})]}
655),n.map(l=>a.jsx(Ff,{page:l,isActive:(e==null?void 0:e.id)===l.id,onClick:()=>{(e==null?void 0:e.id)===l.id?o(`/page/${l.slug}`):t(l)},variant:"sidebar"},l.id)),a.jsxs("button",{onClick:()=>o("/page/create"),className:"flex items-center gap-2 w-full rounded-lg px-3 py-2 text-sm text-muted-foreground hover:bg-accent hover:text-accent-foreground transition-colors",children:[a.jsx(Qr,{className:"h-4 w-4"}),a.jsx("span",{children:"Create Page"})]}),a.jsxs("button",{onClick:()=>o("/pages/discover"),className:"flex items-center gap-2 w-full rounded-lg px-3 py-2 text-sm text-muted-foreground hover:bg-accent hover:text-accent-foreground transition-colors",children:[a.jsx(Ds,{className:"h-4 w-4"}),a.jsx("span",{children:"Discover Pages"})]})]})}function Ff({page:s,isActive:e,onClick:t,showBorder:r,variant:n="sidebar"}){return n==="mobile"?a.jsxs("button",{onClick:t,className:C("flex items-center gap-3 px-4 py-3.5 w-full transition-colors active:bg-accent",r&&"border-b border-border",e&&"bg-primary/5"),children:[a.jsxs(Bs,{className:"h-8 w-8",children:[a.jsx(Vs,{src:pr(s.logo_url)}),a.jsx(Gs,{className:"text-xs bg-primary/10 text-primary",children:sn(s.name)})]}),a.jsxs("div",{className:"flex-1 text-left",children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{className:C("text-sm font-medium truncate",e&&"text-primary"),children:s.name}),a.jsx(wa,{isVerified:s.is_verified||!1,verificationType:s.verification_type,size:"sm",showTooltip:!1})]}),e&&a.jsx("span",{className:"block text-xs text-primary",children:"Active"})]}),a.jsx(us,{className:"h-4 w-4 text-muted-foreground"})]}):a.jsxs("button",{onClick:t,className:C("flex items-center gap-2 w-full rounded-lg px-3 py-2 text-sm font-medium transition-all duration-200",e?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsxs(Bs,{className:"h-5 w-5",children:[a.jsx(Vs,{src:pr(s.logo_url)}),a.jsx(Gs,{className:"text-[8px]",children:sn(s.name)})]}),a.jsx("span",{className:"truncate",children:s.name}),a.jsx(wa,{isVerified:s.is_verified||!1,verificationType:s.verification_type,size:"sm",showTooltip:!1})]})}const ai=768,$f=1024;function dn(){const[s,e]=g.useState(()=>typeof window<"u"?window.innerWidth<ai:!1);return g.useEffect(()=>{const t=window.matchMedia(`(max-width: ${ai-1}px)`),r=()=>{e(window.innerWidth<ai)};return t.addEventListener("change",r),e(window.innerWidth<ai),()=>t.removeEventListener("change",r)},[]),s}function G4(){const[s,e]=g.useState(()=>typeof window<"u"?window.innerWidth>=ai&&window.innerWidth<$f:!1);return g.useEffect(()=>{const t=()=>{e(window.innerWidth>=ai&&window.innerWidth<$f)};return window.addEventListener("resize",t),t(),()=>window.removeEventListener("resize",t)},[]),s}const rr=g.forwardRef(({className:s,type:e,...t},r)=>a.jsx("input",{type:e,className:C("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",s),ref:r,...t}));rr.displayName="Input";var Ik="Separator",Uf="horizontal",Ck=["horizontal","vertical"],Z0=g.forwardRef((s,e)=>{const{decorative:t,orientation:r=Uf,...n}=s,i=Nk(r)?r:Uf,l=t?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return a.jsx(bt.div,{"data-orientation":i,...l,...n,ref:e})});Z0.displayName=Ik;function Nk(s){return Ck.includes(s)}var ex=Z0;const tx=g.forwardRef(({className:s,orientation:e="horizontal",decorative:t=!0,...r},n)=>a.jsx(ex,{ref:n,decorative:t,orientation:e,className:C("shrink-0 bg-border",e==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",s),...r}));tx.displayName=ex.displayName;const Lk=_l,Pk=bl,sx=g.forwardRef(({className:s,...e},t)=>a.jsx(Di,{className:C("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...e,ref:t}));sx.displayName=Di.displayName;const Dk=Pn("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4  border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),rx=g.forwardRef(({side:s="right",className:e,children:t,...r},n)=>
655a.jsxs(Pk,{children:[a.jsx(sx,{}),a.jsxs(Oi,{ref:n,className:C(Dk({side:s}),e),...r,children:[t,a.jsxs(Ma,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-secondary hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[a.jsx(Fs,{className:"h-4 w-4"}),a.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));rx.displayName=Oi.displayName;const Ok=({className:s,...e})=>a.jsx("div",{className:C("flex flex-col space-y-2 text-center sm:text-left",s),...e});Ok.displayName="SheetHeader";const Mk=g.forwardRef(({className:s,...e},t)=>a.jsx(Mi,{ref:t,className:C("text-lg font-semibold text-foreground",s),...e}));Mk.displayName=Mi.displayName;const Fk=g.forwardRef(({className:s,...e},t)=>a.jsx(Fi,{ref:t,className:C("text-sm text-muted-foreground",s),...e}));Fk.displayName=Fi.displayName;const $k="sidebar:state",Uk=60*60*24*7,Bk="20rem",Vk="18rem",Gk="3rem",zk="b",nx=g.createContext(null);function Ba(){const s=g.useContext(nx);if(!s)throw new Error("useSidebar must be used within a SidebarProvider.");return s}const ix=g.forwardRef(({defaultOpen:s=!0,open:e,onOpenChange:t,className:r,style:n,children:i,...o},l)=>{const d=dn(),[c,u]=g.useState(!1),[h,f]=g.useState(s),m=e??h,p=g.useCallback(_=>{const b=typeof _=="function"?_(m):_;t?t(b):f(b),document.cookie=`${$k}=${b}; path=/; max-age=${Uk}`},[t,m]),x=g.useCallback(()=>d?u(_=>!_):p(_=>!_),[d,p,u]);g.useEffect(()=>{const _=b=>{b.key===zk&&(b.metaKey||b.ctrlKey)&&(b.preventDefault(),x())};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[x]);const y=m?"expanded":"collapsed",v=g.useMemo(()=>({state:y,open:m,setOpen:p,isMobile:d,openMobile:c,setOpenMobile:u,toggleSidebar:x}),[y,m,p,d,c,u,x]);return a.jsx(nx.Provider,{value:v,children:a.jsx(Vo,{delayDuration:0,children:a.jsx("div",{style:{"--sidebar-width":Bk,"--sidebar-width-icon":Gk,...n},className:C("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",r),ref:l,...o,children:i})})})});ix.displayName="SidebarProvider";const ax=g.forwardRef(({side:s="left",variant:e="sidebar",collapsible:t="offcanvas",className:r,children:n,...i},o)=>{const{isMobile:l,state:d,openMobile:c,setOpenMobile:u}=Ba();return t==="none"?a.jsx("div",{className:C("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",r),ref:o,...i,children:n}):l?a.jsx(Lk,{open:c,onOpenChange:u,...i,children:a.jsx(rx,{"data-sidebar":"sidebar","data-mobile":"true",className:"w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden",style:{"--sidebar-width":Vk},side:s,children:a.jsx("div",{className:"flex h-full w-full flex-col",children:n})})}):a.jsxs("div",{ref:o,className:"group peer hidden text-sidebar-foreground md:block","data-state":d,"data-collapsible":d==="collapsed"?t:"","data-variant":e,"data-side":s,children:[a.jsx("div",{className:C("relative h-[calc(100svh-3.5rem)] w-[--sidebar-width] bg-transparent transition-[width] duration-200 ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180",e==="floating"||e==="inset"?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),a.jsx("div",{className:C("fixed top-14 bottom-0 z-10 hidden w-[--sidebar-width] transition-[left,right,width] duration-200 ease-linear md:flex",s==="left"?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",e==="floating"||e==="inset"?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",r),...i,children:a.jsx("div",{"data-sidebar":"sidebar",className:"flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow",children:n})})]})});ax.displayName="Sidebar";const qk=g.forwardRef(({className:s,onClick:e,...t},r)=>{const{toggleSidebar:n}=Ba();return a.jsxs(ye,{ref:r,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:C("h-7 w-7",s),onClick:i=>{e==null||e(i),n()},...t,children:[a.jsx(Yw,{}),a.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});qk.displayName="SidebarTrigger";const Hk=g.forwardRef(({className:s,...e},t)=>{const{toggleSidebar:r}=Ba();return a.jsx("button",{ref:t,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:r,title:"Toggle Sidebar",className:C("absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] group-data-[side=left]:-right-4 group-data-[side=right]:left-0 hover:after:bg-sidebar-border sm:flex","[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize","[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize","group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar","[[data-side=left][data-collapsible=offcanvas]_&]:-right-2","[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",s),...e})});Hk.displayName="SidebarRail";const ox=g.forwardRef(({className:s,...e},t)=>a.jsx("main",{ref:t,className:C("relative flex min-h-svh flex-1 flex-col bg-background","peer-data-[variant=inset]:min-
655h-[calc(100svh-theme(spacing.4))] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",s),...e}));ox.displayName="SidebarInset";const Kk=g.forwardRef(({className:s,...e},t)=>a.jsx(rr,{ref:t,"data-sidebar":"input",className:C("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",s),...e}));Kk.displayName="SidebarInput";const Wk=g.forwardRef(({className:s,...e},t)=>a.jsx("div",{ref:t,"data-sidebar":"header",className:C("flex flex-col gap-2 p-2",s),...e}));Wk.displayName="SidebarHeader";const lx=g.forwardRef(({className:s,...e},t)=>a.jsx("div",{ref:t,"data-sidebar":"footer",className:C("flex flex-col gap-2 p-2",s),...e}));lx.displayName="SidebarFooter";const Yk=g.forwardRef(({className:s,...e},t)=>a.jsx(tx,{ref:t,"data-sidebar":"separator",className:C("mx-2 w-auto bg-sidebar-border",s),...e}));Yk.displayName="SidebarSeparator";const cx=g.forwardRef(({className:s,...e},t)=>a.jsx("div",{ref:t,"data-sidebar":"content",className:C("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",s),...e}));cx.displayName="SidebarContent";const Je=g.forwardRef(({className:s,...e},t)=>a.jsx("div",{ref:t,"data-sidebar":"group",className:C("relative flex w-full min-w-0 flex-col p-2",s),...e}));Je.displayName="SidebarGroup";const gt=g.forwardRef(({className:s,asChild:e=!1,...t},r)=>{const n=e?Pi:"div";return a.jsx(n,{ref:r,"data-sidebar":"group-label",className:C("flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opa] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",s),...t})});gt.displayName="SidebarGroupLabel";const Xk=g.forwardRef(({className:s,asChild:e=!1,...t},r)=>{const n=e?Pi:"button";return a.jsx(n,{ref:r,"data-sidebar":"group-action",className:C("absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","group-data-[collapsible=icon]:hidden",s),...t})});Xk.displayName="SidebarGroupAction";const nt=g.forwardRef(({className:s,...e},t)=>a.jsx("div",{ref:t,"data-sidebar":"group-content",className:C("w-full text-sm",s),...e}));nt.displayName="SidebarGroupContent";const ot=g.forwardRef(({className:s,...e},t)=>a.jsx("ul",{ref:t,"data-sidebar":"menu",className:C("flex w-full min-w-0 flex-col gap-1",s),...e}));ot.displayName="SidebarMenu";const de=g.forwardRef(({className:s,...e},t)=>a.jsx("li",{ref:t,"data-sidebar":"menu-item",className:C("group/menu-item relative",s),...e}));de.displayName="SidebarMenuItem";const Qk=Pn("peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",{variants:{variant:{default:"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",outline:"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]"},size:{default:"h-8 text-sm",sm:"h-7 text-xs",lg:"h-12 text-sm group-data-[collapsible=icon]:!p-0"}},defaultVariants:{variant:"default",size:"default"}}),ue=g.forwardRef(({asChild:s=!1,isActive:e=!1,variant:t="default",size:r="default",tooltip:n,className:i,...o},l)=>{const d=s?Pi:"button",{isMobile:c,state:u}=Ba(),h=a.jsx(d,{ref:l,"data-sidebar":"menu-button","data-size":r,"data-active":e,className:C(Qk({variant:t,size:r}),i),...o});return n?(typeof n=="string"&&(n={children:n}),a.jsxs(Go,{children:[a.jsx(zo,{asChild:!0,children:h}),a.jsx(fa,{side:"right",align:"center",hidden:u!=="collapsed"||c,...n})]})):h});ue.displayName="SidebarMenuButton";const Jk=g.forwardRef(({className:s,asChild:e=!1,showOnHover:t=!1,...r},n)=>{const i=e?Pi:"button";return a.jsx(i,{ref:n,"data-sidebar":"menu-action",className:C("absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform peer-hover/menu-button:text-sidebar-accent-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",t&&"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",s),...r})});Jk.displayName="SidebarMenuAction";const Zk=g.forwardRef(({className:s,...e},t)=>a.jsx("div",{ref:t,"data-sidebar":"menu-badge",className:C("pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground","peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",s),...e}));Zk.displayName="SidebarMenuBadge";const eR=g.forwardRef(({className:s,showIcon:e=!1,...t},r)=>{const n=g.useMemo(()=>`${Math.floor(Math.random()*40)+50}%`,[]);return a.jsxs("div",{ref:r,"data-sidebar":"menu-skeleton",className:C("flex h-8 items-center gap-2 rounded-md px-2",s),...t,children:[e&&a.jsx(H,{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),a.jsx(H,{className:"h-4 max-w-[--skeleton-width] flex-1","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":n}})]})});eR.displayName="SidebarMenuSkeleton";const $s=g.forwardRef(({className:s,...e},t)=>a.jsx("ul",{ref:t,"data-sidebar":"menu-sub",className:C("mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5","group-data-[collapsible=icon]:hidden",s),...e}));$s.displayName="SidebarMenuSub";const _t=g.forwardRef(({...s},e)=>a.jsx("li",{ref:e,...s}));_t.displayName="SidebarMenuSubItem";const wt=g.forwardRef(({asChild:s=!1,size:e="md",isActive:t,className:r,...n},i)=>{const o=s?Pi:"a";return a.jsx(o,{ref:i,"data-sidebar":"menu-sub-button","data-size":e,"data-active":t,className:C("flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring aria-disabled:pointer-events-none aria-disabled:opacity-50 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",e==="sm"&&"text-xs",e==="md"&&"text-sm","group-data-[collapsible=icon]:hidden",r),...n})});wt.displayName="SidebarMenuSubButton";var Tl="Collapsible",[tR,z4]=cn(Tl),[sR,Eu]=tR(Tl),dx=g.forwardRef((s,e)=>{const{__scopeCollapsible:t,open:r,defaultOpen:n,disabled:i,onOpenChange:o,...l}=s,[d,c]=Oa({prop:r,defaultProp:n??!1,onChange:o,caller:Tl});return a.jsx(sR,{scope:t,disabled:i,contentId:__(),open:d,onOpenToggle:g.useCallback(()=>c(u=>!u),[c]),children:a.jsx(bt.div,{"data-state":ku(d),"data-disabled":i?"":void 0,...l,ref:e})})});dx.displayName=Tl;var ux="CollapsibleTrigger",Su=g.forwardRef((s,e)=>{const{__scopeCollapsible:t,...r}=s,n=Eu(ux,t);return a.jsx(bt.button,{type:"button","aria-controls":n.contentId,"aria-expanded":n.open||!1,"data-state":ku(n.open
655),"data-disabled":n.disabled?"":void 0,disabled:n.disabled,...r,ref:e,onClick:Et(s.onClick,n.onOpenToggle)})});Su.displayName=ux;var Tu="CollapsibleContent",Au=g.forwardRef((s,e)=>{const{forceMount:t,...r}=s,n=Eu(Tu,s.__scopeCollapsible);return a.jsx(Ln,{present:t||n.open,children:({present:i})=>a.jsx(rR,{...r,ref:e,present:i})})});Au.displayName=Tu;var rR=g.forwardRef((s,e)=>{const{__scopeCollapsible:t,present:r,children:n,...i}=s,o=Eu(Tu,t),[l,d]=g.useState(r),c=g.useRef(null),u=qt(e,c),h=g.useRef(0),f=h.current,m=g.useRef(0),p=m.current,x=o.open||l,y=g.useRef(x),v=g.useRef(void 0);return g.useEffect(()=>{const _=requestAnimationFrame(()=>y.current=!1);return()=>cancelAnimationFrame(_)},[]),xi(()=>{const _=c.current;if(_){v.current=v.current||{transitionDuration:_.style.transitionDuration,animationName:_.style.animationName},_.style.transitionDuration="0s",_.style.animationName="none";const b=_.getBoundingClientRect();h.current=b.height,m.current=b.width,y.current||(_.style.transitionDuration=v.current.transitionDuration,_.style.animationName=v.current.animationName),d(r)}},[o.open,r]),a.jsx(bt.div,{"data-state":ku(o.open),"data-disabled":o.disabled?"":void 0,id:o.contentId,hidden:!x,...i,ref:u,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":p?`${p}px`:void 0,...s.style},children:x&&n})});function ku(s){return s?"open":"closed"}var nR=dx,q4=Su,H4=Au;const ps=nR,gs=Su,xs=Au;var Al="Switch",[iR]=cn(Al),[aR,oR]=iR(Al),hx=g.forwardRef((s,e)=>{const{__scopeSwitch:t,name:r,checked:n,defaultChecked:i,required:o,disabled:l,value:d="on",onCheckedChange:c,form:u,...h}=s,[f,m]=g.useState(null),p=qt(e,b=>m(b)),x=g.useRef(!1),y=f?u||!!f.closest("form"):!0,[v,_]=Oa({prop:n,defaultProp:i??!1,onChange:c,caller:Al});return a.jsxs(aR,{scope:t,checked:v,disabled:l,children:[a.jsx(bt.button,{type:"button",role:"switch","aria-checked":v,"aria-required":o,"data-state":gx(v),"data-disabled":l?"":void 0,disabled:l,value:d,...h,ref:p,onClick:Et(s.onClick,b=>{_(w=>!w),y&&(x.current=b.isPropagationStopped(),x.current||b.stopPropagation())})}),y&&a.jsx(px,{control:f,bubbles:!x.current,name:r,value:d,checked:v,required:o,disabled:l,form:u,style:{transform:"translateX(-100%)"}})]})});hx.displayName=Al;var fx="SwitchThumb",mx=g.forwardRef((s,e)=>{const{__scopeSwitch:t,...r}=s,n=oR(fx,t);return a.jsx(bt.span,{"data-state":gx(n.checked),"data-disabled":n.disabled?"":void 0,...r,ref:e})});mx.displayName=fx;var lR="SwitchBubbleInput",px=g.forwardRef(({__scopeSwitch:s,control:e,checked:t,bubbles:r=!0,...n},i)=>{const o=g.useRef(null),l=qt(o,i),d=su(t),c=ru(e);return g.useEffect(()=>{const u=o.current;if(!u)return;const h=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(h,"checked").set;if(d!==t&&m){const p=new Event("click",{bubbles:r});m.call(u,t),u.dispatchEvent(p)}},[d,t,r]),a.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:t,...n,tabIndex:-1,ref:l,style:{...n.style,...c,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});px.displayName=lR;function gx(s){return s?"checked":"unchecked"}var xx=hx,cR=mx;const yx=g.forwardRef(({className:s,...e},t)=>a.jsx(xx,{className:C("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50",s),...e,ref:t,children:a.jsx(cR,{className:C("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));yx.displayName=xx.displayName;const dR=Pn("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}}),cr=g.forwardRef(({className:s,variant:e,...t},r)=>a.jsx("div",{ref:r,className:C(dR({variant:e}),s),...t}));cr.displayName="Badge";const Bf=[{value:"applied",label:"Applied",icon:qw},{value:"personality_game",label:"Personality Game",icon:Uw},{value:"aptitude",label:"Aptitude Test",icon:Dn},{value:"fgd",label:"Focus Group Discussion",icon:ed},{value:"online_interview",label:"Online Interview",icon:Ds},{value:"presentation",label:"Presentation",icon:$w},{value:"final_interview",label:"Final Interview",icon:Uo},{value:"hired",label:"Hired",icon:Uo},{value:"rejected",label:"Rejected",icon:cu}],uR=[{title:"Standard Assessments",items:[{title:"Personality Trait Test",url:"/applicant/pers
655onality-game",icon:si,highlight:!0,badge:"FREE"},{title:"My Results",url:"/applicant/personality-results",icon:iE},{title:"Test Submission",url:"/applicant/test-submission",icon:Zw}]},{title:"Job Assessment",items:[{title:"My Applications",url:"/applied-jobs",icon:Dn},{title:"Aptitude Tests",url:"/applicant/tests",icon:$a}]}],hR=[{title:"Overview",items:[{title:"Dashboard",url:"/dashboard?view=hr",icon:Dr},{title:"Job Analytics",url:"/hr/analytics",icon:Cr}]},{title:"Aptitude Tests",items:[{title:"All Tests",url:"/hr/aptitude",icon:$a},{title:"Create Test",url:"/hr/aptitude/create",icon:Pw}]},{title:"Account",items:[{title:"Activity Log",url:"/hr/activity-log",icon:e0}]}],fR=[{title:"Dashboard",icon:Dr,path:"/admin"},{title:"Analytics",icon:ni,path:"/admin/analytics"},{title:"Jobs",icon:Es,path:"/admin/jobs"},{title:"Applications",icon:Dn,path:"/admin/applications"},{title:"Ad Review",icon:Xn,path:"/admin/ads"}],mR=[{title:"Security",icon:kr,path:"/admin/security"},{title:"AI Settings",icon:Eo,path:"/admin/ai-settings"},{title:"Cloud Storage",icon:Ow,path:"/admin/cloud-storage"},{title:"Username Settings",icon:Qg,path:"/admin/community/username-settings"},{title:"Maintenance",icon:du,path:"/admin/maintenance"},{title:"Database Backup",icon:Zg,path:"/admin/database-backup"}],pR=[{title:"Pipeline Overview",url:"/applicant/pipeline",icon:Bw},{title:"Saved Items",url:"/applicant/saved-items",icon:Jg},{title:"Activity Log",url:"/applicant/activity-log",icon:e0},{title:"Account Information",url:"/applicant/account",icon:aE},{title:"Deactivation & Deletion",url:"/applicant/account-deletion",icon:oE},{title:"Privacy and Security",url:"/applicant/security",icon:kr},{title:"Hidden Jobs",url:"/applicant/hidden-jobs",icon:Jc},{title:"Request Verification",url:"/applicant/request-verification",icon:Oo}],gR=[{title:"Dashboard",icon:Dr,path:"/expert",permission:"main_menu.dashboard"},{title:"Users",icon:Ss,path:"/expert/users",permission:"main_menu.users"},{title:"Jobs",icon:Es,path:"/expert/jobs",permission:"main_menu.jobs"},{title:"Applications",icon:Dn,path:"/expert/applications",permission:"main_menu.applications"}];function xR(){const{signOut:s,user:e}=$t(),{hasHRAccess:t,isCollaboratorOnly:r,hrCompanyName:n}=U0(),{activePage:i,isPageMode:o}=bu(),{theme:l,setTheme:d}=p0(),c=br(),u=hs(),[h,f]=g.useState({}),[m,p]=g.useState(!0),[x,y]=g.useState(!0),[v,_]=g.useState(!1),[b,w]=g.useState(!1),[T,A]=g.useState(!1),[S,I]=g.useState(!1),[j,R]=g.useState(!1),[k,D]=g.useState(!1),[Y,q]=g.useState(!1),[X,F]=g.useState(!1),[P,N]=g.useState(!1),[O,$]=g.useState(!1),[B,U]=g.useState(!1),{data:K,isLoading:ee}=Wt({queryKey:["user-profile-sidebar",e==null?void 0:e.id],queryFn:async()=>{const{data:W,error:Se}=await L.from("profiles").select("full_name, avatar_url, gender").eq("user_id",e.id).single();if(Se)throw Se;return W},enabled:!!(e!=null&&e.id),staleTime:1e3*60*5}),ce=pr(K==null?void 0:K.avatar_url)||_i(K==null?void 0:K.gender),{data:Q}=Wt({queryKey:["user-is-admin",e==null?void 0:e.id],queryFn:async()=>{const{data:W,error:Se}=await L.from("user_roles").select("role").eq("user_id",e.id).eq("role","admin").maybeSingle();if(Se)throw Se;return!!W},enabled:!!(e!=null&&e.id),staleTime:1e3*60*5}),{data:re}=Wt({queryKey:["user-is-expert",e==null?void 0:e.id],queryFn:async()=>{const{data:W,error:Se}=await L.from("user_roles").select("role").eq("user_id",e.id).eq("role","expert").maybeSingle();if(Se)throw Se;return!!W},enabled:!!(e!=null&&e.id),staleTime:1e3*60*5}),{data:ve}=Wt({queryKey:["user-is-trainer",e==null?void 0:e.id],queryFn:async()=>{const{data:W,error:Se}=await L.from("user_roles").select("role").eq("user_id",e.id).eq("role","trainer").maybeSingle();if(Se)throw Se;return!!W},enabled:!!(e!=null&&e.id),staleTime:1e3*60*5}),{data:Ce=[]}=Wt({queryKey:["expert-permissions",e==null?void 0:e.id],queryFn:async()=>{if(!(e!=null&&e.id))return[];const{data:W,error:Se}=await L.from("expert_permissions").select("permission_key").eq("user_id",e.id);if(Se)throw Se;return(W==null?void 0:W.map(it=>it.permission_key))||[]},enabled:!!(e!=null&&e.id)&&!!re}),{data:Pe=[]}=Wt({queryKey:["aptitude-categories"],queryFn:async()=>{const{data:W,error:Se}=await L.from("aptitude_categories").select("*").order("display_order",{ascending:!0});if(Se)throw Se;return W},enabled:!!Q||Ce.some(W=>W.startsWith("aptitude."))}),{data:Me=[]}=Wt({queryKey:["personality-trait-sections"],queryFn:async()=>{const{data:W,error:Se}=await L.from("personality_trait_sections").select("*").order("display_order",{ascending:!0});if(Se)throw Se;return W},enabled:!!Q||Ce.some(W=>W.startsWith("personality."))}),{data:le=0}=Wt({queryKey:["pending-reports-count"],queryFn:async()=>{const{count:W,error:Se}=await L.from("job_reports").select("id",{count:"exact",head:!0}
655).eq("status","pending");if(Se)throw Se;return W||0},enabled:!!Q}),oe=async()=>{await s(),u("/",{replace:!0})};g.useEffect(()=>{e&&t&&He()},[e,t]),g.useEffect(()=>{Q&&c.pathname.startsWith("/admin")&&(c.pathname.includes("/admin/aptitude")&&_(!0),c.pathname.includes("/admin/personality-game")&&w(!0),(c.pathname.includes("/admin/community")||c.pathname==="/admin/users"||c.pathname.includes("/admin/appeals")||c.pathname==="/admin/verified-users"||c.pathname==="/admin/verified-pages")&&A(!0),c.pathname.includes("/admin/customization")&&I(!0),c.pathname.includes("/admin/reports")&&R(!0),c.pathname.includes("/admin/course")&&D(!0))},[Q,c.pathname]);const He=async()=>{if(e)try{const{data:W,error:Se}=await L.from("jobs").select("id").eq("hr_user_id",e.id);if(Se)throw Se;if(!W||W.length===0){f({});return}const it=W.map(at=>at.id),{data:Ct,error:Ne}=await L.from("applications").select("tracking_stage, job_id").in("job_id",it);if(Ne)throw Ne;const Ge={};Ct==null||Ct.forEach(at=>{const Xe=at.tracking_stage||"applied";Ge[Xe]||(Ge[Xe]=new Set),Ge[Xe].add(at.job_id)});const ht={};Object.entries(Ge).forEach(([at,Xe])=>{ht[at]=Xe.size}),f(ht)}catch(W){console.error("Error fetching pipeline counts:",W)}},ct=Object.values(h).reduce((W,Se)=>W+Se,0),se=(W,Se)=>{const[it,Ct]=W.split("?"),Ne=Se?c.pathname===it:c.pathname.startsWith(it),Ge=!Ct||c.search.includes(Ct);return Ne&&Ge},Be=c.pathname.startsWith("/admin"),Ke=c.pathname.startsWith("/expert"),Ee=W=>Ce.includes(W),fe=Ce.some(W=>W.startsWith("main_menu.")),et=Ce.some(W=>W.startsWith("aptitude.")),rt=Ce.some(W=>W.startsWith("personality.")),We=Ce.some(W=>W.startsWith("customization.")),dt=Ce.some(W=>W.startsWith("technical_team.")),pe=Ce.some(W=>W.startsWith("settings.")),ge=Ce.some(W=>W.startsWith("community.")),be=Ce.some(W=>W.startsWith("billing.")),ie=Ce.some(W=>W.startsWith("projects.")),Qe=gR.filter(W=>Ee(W.permission)),Ve=uR,It=hR.flatMap(W=>W.items),[At,Yt]=g.useState(c.pathname.startsWith("/hr")||c.pathname==="/dashboard");return g.useEffect(()=>{re&&Ke&&(c.pathname.includes("/expert/aptitude")&&q(!0),c.pathname.includes("/expert/personality-game")&&F(!0),c.pathname.includes("/expert/customization")&&N(!0),(c.pathname.includes("/expert/reports")||c.pathname.includes("/expert/algorithm-debug")||c.pathname.includes("/expert/feed-algorithm")||c.pathname.includes("/expert/cross-learning")||c.pathname.includes("/expert/identity-verifications"))&&$(!0),(c.pathname.includes("/expert/community")||c.pathname==="/expert/users"||c.pathname==="/expert/verified-users"||c.pathname==="/expert/verified-pages"||c.pathname==="/expert/appeals"||c.pathname==="/expert/broadcast")&&U(!0))},[re,Ke,c.pathname]),a.jsxs(ax,{collapsible:"offcanvas",className:"border-r bg-card",children:[a.jsxs(cx,{className:"px-3 py-4 overflow-y-auto",children:[Q&&Be&&a.jsx(Je,{className:"mb-4",children:a.jsxs("div",{className:"flex items-center gap-3 px-3 py-3 rounded-lg bg-purple-500/10 border border-purple-500/20",children:[a.jsx(kr,{className:"h-5 w-5 text-purple-500"}),a.jsx("span",{className:"text-base font-semibold text-foreground",children:"Admin Panel"})]})}),!Be&&!Ke&&a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:o?"Page":"Profile"}),a.jsx(nt,{children:a.jsx(ot,{children:a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:o&&i?`/page/${i.slug}`:"/profile",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",se(o&&i?`/page/${i.slug}`:"/profile")?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[ee&&!o?a.jsx(H,{className:"h-6 w-6 rounded-full"}):a.jsxs(Bs,{className:"h-6 w-6",children:[a.jsx(Vs,{src:o&&(i!=null&&i.logo_url)?i.logo_url:ce,alt:o&&i?i.name:(K==null?void 0:K.full_name)||"Profile"}),a.jsx(Gs,{className:"text-[10px] bg-muted",children:sn(o&&i?i.name:K==null?void 0:K.full_name)})]}),a.jsxs("span",{className:"flex-1 flex items-center gap-1 min-w-0",children:[a.jsx("span",{className:"truncate",children:o&&i?i.name:ee?a.jsx(H,{className:"h-4 w-20"}):(K==null?void 0:K.full_name)||"Profile"}),o&&(i==null?void 0:i.is_verified)&&a.jsx(wa,{isVerified:!0,verificationType:i.verification_type,size:"sm",showTooltip:!1})]})]})})})})})]}),!Be&&!Ke&&a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Your Pages"}),a.jsx(nt,{children:a.jsx(jk,{variant:"sidebar"})})]}),!Be&&!Ke&&a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Ads Manager"}),a.jsx(nt,{children:a.jsxs(ot,{children:[a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/hr/boosts",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",se("/hr/boosts")&&!se("/hr/boosts/analytics")&&!se("/hr/boosts/disputes")?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Xn,{className:C("h-4 w-4",se("/hr/boosts")&&!se("/hr/boosts/analytics")&&!se("/hr/boosts/disputes")&&"text-primary-foreground")}),a.jsx("span",{children:"Campaigns"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/hr/boosts/analytics",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",se("/hr/boosts/analytics")?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Xn,{className:C("h-4 w-4",se("/hr/boosts/analytics")&&"text-primary-foreground")}),a.jsx("span",{children:"Analytics"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/hr/boosts/disputes",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",se("/hr/boosts/disputes")?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Xn,{className:C("h-4 w-4",se("/hr/boosts/disputes")&&"text-primary-foreground")}),a.jsx("span",{children:"Disputes"})]})})})]})})]}),Q&&Be&&a.jsxs(a.Fragment,{children:[a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Main Menu"}),a.jsx(nt,{children:a.jsxs(ot,{children:[fR.map(W=>a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:W.path,className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname===W.path?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(W.icon,{className:C("h-4 w-4",c.pathname===W.path&&"text-primary-foreground")}),a.jsx("span",{children:W.title})]})})},W.path)),a.jsx(ps,{open:k,onOpenChange:D,children:a.jsxs(de,{children:[a.jsx(gs,{asChild:!0,children:a.jsxs(ue,{className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200 w-full",c.pathname.includes("/admin/course")?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Mn,{className:"h-4 w-4"}),a.jsx("span",{className:"flex-1 text-left",children:"Courses"}),a.jsx(us,{className:C("h-4 w-4 transition-transform",k&&"rotate-90")})]})}),a.jsx(xs,{children:a.jsxs($s,{children:[a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u("/admin/courses"),isActive:c.pathname==="/admin/courses",children:[a.jsx(Mn,{className:"h-3 w-3"}),a.jsx("span",{children:"All Courses"})]})}),a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u("/admin/course-categories"),isActive:c.pathname==="/admin/course-categories",children:[a.jsx(Kl,{className:"h-3 w-3"}),a.jsx("span",{children:"Categories"})]})}),a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u("/admin/trainer-royalties"),isActive:c.pathname==="/admin/trainer-royalties",children:[a.jsx(Nr,{className:"h-3 w-3"}),a.jsx("span",{children:"Trainer Royalties"})]})}),a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u("/admin/trainer-applications"),isActive:c.pathname==="/admin/trainer-applications",children:[a.jsx(Dn,{className:"h-3 w-3"}),a.jsx("span",{children:"Trainer Applications"})]})})]})})]})})]})})]}),a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Technical Team"}),a.jsx(nt,{children:a.jsxs(ot,{children:[a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/algorithm-debug",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/algorithm-debug"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Cr,{className:C("h-4 w-4",c.pathname==="/admin/algorithm-debug"&&"text-primary-foreground")}),a.jsx("span",{children:"Algorithm Debug"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/feed-algorithm",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/feed-algorithm"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Lh,{className:C("h-4 w-4",c.pathname==="/admin/feed-algorithm"&&"text-primary-foreground")}),a.jsx("span",{children:"Feed Algorithm"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/cross-learning",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/cross-learning"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(si,{className:C("h-4 w-4",c.pathname==="/admin/cross-learning"&&"text-primary-foreground")}),a.jsx("span",{children:"Cross-Learning"})]})})}),a.jsx(ps,{open:j,onOpenChange:R,children:a.jsxs(de,{children:[a.jsx(gs,{asChild:!0,children:a.jsxs(ue,{className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200 w-full",c.pathname.includes("/admin/reports")?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Oh,{className:"h-4 w-4"}),a.jsx("span",{className:"flex-1 text-left",children:"Support"}),a.jsx(us,{className:C("h-4 w-4 transition-transform",j&&"rotate-90")})]})}),a.jsx(xs,{children:a.jsx($s,{children:a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u("/admin/reports"),isActive:c.pathname==="/admin/reports"||c.pathname.startsWith("/admin/reports/"),children:[a.jsx(Bh,{className:"h-3 w-3"}),a.jsx("span",{children:"Reports"})]})})})})]})})]})})]}),a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Settings & Security"}),a.jsx(nt,{children:a.jsx(ot,{children:mR.map(W=>a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:W.path,className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname===W.path?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(W.icon,{className:C("h-4 w-4",c.pathname===W.path&&"text-primary-foreground")}),a.jsx("span",{children:W.title})]})})},W.path))})})]}),a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Documentation"}),a.jsx(nt,{children:a.jsxs(ot,{children:[a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/docs/total-revenue",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/docs/total-revenue"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Cw,{className:C("h-4 w-4",c.pathname==="/admin/docs/total-revenue"&&"text-primary-foreground")}),a.jsx("span",{children:"Total Revenue"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/docs/ads",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/docs/ads"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Mn,{className:C("h-4 w-4",c.pathname==="/admin/docs/ads"&&"text-primary-foreground")}),a.jsx("span",{children:"Ads Platform"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/docs/ads-analytics",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/docs/ads-analytics"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Cr,{className:C("h-4 w-4",c.pathname==="/admin/docs/ads-analytics"&&"text-primary-foreground")}),a.jsx("span",{children:"Ads Analytics"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/docs/marketplace-escrow",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/docs/marketplace-escrow"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(zr,{className:C("h-4 w-4",c.pathname==="/admin/docs/marketplace-escrow"&&"text-primary-foreground")}),a.jsx("span",{children:"Marketplace & Escrow"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/docs/learning-revenue",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/docs/learning-revenue"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Nr,{className:C("h-4 w-4",c.pathname==="/admin/docs/learning-revenue"&&"text-primary-foreground")}),a.jsx("span",{children:"Learning Revenue"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/docs/profile-match",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/docs/profile-match"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Ds,{className:C("h-4 w-4",c.pathname==="/admin/docs/profile-match"&&"text-primary-foreground")}),a.jsx("span",{children:"Profile Match"})]})})})]})})]}),a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Aptitude Exams"}),a.jsx(nt,{children:a.jsx(ot,{children:a.jsx(ps,{open:v,onOpenChange:_,children:a.jsxs(de,{children:[a.jsx(gs,{asChild:!0,children:a.jsxs(ue,{className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200 w-full",c.pathname.includes("/admin/aptitude")?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Mn,{className:"h-4 w-4"}),a.jsx("span",{className:"flex-1 text-left",children:"Categories"}),a.jsx(us,{className:C("h-4 w-4 transition-transform",v&&"rotate-90")})]})}),a.jsx(xs,{children:a.jsxs($s,{children:[a.jsx(_t,{children:a.jsx(wt,{onClick:()=>u("/admin/aptitude"),isActive:c.pathname==="/admin/aptitude",children:a.jsx("span",{children:"All Categories"})})}),a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u("/admin/aptitude/new"),isActive:c.pathname==="/admin/aptitude/new",children:[a.jsx(Qr,{className:"h-3 w-3"}),a.jsx("span",{children:"Add Category"})]})}),Pe.map(W=>a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u(`/admin/aptitude/${W.id}`),isActive:c.pathname===`/admin/aptitude/${W.id}`,children:[a.jsx("span",{className
655:"truncate",children:W.name}),!W.is_active&&a.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:"(inactive)"})]})},W.id))]})})]})})})})]}),a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Personality Trait Game"}),a.jsx(nt,{children:a.jsxs(ot,{children:[a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/personality-game/overview",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/personality-game/overview"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Cr,{className:"h-4 w-4"}),a.jsx("span",{children:"Overview"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/personality-game",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/personality-game"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(bn,{className:"h-4 w-4"}),a.jsx("span",{children:"Game Settings"})]})})}),a.jsx(ps,{open:b,onOpenChange:w,children:a.jsxs(de,{children:[a.jsx(gs,{asChild:!0,children:a.jsxs(ue,{className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200 w-full",c.pathname.includes("/admin/personality-game/sections")?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(si,{className:"h-4 w-4"}),a.jsx("span",{className:"flex-1 text-left",children:"Trait Sections"}),a.jsx(us,{className:C("h-4 w-4 transition-transform",b&&"rotate-90")})]})}),a.jsx(xs,{children:a.jsxs($s,{children:[a.jsx(_t,{children:a.jsx(wt,{onClick:()=>u("/admin/personality-game/sections"),isActive:c.pathname==="/admin/personality-game/sections",children:a.jsx("span",{children:"All Sections"})})}),Me.map(W=>a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u(`/admin/personality-game/sections/${W.id}`),isActive:c.pathname===`/admin/personality-game/sections/${W.id}`,children:[a.jsx("span",{className:"truncate",children:W.section_name}),!W.is_active&&a.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:"(inactive)"})]})},W.id))]})})]})})]})})]}),a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Community"}),a.jsx(nt,{children:a.jsxs(ot,{children:[a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/users",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/users"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Ss,{className:"h-4 w-4"}),a.jsx("span",{children:"Users"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/verified-users",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/verified-users"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Oo,{className:"h-4 w-4 text-[#1DA1F2]"}),a.jsx("span",{children:"Verified Users"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/verified-pages",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/verified-pages"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(wo,{className:"h-4 w-4 text-[#1DA1F2]"}),a.jsx("span",{children:"Verified Pages"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/appeals",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/appeals"||c.pathname.startsWith("/admin/appeals/")?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Gh,{className:"h-4 w-4"}),a.jsx("span",{children:"Appeals"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/broadcast",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/broadcast"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Xn,{className:"h-4 w-4"}),a.jsx("span",{children:"Broadcast"})]})})}),a.jsx(ps,{open:T,onOpenChange:A,children:a.jsxs(de,{children:[a.jsx(gs,{asChild:!0,children:a.jsxs(ue,{className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200 w-full",c.pathname.includes("/admin/community")?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Xh,{className:"h-4 w-4"}),a.jsx("span",{className:"flex-1 text-left",children:"Moderation"}),a.jsx(us,{className:C("h-4 w-4 transition-transform",T&&"rotate-90")})]})}),a.jsx(xs,{children:a.jsxs($s,{children:[a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u("/admin/community/content-moderation"),isActive:c.pathname==="/admin/community/content-moderation",children:[a.jsx(kr,{className:"h-3 w-3"}),a.jsx("span",{children:"Content Moderation"})]})}),a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u("/admin/community/reported-jobs"),isActive:c.pathname==="/admin/community/reported-jobs",children:[a.jsx(Fo,{className:"h-3 w-3"}),a.jsx("span",{children:"Reported Jobs"}),le>0&&a.jsx(cr,{variant:"destructive",className:"ml-auto h-5 w-5 p-0 justify-center text-xs",children:le>99?"99+":le})]})})]})})]})})]})})]}),a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Site Customization"}),a.jsx(nt,{children:a.jsx(ot,{children:a.jsx(ps,{open:S,onOpenChange:I,children:a.jsxs(de,{children:[a.jsx(gs,{asChild:!0,children:a.jsxs(ue,{className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200 w-full",c.pathname.includes("/admin/customization")?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(zh,{className:"h-4 w-4"}),a.jsx("span",{className:"flex-1 text-left",children:"Customization"}),a.jsx(us,{className:C("h-4 w-4 transition-transform",S&&"rotate-90")})]})}),a.jsx(xs,{children:a.jsxs($s,{children:[a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u("/admin/customization/brand"),isActive:c.pathname==="/admin/customization/brand",children:[a.jsx(Zc,{className:"h-3 w-3"}),a.jsx("span",{children:"Brand & Logo"})]})}),a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u("/admin/customization/footer"),isActive:c.pathname==="/admin/customization/footer",children:[a.jsx($h,{className:"h-3 w-3"}),a.jsx("span",{children:"Footer"})]})}),a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u("/admin/customization/legal"),isActive:c.pathname==="/admin/customization/legal",children:[a.jsx(Wh,{className:"h-3 w-3"}),a.jsx("span",{children:"Legal Pages"})]})}),a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u("/admin/customization/certificate"),isActive:c.pathname==="/admin/customization/certificate",children:[a.jsx(Iw,{className:"h-3 w-3"}),a.jsx("span",{children:"Certificates"})]})})]})})]})})})})]}),a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Marketplace"}),a.jsx(nt,{children:a.jsxs(ot,{children:[a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/projects",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/projects"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Kl,{className:"h-4 w-4"}),a.jsx("span",{children:"Projects"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/mentorship",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/mentorship"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Nr,{className:"h-4 w-4"}),a.jsx("span",{children:"Mentorship"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/disputes",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/disputes"||c.pathname.startsWith("/admin/disputes/")?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Uh,{className:"h-4 w-4"}),a.jsx("span",{children:"Disputes"})]})})})]})})]}),a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Billing"}),a.jsx(nt,{children:a.jsxs(ot,{children:[a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/billing",end:!0,className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/billing"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(zr,{className:"h-4 w-4"}),a.jsx("span",{children:"Billing Admin"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/billing/revenue",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/billing/revenue"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(ni,{className:"h-4 w-4"}),a.jsx("span",{children:"Revenue Overview"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/billing/transactions",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/billing/transactions"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Hh,{className:"h-4 w-4"}),a.jsx("span",{children:"Transactions"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/billing/invoices",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/billing/invoices"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Wl,{className:"h-4 w-4"}),a.jsx("span",{children:"Invoices"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/billing/regional-pricing",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/billing/regional-pricing"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(ra,{className:"h-4 w-4"}),a.jsx("span",{children:"Regional Pricing"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/billing/payment-verification",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/billing/payment-verification"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(bi,{className:"h-4 w-4"}),a.jsx("span",{children:"Payment Verification"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/billing/payment-methods",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/billing/payment-methods"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Yh,{className:"h-4 w-4"}),a.jsx("span",{children:"Payment Methods"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/billing/withdrawals",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/billing/withdrawals"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(zr,{className:"h-4 w-4"}),a.jsx("span",{children:"Withdrawal Requests"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin/billing/escrow",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/admin/billing/escrow"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(kr,{className:"h-4 w-4"}),a.jsx("span",{children:"Escrow Management"})]})})})]})})]})]}),re&&Ke&&a.jsxs(a.Fragment,{children:[a.jsx(Je,{className:"mb-4",children:a.jsxs("div",{className:"flex items-center gap-3 px-3 py-3 rounded-lg bg-amber-500/10 border border-amber-500/20",children:[a.jsx(sE,{className:"h-5 w-5 text-amber-500"}),a.jsxs("div",{className:"flex flex-col",children:[a.jsx("span",{className:"text-base font-semibold text-foreground",children:"Expert Panel"}),a.jsx("span",{className:"text-xs text-muted-foreground",children:"Limited Access"})]})]})}),fe&&Qe.length>0&&a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Main Menu"}),a.jsx(nt,{children:a.jsx(ot,{children:Qe.map(W=>a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:W.path,className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname===W.path?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(W.icon,{className:C("h-4 w-4",c.pathname===W.path&&"text-primary-foreground")}),a.jsx("span",{children:W.title})]})})},W.path))})})]}),et&&a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Aptitude Exams"}),a.jsx(nt,{children:a.jsx(ot,{children:a.jsx(ps,{open:Y,onOpenChange:q,children:a.jsxs(de,{children:[a.jsx(gs,{asChild:!0,children:a.jsxs(ue,{className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200 w-full",c.pathname.includes("/expert/aptitude")?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Mn,{className:"h-4 w-4"}),a.jsx("span",{className:"flex-1 text-left",children:"Categories"}),a.jsx(us,{className:C("h-4 w-4 transition-transform",Y&&"rotate-90")})]})}),a.jsx(xs,{children:a.jsxs($s,{children:[Ee("aptitude.categories")&&a.jsxs(a.Fragment,{children:[a.jsx(_t,{children:a.jsx(wt,{onClick:()=>u("/expert/aptitude"),isActive:c.pathname==="/expert/aptitude",children:a.jsx("span",{children:"All Categories"})})}),a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u("/expert/aptitude/new"),isActive:c.pathname==="/expert/aptitude/new",children:[a.jsx(Qr,{className:"h-3 w-3"}),a.jsx("span",{children:"Add Category"})]})})]}),Ee("aptitude.questions")&&Pe.map(W=>a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u(`/expert/aptitude/${W.id}`),isActive:c.pathname===`/expert/aptitude/${W.id}`,children:[a.jsx("span",{className:"truncate",children:W.name}),!W.is_active&&a.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:"(inactive)"})]})},W.id))]})})]})})})})]}),rt&&a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground up
655percase tracking-widest px-3 mb-2",children:"Personality Trait Game"}),a.jsx(nt,{children:a.jsxs(ot,{children:[Ee("personality.overview")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/personality-game/overview",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/personality-game/overview"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Cr,{className:"h-4 w-4"}),a.jsx("span",{children:"Overview"})]})})}),Ee("personality.settings")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/personality-game",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/personality-game"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(bn,{className:"h-4 w-4"}),a.jsx("span",{children:"Game Settings"})]})})}),Ee("personality.sections")&&a.jsx(ps,{open:X,onOpenChange:F,children:a.jsxs(de,{children:[a.jsx(gs,{asChild:!0,children:a.jsxs(ue,{className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200 w-full",c.pathname.includes("/expert/personality-game/sections")?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(si,{className:"h-4 w-4"}),a.jsx("span",{className:"flex-1 text-left",children:"Trait Sections"}),a.jsx(us,{className:C("h-4 w-4 transition-transform",X&&"rotate-90")})]})}),a.jsx(xs,{children:a.jsxs($s,{children:[a.jsx(_t,{children:a.jsx(wt,{onClick:()=>u("/expert/personality-game/sections"),isActive:c.pathname==="/expert/personality-game/sections",children:a.jsx("span",{children:"All Sections"})})}),Me.map(W=>a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u(`/expert/personality-game/sections/${W.id}`),isActive:c.pathname===`/expert/personality-game/sections/${W.id}`,children:[a.jsx("span",{className:"truncate",children:W.section_name}),!W.is_active&&a.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:"(inactive)"})]})},W.id))]})})]})})]})})]}),We&&a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Site Customization"}),a.jsx(nt,{children:a.jsx(ot,{children:a.jsx(ps,{open:P,onOpenChange:N,children:a.jsxs(de,{children:[a.jsx(gs,{asChild:!0,children:a.jsxs(ue,{className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200 w-full",c.pathname.includes("/expert/customization")?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(zh,{className:"h-4 w-4"}),a.jsx("span",{className:"flex-1 text-left",children:"Customization"}),a.jsx(us,{className:C("h-4 w-4 transition-transform",P&&"rotate-90")})]})}),a.jsx(xs,{children:a.jsxs($s,{children:[Ee("customization.brand")&&a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u("/expert/customization/brand"),isActive:c.pathname==="/expert/customization/brand",children:[a.jsx(Zc,{className:"h-3 w-3"}),a.jsx("span",{children:"Brand & Logo"})]})}),Ee("customization.footer")&&a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u("/expert/customization/footer"),isActive:c.pathname==="/expert/customization/footer",children:[a.jsx($h,{className:"h-3 w-3"}),a.jsx("span",{children:"Footer"})]})}),Ee("customization.legal")&&a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u("/expert/customization/legal"),isActive:c.pathname==="/expert/customization/legal",children:[a.jsx(Wh,{className:"h-3 w-3"}),a.jsx("span",{children:"Legal Pages"})]})})]})})]})})})})]}),dt&&a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Technical Team"}),a.jsx(nt,{children:a.jsxs(ot,{children:[Ee("technical_team.algorithm_debug")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/algorithm-debug",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/algorithm-debug"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Cr,{className:"h-4 w-4"}),a.jsx("span",{children:"Algorithm Debug"})]})})}),Ee("technical_team.feed_algorithm")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/feed-algorithm",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/feed-algorithm"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Lh,{className:"h-4 w-4"}),a.jsx("span",{children:"Feed Algorithm"})]})})}),Ee("technical_team.cross_learning")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/cross-learning",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/cross-learning"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(si,{className:"h-4 w-4"}),a.jsx("span",{children:"Cross-Learning"})]})})}),Ee("technical_team.reports")&&a.jsx(ps,{open:O,onOpenChange:$,children:a.jsxs(de,{children:[a.jsx(gs,{asChild:!0,children:a.jsxs(ue,{className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200 w-full",c.pathname.includes("/expert/reports")?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Oh,{className:"h-4 w-4"}),a.jsx("span",{className:"flex-1 text-left",children:"Support"}),a.jsx(us,{className:C("h-4 w-4 transition-transform",O&&"rotate-90")})]})}),a.jsx(xs,{children:a.jsx($s,{children:a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u("/expert/reports"),isActive:c.pathname==="/expert/reports"||c.pathname.startsWith("/expert/reports/"),children:[a.jsx(Bh,{className:"h-3 w-3"}),a.jsx("span",{children:"Reports"})]})})})})]})}),Ee("technical_team.identity_verifications")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/identity-verifications",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/identity-verifications"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Vw,{className:"h-4 w-4"}),a.jsx("span",{children:"Identity Verifications"})]})})})]})})]}),pe&&a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Settings & Security"}),a.jsx(nt,{children:a.jsxs(ot,{children:[Ee("settings.security")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/security",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/security"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(kr,{className:"h-4 w-4"}),a.jsx("span",{children:"Security"})]})})}),Ee("settings.ai_settings")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/ai-settings",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/ai-settings"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Eo,{className:"h-4 w-4"}),a.jsx("span",{children:"AI Settings"})]})})}),Ee("settings.maintenance")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/maintenance",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/maintenance"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(du,{className:"h-4 w-4"}),a.jsx("span",{children:"Maintenance"})]})})}),Ee("settings.database_backup")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/database-backup",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/database-backup"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Zg,{className:"h-4 w-4"}),a.jsx("span",{children:"Database Backup"})]})})})]})})]}),ge&&a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Community"}),a.jsx(nt,{children:a.jsxs(ot,{children:[Ee("community.users")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/users",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/users"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Ss,{className:"h-4 w-4"}),a.jsx("span",{children:"Users"})]})})}),Ee("community.verified_users")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/verified-users",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/verified-users"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Oo,{className:"h-4 w-4 text-[#1DA1F2]"}),a.jsx("span",{children:"Verified Users"})]})})}),Ee("community.verified_users")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/verified-pages",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/verified-pages"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(wo,{className:"h-4 w-4 text-[#1DA1F2]"}),a.jsx("span",{children:"Verified Pages"})]})})}),Ee("community.appeals")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/appeals",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/appeals"||c.pathname.startsWith("/expert/appeals/")?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Gh,{className:"h-4 w-4"}),a.jsx("span",{children:"Appeals"})]})})}),Ee("community.broadcast")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/broadcast",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/broadcast"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Xn,{className:"h-4 w-4"}),a.jsx("span",{children:"Broadcast"})]})})}),(Ee("community.content_moderation")||Ee("community.reported_jobs"))&&a.jsx(ps,{open:B,onOpenChange:U,children:a.jsxs(de,{children:[a.jsx(gs,{asChild:!0,children:a.jsxs(ue,{className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200 w-full",c.pathname.includes("/expert/community")?"bg-primary/10 text-primary":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Xh,{className:"h-4 w-4"}),a.jsx("span",{className:"flex-1 text-left",children:"Moderation"}),a.jsx(us,{className:C("h-4 w-4 transition-transform",B&&"rotate-90")})]})}),a.jsx(xs,{children:a.jsxs($s,{children:[Ee("community.content_moderation")&&a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u("/expert/community/content-moderation"),isActive:c.pathname==="/expert/community/content-moderation",children:[a.jsx(kr,{className:"h-3 w-3"}),a.jsx("span",{children:"Content Moderation"})]})}),Ee("community.reported_jobs")&&a.jsx(_t,{children:a.jsxs(wt,{onClick:()=>u("/expert/community/reported-jobs"),isActive:c.pathname==="/expert/community/reported-jobs",children:[a.jsx(Fo,{className:"h-3 w-3"}),a.jsx("span",{children:"Reported Jobs"})]})})]})})]})}),Ee("community.username_settings")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/community/username-settings",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/community/username-settings"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Qg,{className:"h-4 w-4"}),a.jsx("span",{children:"Username Settings"})]})})})]})})]}),be&&a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Billing"}),a.jsx(nt,{children:a.jsxs(ot,{children:[Ee("billing.admin")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/billing",end:!0,className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/billing"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(zr,{className:"h-4 w-4"}),a.jsx("span",{children:"Billing Admin"})]})})}),Ee("billing.revenue")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/billing/revenue",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/billing/revenue"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(ni,{className:"h-4 w-4"}),a.jsx("span",{children:"Revenue Overview"})]})})}),Ee("billing.transactions")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/billing/transactions",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/billing/transactions"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Hh,{className:"h-4 w-4"}),a.jsx("span",{children:"Transactions"})]})})}),Ee("billing.invoices")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/billing/invoices",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/billing/invoices"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Wl,{className:"h-4 w-4"}),a.jsx("span",{children:"Invoices"})]})})}),Ee("billing.regional_pricing")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/billing/regional-pricing",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/billing/regional-pricing"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(ra,{className:"h-4 w-4"}),a.jsx("span",{children:"Regional Pricing"})]})})}),Ee("billing.payment_verification")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/billing/payment-verification",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/billing/payment-verification"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(bi,{className:"h-4 w-4"}),a.jsx("span",{children:"Payment Verification"})]})})}),Ee("billing.payment_methods")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expe
655rt/billing/payment-methods",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/billing/payment-methods"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Yh,{className:"h-4 w-4"}),a.jsx("span",{children:"Payment Methods"})]})})}),Ee("billing.withdrawals")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/billing/withdrawals",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/billing/withdrawals"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(zr,{className:"h-4 w-4"}),a.jsx("span",{children:"Withdrawal Requests"})]})})}),Ee("billing.escrow")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/billing/escrow",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/billing/escrow"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(kr,{className:"h-4 w-4"}),a.jsx("span",{children:"Escrow Management"})]})})})]})})]}),ie&&a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Projects"}),a.jsx(nt,{children:a.jsx(ot,{children:Ee("projects.disputes")&&a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/expert/project-disputes",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/expert/project-disputes"||c.pathname.startsWith("/expert/project-disputes/")?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Uh,{className:"h-4 w-4"}),a.jsx("span",{children:"Project Disputes"})]})})})})})]})]}),ve&&!Be&&!Ke&&a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Nr,{className:"h-3 w-3"}),"Trainer Portal"]})}),a.jsx(nt,{children:a.jsxs(ot,{children:[a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/trainer",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/trainer"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Dr,{className:"h-4 w-4"}),a.jsx("span",{children:"Dashboard"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/trainer/courses",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/trainer/courses"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Mn,{className:"h-4 w-4"}),a.jsx("span",{children:"My Courses"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/trainer/earnings",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",c.pathname==="/trainer/earnings"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(zr,{className:"h-4 w-4"}),a.jsx("span",{children:"Earnings"})]})})})]})})]}),!Be&&!Ke&&a.jsx(a.Fragment,{children:o&&i?a.jsxs(a.Fragment,{children:[a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Page Management"}),a.jsx(nt,{children:a.jsxs(ot,{children:[a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:`/page/${i.slug}/settings`,className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",se(`/page/${i.slug}/settings`)?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(bn,{className:C("h-4 w-4",se(`/page/${i.slug}/settings`)&&"text-primary-foreground")}),a.jsx("span",{children:"Page Settings"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:`/page/${i.slug}`,className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",se(`/page/${i.slug}`,!0)?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(ra,{className:C("h-4 w-4",se(`/page/${i.slug}`,!0)&&"text-primary-foreground")}),a.jsx("span",{children:"View Page"})]})})})]})})]}),i.has_hr_access&&a.jsxs(a.Fragment,{children:[a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Recruiting"}),a.jsx(nt,{children:a.jsxs(ot,{children:[a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/dashboard",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",se("/dashboard",!0)?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Dr,{className:C("h-4 w-4",se("/dashboard",!0)&&"text-primary-foreground")}),a.jsx("span",{children:"Dashboard"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/hr/analytics",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",se("/hr/analytics")?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Cr,{className:C("h-4 w-4",se("/hr/analytics")&&"text-primary-foreground")}),a.jsx("span",{children:"Job Analytics"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/dashboard",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",se("/dashboard")?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Es,{className:C("h-4 w-4",se("/dashboard")&&"text-primary-foreground")}),a.jsx("span",{children:"My Jobs"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/hr/aptitude",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",se("/hr/aptitude")?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx($a,{className:C("h-4 w-4",se("/hr/aptitude")&&"text-primary-foreground")}),a.jsx("span",{children:"Aptitude Tests"})]})})})]})})]}),a.jsx(Je,{className:"mb-2",children:a.jsxs(ps,{open:m,onOpenChange:p,children:[a.jsx(gs,{className:"w-full",children:a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 text-[11px] font-semibold text-muted-foreground uppercase tracking-widest hover:text-foreground transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ni,{className:"h-3.5 w-3.5"}),a.jsx("span",{children:"Pipeline Overview"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[ct>0&&a.jsx(cr,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:ct}),a.jsx(ri,{className:C("h-4 w-4 transition-transform",m&&"rotate-180")}
655)]})]})}),a.jsx(xs,{children:a.jsx(nt,{children:a.jsx(ot,{children:Bf.map(W=>{const Se=h[W.value]||0,it=c.pathname===`/hr/pipeline/${W.value}`,Ct=W.icon;return a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:`/hr/pipeline/${W.value}`,className:C("flex items-center justify-between rounded-lg px-3 py-2 text-sm font-medium transition-all duration-200",it?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Ct,{className:C("h-4 w-4",it&&"text-primary-foreground")}),a.jsx("span",{children:W.label})]}),Se>0&&a.jsx(cr,{variant:it?"secondary":"outline",className:C("h-5 px-1.5 text-[10px] min-w-[20px] justify-center",it&&"bg-primary-foreground/20 text-primary-foreground border-0"),children:Se})]})})},W.value)})})})})]})})]})]}):a.jsxs(a.Fragment,{children:[Ve.map(W=>a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:W.title}),a.jsx(nt,{children:a.jsx(ot,{children:W.items.map(Se=>{const it=se(Se.url,Se.exact),Ct=Se.highlight,Ne=Se.badge;return a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:Se.url,className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",it?"bg-primary text-primary-foreground shadow-sm":Ct?"bg-gradient-to-r from-accent/20 to-primary/20 text-foreground hover:from-accent/30 hover:to-primary/30 border border-accent/30":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Se.icon,{className:C("h-4 w-4",it&&"text-primary-foreground",Ct&&!it&&"text-primary")}),a.jsx("span",{className:"flex-1",children:Se.title}),Ne&&!it&&a.jsxs(cr,{variant:"secondary",className:"ml-auto h-5 px-1.5 text-[10px] font-semibold bg-primary/10 text-primary border-0",children:[a.jsx(Eo,{className:"h-2.5 w-2.5 mr-0.5"}),Ne]})]})})},Se.title)})})})]},W.title)),t&&a.jsx(Je,{className:"mb-2",children:a.jsxs(ps,{open:At,onOpenChange:Yt,children:[a.jsx(gs,{className:"w-full",children:a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 text-[11px] font-semibold text-muted-foreground uppercase tracking-widest hover:text-foreground transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Es,{className:"h-3.5 w-3.5"}),a.jsx("span",{children:"HR Overview"}),r&&a.jsx(cr,{variant:"secondary",className:"h-4 px-1.5 text-[9px] font-normal normal-case tracking-normal",children:"Shared"})]}),a.jsx(ri,{className:C("h-4 w-4 transition-transform",At&&"rotate-180")})]})}),a.jsx(xs,{children:a.jsx(nt,{children:a.jsx(ot,{children:It.filter(W=>!(r&&W.url==="/hr/aptitude/create")).map(W=>{const Se=se(W.url,W.exact);return a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:W.url,className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",Se?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(W.icon,{className:C("h-4 w-4",Se&&"text-primary-foreground")}),a.jsx("span",{children:W.title})]})})},W.title+W.url)})})})})]})}),t&&a.jsx(Je,{className:"mb-2",children:a.jsxs(ps,{open:m,onOpenChange:p,children:[a.jsx(gs,{className:"w-full",children:a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 text-[11px] font-semibold text-muted-foreground uppercase tracking-widest hover:text-foreground transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ni,{className:"h-3.5 w-3.5"}),a.jsx("span",{children:"Pipeline Overview"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[ct>0&&a.jsx(cr,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:ct}),a.jsx(ri,{className:C("h-4 w-4 transition-transform",m&&"rotate-180")})]})]})}),a.jsx(xs,{children:a.jsx(nt,{children:a.jsx(ot,{children:Bf.map(W=>{const Se=h[W.value]||0,it=c.pathname===`/hr/pipeline/${W.value}`,Ct=W.icon;return a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:`/hr/pipeline/${W.value}`,className:C("flex items-center justify-between rounded-lg px-3 py-2 text-sm font-medium transition-all duration-200",it?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Ct,{className:C("h-4 w-4",it&&"text-primary-foreground")}),a.jsx("span",{children:W.label})]}),Se>0&&a.jsx(cr,{variant:it?"secondary":"outline",className:C("h-5 px-1.5 text-[10px] min-w-[20px] justify-center",it&&"bg-primary-foreground
655/20 text-primary-foreground border-0"),children:Se})]})})},W.value)})})})})]})}),Q&&a.jsx(Je,{className:"mb-2",children:a.jsx(nt,{children:a.jsx(ot,{children:a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/admin",className:`flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium 
656                                         bg-gradient-to-r from-purple-500/10 to-purple-600/10 
657                                         border border-purple-500/20 hover:border-purple-500/40
658                                         text-foreground transition-all`,children:[a.jsx(kr,{className:"h-4 w-4 text-purple-500"}),a.jsx("span",{className:"flex-1",children:"Admin Dashboard"}),a.jsx(cr,{variant:"secondary",className:"bg-purple-500/10 text-purple-500 text-[10px] border-0",children:"ADMIN"})]})})})})})}),!t&&a.jsx(Je,{className:"mb-2",children:a.jsx(nt,{children:a.jsx(ot,{children:a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/settings/enable-hr",className:`flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium 
659                                         bg-gradient-to-r from-primary/10 to-accent/10 
660                                         border border-primary/20 hover:border-primary/40
661                                         text-foreground transition-all`,children:[a.jsx(wo,{className:"h-4 w-4 text-primary"}),a.jsx("span",{className:"flex-1",children:"Become a Recruiter"}),a.jsxs(cr,{variant:"secondary",className:"bg-primary/10 text-primary text-[10px] border-0",children:[a.jsx(Eo,{className:"h-2.5 w-2.5 mr-0.5"}),"FREE"]})]})})})})})}),a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Projects"}),a.jsx(nt,{children:a.jsxs(ot,{children:[a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/projects",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",se("/projects",!0)?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Ds,{className:C("h-4 w-4",se("/projects",!0)&&"text-primary-foreground")}),a.jsx("span",{children:"Browse Projects"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/my-projects",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",se("/my-projects")?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Kl,{className:C("h-4 w-4",se("/my-projects")&&"text-primary-foreground")}),a.jsx("span",{children:"My Projects"})]})})})]})})]}),a.jsxs(Je,{className:"mb-2",children:[a.jsx(gt,{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-widest px-3 mb-2",children:"Billing"}),a.jsx(nt,{children:a.jsxs(ot,{children:[a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/billing/summary",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",se("/billing/summary")?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(zr,{className:C("h-4 w-4",se("/billing/summary")&&"text-primary-foreground")}),a.jsx("span",{children:"Billing Summary"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/billing/settings",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",se("/billing/settings")?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(bn,{className:C("h-4 w-4",se("/billing/settings")&&"text-primary-foreground")}),a.jsx("span",{children:"Payment Settings"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/billing/invoices",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",se("/billing/invoices")?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Wl,{className:C("h-4 w-4",se("/billing/invoices")&&"text-primary-foreground")}),a.jsx("span",{children:"Invoices"})]})})}),a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/billing/transactions",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",se("/billing/transactions")?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Jg,{className:C("h-4 w-4",se("/billing/transactions")&&"text-primary-foreground")}),a.jsx("span",{children:"Transactions"})]})})})]})})]}),a.jsx(Je,{className:"mb-2",children:a.jsxs(ps,{open:x,onOpenChange:y,children:[a.jsx(gs,{className:"w-full",children:a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 text-[11px] font-semibold text-muted-foreground uppercase tracking-widest hover:text-foreground transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(bn,{className:"h-3.5 w-3.5"}),a.jsx("span",{children:"Account Center"})]}),a.jsx(ri,{className:C("h-4 w-4 transition-transform",x&&"rotate-180")}
661)]})}),a.jsx(xs,{children:a.jsx(nt,{children:a.jsx(ot,{children:pR.map(W=>{const Se=se(W.url);return a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:W.url,className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",Se?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(W.icon,{className:C("h-4 w-4",Se&&"text-primary-foreground")}),a.jsx("span",{children:W.title})]})})},W.title)})})})})]})})]})}),!Be&&!Ke&&a.jsx(Je,{className:"mb-2",children:a.jsx(nt,{children:a.jsx(ot,{children:a.jsx(de,{children:a.jsxs("div",{className:"flex items-center justify-between rounded-lg px-3 py-2.5",children:[a.jsxs("div",{className:"flex items-center gap-3 text-sm font-medium text-muted-foreground",children:[l==="dark"?a.jsx(Ww,{className:"h-4 w-4"}):a.jsx(rE,{className:"h-4 w-4"}),a.jsx("span",{children:"Dark Mode"})]}),a.jsx(yx,{checked:l==="dark",onCheckedChange:W=>d(W?"dark":"light")})]})})})})}),!Be&&!Ke&&a.jsx(Je,{className:"mb-2",children:a.jsx(nt,{children:a.jsx(ot,{children:a.jsx(de,{children:a.jsx(ue,{asChild:!0,children:a.jsxs(me,{to:"/reports",className:C("flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200",se("/reports")?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:[a.jsx(Lw,{className:C("h-4 w-4",se("/reports")&&"text-primary-foreground")}),a.jsx("span",{children:"Help and Support"})]})})})})})})]}),a.jsx(lx,{className:"border-t p-4",children:a.jsxs(ye,{variant:"ghost",className:"w-full justify-start gap-3 text-muted-foreground hover:text-destructive hover:bg-destructive/10",onClick:oe,children:[a.jsx(Hw,{className:"h-4 w-4"}),"Sign Out"]})})]})}function vx(){const{user:s}=$t(),[e,t]=g.useState([]),[r,n]=g.useState(0),[i,o]=g.useState(!0),l=async()=>{if(!s){t([]),n(0),o(!1);return}try{const{data:u,error:h}=await L.from("notifications").select("*").eq("user_id",s.id).order("created_at",{ascending:!1}).limit(20);if(h)throw h;t(u||[]),n((u==null?void 0:u.filter(f=>!f.is_read).length)||0)}catch(u){console.error("Error fetching notifications:",u)}finally{o(!1)}},d=async u=>{try{const{error:h}=await L.from("notifications").update({is_read:!0}).eq("id",u);if(h)throw h;t(f=>f.map(m=>m.id===u?{...m,is_read:!0}:m)),n(f=>Math.max(0,f-1))}catch(h){console.error("Error marking notification as read:",h)}},c=async()=>{if(s)try{const{error:u}=await L.from("notifications").update({is_read:!0}).eq("user_id",s.id).eq("is_read",!1);if(u)throw u;t(h=>h.map(f=>({...f,is_read:!0}))),n(0)}catch(u){console.error("Error marking all notifications as read:",u)}};return g.useEffect(()=>{l()},[s]),g.useEffect(()=>{if(!s)return;const u=L.channel("notifications-realtime").on("postgres_changes",{event:"INSERT",schema:"public",table:"notifications",filter:`user_id=eq.${s.id}`},h=>{const f=h.new;t(m=>[f,...m]),f.is_read||n(m=>m+1)}).on("postgres_changes",{event:"UPDATE",schema:"public",table:"notifications",filter:`user_id=eq.${s.id}`},h=>{const f=h.new;t(m=>m.map(p=>p.id===f.id?f:p))}).subscribe();return()=>{L.removeChannel(u)}},[s]),{notifications:e,unreadCount:r,loading:i,markAsRead:d,markAllAsRead:c,refetch:l}}const yR=E_,vR=S_,bx=g.forwardRef(({className:s,align:e="center",sideOffset:t=4,...r},n)=>a.jsx(w_,{children:a.jsx(xg,{ref:n,align:e,sideOffset:t,className:C("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...r})}));bx.displayName=xg.displayName;function bR(s,e){return g.useReducer((t,r)=>e[t][r]??t,s)}var Ru="ScrollArea",[_x]=cn(Ru),[_R,qs]=_x(Ru),wx=g.forwardRef((s,e)=>{const{__scopeScrollArea:t,type:r="hover",dir:n,scrollHideDelay:i=600,...o}=s,[l,d]=g.useState(null),[c,u]=g.useState(null),[h,f]=g.useState(null),[m,p]=g.useState(null),[x,y]=g.useState(null),[v,_]=g.useState(0),[b,w]=g.useState(0),[T,A]=g.useState(!1),[S,I]=g.useState(!1),j=qt(e,k=>d(k)),R=yg(n);return a.jsx(_R,{scope:t,type:r,dir:R,scrollHideDelay:i,scrollArea:l,viewport:c,onViewportChange:u,content:h,onContentChange:f,scrollbarX:m,onScrollbarXChange:p,scrollbarXEnabled:T,onScrollbarXEnabledChange:A,scrollbarY:x,onScrollbarYChange:y,scrollbarYEnabled:S,onScrollbarYEnabledChange:I,onCornerWidthChange:_,onCornerHeight
vendor: 5,685 bytes, line 661
661Change:w,children:a.jsx(bt.div,{dir:R,...o,ref:j,style:{position:"relative","--radix-scroll-area-corner-width":v+"px","--radix-scroll-area-corner-height":b+"px",...s.style}})})});wx.displayName=Ru;var Ex="ScrollAreaViewport",Sx=g.forwardRef((s,e)=>{const{__scopeScrollArea:t,children:r,nonce:n,...i}=s,o=qs(Ex,t),l=g.useRef(null),d=qt(e,l,o.onViewportChange);return a.jsxs(a.Fragment,{children:[a.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:n}),a.jsx(bt.div,{"data-radix-scroll-area-viewport":"",...i,ref:d,style:{overflowX:o.scrollbarXEnabled?"scroll":"hidden",overflowY:o.scrollbarYEnabled?"scroll":"hidden",...s.style},children:a.jsx("div",{ref:o.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});Sx.displayName=Ex;var wr="ScrollAreaScrollbar",ju=g.forwardRef((s,e)=>{const{forceMount:t,...r}=s,n=qs(wr,s.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:o}=n,l=s.orientation==="horizontal";return g.useEffect(()=>(l?i(!0):o(!0),()=>{l?i(!1):o(!1)}),[l,i,o]),n.type==="hover"?a.jsx(wR,{...r,ref:e,forceMount:t}):n.type==="scroll"?a.jsx(ER,{...r,ref:e,forceMount:t}):n.type==="auto"?a.jsx(Tx,{...r,ref:e,forceMount:t}):n.type==="always"?a.jsx(Iu,{...r,ref:e}):null});ju.displayName=wr;var wR=g.forwardRef((s,e)=>{const{forceMount:t,...r}=s,n=qs(wr,s.__scopeScrollArea),[i,o]=g.useState(!1);return g.useEffect(()=>{const l=n.scrollArea;let d=0;if(l){const c=()=>{window.clearTimeout(d),o(!0)},u=()=>{d=window.setTimeout(()=>o(!1),n.scrollHideDelay)};return l.addEventListener("pointerenter",c),l.addEventListener("pointerleave",u),()=>{window.clearTimeout(d),l.removeEventListener("pointerenter",c),l.removeEventListener("pointerleave",u)}}},[n.scrollArea,n.scrollHideDelay]),a.jsx(Ln,{present:t||i,children:a.jsx(Tx,{"data-state":i?"visible":"hidden",...r,ref:e})})}),ER=g.forwardRef((s,e)=>{const{forceMount:t,...r}=s,n=qs(wr,s.__scopeScrollArea),i=s.orientation==="horizontal",o=Rl(()=>d("SCROLL_END"),100),[l,d]=bR("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return g.useEffect(()=>{if(l==="idle"){const c=window.setTimeout(()=>d("HIDE"),n.scrollHideDelay);return()=>window.clearTimeout(c)}},[l,n.scrollHideDelay,d]),g.useEffect(()=>{const c=n.viewport,u=i?"scrollLeft":"scrollTop";if(c){let h=c[u];const f=()=>{const m=c[u];h!==m&&(d("SCROLL"),o()),h=m};return c.addEventListener("scroll",f),()=>c.removeEventListener("scroll",f)}},[n.viewport,i,d,o]),a.jsx(Ln,{present:t||l!=="hidden",children:a.jsx(Iu,{"data-state":l==="hidden"?"hidden":"visible",...r,ref:e,onPointerEnter:Et(s.onPointerEnter,()=>d("POINTER_ENTER")),onPointerLeave:Et(s.onPointerLeave,()=>d("POINTER_LEAVE"))})})}),Tx=g.forwardRef((s,e)=>{const t=qs(wr,s.__scopeScrollArea),{forceMount:r,...n}=s,[i,o]=g.useState(!1),l=s.orientation==="horizontal",d=Rl(()=>{if(t.viewport){const c=t.viewport.offsetWidth<t.viewport.scrollWidth,u=t.viewport.offsetHeight<t.viewport.scrollHeight;o(l?c:u)}},10);return Ei(t.viewport,d),Ei(t.content,d),a.jsx(Ln,{present:r||i,children:a.jsx(Iu,{"data-state":i?"visible":"hidden",...n,ref:e})})}),Iu=g.forwardRef((s,e)=>{const{orientation:t="vertical",...r}=s,n=qs(wr,s.__scopeScrollArea),i=g.useRef(null),o=g.useRef(0),[l,d]=g.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),c=Ix(l.viewport,l.content),u={...r,sizes:l,onSizesChange:d,hasThumb:c>0&&c<1,onThumbChange:f=>i.current=f,onThumbPointerUp:()=>o.current=0,onThumbPointerDown:f=>o.current=f};function h(f,m){return jR(f,o.current,l,m)}return t==="horizontal"?a.jsx(SR,{...u,ref:e,onThumbPositionChange:()=>{if(n.viewport&&i.current){const f=n.viewport.scrollLeft,m=Vf(f,l,n.dir);i.current.style.transform=`translate3d(${m}px, 0, 0)`}},onWheelScroll:f=>{n.viewport&&(n.viewport.scrollLeft=f)},onDragScroll:f=>{n.viewport&&(n.viewport.scrollLeft=h(f,n.dir))}}):t==="vertical"?a.jsx(TR,{...u,ref:e,onThumbPositionChange:()=>{if(n.viewport&&i.current){const f=n.viewport.scrollTop,m=Vf(f,l);i.current.style.transform=`translate3d(0, ${m}px, 0)`}},onWheelScroll:f=>{n.viewport&&(n.viewport.scrollTop=f)},onDragScroll:f=>{n.viewport&&(n.viewport.scrollTop=h(f))}}):null}),SR=g.forwardRef((s,e)=>{const{sizes:t,onSizesChange:r,...n}=s,i=qs(wr,s.__scopeScrollArea),[o,l]=g.useState(),d=g.useRef(null),c=qt(e,d,i.onScrollbarXChange);return g.useEffect(()=>{d.current&&l(getComputedStyle(d.current))},[d]),a.jsx(kx,{"data-orientation":"horizontal",...n,ref:c,sizes:t,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":kl(t)+"px",...s.style},onThumbPointerDown:u=>s.onThumbPointerDown(u.x),onDragScroll:u=>s.onDragScroll(u.x),onWheelScroll:(u,h)=>{if(i.viewport){const f=i.viewport.scrollLeft+u.deltaX;s.onWheelScroll(f),Nx(f,h)&&u.preventDefault()}},onResize:()=>{d.current&&i.viewport&&o&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:d.current.clientWidth,paddingStart:Xo(o.paddingLeft),paddingEnd:Xo(o.paddingRight)}})}})}),TR=g.forwardRef((s,e)=>{const{sizes:t,onSizesChange:r,...n}=s,i=qs(wr,s.__scopeScrollArea),[o,l]=g.useState(),d=g.useRef(null),c=qt(e,d,i.onScrollbarYChange);return g.useEffect(()=>{d.current&&l(getComputedStyle(d.current))},[d]),a.jsx(kx,{"data-orientation":"vertical",...n,ref:c,sizes:t,style:{to
vendor: 5,543 bytes, line 661
661p:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":kl(t)+"px",...s.style},onThumbPointerDown:u=>s.onThumbPointerDown(u.y),onDragScroll:u=>s.onDragScroll(u.y),onWheelScroll:(u,h)=>{if(i.viewport){const f=i.viewport.scrollTop+u.deltaY;s.onWheelScroll(f),Nx(f,h)&&u.preventDefault()}},onResize:()=>{d.current&&i.viewport&&o&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:d.current.clientHeight,paddingStart:Xo(o.paddingTop),paddingEnd:Xo(o.paddingBottom)}})}})}),[AR,Ax]=_x(wr),kx=g.forwardRef((s,e)=>{const{__scopeScrollArea:t,sizes:r,hasThumb:n,onThumbChange:i,onThumbPointerUp:o,onThumbPointerDown:l,onThumbPositionChange:d,onDragScroll:c,onWheelScroll:u,onResize:h,...f}=s,m=qs(wr,t),[p,x]=g.useState(null),y=qt(e,j=>x(j)),v=g.useRef(null),_=g.useRef(""),b=m.viewport,w=r.content-r.viewport,T=Us(u),A=Us(d),S=Rl(h,10);function I(j){if(v.current){const R=j.clientX-v.current.left,k=j.clientY-v.current.top;c({x:R,y:k})}}return g.useEffect(()=>{const j=R=>{const k=R.target;(p==null?void 0:p.contains(k))&&T(R,w)};return document.addEventListener("wheel",j,{passive:!1}),()=>document.removeEventListener("wheel",j,{passive:!1})},[b,p,w,T]),g.useEffect(A,[r,A]),Ei(p,S),Ei(m.content,S),a.jsx(AR,{scope:t,scrollbar:p,hasThumb:n,onThumbChange:Us(i),onThumbPointerUp:Us(o),onThumbPositionChange:A,onThumbPointerDown:Us(l),children:a.jsx(bt.div,{...f,ref:y,style:{position:"absolute",...f.style},onPointerDown:Et(s.onPointerDown,j=>{j.button===0&&(j.target.setPointerCapture(j.pointerId),v.current=p.getBoundingClientRect(),_.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",m.viewport&&(m.viewport.style.scrollBehavior="auto"),I(j))}),onPointerMove:Et(s.onPointerMove,I),onPointerUp:Et(s.onPointerUp,j=>{const R=j.target;R.hasPointerCapture(j.pointerId)&&R.releasePointerCapture(j.pointerId),document.body.style.webkitUserSelect=_.current,m.viewport&&(m.viewport.style.scrollBehavior=""),v.current=null})})})}),Yo="ScrollAreaThumb",Rx=g.forwardRef((s,e)=>{const{forceMount:t,...r}=s,n=Ax(Yo,s.__scopeScrollArea);return a.jsx(Ln,{present:t||n.hasThumb,children:a.jsx(kR,{ref:e,...r})})}),kR=g.forwardRef((s,e)=>{const{__scopeScrollArea:t,style:r,...n}=s,i=qs(Yo,t),o=Ax(Yo,t),{onThumbPositionChange:l}=o,d=qt(e,h=>o.onThumbChange(h)),c=g.useRef(void 0),u=Rl(()=>{c.current&&(c.current(),c.current=void 0)},100);return g.useEffect(()=>{const h=i.viewport;if(h){const f=()=>{if(u(),!c.current){const m=IR(h,l);c.current=m,l()}};return l(),h.addEventListener("scroll",f),()=>h.removeEventListener("scroll",f)}},[i.viewport,u,l]),a.jsx(bt.div,{"data-state":o.hasThumb?"visible":"hidden",...n,ref:d,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:Et(s.onPointerDownCapture,h=>{const m=h.target.getBoundingClientRect(),p=h.clientX-m.left,x=h.clientY-m.top;o.onThumbPointerDown({x:p,y:x})}),onPointerUp:Et(s.onPointerUp,o.onThumbPointerUp)})});Rx.displayName=Yo;var Cu="ScrollAreaCorner",jx=g.forwardRef((s,e)=>{const t=qs(Cu,s.__scopeScrollArea),r=!!(t.scrollbarX&&t.scrollbarY);return t.type!=="scroll"&&r?a.jsx(RR,{...s,ref:e}):null});jx.displayName=Cu;var RR=g.forwardRef((s,e)=>{const{__scopeScrollArea:t,...r}=s,n=qs(Cu,t),[i,o]=g.useState(0),[l,d]=g.useState(0),c=!!(i&&l);return Ei(n.scrollbarX,()=>{var h;const u=((h=n.scrollbarX)==null?void 0:h.offsetHeight)||0;n.onCornerHeightChange(u),d(u)}),Ei(n.scrollbarY,()=>{var h;const u=((h=n.scrollbarY)==null?void 0:h.offsetWidth)||0;n.onCornerWidthChange(u),o(u)}),c?a.jsx(bt.div,{...r,ref:e,style:{width:i,height:l,position:"absolute",right:n.dir==="ltr"?0:void 0,left:n.dir==="rtl"?0:void 0,bottom:0,...s.style}}):null});function Xo(s){return s?parseInt(s,10):0}function Ix(s,e){const t=s/e;return isNaN(t)?0:t}function kl(s){const e=Ix(s.viewport,s.content),t=s.scrollbar.paddingStart+s.scrollbar.paddingEnd,r=(s.scrollbar.size-t)*e;return Math.max(r,18)}function jR(s,e,t,r="ltr"){const n=kl(t),i=n/2,o=e||i,l=n-o,d=t.scrollbar.paddingStart+o,c=t.scrollbar.size-t.scrollbar.paddingEnd-l,u=t.content-t.viewport,h=r==="ltr"?[0,u]:[u*-1,0];return Cx([d,c],h)(s)}function Vf(s,e,t="ltr"){const r=kl(e),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,i=e.scrollbar.size-n,o=e.content-e.viewport,l=i-r,d=t==="ltr"?[0,o]:[o*-1,0],c=nu(s,d);return Cx([0,o],[0,l])(c)}function Cx(s,e){return t=>{if(s[0]===s[1]||e[0]===e[1])return e[0];const r=(e[1]-e[0])/(s[1]-s[0]);return e[0]+r*(t-s[0])}}function Nx(s,e){return s>0&&s<e}var IR=(s,e=()=>{})=>{let t={left:s.scrollLeft,top:s.scrollTop},r=0;return function n(){const i={left:s.scrollLeft,top:s.scrollTop},o=t.left!==i.left,l=t.top!==i.top;(o||l)&&e(),t=i,r=window.requestAnimationFrame(n)}(),()=>window.cancelAnimationFrame(r)};function Rl(s,e){const t=Us(s),r=g.useRef(0);return g.useEffect(()=>()=>window.clearTimeout(r.current),[]),g.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(t,e)},[t,e])}function Ei(s,e){const t=Us(e);xi(()=>{let r=0;if(s){const n=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(t)});return n.observe(s),()=>{window.cancelAnimationFrame(r),n.unobserve(s)}}},[s,t])}var Lx=wx,CR=Sx,NR=jx;const jl=g.forwardRef(({className:s,children:e,...t},r)=>a.jsxs(Lx,{ref:r,className:C("relative overflow-hidden",s),...t,children:[a.jsx(CR,{className:"h-full w-full rounded-[inherit]",children:e}),a.jsx(Px,{}),a.jsx(NR,{})]}));
661jl.displayName=Lx.displayName;const Px=g.forwardRef(({className:s,orientation:e="vertical",...t},r)=>a.jsx(ju,{ref:r,orientation:e,className:C("flex touch-none select-none transition-colors",e==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",e==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",s),...t,children:a.jsx(Rx,{className:"relative flex-1 rounded-full bg-border"})}));Px.displayName=ju.displayName;function St(s){const e=Object.prototype.toString.call(s);return s instanceof Date||typeof s=="object"&&e==="[object Date]"?new s.constructor(+s):typeof s=="number"||e==="[object Number]"||typeof s=="string"||e==="[object String]"?new Date(s):new Date(NaN)}function Or(s,e){return s instanceof Date?new s.constructor(e):new Date(e)}function LR(s,e){const t=St(s);return isNaN(e)?Or(s,NaN):(e&&t.setDate(t.getDate()+e),t)}const Dx=6048e5,PR=864e5,K4=6e4,W4=36e5,Ja=43200,Gf=1440;let DR={};function Va(){return DR}function An(s,e){var l,d,c,u;const t=Va(),r=(e==null?void 0:e.weekStartsOn)??((d=(l=e==null?void 0:e.locale)==null?void 0:l.options)==null?void 0:d.weekStartsOn)??t.weekStartsOn??((u=(c=t.locale)==null?void 0:c.options)==null?void 0:u.weekStartsOn)??0,n=St(s),i=n.getDay(),o=(i<r?7:0)+i-r;return n.setDate(n.getDate()-o),n.setHours(0,0,0,0),n}function Qo(s){return An(s,{weekStartsOn:1})}function Ox(s){const e=St(s),t=e.getFullYear(),r=Or(s,0);r.setFullYear(t+1,0,4),r.setHours(0,0,0,0);const n=Qo(r),i=Or(s,0);i.setFullYear(t,0,4),i.setHours(0,0,0,0);const o=Qo(i);return e.getTime()>=n.getTime()?t+1:e.getTime()>=o.getTime()?t:t-1}function Jo(s){const e=St(s);return e.setHours(0,0,0,0),e}function Zo(s){const e=St(s),t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),+s-+t}function OR(s,e){const t=Jo(s),r=Jo(e),n=+t-Zo(t),i=+r-Zo(r);return Math.round((n-i)/PR)}function MR(s){const e=Ox(s),t=Or(s,0);return t.setFullYear(e,0,4),t.setHours(0,0,0,0),Qo(t)}function To(s,e){const t=St(s),r=St(e),n=t.getTime()-r.getTime();return n<0?-1:n>0?1:n}function Il(s){return Or(s,Date.now())}function Mx(s,e){const t=Jo(s),r=Jo(e);return+t==+r}function FR(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function $R(s){if(!FR(s)&&typeof s!="number")return!1;const e=St(s);return!isNaN(Number(e))}function UR(s,e){const t=St(s),r=St(e),n=t.getFullYear()-r.getFullYear(),i=t.getMonth()-r.getMonth();return n*12+i}function BR(s){return e=>{const r=(s?Math[s]:Math.trunc)(e);return r===0?0:r}}function VR(s,e){return+St(s)-+St(e)}function GR(s){const e=St(s);return e.setHours(23,59,59,999),e}function zR(s){const e=St(s),t=e.getMonth();return e.setFullYear(e.getFullYear(),t+1,0),e.setHours(23,59,59,999),e}function qR(s){const e=St(s);return+GR(e)==+zR(e)}function HR(s,e){const t=St(s),r=St(e),n=To(t,r),i=Math.abs(UR(t,r));let o;if(i<1)o=0;else{t.getMonth()===1&&t.getDate()>27&&t.setDate(30),t.setMonth(t.getMonth()-n*i);let l=To(t,r)===-n;qR(St(s))&&i===1&&To(s,r)===1&&(l=!1),o=n*(i-Number(l))}return o===0?0:o}function Fx(s,e,t){const r=VR(s,e)/1e3;return BR(t==null?void 0:t.roundingMethod)(r)}function KR(s){const e=St(s),t=Or(s,0);return t.setFullYear(e.getFullYear(),0,1),t.setHours(0,0,0,0),t}const WR={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},YR=(s,e,t)=>{let r;const n=WR[s];return typeof n=="string"?r=n:e===1?r=n.one:r=n.other.replace("{{count}}",e.toString()),t!=null&&t.addSuffix?t.comparison&&t.comparison>0?"in "+r:r+" ago":r};function lc(s){return(e={})=>{const t=e.width?String(e.width):s.defaultWidth;return s.formats[t]||s.formats[s.defaultWidth]}}const XR={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},QR={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},JR={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},ZR={date:lc({formats:XR,defaultWidth:"full"}),time:lc({formats:QR,defaultWidth:"full"}),dateTime:lc({formats:JR,defaultWidth:"full"})},ej={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},tj=(s,e,t,r)=>ej[s];function qi(s){return(e,t)=>{const r=t!=null&&t.context?String(t.context):"standalone";let n;if(r==="formatting"&&s.formattingValues){const o=s.defaultFormattingWidth||s.defaultWidth,l=t!=null&&t.width?String(t.width):o;n=s.formattingValues[l]||s.formattingValues[o]}else{const o=s.defaultWidth,l=t!=null&&t.width?String(t.width):s.defaultWidth;n=s.values[l]||s.values[o]}const i=s.argumentCallback?s.argumentCallback(e):e;return n[i]}}const sj={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},rj={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},nj={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},ij={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Frid
661ay","Saturday"]},aj={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},oj={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},lj=(s,e)=>{const t=Number(s),r=t%100;if(r>20||r<10)switch(r%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},cj={ordinalNumber:lj,era:qi({values:sj,defaultWidth:"wide"}),quarter:qi({values:rj,defaultWidth:"wide",argumentCallback:s=>s-1}),month:qi({values:nj,defaultWidth:"wide"}),day:qi({values:ij,defaultWidth:"wide"}),dayPeriod:qi({values:aj,defaultWidth:"wide",formattingValues:oj,defaultFormattingWidth:"wide"})};function Hi(s){return(e,t={})=>{const r=t.width,n=r&&s.matchPatterns[r]||s.matchPatterns[s.defaultMatchWidth],i=e.match(n);if(!i)return null;const o=i[0],l=r&&s.parsePatterns[r]||s.parsePatterns[s.defaultParseWidth],d=Array.isArray(l)?uj(l,h=>h.test(o)):dj(l,h=>h.test(o));let c;c=s.valueCallback?s.valueCallback(d):d,c=t.valueCallback?t.valueCallback(c):c;const u=e.slice(o.length);return{value:c,rest:u}}}function dj(s,e){for(const t in s)if(Object.prototype.hasOwnProperty.call(s,t)&&e(s[t]))return t}function uj(s,e){for(let t=0;t<s.length;t++)if(e(s[t]))return t}function hj(s){return(e,t={})=>{const r=e.match(s.matchPattern);if(!r)return null;const n=r[0],i=e.match(s.parsePattern);if(!i)return null;let o=s.valueCallback?s.valueCallback(i[0]):i[0];o=t.valueCallback?t.valueCallback(o):o;const l=e.slice(n.length);return{value:o,rest:l}}}const fj=/^(\d+)(th|st|nd|rd)?/i,mj=/\d+/i,pj={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},gj={any:[/^b/i,/^(a|c)/i]},xj={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},yj={any:[/1/i,/2/i,/3/i,/4/i]},vj={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},bj={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},_j={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},wj={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},Ej={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},Sj={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},Tj={ordinalNumber:hj({matchPattern:fj,parsePattern:mj,valueCallback:s=>parseInt(s,10)}),era:Hi({matchPatterns:pj,defaultMatchWidth:"wide",parsePatterns:gj,defaultParseWidth:"any"}),quarter:Hi({matchPatterns:xj,defaultMatchWidth:"wide",parsePatterns:yj,defaultParseWidth:"any",valueCallback:s=>s+1}),month:Hi({matchPatterns:vj,defaultMatchWidth:"wide",parsePatterns:bj,defaultParseWidth:"any"}),day:Hi({matchPatterns:_j,defaultMatchWidth:"wide",parsePatterns:wj,defaultParseWidth:"any"}),dayPeriod:Hi({matchPatterns:Ej,defaultMatchWidth:"any",parsePatterns:Sj,defaultParseWidth:"any"})},$x={code:"en-US",formatDistance:YR,formatLong:ZR,formatRelative:tj,localize:cj,match:Tj,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Aj(s){const e=St(s);return OR(e,KR(e))+1}function kj(s){const e=St(s),t=+Qo(e)-+MR(e);return Math.round(t/Dx)+1}function Ux(s,e){var u,h,f,m;const t=St(s),r=t.getFullYear(),n=Va(),i=(e==null?void 0:e.firstWeekContainsDate)??((h=(u=e==null?void 0:e.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??n.firstWeekContainsDate??((m=(f=n.locale)==null?void 0:f.options)==null?void 0:m.firstWeekContainsDate)??1,o=Or(s,0);o.setFullYear(r+1,0,i),o.setHours(0,0,0,0);const l=An(o,e),d=Or(s,0);d.setFullYear(r,0,i),d.setHours(0,0,0,0);const c=An(d,e);return t.getTime()>=l.getTime()?r+1:t.getTime()>=c.getTime()?r:r-1}function Rj(s,e){var l,d,c,u;const t=Va(),r=(e==null?void 0:e.firstWeekContainsDate)??((d=(l=e==null?void 0:e.locale)==null?void 0:l.options)==null?void 0:d.firstWeekContainsDate)??t.firstWeekContainsDate??((u=(c=t.locale)==null?void 0:c.options)==null?void 0:u.firstWeekContainsDate)??1,n=Ux(s,e),i=Or(s,0);return i.setFullYear(n,0,r),i.setHours(0,0,0,0),An(i,e)}function jj(s,e){const t=St(s),r=+An(t,e)-+Rj(t,e);return Math.round(r/Dx)+1}function xt(s,e){const t=s<0?"-":"",r=Math.abs(s).toString().padStart(e,"0");return t+r}const Br={y(s,e){const t=s.getFullYear(),r=t>0?t:1-t;return xt(e==="yy"?r%100:r,e.length)},M(s,e){const t=s.getMonth();return e==="M"?String(t+1):xt(t+1,2)},d(s,e){return xt(s.getDate(),e.length)},a(s,e){const t=s.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return t.toUpperCase();case"aaa":return t;case"aaaaa":return t[0];case"aaaa":default:return t==="am"?"a.m.":"p.m."}},h(s,e){return xt(s.getHours()%12||12,e.length)},H(s,e){return xt(s.getHours(),e.length)},m(s,e){return xt(s.getMinutes(),e.length)},s(s,e){return xt(s.getSeconds(),e.length)},S(s,e){const t=e.length,r=s.getMilliseconds(),n=Math.trunc(r*Math.pow(10,t-3));return xt(n,e.length)}},zn={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},zf={G:function(s,e,t){const r=s.getFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return t.era(r,{width:"abbreviated"});case"GGGGG":return t.era(r,{width:"narrow"});case"GGGG":default:return t.era(r,{width:"wide"})}},y:function(s,e,t){if(e==="yo"){const r=s.getFullYear(),n=r>0?r:1-r;return t.ordinalNumber(n,{unit:"year"})}return Br.y(s,e)},Y:function(s,e,t,r){const n=Ux(s,r),i=n>0?n:1-n;if(e==="YY"){const o=i%100;return xt(o,2)}return e==="Yo"?t.ordinalNumber(i,{unit:"year"}):xt(i,e.length)},R:function(s,e){const t=Ox(s);return xt(t,e.length)},u:function(s,e){const t=s.getFullYear();return xt(t,e.length)},Q:function(s,e,t){const r=Math.ceil((s.getMonth()+1)/3);switch(e){case"Q":return String(r);case"QQ":return xt(r,2);case"Qo":return t.ordinalNumber(r,{unit:"quarter"});case"QQQ":return t.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(r,{width:"narrow",context:"formatting"});case"QQQQ":default:return t.quarter(r,{width:"wide",context:"formatting"})}},q:function(s,e,t){const r=Math.ceil((s.getMonth()+1)/3);switch(e){case"q":return String(r);case"qq":return xt(r,2);case"qo":return t.ordinalNumber(r,{unit:"quarter"});case"qqq":return t.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(r,{width:"narrow",context:"standalone"});case"qqqq":default:return t.quarter(r,{width:"wide",context:"standalone"})}},M:function(s,e,t){const r=s.getMonth();switch(e){case"M":case"MM":return Br.M(s,e);case"Mo":return t.ordinalNumber(r+1,{unit:"month"});case"MMM":return t.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return t.month(r,{width:"wide",context:"formatting"})}},L:function(s,e,t){const r=s.getMonth();switch(e){case"L":return String(r+1);case"LL":return xt(r+1,2);case"Lo":return t.ordinalNumber(r+1,{unit:"month"});case"LLL":return t.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(r,{width:"narrow",context:"standalone"});case"LLLL":default:return t.month(r,{width:"wide",context:"standalone"})}},w:function(s,e,t,r){const n=jj(s,r);return e==="wo"?t.ordinalNumber(n,{unit:"week"}):xt(n,e.length)},I:function(s,e,t){const r=kj(s);return e==="Io"?t.ordinalNumber(r,{unit:"week"}):xt(r,e.length)},d:function(s,e,t){return e==="do"?t.ordinalNumber(s.getDate(),{unit:"date"}):Br.d(s,e)},D:function(s,e,t){const r=Aj(s);return e==="Do"?t.ordinalNumber(r,{unit:"dayOfYear"}):xt(r,e.length)},E:function(s,e,t){const r=s.getDay();switch(e){case"E":case"EE":case"EEE":return t.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(r,{width:"short",context:"formatting"});case"EEEE":default:return t.day(r,{width:"wide",context:"formatting"})}},e:function(s,e,t,r){const n=s.getDay(),i=(n-r.weekStartsOn+8)%7||7;switch(e){case"e":return String(i);case"ee":return xt(i,2);case"eo":return t.ordinalNumber(i,{unit:"day"});case"eee":return t.day(n,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(n,{width:"short",context:"formatting"});case"eeee":default:return t.day(n,{width:"wide",context:"formatting"})}},c:function(s,e,t,r){const n=s.getDay(),i=(n-r.weekStartsOn+8)%7||7;switch(e){case"c":return String(i);case"cc":return xt(i,e.length);case"co":return t.ordinalNumber(i,{unit:"day"});case"ccc":return t.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(n,{width:"narrow",context:"standalone"});case"cccccc":return t.day(n,{width:"short",context:"standalone"});case"cccc":default:return t.day(n,{width:"wide",context:"standalone"})}},i:function(s,e,t){const r=s.getDay(),n=r===0?7:r;switch(e){case"i":return String(n);case"ii":return xt(n,e.length);case"io":return t.ordinalNumber(n,{unit:"day"});case"iii":return t.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(r,{width:"short",context:"formatting"});case"iiii":default:return t.day(r,{width:"wide",context:"formatting"})}},a:function(s,e,t){const n=s.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(n,{width:"narrow",context:"formatting"});case"aaaa":default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},b:function(s,e,t){const r=s.getHours();let n;switch(r===12?n=zn.noon:r===0?n=zn.midnight:n=r/12>
vendor: 4,693 bytes, line 661
661=1?"pm":"am",e){case"b":case"bb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(n,{width:"narrow",context:"formatting"});case"bbbb":default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(s,e,t){const r=s.getHours();let n;switch(r>=17?n=zn.evening:r>=12?n=zn.afternoon:r>=4?n=zn.morning:n=zn.night,e){case"B":case"BB":case"BBB":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(n,{width:"narrow",context:"formatting"});case"BBBB":default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(s,e,t){if(e==="ho"){let r=s.getHours()%12;return r===0&&(r=12),t.ordinalNumber(r,{unit:"hour"})}return Br.h(s,e)},H:function(s,e,t){return e==="Ho"?t.ordinalNumber(s.getHours(),{unit:"hour"}):Br.H(s,e)},K:function(s,e,t){const r=s.getHours()%12;return e==="Ko"?t.ordinalNumber(r,{unit:"hour"}):xt(r,e.length)},k:function(s,e,t){let r=s.getHours();return r===0&&(r=24),e==="ko"?t.ordinalNumber(r,{unit:"hour"}):xt(r,e.length)},m:function(s,e,t){return e==="mo"?t.ordinalNumber(s.getMinutes(),{unit:"minute"}):Br.m(s,e)},s:function(s,e,t){return e==="so"?t.ordinalNumber(s.getSeconds(),{unit:"second"}):Br.s(s,e)},S:function(s,e){return Br.S(s,e)},X:function(s,e,t){const r=s.getTimezoneOffset();if(r===0)return"Z";switch(e){case"X":return Hf(r);case"XXXX":case"XX":return yn(r);case"XXXXX":case"XXX":default:return yn(r,":")}},x:function(s,e,t){const r=s.getTimezoneOffset();switch(e){case"x":return Hf(r);case"xxxx":case"xx":return yn(r);case"xxxxx":case"xxx":default:return yn(r,":")}},O:function(s,e,t){const r=s.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+qf(r,":");case"OOOO":default:return"GMT"+yn(r,":")}},z:function(s,e,t){const r=s.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+qf(r,":");case"zzzz":default:return"GMT"+yn(r,":")}},t:function(s,e,t){const r=Math.trunc(s.getTime()/1e3);return xt(r,e.length)},T:function(s,e,t){const r=s.getTime();return xt(r,e.length)}};function qf(s,e=""){const t=s>0?"-":"+",r=Math.abs(s),n=Math.trunc(r/60),i=r%60;return i===0?t+String(n):t+String(n)+e+xt(i,2)}function Hf(s,e){return s%60===0?(s>0?"-":"+")+xt(Math.abs(s)/60,2):yn(s,e)}function yn(s,e=""){const t=s>0?"-":"+",r=Math.abs(s),n=xt(Math.trunc(r/60),2),i=xt(r%60,2);return t+n+e+i}const Kf=(s,e)=>{switch(s){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});case"PPPP":default:return e.date({width:"full"})}},Bx=(s,e)=>{switch(s){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});case"pppp":default:return e.time({width:"full"})}},Ij=(s,e)=>{const t=s.match(/(P+)(p+)?/)||[],r=t[1],n=t[2];if(!n)return Kf(s,e);let i;switch(r){case"P":i=e.dateTime({width:"short"});break;case"PP":i=e.dateTime({width:"medium"});break;case"PPP":i=e.dateTime({width:"long"});break;case"PPPP":default:i=e.dateTime({width:"full"});break}return i.replace("{{date}}",Kf(r,e)).replace("{{time}}",Bx(n,e))},Cj={p:Bx,P:Ij},Nj=/^D+$/,Lj=/^Y+$/,Pj=["D","DD","YY","YYYY"];function Dj(s){return Nj.test(s)}function Oj(s){return Lj.test(s)}function Mj(s,e,t){const r=Fj(s,e,t);if(console.warn(r),Pj.includes(s))throw new RangeError(r)}function Fj(s,e,t){const r=s[0]==="Y"?"years":"days of the month";return`Use \`${s.toLowerCase()}\` instead of \`${s}\` (in \`${e}\`) for formatting ${r} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const $j=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Uj=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Bj=/^'([^]*?)'?$/,Vj=/''/g,Gj=/[a-zA-Z]/;function nr(s,e,t){var u,h,f,m,p,x,y,v;const r=Va(),n=(t==null?void 0:t.locale)??r.locale??$x,i=(t==null?void 0:t.firstWeekContainsDate)??((h=(u=t==null?void 0:t.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??r.firstWeekContainsDate??((m=(f=r.locale)==null?void 0:f.options)==null?void 0:m.firstWeekContainsDate)??1,o=(t==null?void 0:t.weekStartsOn)??((x=(p=t==null?void 0:t.locale)==null?void 0:p.options)==null?void 0:x.weekStartsOn)??r.weekStartsOn??((v=(y=r.locale)==null?void 0:y.options)==null?void 0:v.weekStartsOn)??0,l=St(s);if(!$R(l))throw new RangeError("Invalid time value");let d=e.match(Uj).map(_=>{const b=_[0];if(b==="p"||b==="P"){const w=Cj[b];return w(_,n.formatLong)}return _}).join("").match($j).map(_=>{if(_==="''")return{isToken:!1,value:"'"};const b=_[0];if(b==="'")return{isToken:!1,value:zj(_)};if(zf[b])return{isToken:!0,value:_};
661if(b.match(Gj))throw new RangeError("Format string contains an unescaped latin alphabet character `"+b+"`");return{isToken:!1,value:_}});n.localize.preprocessor&&(d=n.localize.preprocessor(l,d));const c={firstWeekContainsDate:i,weekStartsOn:o,locale:n};return d.map(_=>{if(!_.isToken)return _.value;const b=_.value;(!(t!=null&&t.useAdditionalWeekYearTokens)&&Oj(b)||!(t!=null&&t.useAdditionalDayOfYearTokens)&&Dj(b))&&Mj(b,e,String(s));const w=zf[b[0]];return w(l,b,n.localize,c)}).join("")}function zj(s){const e=s.match(Bj);return e?e[1].replace(Vj,"'"):s}function qj(s,e,t){const r=Va(),n=(t==null?void 0:t.locale)??r.locale??$x,i=2520,o=To(s,e);if(isNaN(o))throw new RangeError("Invalid time value");const l=Object.assign({},t,{addSuffix:t==null?void 0:t.addSuffix,comparison:o});let d,c;o>0?(d=St(e),c=St(s)):(d=St(s),c=St(e));const u=Fx(c,d),h=(Zo(c)-Zo(d))/1e3,f=Math.round((u-h)/60);let m;if(f<2)return t!=null&&t.includeSeconds?u<5?n.formatDistance("lessThanXSeconds",5,l):u<10?n.formatDistance("lessThanXSeconds",10,l):u<20?n.formatDistance("lessThanXSeconds",20,l):u<40?n.formatDistance("halfAMinute",0,l):u<60?n.formatDistance("lessThanXMinutes",1,l):n.formatDistance("xMinutes",1,l):f===0?n.formatDistance("lessThanXMinutes",1,l):n.formatDistance("xMinutes",f,l);if(f<45)return n.formatDistance("xMinutes",f,l);if(f<90)return n.formatDistance("aboutXHours",1,l);if(f<Gf){const p=Math.round(f/60);return n.formatDistance("aboutXHours",p,l)}else{if(f<i)return n.formatDistance("xDays",1,l);if(f<Ja){const p=Math.round(f/Gf);return n.formatDistance("xDays",p,l)}else if(f<Ja*2)return m=Math.round(f/Ja),n.formatDistance("aboutXMonths",m,l)}if(m=HR(c,d),m<12){const p=Math.round(f/Ja);return n.formatDistance("xMonths",p,l)}else{const p=m%12,x=Math.trunc(m/12);return p<3?n.formatDistance("aboutXYears",x,l):p<9?n.formatDistance("overXYears",x,l):n.formatDistance("almostXYears",x+1,l)}}function Nu(s,e){return qj(s,Il(s),e)}function Hj(s,e,t){const r=An(s,t),n=An(e,t);return+r==+n}function Vx(s,e){return Hj(s,Il(s),e)}function el(s){return Mx(s,Il(s))}function Kj(s,e){return LR(s,-e)}function tl(s){return Mx(s,Kj(Il(s),1))}function Wj({isOpen:s,onClose:e}){const{notifications:t,unreadCount:r,loading:n,markAsRead:i,markAllAsRead:o}=vx(),l=hs();g.useEffect(()=>{const h=f=>{f.key==="Escape"&&s&&e()};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[s,e]),g.useEffect(()=>(s?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[s]);const d=async h=>{h.is_read||await i(h.id),h.link&&l(h.link),e()},c=h=>{switch(h){case"success":return"✓";case"warning":return"⚠";case"error":return"✕";case"application":return"📋";case"interview":return"📅";default:return"ℹ"}},u=h=>{switch(h){case"success":return"text-green-500";case"warning":return"text-yellow-500";case"error":return"text-red-500";case"application":return"text-blue-500";case"interview":return"text-purple-500";default:return"text-muted-foreground"}};return s?a.jsxs("div",{className:"fixed inset-0 z-50 bg-background animate-in slide-in-from-right duration-300",children:[a.jsxs("div",{className:"flex items-center justify-between border-b border-border px-3 py-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ye,{type:"button",variant:"ghost",size:"icon",onClick:e,className:"shrink-0",children:a.jsx(yi,{className:"w-5 h-5"})}),a.jsx("h1",{className:"text-lg font-semibold",children:"Notifications"})]}),r>0&&a.jsxs(ye,{variant:"ghost",size:"sm",className:"text-xs text-muted-foreground hover:text-foreground gap-1",onClick:o,children:[a.jsx(vi,{className:"h-3.5 w-3.5"}),"Mark all read"]})]}),a.jsx("div",{className:"h-[calc(100vh-57px)] overflow-y-auto",children:n?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})}):t.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center px-4",children:[a.jsx(Qc,{className:"mb-3 h-12 w-12 text-muted-foreground
661/50"}),a.jsx("span",{className:"text-base font-medium text-muted-foreground",children:"No notifications yet"}),a.jsx("p",{className:"text-sm text-muted-foreground/60 mt-1",children:"You'll see updates about your applications here"})]}):a.jsx("div",{className:"divide-y divide-border",children:t.map(h=>a.jsxs("button",{className:C("flex w-full items-start gap-3 p-4 text-left transition-colors hover:bg-muted/50 active:bg-muted/70",!h.is_read&&"bg-muted/30"),onClick:()=>d(h),children:[a.jsx("span",{className:C("mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm",u(h.type)),children:c(h.type)}),a.jsxs("div",{className:"flex-1 space-y-1 overflow-hidden",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsx("p",{className:C("text-sm font-medium leading-tight",!h.is_read&&"text-foreground"),children:h.title}),!h.is_read&&a.jsx("span",{className:"mt-1 h-2 w-2 shrink-0 rounded-full bg-primary"})]}),a.jsx("p",{className:"line-clamp-2 text-sm text-muted-foreground",children:h.message}),a.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[a.jsx("span",{children:Nu(new Date(h.created_at),{addSuffix:!0})}),h.link&&a.jsx(sa,{className:"h-3 w-3"})]})]})]},h.id))})})]}):null}function cc(){const{notifications:s,unreadCount:e,loading:t,markAsRead:r,markAllAsRead:n}=vx(),i=hs(),o=dn(),[l,d]=g.useState(!1),c=async m=>{m.is_read||await r(m.id),m.link&&i(m.link)},u=m=>{switch(m){case"success":return"✓";case"warning":return"⚠";case"error":return"✕";case"application":return"📋";case"interview":return"📅";default:return"ℹ"}},h=m=>{switch(m){case"success":return"text-green-500";case"warning":return"text-yellow-500";case"error":return"text-red-500";case"application":return"text-blue-500";case"interview":return"text-purple-500";default:return"text-muted-foreground"}},f=a.jsxs(ye,{variant:"ghost",size:"icon",className:"relative h-9 w-9","aria-label":`Notifications${e>0?` (${e} unread)`:""}`,onClick:o?()=>d(!0):void 0,children:[a.jsx(Qc,{className:"h-5 w-5"}),e>0&&a.jsx("span",{className:"absolute -top-0.5 -right-0.5 flex h-5 min-w-5 items-center justify-center rounded-full bg-destructive px-1 text-[10px] font-medium text-destructive-foreground animate-in zoom-in-50",children:e>9?"9+":e})]});return o?a.jsxs(a.Fragment,{children:[f,a.jsx(Wj,{isOpen:l,onClose:()=>d(!1)})]}):a.jsxs(yR,{children:[a.jsx(vR,{asChild:!0,children:f}),a.jsxs(bx,{className:"w-80 p-0",align:"end",children:[a.jsxs("div",{className:"flex items-center justify-between border-b px-4 py-3",children:[a.jsx("h4",{className:"font-semibold",children:"Notifications"}),e>0&&a.jsxs(ye,{variant:"ghost",size:"sm",className:"h-auto p-0 text-xs text-muted-foreground hover:text-foreground",onClick:n,children:[a.jsx(vi,{className:"mr-1 h-3 w-3"}),"Mark all read"]})]}),a.jsx(jl,{className:"max-h-[300px]",children:t?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})}):s.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[a.jsx(Qc,{className:"mb-2 h-8 w-8 text-muted-foreground/50"}),a.jsx("span",{className:"text-sm text-muted-foreground",children:"No notifications yet"})]}):a.jsx("div",{className:"divide-y",children:s.map(m=>a.jsxs("button",{className:C("flex w-full items-start gap-3 p-3 text-left transition-colors hover:bg-muted/50",!m.is_read&&"bg-muted/30"),onClick:()=>c(m),children:[a.jsx("span",{className:C("mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-muted text-xs",h(m.type)),children:u(m.type)}),a.jsxs("div",{className:"flex-1 space-y-1 overflow-hidden",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsx("p",{className:C("text-sm font-medium leading-tight",!m.is_read&&"text-foreground"),children:m.title}),!m.is_read&&a.jsx("span",{className:"mt-1 h-2 w-2 shrink-0 rounded-full bg-primary"})]}),a.jsx("p",{className:"line-clamp-2 text-xs text-muted-foreground",children:m.message}),a.jsxs("div",{className:"flex items-center gap-2 text-[10px] text-muted-foreground",children:[a.jsx("span",{children:Nu(new Date(m.created_at),{addSuffix:!0})}),m.link&&a.jsx(sa,{className:"h-3 w-3"})]})]})]},m.id))})})]})]})}function Gx(s){return Wt({queryKey:["site-settings",s],queryFn:async()=>{const{data:e,error:t}=await L.from("site_settings").select("setting_value").eq("setting_key",s).single();if(t)throw t;return e==null?void 0:e.setting_value}})}function Yj(s){const e=Da();return Kc({mutationFn:async t=>{const{error:r}=await L.from("site_settings").update({setting_value:t}).eq("setting_key",s);if(r)throw r},onSuccess:()=>
661{e.invalidateQueries({queryKey:["site-settings",s]})}})}function Xj(){return Gx("brand")}function Y4(){return Gx("certificate_settings")}function X4(){return Yj("certificate_settings")}const zx=g.createContext(null);function Qj({children:s}){const[e,t]=g.useState(0),r=g.useRef(null),n=g.useRef(0);n.current=e;const i=g.useCallback((o,l)=>{const d=r.current;if(!d)return;const c=100/6,u=n.current*c,h=o*c,f=u+h;d.style.left=`calc(${f}% + 2px)`,d.style.transition=l?"none":"left 0.3s ease-out"},[]);return a.jsx(zx.Provider,{value:{activeTabIndex:e,setActiveTabIndex:t,tabIndicatorRef:r,updateSwipeVisuals:i},children:s})}function Lu(){const s=g.useContext(zx);return s||{activeTabIndex:0,setActiveTabIndex:()=>{},tabIndicatorRef:{current:null},updateSwipeVisuals:()=>{}}}const Jj=({className:s,placeholder:e,value:t,onChange:r,onSubmit:n})=>a.jsx("form",{onSubmit:n,className:C("flex items-center",s),children:a.jsxs("div",{className:"relative w-full",children:[a.jsx(Ds,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a.jsx(rr,{type:"text",placeholder:e,value:t,onChange:i=>r(i.target.value),className:"w-full pl-9 pr-8 h-9 bg-muted border-0 rounded-full focus-visible:ring-1"}),t&&a.jsx("button",{type:"button",onClick:()=>r(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:a.jsx(Fs,{className:"h-4 w-4"})})]})}),Wf=[{to:"/social",icon:ua,label:"Feed"},{to:"/reels",icon:Mo,label:"Reels"},{to:"/dashboard",icon:Es,label:"Jobs"},{to:"/my-network",icon:Ss,label:"Connections"},{to:"/courses",icon:Nr,label:"Courses",iconClass:"h-7 w-7"},{to:"/messenger",icon:Tn,label:"Messages"}],Zj=[{to:"/social",icon:ua,label:"Feed"},{to:"/reels",icon:Mo,label:"Reels"},{to:"/dashboard",icon:Es,label:"Jobs"},{to:"/my-network",icon:Ss,label:"Connections"},{to:"/courses",icon:Nr,label:"Courses",iconClass:"h-[22px] w-[22px]"}],eI=[{to:"/admin",icon:Dr,label:"Dashboard"},{to:"/admin/users",icon:Ss,label:"Users"},{to:"/admin/jobs",icon:Es,label:"Jobs"},{to:"/admin/reports",icon:Fo,label:"Reports"}],Yf=[{to:"/admin",icon:Dr,label:"Dashboard"},{to:"/admin/analytics",icon:ni,label:"Analytics"},{to:"/admin/users",icon:Ss,label:"Users"},{to:"/admin/jobs",icon:Es,label:"Jobs"},{to:"/admin/reports",icon:Fo,label:"Reports"},{to:"/admin/security",icon:bn,label:"Security"}],tI=[{to:"/expert",icon:Dr,label:"Dashboard"},{to:"/expert/users",icon:Ss,label:"Users"},{to:"/expert/jobs",icon:Es,label:"Jobs"},{to:"/expert/aptitude",icon:$a,label:"Aptitude"}],Xf=[{to:"/expert",icon:Dr,label:"Dashboard"},{to:"/expert/users",icon:Ss,label:"Users"},{to:"/expert/jobs",icon:Es,label:"Jobs"},{to:"/expert/aptitude",icon:$a,label:"Aptitude"},{to:"/expert/personality-game/overview",icon:si,label:"Personality"}];function sI({onSearchOpen:s}){const{data:e,isLoading:t}=Xj(),{user:r}=$t(),{hasHRAccess:n}=U0(),{activePage:i,isPageMode:o}=bu(),l=hs(),d=br(),[c,u]=g.useState(""),h=g.useRef(!1),[f,m]=g.useState(!1),p=g.useMemo(()=>({clipPath:"circle(50%)",WebkitClipPath:"circle(50%)",WebkitMaskImage:"radial-gradient(circle, black 99%, transparent 100%)",maskImage:"radial-gradient(circle, black 99%, transparent 100%)"}),[]),x=g.useMemo(()=>[{to:"/social",icon:ua,label:"Feed"},{to:"/reels",icon:Mo,label:"Reels"},{to:i?`/page/${i.slug}/analytics`:"/social",icon:Cr,label:"Analytics"},{to:"/my-network",icon:Ss,label:"Connections"},{to:"/courses",icon:Nr,label:"Courses",iconClass:"h-[22px] w-[22px]"}],[i]),y=g.useMemo(()=>[{to:"/social",icon:ua,label:"Feed"},{to:"/reels",icon:Mo,label:"Reels"},{to:i?`/page/${i.slug}/analytics`:"/social",icon:Cr,label:"Analytics"},{to:"/my-network",icon:Ss,label:"Connections"},{to:"/courses",icon:Nr,label:"Courses",iconClass:"h-7 w-7"},{to:"/messenger",icon:Tn,label:"Messages"}],[i]),{data:v}=Wt({queryKey:["header-profile",r==null?void 0:r.id],queryFn:async()=>{if(!(r!=null&&r.id))return null;const{data:O}=await L.from("profiles").select("full_name, avatar_url, gender").eq("user_id",r.id).maybeSingle();return O},enabled:!!(r!=null&&r.id),staleTime:1e3*60*5,gcTime:1e3*60*10,placeholderData:d_}),b=`Search on ${(e==null?void 0:e.company_name)||"Gradzen"}`,w=O=>{O.preventDefault(),c.trim()&&(l(`/search?q=${encodeURIComponent(c.trim())}`),u(""))},T=g.useRef(null),A=g.useRef(""),S=g.useMemo(()=>{const O=pr(v==null?void 0:v.avatar_url)||_i(v==null?void 0:v.gender);return O&&(T.current=O),T.current||_i(void 0)},[v==null?void 0:v.avatar_url,v==null?void 0:v.gender]),I=g.useMemo(()=>{const O=sn(v==null?void 0:v.full_name);return O&&O!=="?"&&(A.current=O),A.current||"?"},[v==null?void 0:v.full_name]),j=o?i!=null&&i.logo_url?pr(i.logo_url):void 0:S,R=o&&(i!=null&&i.name)?sn(i.name):I,k=({showName:O=!1})=>a.jsxs(er,{to:"/social",className:"flex items-center gap-2 shrink-0",children:[t?a.jsx("div",{className:"h-8 w-8 rounded-lg bg-muted animate-pulse"}):(e==null?void 0:e.logo_url)&&a.jsx("img",{src:e.logo_url,alt:e.company_name||"Logo",className:"h-8 w-8 rounded-lg object-contain"}),O&&(t?a.jsx("div",{className:"h-5 w-24 bg-muted rounded animate-pulse"}):a.jsx("span",{className:"font-semibold text-foreground text-lg truncate max-w-[140px]",children:(e==null?void 0:e.company_name)||"Gradzen"}))]}),D=O=>a.jsx(Jj,{className:O,placeholder:b,value:c,onChange:u,onSubmit:w}),Y=a.jsx(ye,{variant:"ghost",size:"icon",className:"h-9 w-9 rounded-full",onClick:()=>l(o&&i?`/page/${i.slug}`:"/profile"),children:a.jsxs("div",{className:"relative h-8 w-8 rounded-full overflow-hidden bg-primary",style:p,children:[a.jsx("img",{src:j,alt:"Profile",className:"h-full w-full object-cover rounded-full",onLoad:()=>{h.current=!0,m(!0)},onError:()=>m(!1),style:{display:h.current||f?"block":"none"}}),!h.current&&!f&&a.jsx("span",{className:"absolute inset-0 flex items-center justify-center rounded-full text-xs text-primary-foreground",children:R})]})}),{toggleSidebar:q}=Ba(),X=d.pathname==="/menu";er,C("flex flex-col items-center justify-center gap-0.5 flex-1 py-2",X?"text-primary":"text-muted-foreground");const F=d.pathname==="/reels",P=/^\/courses\/[^/]+\/watch\/[^/]+/.test(d.pathname),N=F||P;return a.jsx("div",{className:N?"dark":void 0,children:a.jsxs("header",{className:"sticky top-0 bg-background z-50 border-b border-border overflow-hidden",children:[a.jsxs("div",{className:"hidden lg:flex h-14 relative z-10",children:[a.jsxs("div",{className:"flex items-center gap-3 w-[20rem] flex-shrink-0 px-4 border-r border-background bg-background",children:[a.jsx(k,{}),D("flex-1")]}),a.jsxs("div",{className:"grid flex-1 grid-cols-[1fr_320px] gap-6 max-w-7xl mx-auto px-4 h-full items-center",children:[a.jsx("nav",{className:"flex items-center justify-center h-full border-0 overflow-visible",children:a.jsx("div",{className:"flex h-full w-full max-w-3xl border-0 overflow-visible",children:a.jsx(Vo,{delayDuration:0,
661children:(()=>{const O=d.pathname.startsWith("/admin"),$=d.pathname.startsWith("/expert");return(O?Yf:$?Xf:o?y:Wf).map(U=>{const K=U.to==="/admin"?d.pathname==="/admin":U.to==="/expert"?d.pathname==="/expert":d.pathname===U.to||d.pathname.startsWith(U.to+"/");return a.jsxs(Go,{children:[a.jsx(zo,{asChild:!0,children:a.jsx(er,{to:U.to,"aria-label":U.label,title:U.label,className:C("relative group flex h-full flex-1 items-center justify-center cursor-pointer rounded-md transition-colors","hover:bg-accent/60 hover:text-foreground",K?"text-primary":"text-muted-foreground"),children:a.jsx(U.icon,{className:U.iconClass||"h-6 w-6"})})}),a.jsx(fa,{side:"bottom",className:"font-medium",children:U.label})]},U.to)})})()})})}),a.jsxs("div",{className:"flex items-center justify-end gap-2 h-full",children:[a.jsx(cc,{}),Y]})]})]}),a.jsxs("div",{className:"hidden md:flex lg:hidden h-14 w-full items-center justify-between px-4",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(k,{}),D("w-48")]}),a.jsx("nav",{className:"flex items-center gap-1 border-0",children:a.jsx(Vo,{delayDuration:0,children:(()=>{const O=d.pathname.startsWith("/admin"),$=d.pathname.startsWith("/expert");return(O?Yf:$?Xf:o?y:Wf).map(U=>{const K=U.to==="/admin"?d.pathname==="/admin":U.to==="/expert"?d.pathname==="/expert":d.pathname===U.to||d.pathname.startsWith(U.to+"/");return a.jsxs(Go,{children:[a.jsx(zo,{asChild:!0,children:a.jsx(er,{to:U.to,"aria-label":U.label,title:U.label,className:C("relative group flex items-center justify-center p-2 rounded-lg cursor-pointer transition-colors","hover:bg-accent/60 hover:text-foreground",K?"text-primary":"text-muted-foreground"),children:a.jsx(U.icon,{className:U.iconClass||"h-5 w-5"})})}),a.jsx(fa,{side:"bottom",className:"font-medium",children:U.label})]},U.to)})})()})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(cc,{}),Y]})]}),a.jsxs("div",{className:"flex md:hidden flex-col",children:[a.jsx("div",{className:"overflow-hidden transition-all duration-200 ease-in-out",style:{maxHeight:d.pathname==="/social"?"48px":"0px",opacity:d.pathname==="/social"?1:0},children:a.jsxs("div",{className:"flex h-12 items-center justify-between px-3",children:[a.jsx(er,{to:"/social",className:"flex items-center gap-2 shrink-0",children:t?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"h-7 w-7 rounded-lg bg-muted animate-pulse"}),a.jsx("div",{className:"h-5 w-20 bg-muted rounded animate-pulse"})]}):a.jsxs(a.Fragment,{children:[(e==null?void 0:e.logo_url)&&a.jsx("img",{src:e.logo_url,alt:e.company_name||"Logo",className:"h-7 w-7 rounded-lg object-contain"}),a.jsx("span",{className:"font-semibold text-primary text-lg truncate max-w-[140px]",children:(e==null?void 0:e.company_name)||"Gradzen"})]})}),a.jsxs("div",{className:"flex items-center gap-0.5",children:[o&&i?a.jsxs("span",{className:"flex items-center gap-1 px-2 py-1 rounded-full bg-primary/10 text-primary text-xs font-medium max-w-[140px]",children:[i.logo_url&&a.jsx("img",{src:pr(i.logo_url),alt:"",className:"h-4 w-4 rounded-full object-cover shrink-0"}),a.jsx("span",{className:"truncate",children:i.name}),i.is_verified&&a.jsx(wa,{isVerified:!0,verificationType:i.verification_type,size:"sm",showTooltip:!1})]}):null,a.jsx(cc,{}),a.jsx(ye,{variant:"ghost",size:"icon",className:"h-9 w-9",onClick:s,"aria-label":"Search",children:a.jsx(Ds,{className:"h-5 w-5"})}),a.jsx(ye,{variant:"ghost",size:"icon",className:"h-9 w-9",onClick:()=>l(o&&i?`/messenger?page=${i.id}`:"/messenger"),"aria-label":"Messages",children:a.jsx(Tn,{className:"h-5 w-5"})})]})]})}),(()=>{const O=d.pathname.startsWith("/admin"),$=d.pathname.startsWith("/expert"),B=O?eI:$?tI:o?x:Zj,U=d.pathname==="/menu",K=i?`/page/${i.slug}/analytics`:"/social",ee=B.findIndex(le=>d.pathname===le.to||le.to!=="/admin"&&le.to!=="/expert"&&le.to!==K&&d.pathname.startsWith(le.to+"/")||le.to==="/admin"&&d.pathname==="/admin"||le.to==="/expert"&&d.pathname==="/expert"||le.to===K&&d.pathname===K),ce=U?5:ee,{setActiveTabIndex:Q,tabIndicatorRef:re}=Lu(),Pe=o?["/social","/reels",K,"/my-network","/courses","/menu"]:["/social","/reels","/dashboard","/my-network","/courses","/menu"],Me=Pe.length;return a.jsxs("nav",{className:"flex h-11 items-stretch justify-around bg-background border-b border-border relative",children:[B.map(le=>{const oe=d.pathname===le.to||d.pathname.startsWith(le.to+"/"),He=Pe.indexOf(le.to);return a.jsxs(er,{to:le.to,onClick:ct=>{He>=0&&(ct.preventDefault(),Q(He),l(le.to,{replace:!0}))},className:C("flex flex-col items-center justify-center gap-0.5 flex-1 h-full py-1 transition-colors",oe?"text-primary":"text-muted-foreground"),children:[a.jsx(le.icon,{className:le.iconClass||"h-5 w-5"}),o&&a.jsx("span",{className:"text-[10px]",children:le.label})]},le.to)}),(()=>{const le=Pe.indexOf("/menu");return a.jsxs(er,{to:"/menu",onClick:oe=>{le>=0&&(oe.preventDefault(),Q(le),l("/menu",{replace:!0}))},className:C("flex flex-col items-center justify-center gap-0.5 flex-1 py-2",U?"text-primary":"text-muted-foreground"),"aria-label":"Open menu",children:[a.jsxs(Bs,{className:"h-6 w-6",children:[a.jsx(Vs,{src:j,alt:"Menu",className:"object-cover"}),a.jsx(Gs,{className:"text-[10px] bg-primary text-primary-foreground",children:R})]}),o&&a.jsx("span",{className:"text-[10px]",children:"Menu"})]})})(),ce>=0&&a.jsx("span",{ref:re,className:"absolute bottom-0 h-[3px] bg-primary rounded-full z-10",style:{width:`calc(100% / ${Me} - 4px)`,left:`calc(${ce*(100/Me)}% + 2px)`,transition:"left 0.3s ease-out"}})]})})()]})]})})}function rI({search:s,onSelect:e,onRemove:t}){const r=i=>{i.stopPropagation(),t(s.id)},n=()=>{switch(s.type){case"company":return a.jsx(wo,{className:"w-4 h-4"});case"job":case"position":default:return a.jsx(Es,{className:"w-4 h-4"})}};return a.jsxs("div",{onClick:()=>e(s),className:"flex items-center gap-3 px-4 py-3 hover:bg-secondary/50 cursor-pointer transition-colors group",children:[a.jsxs(Bs,{className:"h-10 w-10 shrink-0",children:[s.avatarUrl?a.jsx(Vs,{src:pr(s.avatarUrl),alt:s.title}):null,a.jsx(Gs,{className:"bg-primary/10 text-primary",children:n()})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"font-medium text-foreground truncate",children:s.title}),a.jsx("p",{className:"text-sm text-muted-foreground truncate",children:s.subtitle})]}),a.jsx(ye,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:r,children:a.jsx(Fs,{className:"w-4 h-4 text-muted-foreground"})})]})}const dc="recent_job_searches",nI=10;function iI(){const[s,e]=g.useState([]);g.useEffect(()=>{try{const o=localStorage.getItem(dc);if(o){const l=JSON.parse(o);e(l)}}catch(o){console.error("Error loading recent searches:",o)}},[]);const t=g.useCallback(o=>{try{localStorage.setItem(dc,JSON.stringify(o))}catch(l){console.error("Error saving recent searches:",l)}},[]),r=g.useCallback(o=>{e(l=>{const d=l.filter(h=>h.query.toLowerCase()!==o.query.toLowerCase()),u=[{...o,id:crypto.randomUUID(),timestamp:Date.now()},...d].slice(0,nI);return t(u),u})},[t]),n=g.useCallback(o=>{e(l=>{const d=l.filter(c=>c.id!==o);return t(d),d})},[t]),i=g.useCallback(()=>{e([]),localStorage.removeItem(dc)},[]);return{recentSearches:s,addSearch:r,removeSearch:n,clearAll:i}}function aI({isOpen:s,onClose:e,onSearchSubmit:t}){const r=hs(),[n,i]=g.useState(""),o=g.useRef(null),l=dn(),{recentSearches:d,addSearch:c,removeSearch:u,clearAll:h}=iI();g.useEffect(()=>{if(s){const v=setTimeout(()=>{var _;(_=o.current)==null||_.focus()},100);return()=>clearTimeout(v)}else i("")},[s]),g.useEffect(()=>{const v=_=>{_.key==="Escape"&&s&&e()};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[s,e]),g.useEffect(()=>(s&&l?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[s,l]);const f=g.useRef(null);g.useEffect(()=>{if(!s||l)return;const v=b=>
661{f.current&&!f.current.contains(b.target)&&e()},_=setTimeout(()=>{document.addEventListener("mousedown",v)},100);return()=>{clearTimeout(_),document.removeEventListener("mousedown",v)}},[s,l,e]);const m=v=>{c({query:v.trim(),type:"position",title:v.trim(),subtitle:"Search query"}),r(`/search?q=${encodeURIComponent(v.trim())}`),t==null||t(v.trim()),e()},p=v=>{v.preventDefault(),n.trim()&&m(n.trim())},x=v=>{m(v.query)},y=()=>{var v;i(""),(v=o.current)==null||v.focus()};return s?a.jsxs(a.Fragment,{children:[!l&&a.jsx("div",{className:"fixed inset-0 z-40 bg-black/5"}),a.jsxs("div",{ref:f,className:`fixed z-50 border border-border ${l?"inset-0 bg-background animate-in slide-in-from-right duration-300":"top-16 right-4 w-80 md:w-96 rounded-xl shadow-2xl bg-card animate-in slide-in-from-top-2 fade-in-0 duration-200 max-h-[calc(100vh-80px)] overflow-hidden"}`,children:[a.jsx("form",{onSubmit:p,className:"border-b border-border",children:a.jsxs("div",{className:"flex items-center gap-2 p-3",children:[a.jsx(ye,{type:"button",variant:"ghost",size:"icon",onClick:e,className:"shrink-0",children:a.jsx(yi,{className:"w-5 h-5"})}),a.jsxs("div",{className:"relative flex-1",children:[a.jsx(Ds,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground pointer-events-none"}),a.jsx("input",{ref:o,type:"text",placeholder:"Search jobs, people, pages...",value:n,onChange:v=>i(v.target.value),className:"w-full pl-10 pr-10 py-2.5 text-sm rounded-lg border border-border bg-secondary/50 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:bg-background transition-all"}),n&&a.jsx(ye,{type:"button",variant:"ghost",size:"icon",className:"absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7",onClick:y,children:a.jsx(Fs,{className:"w-4 h-4"})})]})]})}),a.jsx("div",{className:`overflow-y-auto ${l?"h-[calc(100vh-70px)]":"max-h-[60vh]"}`,children:d.length>0?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border",children:[a.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Recent"}),a.jsx(ye,{variant:"ghost",size:"sm",onClick:h,className:"text-xs text-muted-foreground hover:text-foreground h-auto py-1",children:"Clear all"})]}),a.jsx("div",{className:"divide-y divide-border",children:d.map(v=>a.jsx(rI,{search:v,onSelect:x,onRemove:u},v.id))})]}):a.jsxs("div",{className:"px-4 py-12 text-center",children:[a.jsx(Ds,{className:"w-12 h-12 mx-auto mb-3 text-muted-foreground/50"}),a.jsx("p",{className:"text-muted-foreground text-sm",children:"No recent searches"}),a.jsx("p",{className:"text-muted-foreground/60 text-xs mt-1",children:"Search for jobs by position or company name"})]})})]})]}):null}const Pu=g.createContext(!1);function oI(s){return g.useContext(Pu)?s.contentClassName?a.jsx("div",{className:s.contentClassName,children:s.children}):a.jsx(a.Fragment,{children:s.children}):a.jsx(lI,{...s})}function lI({children:s,title:e,breadcrumbs:t=[],showSearchIcon:r=!0,onSearchSubmit:n,contentClassName:i,hideSidebar:o=!1}){const[l,d]=g.useState(!1),c=u=>{n&&n(u)};return a.jsx(ix,{children:a.jsxs("div",{className:"h-screen flex flex-col w-full overflow-hidden",children:[a.jsx(sI,{onSearchOpen:()=>d(!0)}),a.jsx(aI,{isOpen:l,onClose:()=>d(!1),onSearchSubmit:c}),a.jsxs("div",{className:`flex-1 flex w-full overflow-hidden border-t-0${o?" bg-black":""}`,children:[!o&&a.jsx(xR,{}),a.jsx(ox,{className:`flex-1 flex flex-col overflow-hidden min-w-0${o?" min-h-0":""}`,children:a.jsx("div",{className:`flex-1 ${i??"p-2 sm:p-4 overflow-y-auto"} overflow-x-hidden max-w-full min-w-0`,children:i?s:a.jsx("div",{className:"w-full max-w-full pb-32",children:s})})})]})]})})}const qx=g.createContext(!0),Q4=()=>g.useContext(qx),Hx=["/social","/reels","/dashboard","/my-network","/courses","/menu"],cI=g.memo(function({children:e,isActive:t,isMounted:r,isAdjacent:n,path:i}){const o=i==="/reels";return a.jsx("div",{style:{flex:"0 0 100%",height:"100%",overflowY:o?"hidden":"auto",overflowX:"hidden",overscrollBehavior:"contain",WebkitOverflowScrolling:"touch",touchAction:"pan-y",pointerEvents:t?"auto":"none",contentVisibility:t||n?"visible":"auto"},className:o?"":"p-2 sm:p-4",children:r?a.jsx(qx.Provider,{value:t,children:o?e:a.jsx("div",{className:"w-full max-w-full pb-32",children:e})}):null})});function dI({activeIndex:s,onTabChange:e,children:t,tabPaths:r=Hx}){const n=dn(),i=hs(),{updateSwipeVisuals:o}=Lu(),l=g.useRef(null),d=g.useRef(null),c=g.useRef(!1),u=g.useRef(null),h=g.useRef(0),f=g.useRef(0),m=g.useRef(0),p=g.useRef([]),x=g.useRef(null),y=g.useRef(!1),v=g.useRef(!1),_=g.useRef(s);_.current=s;const[b,w]=g.useState(()=>new Set([s]));g.useEffect(()=>{w(k=>k.has(s)?k:new Set(k).add(s));const R=()=>{w(k=>{const D=new Set(k);return s>0&&D.add(s-1),s<r.length-1&&D.add(s+1),D.size===k.size?k:D})};if("requestIdleCallback"in window){const k=requestIdleCallback(R);return()=>cancelIdleCallback(k)}
661else{const k=setTimeout(R,200);return()=>clearTimeout(k)}},[s]);const T=g.useCallback((R,k)=>{const D=l.current;if(D){if(k){y.current=!0,D.style.transition="transform 300ms cubic-bezier(0.25, 1, 0.5, 1)";const Y=()=>{y.current=!1,D.style.transition="none",D.removeEventListener("transitionend",Y)};D.addEventListener("transitionend",Y)}else D.style.transition="none";D.style.transform=`translate3d(${-R*100}%, 0, 0)`,m.current=0}},[]);g.useEffect(()=>{if(v.current){v.current=!1;return}T(s,!0),o(0,!1)},[s,T,o]);const A=g.useCallback(()=>{var X;const R=l.current;if(!R)return;const k=-_.current*100,D=((X=d.current)==null?void 0:X.offsetWidth)||window.innerWidth,Y=m.current/D*100;R.style.transform=`translate3d(${k+Y}%, 0, 0)`;const q=-(m.current/D);o(q,!0),x.current=null},[o]),S=g.useCallback(()=>{x.current===null&&(x.current=requestAnimationFrame(A))},[A]),I=g.useCallback(()=>{const R=p.current;if(R.length<2)return 0;const k=R.slice(-5),D=k[0],Y=k[k.length-1],q=Y.t-D.t;return q===0?0:(Y.x-D.x)/q},[]),j=g.useCallback(R=>{const k=_.current,D=k===0&&R>0,Y=k===r.length-1&&R<0;return D||Y?Math.sign(R)*(1-Math.exp(-Math.abs(R)/150))*40:R},[]);return g.useEffect(()=>{const R=d.current;if(!R||!n)return;const k=()=>{c.current=!1,u.current=null,m.current=0,p.current=[],x.current!==null&&(cancelAnimationFrame(x.current),x.current=null),o(0,!1)},D=F=>{if(y.current)return;if(F.touches.length!==1){k();return}let P=F.target;for(;P&&P!==R;){const $=getComputedStyle(P).overflowX;if(($==="auto"||$==="scroll")&&P.scrollWidth>P.clientWidth)return;P=P.parentElement}let N=F.target;for(;N&&N!==R;){if(N.hasAttribute("data-no-swipe"))return;N=N.parentElement}const O=F.touches[0];c.current=!0,u.current=null,h.current=O.clientX,f.current=O.clientY,m.current=0,p.current=[{x:O.clientX,t:performance.now()}],l.current&&(l.current.style.transition="none")},Y=F=>{if(!c.current)return;if(F.touches.length!==1){k(),T(_.current,!0);return}const P=F.touches[0],N=P.clientX-h.current,O=P.clientY-f.current,$=Math.abs(N),B=Math.abs(O);if(u.current===null)if($>B*1.2&&$>10)u.current="h";else if(B>10){u.current="v",c.current=!1;return}else return;u.current==="h"&&(F.preventDefault(),p.current.push({x:P.clientX,t:performance.now()}),p.current.length>10&&p.current.shift(),m.current=j(N),S())},q=F=>{if(!c.current)return;if(c.current=!1,x.current!==null&&(cancelAnimationFrame(x.current),x.current=null),u.current!=="h"){u.current=null,o(0,!1);return}const P=m.current,N=I(),O=Math.abs(P),$=Math.abs(N);let B=_.current;(O>80||$>.4)&&(P<0&&B<r.length-1?B++:P>0&&B>0&&B--),B!==_.current&&"vibrate"in navigator&&navigator.vibrate(10),w(U=>U.has(B)?U:new Set(U).add(B)),u.current=null,m.current=0,p.current=[],T(B,!0),o(0,!1),B!==_.current&&(v.current=!0,i(r[B],{replace:!0}),e(B))},X=()=>{k(),T(_.current,!0)};return R.addEventListener("touchstart",D,{passive:!0}),R.addEventListener("touchmove",Y,{passive:!1}),R.addEventListener("touchend",q,{passive:!0}),R.addEventListener("touchcancel",X,{passive:!0}),()=>{R.removeEventListener("touchstart",D),R.removeEventListener("touchmove",Y),R.removeEventListener("touchend",q),R.removeEventListener("touchcancel",X)}},[n,r,j,S,o,I,i,e,T]),g.useEffect(()=>()=>{x.current!==null&&cancelAnimationFrame(x.current)},[]),a.jsx("div",{ref:d,style:{overflow:"hidden",position:"relative",width:"100%",height:"100%",overscrollBehavior:"contain",touchAction:"pan-y"},children:a.jsx("div",{ref:l,style:{display:"flex",width:"100%",height:"100%",willChange:"transform",transform:`translate3d(${-s*100}%, 0, 0)`,transition:"none",touchAction:"pan-y"},children:t.map((R,k)=>a.jsx(cI,{isActive:k===s,isMounted:b.has(k),isAdjacent:Math.abs(k-s)===1,path:r[k],children:R},r[k]))})})}let Ea=null,Kx=new Set;function Wx(){window.dispatchEvent(new Event("pipStateChanged"))}function J4(s){Ea={...s},Wx()}function Qf(){Ea=null,Wx()}function uI(s){Ea&&(Ea.muted=s)}function uc(){return Ea}function Z4(s){return Kx.has(s)}function e3(s){Kx.add(s)}const xe=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},hI=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=fI},fI=Number.MAX_SAFE_INTEGER||9007199254740991;
661let Re=function(s){return s.NETWORK_ERROR="networkError",s.MEDIA_ERROR="mediaError",s.KEY_SYSTEM_ERROR="keySystemError",s.MUX_ERROR="muxError",s.OTHER_ERROR="otherError",s}({}),z=function(s){return s.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",s.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",s.KEY_SYSTEM_NO_SESSION="keySystemNoSession",s.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",s.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",s.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",s.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",s.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",s.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",s.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",s.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",s.MANIFEST_LOAD_ERROR="manifestLoadError",s.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",s.MANIFEST_PARSING_ERROR="manifestParsingError",s.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",s.LEVEL_EMPTY_ERROR="levelEmptyError",s.LEVEL_LOAD_ERROR="levelLoadError",s.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",s.LEVEL_PARSING_ERROR="levelParsingError",s.LEVEL_SWITCH_ERROR="levelSwitchError",s.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",s.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",s.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",s.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",s.FRAG_LOAD_ERROR="fragLoadError",s.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",s.FRAG_DECRYPT_ERROR="fragDecryptError",s.FRAG_PARSING_ERROR="fragParsingError",s.FRAG_GAP="fragGap",s.REMUX_ALLOC_ERROR="remuxAllocError",s.KEY_LOAD_ERROR="keyLoadError",s.KEY_LOAD_TIMEOUT="keyLoadTimeOut",s.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",s.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",s.BUFFER_APPEND_ERROR="bufferAppendError",s.BUFFER_APPENDING_ERROR="bufferAppendingError",s.BUFFER_STALLED_ERROR="bufferStalledError",s.BUFFER_FULL_ERROR="bufferFullError",s.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",s.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",s.ASSET_LIST_LOAD_ERROR="assetListLoadError",s.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",s.ASSET_LIST_PARSING_ERROR="assetListParsingError",s.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",s.INTERNAL_EXCEPTION="internalException",s.INTERNAL_ABORTED="aborted",s.ATTACH_MEDIA_ERROR="attachMediaError",s.UNKNOWN="unknown",s}({}),E=function(s){return s.MEDIA_ATTACHING="hlsMediaAttaching",s.MEDIA_ATTACHED="hlsMediaAttached",s.MEDIA_DETACHING="hlsMediaDetaching",s.MEDIA_DETACHED="hlsMediaDetached",s.MEDIA_ENDED="hlsMediaEnded",s.STALL_RESOLVED="hlsStallResolved",s.BUFFER_RESET="hlsBufferReset",s.BUFFER_CODECS="hlsBufferCodecs",s.BUFFER_CREATED="hlsBufferCreated",s.BUFFER_APPENDING="hlsBufferAppending",s.BUFFER_APPENDED="hlsBufferAppended",s.BUFFER_EOS="hlsBufferEos",s.BUFFERED_TO_END="hlsBufferedToEnd",s.BUFFER_FLUSHING="hlsBufferFlushing",s.BUFFER_FLUSHED="hlsBufferFlushed",s.MANIFEST_LOADING="hlsManifestLoading",s.MANIFEST_LOADED="hlsManifestLoaded",s.MANIFEST_PARSED="hlsManifestParsed",s.LEVEL_SWITCHING="hlsLevelSwitching",s.LEVEL_SWITCHED="hlsLevelSwitched",s.LEVEL_LOADING="hlsLevelLoading",s.LEVEL_LOADED="hlsLevelLoaded",s.LEVEL_UPDATED="hlsLevelUpdated",s.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",s.LEVELS_UPDATED="hlsLevelsUpdated",s.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",s.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",s.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",s.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",s.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",s.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",s.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",s.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",s.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",s.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",s.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",s.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",s.SUBTITLE_FRAG_PROCESSED="hl
661sSubtitleFragProcessed",s.CUES_PARSED="hlsCuesParsed",s.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",s.INIT_PTS_FOUND="hlsInitPtsFound",s.FRAG_LOADING="hlsFragLoading",s.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",s.FRAG_LOADED="hlsFragLoaded",s.FRAG_DECRYPTED="hlsFragDecrypted",s.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",s.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",s.FRAG_PARSING_METADATA="hlsFragParsingMetadata",s.FRAG_PARSED="hlsFragParsed",s.FRAG_BUFFERED="hlsFragBuffered",s.FRAG_CHANGED="hlsFragChanged",s.FPS_DROP="hlsFpsDrop",s.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",s.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",s.ERROR="hlsError",s.DESTROYING="hlsDestroying",s.KEY_LOADING="hlsKeyLoading",s.KEY_LOADED="hlsKeyLoaded",s.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",s.BACK_BUFFER_REACHED="hlsBackBufferReached",s.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",s.ASSET_LIST_LOADING="hlsAssetListLoading",s.ASSET_LIST_LOADED="hlsAssetListLoaded",s.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",s.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",s.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",s.INTERSTITIAL_STARTED="hlsInterstitialStarted",s.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",s.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",s.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",s.INTERSTITIAL_ENDED="hlsInterstitialEnded",s.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",s.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",s.EVENT_CUE_ENTER="hlsEventCueEnter",s}({});var tt={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},we={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class qn{constructor(e,t=0,r=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=r}sample(e,t){const r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class mI{constructor(e,t,r,n=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_
vendor: 4,294 bytes, line 661
661=new qn(e),this.fast_=new qn(t),this.defaultTTFB_=n,this.ttfb_=new qn(e)}update(e,t){const{slow_:r,fast_:n,ttfb_:i}=this;r.halfLife!==e&&(this.slow_=new qn(e,r.getEstimate(),r.getTotalWeight())),n.halfLife!==t&&(this.fast_=new qn(t,n.getEstimate(),n.getTotalWeight())),i.halfLife!==e&&(this.ttfb_=new qn(e,i.getEstimate(),i.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const r=8*t,n=e/1e3,i=r/n;this.fast_.sample(n,i),this.slow_.sample(n,i)}sampleTTFB(e){const t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function pI(s,e,t){return(e=xI(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function Tt(){return Tt=Object.assign?Object.assign.bind():function(s){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var r in t)({}).hasOwnProperty.call(t,r)&&(s[r]=t[r])}return s},Tt.apply(null,arguments)}function Jf(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);e&&(r=r.filter(function(n){return Object.getOwnPropertyDescriptor(s,n).enumerable})),t.push.apply(t,r)}return t}function yt(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Jf(Object(t),!0).forEach(function(r){pI(s,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):Jf(Object(t)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(t,r))})}return s}function gI(s,e){if(typeof s!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var r=t.call(s,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(s)}function xI(s){var e=gI(s,"string");return typeof e=="symbol"?e:e+""}class Hs{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const r=`[${e}]:`;this.trace=Hr,this.debug=t.debug.bind(null,r),this.log=t.log.bind(null,r),this.warn=t.warn.bind(null,r),this.info=t.info.bind(null,r),this.error=t.error.bind(null,r)}}const Hr=function(){},yI={trace:Hr,debug:Hr,log:Hr,warn:Hr,info:Hr,error:Hr};function vd(){return Tt({},yI)}function vI(s,e){const t=self.console[s];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${s}] >`):Hr}function Zf(s,e,t){return e[s]?e[s].bind(e):vI(s,t)}const bd=vd();function bI(s,e,t){const r=vd();if(typeof console=="object"&&s===!0||typeof s=="object"){const n=["debug","log","info","warn","error"];n.forEach(i=>{r[i]=Zf(i,s,t)});try{r.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return vd()}n.forEach(i=>{bd[i]=Zf(i,s)})}else Tt(bd,r);return r}const vt=bd;function rn(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function _I(s){return typeof self<"u"&&s===self.ManagedMediaSource}function Yx(s,e){const t=Object.keys(s),r=Object.keys(e),n=t.length,i=r.length;return!n||!i||n===i&&!t.some(o=>r.indexOf(o)===-1)}function Os(s,e=!1){if(typeof TextDecoder<"u"){const c=new TextDecoder("utf-8").decode(s);if(e){const u=c.indexOf("\0");return u!==-1?c.substring(0,u):c}return c.replace(/\0/g,"")}const t=s.length;let r,n,i,o="",l=0;for(;l<t;){if(r=s[l++],r===0&&e)return o;if(r===0||r===3)continue;switch(r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(r);break;case 12:case 13:n=s[l++],o+=String.fromCharCode((r&31)<<6|n&63);break;case 14:n=s[l++],i=s[l++],o+=String.fromCharCode((r&15)<<12|(n&63)<<6|(i&63)<<0);break}}return o}function ls(s){let e="";for(let t=0;t<s.length;t++){let r=s[t].toString(16);r.length<2&&(r="0"+r),e+=r}return e}function Xx(s){return Uint8Array.from(s.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function wI(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?
vendor: 8,045 bytes, line 661
661s.default:s}var hc={exports:{}},em;function EI(){return em||(em=1,function(s,e){(function(t){var r=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,n=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,o=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,l={buildAbsoluteURL:function(d,c,u){if(u=u||{},d=d.trim(),c=c.trim(),!c){if(!u.alwaysNormalize)return d;var h=l.parseURL(d);if(!h)throw new Error("Error trying to parse base URL.");return h.path=l.normalizePath(h.path),l.buildURLFromParts(h)}var f=l.parseURL(c);if(!f)throw new Error("Error trying to parse relative URL.");if(f.scheme)return u.alwaysNormalize?(f.path=l.normalizePath(f.path),l.buildURLFromParts(f)):c;var m=l.parseURL(d);if(!m)throw new Error("Error trying to parse base URL.");if(!m.netLoc&&m.path&&m.path[0]!=="/"){var p=n.exec(m.path);m.netLoc=p[1],m.path=p[2]}m.netLoc&&!m.path&&(m.path="/");var x={scheme:m.scheme,netLoc:f.netLoc,path:null,params:f.params,query:f.query,fragment:f.fragment};if(!f.netLoc&&(x.netLoc=m.netLoc,f.path[0]!=="/"))if(!f.path)x.path=m.path,f.params||(x.params=m.params,f.query||(x.query=m.query));else{var y=m.path,v=y.substring(0,y.lastIndexOf("/")+1)+f.path;x.path=l.normalizePath(v)}return x.path===null&&(x.path=u.alwaysNormalize?l.normalizePath(f.path):f.path),l.buildURLFromParts(x)},parseURL:function(d){var c=r.exec(d);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[6]||""}:null},normalizePath:function(d){for(d=d.split("").reverse().join("").replace(i,"");d.length!==(d=d.replace(o,"")).length;);return d.split("").reverse().join("")},buildURLFromParts:function(d){return d.scheme+d.netLoc+d.path+d.params+d.query+d.fragment}};s.exports=l})()}(hc)),hc.exports}var Du=EI();class Ou{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var kt={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Qx{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,TI(this,"stats")}setByteRange(e,t){const r=e.split("@",2);let n;r.length===1?n=(t==null?void 0:t.byteRangeEndOffset)||0:n=parseInt(r[1]),this._byteRange=[n,parseInt(r[0])+n]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[kt.AUDIO]:null,[kt.VIDEO]:null,[kt.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Ou),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Du.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[kt.AUDIO]=null,e[kt.VIDEO]=null,e[kt.AUDIOVIDEO]=null}}function zt(s){return s.sn!=="initSegment"}class fc extends Qx{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(xe(e)&&xe(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const r=Object.keys(t);if(r.length===1){const n=this._decryptdata=t[r[0]]||null;n&&(this._decryptdata=n.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=xe(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const r=Object.keys(this.levelkeys),n=r.length;if(n>1||n===1&&(t=this.levelkeys[r[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!xe(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return zt(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var r;const n=t[e];n&&!((r=this._decryptdata)!=null&&r.keyId)&&(this._decryptdata=n.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,r,n,i,o=!1){const{elementaryStreams:l}=this,d=l[e];if(!d){l[e]={startPTS:t,endPTS:r,startDTS:n,endDTS:i,partial:o};return}d.startPTS=Math.min(d.startPTS,t),d.endPTS=Math.max(d.endPTS,r),d.startDTS=Math.min(d.startDTS,n),d.endDTS=Math.max(d.endDTS,i)}}class SI extends Qx{constructor(e,t,r,n,i){super(r),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=n;const o=e.enumeratedString("BYTERANGE");o&&this.setByteRange(o,i),i&&(this.fragOffset=i.fragOffset+i.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function Jx(s,e){const t=Object.getPrototypeOf(s);if(t){const r=Object.getOwnPropertyDescriptor(t,e);return r||Jx(t,e)}}function TI(s,e){const t=Jx(s,e);t&&(t.enumerable=!0,Object.defineProperty(s,e,t))}const tm=Math.pow(2,32)-1,AI=[].push,Zx={video:1,audio:2,id3:3,text:4};function Zt(s){return String.fromCharCode.apply(null,s)}function ey(s,e){const t=s[e]<<8|s[e+1];return t<0?65536+t:t}function Fe(s,e){const t=ty(s,e);return t<0?4294967296+t:t}function sm(s,e){let t=Fe(s,e);return t*=Math.pow(2,32),t+=Fe(s,e+4),t}function ty(s,e){return s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3]}function kI(s){const e=s.byteLength;for(let t=0;t<e;){const r=Fe(s,t);if(r>8&&s[t+4]===109&&s[t+5]===111&&s[t+6]===111&&s[t+7]===102)return!0;t=r>1?t+r:e}return!1}function Ze(s,e){const t=[];if(!e.length)return t;const r=s.byteLength;for(let n=0;n<r;){const i=Fe(s,n),o=Zt(s.subarray(n+4,n+8)),l=i>1?n+i:r;if(o===e[0])if(e.length===1)t.push(s.subarray(n+8,l));else{const d=Ze(s.subarray(n+8,l),e.slice(1));d.length&&AI.apply(t,d)}n=l}return t}function RI(s){const e=[],t=s[0];let r=8;const n=Fe(s,r);r+=4;let i=0,o=0;t===0?(i=Fe(s,r),o=Fe(s,r+4),r+=8):(i=sm(s,r),o=sm(s,r+8),r+=16),r+=2;let l=s.length+o;const d=ey(s,r);r+=2;
vendor: 4,240 bytes, line 661
661for(let c=0;c<d;c++){let u=r;const h=Fe(s,u);u+=4;const f=h&2147483647;if((h&2147483648)>>>31===1)return vt.warn("SIDX has hierarchical references (not supported)"),null;const p=Fe(s,u);u+=4,e.push({referenceSize:f,subsegmentDuration:p,info:{duration:p/n,start:l,end:l+f-1}}),l+=f,u+=4,r=u}return{earliestPresentationTime:i,timescale:n,version:t,referencesCount:d,references:e}}function sy(s){const e=[],t=Ze(s,["moov","trak"]);for(let n=0;n<t.length;n++){const i=t[n],o=Ze(i,["tkhd"])[0];if(o){let l=o[0];const d=Fe(o,l===0?12:20),c=Ze(i,["mdia","mdhd"])[0];if(c){l=c[0];const u=Fe(c,l===0?12:20),h=Ze(i,["mdia","hdlr"])[0];if(h){const f=Zt(h.subarray(8,12)),m={soun:kt.AUDIO,vide:kt.VIDEO}[f],p=Ze(i,["mdia","minf","stbl","stsd"])[0],x=jI(p);m?(e[d]={timescale:u,type:m,stsd:x},e[m]=yt({timescale:u,id:d},x)):e[d]={timescale:u,type:f,stsd:x}}}}}return Ze(s,["moov","mvex","trex"]).forEach(n=>{const i=Fe(n,4),o=e[i];o&&(o.default={duration:Fe(n,12),flags:Fe(n,20)})}),e}function jI(s){const e=s.subarray(8),t=e.subarray(86),r=Zt(e.subarray(4,8));let n=r,i;const o=r==="enca"||r==="encv";if(o){const c=Ze(e,[r])[0].subarray(r==="enca"?28:78);Ze(c,["sinf"]).forEach(h=>{const f=Ze(h,["schm"])[0];if(f){const m=Zt(f.subarray(4,8));if(m==="cbcs"||m==="cenc"){const p=Ze(h,["frma"])[0];p&&(n=Zt(p))}}})}const l=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const d=Ze(t,["avcC"])[0];d&&d.length>3&&(n+="."+eo(d[1])+eo(d[2])+eo(d[3]),i=Za(l==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const d=Ze(e,[r])[0],c=Ze(d.subarray(28),["esds"])[0];if(c&&c.length>7){let u=4;if(c[u++]!==3)break;u=mc(c,u),u+=2;const h=c[u++];if(h&128&&(u+=2),h&64&&(u+=c[u++]),c[u++]!==4)break;u=mc(c,u);const f=c[u++];if(f===64)n+="."+eo(f);else break;if(u+=12,c[u++]!==5)break;u=mc(c,u);const m=c[u++];let p=(m&248)>>3;p===31&&(p+=1+((m&7)<<3)+((c[u]&224)>>5)),n+="."+p}break}case"hvc1":case"hev1":{const d=Ze(t,["hvcC"])[0];if(d&&d.length>12){const c=d[1],u=["","A","B","C"][c>>6],h=c&31,f=Fe(d,2),m=(c&32)>>5?"H":"L",p=d[12],x=d.subarray(6,12);n+="."+u+h,n+="."+II(f).toString(16).toUpperCase(),n+="."+m+p;let y="";for(let v=x.length;v--;){const _=x[v];(_||y)&&(y="."+_.toString(16).toUpperCase()+y)}n+=y}i=Za(l=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{n=Za(n,t)||n;break}case"vp09":{const d=Ze(t,["vpcC"])[0];if(d&&d.length>6){const c=d[4],u=d[5],h=d[6]>>4&15;n+="."+dr(c)+"."+dr(u)+"."+dr(h)}break}case"av01":{const d=Ze(t,["av1C"])[0];if(d&&d.length>2){const c=d[1]>>>5,u=d[1]&31,h=d[2]>>>7?"H":"M",f=(d[2]&64)>>6,m=(d[2]&32)>>5,p=c===2&&f?m?12:10:f?10:8,x=(d[2]&16)>>4,y=(d[2]&8)>>3,v=(d[2]&4)>>2,_=d[2]&3;n+="."+c+"."+dr(u)+h+"."+dr(p)+"."+x+"."+y+v+_+"."+dr(1)+"."+dr(1)+"."+dr(1)+"."+0,i=Za("dav1",t)}break}}return{codec:n,encrypted:o,supplemental:i}}function Za(s,e){const t=Ze(e,["dvvC"]),r=t.length?t[0]:Ze(e,["dvcC"])[0];if(r){const n=r[2]>>1&127,i=r[2]<<5&32|r[3]>>3&31;return s+"."+dr(n)+"."+dr(i)}}function II(s){let e=0;for(let t=0;t<32;t++)e|=(s>>t&1)<<31-t;return e>>>0}function mc(s,e){const t=e+5;for(;s[e++]&128&&e<t;);return e}function eo(s){return("0"+s.toString(16).toUpperCase()).slice(-2)}function dr(s){return(s<10?"0":"")+s}function CI(s,e){if(!s||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&ry(s,(r,n)=>{const i=r.subarray(8,24);i.some(o=>o!==0)||(vt.log(`[eme] Patching keyId in 'enc${n?"a":"v"}>sinf>>tenc' box: ${ls(i)} -> ${ls(t)}`),r.set(t,8))})}function NI(s){const e=[];return ry(s,t=>e.push(t.subarray(8,24))),e}function ry(s,e){Ze(s,["moov","trak"]).forEach(r=>{const n=Ze(r,["mdia","minf","stbl","stsd"])[0];if(!n)return;const i=n.subarray(8);let o=Ze(i,["enca"]);const l=o.length>0;l||(o=Ze(i,["encv"])),o.forEach(d=>{const c=l?d.subarray(28):d.subarray(78);Ze(c,["sinf"]).forEach(h=>{const f=ny(h);f&&e(f,l)})})})}function ny(s){const e=Ze(s,["schm"])[0];if(e){const t=Zt(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const r=Ze(s,["schi","tenc"])[0];if(r)return r}}}function LI(s,e,t){const r={},n=Ze(s,["moof","traf"]);for(let i=0;i<n.length;i++){const o=n[i],l=Ze(o,["tfhd"])[0],d=Fe(l,4),c=e[d];if(!c)continue;r[d]||(r[d]={start:NaN,duration:0,sampleCount:0,timescale:c.timescale,type:c.type});const u=r[d],h=Ze(o,["tfdt"])[0];if(h){const b=h[0];let w=Fe(h,4);
vendor: 16,823 bytes, line 661
661b===1&&(w===tm?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(w*=tm+1,w+=Fe(h,8))),xe(w)&&(!xe(u.start)||w<u.start)&&(u.start=w)}const f=c.default,m=Fe(l,0)|(f==null?void 0:f.flags);let p=(f==null?void 0:f.duration)||0;m&8&&(m&2?p=Fe(l,12):p=Fe(l,8));const x=Ze(o,["trun"]);let y=u.start||0,v=0,_=p;for(let b=0;b<x.length;b++){const w=x[b],T=Fe(w,4),A=u.sampleCount;u.sampleCount+=T;const S=w[3]&1,I=w[3]&4,j=w[2]&1,R=w[2]&2,k=w[2]&4,D=w[2]&8;let Y=8,q=T;for(S&&(Y+=4),I&&T&&(!(w[Y+1]&1)&&u.keyFrameIndex===void 0&&(u.keyFrameIndex=A),Y+=4,j?(_=Fe(w,Y),Y+=4):_=p,R&&(Y+=4),D&&(Y+=4),y+=_,v+=_,q--);q--;)j?(_=Fe(w,Y),Y+=4):_=p,R&&(Y+=4),k&&(w[Y+1]&1||u.keyFrameIndex===void 0&&(u.keyFrameIndex=u.sampleCount-(q+1),u.keyFrameStart=y),Y+=4),D&&(Y+=4),y+=_,v+=_;!v&&p&&(v+=p*T)}u.duration+=v}if(!Object.keys(r).some(i=>r[i].duration)){let i=1/0,o=0;const l=Ze(s,["sidx"]);for(let d=0;d<l.length;d++){const c=RI(l[d]);if(c!=null&&c.references){i=Math.min(i,c.earliestPresentationTime/c.timescale);const u=c.references.reduce((h,f)=>h+f.info.duration||0,0);o=Math.max(o,u+c.earliestPresentationTime/c.timescale)}}o&&xe(o)&&Object.keys(r).forEach(d=>{r[d].duration||(r[d].duration=o*r[d].timescale-r[d].start)})}return r}function PI(s){const e={valid:null,remainder:null},t=Ze(s,["moof"]);if(t.length<2)return e.remainder=s,e;const r=t[t.length-1];return e.valid=s.slice(0,r.byteOffset-8),e.remainder=s.slice(r.byteOffset-8),e}function zs(s,e){const t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function rm(s,e){const t=[],r=e.samples,n=e.timescale,i=e.id;let o=!1;return Ze(r,["moof"]).map(d=>{const c=d.byteOffset-8;Ze(d,["traf"]).map(h=>{const f=Ze(h,["tfdt"]).map(m=>{const p=m[0];let x=Fe(m,4);return p===1&&(x*=Math.pow(2,32),x+=Fe(m,8)),x/n})[0];return f!==void 0&&(s=f),Ze(h,["tfhd"]).map(m=>{const p=Fe(m,4),x=Fe(m,0)&16777215,y=(x&1)!==0,v=(x&2)!==0,_=(x&8)!==0;let b=0;const w=(x&16)!==0;let T=0;const A=(x&32)!==0;let S=8;p===i&&(y&&(S+=8),v&&(S+=4),_&&(b=Fe(m,S),S+=4),w&&(T=Fe(m,S),S+=4),A&&(S+=4),e.type==="video"&&(o=Cl(e.codec)),Ze(h,["trun"]).map(I=>{const j=I[0],R=Fe(I,0)&16777215,k=(R&1)!==0;let D=0;const Y=(R&4)!==0,q=(R&256)!==0;let X=0;const F=(R&512)!==0;let P=0;const N=(R&1024)!==0,O=(R&2048)!==0;let $=0;const B=Fe(I,4);let U=8;k&&(D=Fe(I,U),U+=4),Y&&(U+=4);let K=D+c;for(let ee=0;ee<B;ee++){if(q?(X=Fe(I,U),U+=4):X=b,F?(P=Fe(I,U),U+=4):P=T,N&&(U+=4),O&&(j===0?$=Fe(I,U):$=ty(I,U),U+=4),e.type===kt.VIDEO){let ce=0;for(;ce<P;){const Q=Fe(r,K);if(K+=4,DI(o,r[K])){const re=r.subarray(K,K+Q);Mu(re,o?2:1,s+$/n,t)}K+=Q,ce+=Q+4}}s+=X/n}}))})})}),t}function Cl(s){if(!s)return!1;const e=s.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function DI(s,e){if(s){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Mu(s,e,t,r){const n=iy(s);let i=0;i+=e;let o=0,l=0,d=0;for(;i<n.length;){o=0;do{if(i>=n.length)break;d=n[i++],o+=d}while(d===255);l=0;do{if(i>=n.length)break;d=n[i++],l+=d}while(d===255);const c=n.length-i;let u=i;if(l<c)i+=l;else if(l>c){vt.error(`Malformed SEI payload. ${l} is too small, only ${c} bytes left to parse.`);break}if(o===4){if(n[u++]===181){const f=ey(n,u);if(u+=2,f===49){const m=Fe(n,u);if(u+=4,m===1195456820){const p=n[u++];if(p===3){const x=n[u++],y=31&x,v=64&x,_=v?2+y*3:0,b=new Uint8Array(_);if(v){b[0]=x;for(let w=1;w<_;w++)b[w]=n[u++]}r.push({type:p,payloadType:o,pts:t,bytes:b})}}}}}else if(o===5&&l>16){const h=[];for(let p=0;p<16;p++){const x=n[u++].toString(16);h.push(x.length==1?"0"+x:x),(p===3||p===5||p===7||p===9)&&h.push("-")}const f=l-16,m=new Uint8Array(f);for(let p=0;p<f;p++)m[p]=n[u++];r.push({payloadType:o,pts:t,uuid:h.join(""),userData:Os(m),userDataBytes:m})}}}function iy(s){const e=s.byteLength,t=[];let r=1;for(;r<e-2;)s[r]===0&&s[r+1]===0&&s[r+2]===3?(t.push(r+2),r+=2):r++;if(t.length===0)return s;const n=e-t.length,i=new Uint8Array(n);let o=0;for(r=0;r<n;o++,r++)o===t[0]&&(o++,t.shift()),i[r]=s[o];return i}function OI(s){const e=s[0];let t="",r="",n=0,i=0,o=0,l=0,d=0,c=0;if(e===0){for(;Zt(s.subarray(c,c+1))!=="\0";)t+=Zt(s.subarray(c,c+1)),c+=1;for(t+=Zt(s.subarray(c,c+1)),c+=1;Zt(s.subarray(c,c+1))!=="\0";)r+=Zt(s.subarray(c,c+1)),c+=1;r+=Zt(s.subarray(c,c+1)),c+=1,n=Fe(s,12),i=Fe(s,16),l=Fe(s,20),d=Fe(s,24),c=28}else if(e===1){c+=4,n=Fe(s,c),c+=4;const h=Fe(s,c);c+=4;const f=Fe(s,c);for(c+=4,o=2**32*h+f,hI(o)||(o=Number.MAX_SAFE_INTEGER,vt.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),l=Fe(s,c),c+=4,d=Fe(s,c),c+=4;Zt(s.subarray(c,c+1))!=="\0";)t+=Zt(s.subarray(c,c+1)),c+=1;for(t+=Zt(s.subarray(c,c+1)),c+=1;Zt(s.subarray(c,c+1))!=="\0";)r+=Zt(s.subarray(c,c+1)),c+=1;r+=Zt(s.subarray(c,c+1)),c+=1}const u=s.subarray(c,s.byteLength);return{schemeIdUri:t,value:r,timeScale:n,presentationTime:o,presentationTimeDelta:i,eventDuration:l,id:d,payload:u}}function MI(s,...e){const t=e.length;let r=8,n=t;for(;n--;)r+=e[n].byteLength;const i=new Uint8Array(r);for(i[0]=r>>24&255,i[1]=r>>16&255,i[2]=r>>8&255,i[3]=r&255,i.set(s,4),n=0,r=8;n<t;n++)i.set(e[n],r),r+=e[n].byteLength;return i}function FI(s,e,t){if(s.byteLength!==16)throw new RangeError("Invalid system id");let r,n;r=0,n=new Uint8Array;let i;r>0?(i=new Uint8Array(4),e.length>0&&new DataView(i.buffer).setUint32(0,e.length,!1)):i=new Uint8Array;const o=new Uint8Array(4);return t.byteLength>0&&new DataView(o.buffer).setUint32(0,t.byteLength,!1),MI([112,115,115,104],new Uint8Array([r,0,0,0]),s,i,n,o,t)}function $I(s){const e=[];if(s instanceof ArrayBuffer){const t=s.byteLength;let r=0;for(;r+32<t;){const n=new DataView(s,r),i=UI(n);e.push(i),r+=i.size}}return e}function UI(s){const e=s.getUint32(0),t=s.byteOffset,r=s.byteLength;if(r<e)return{offset:t,size:r};if(s.getUint32(4)!==1886614376)return{offset:t,size:e};const i=s.getUint32(8)>>>24;if(i!==0&&i!==1)return{offset:t,size:e};const o=s.buffer,l=ls(new Uint8Array(o,t+12,16));let d=null,c=null,u=0;if(i===0)u=28;else{const f=s.getUint32(28);if(!f||r<32+f*16)return{offset:t,size:e};d=[];for(let m=0;m<f;m++)d.push(new Uint8Array(o,t+32+m*16,16));u=32+f*16}if(!u)return{offset:t,size:e};const h=s.getUint32(u);return e-32<h?{offset:t,size:e}:(c=new Uint8Array(o,t+u+4,h),{version:i,systemId:l,kids:d,data:c,offset:t,size:e})}const ay=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Si={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Fu(s,e){const t=Si[e];return!!t&&!!t[s.slice(0,4)]}function Sa(s,e,t=!0){return!s.split(",").some(r=>!$u(r,e,t))}function $u(s,e,t=!0){var r;const n=rn(t);return(r=n==null?void 0:n.isTypeSupported(Ta(s,e)))!=null?r:!1}function Ta(s,e){return`${e}/mp4;codecs=${s}`}function nm(s){if(s){const e=s.substring(0,4);return Si.video[e]}return 2}function sl(s){const e=ay();return s.split(",").reduce((t,r)=>{const i=e&&Cl(r)?9:Si.video[r];return i?(i*2+t)/(t?3:2):(Si.audio[r]+t)/(t?2:1)},0)}const pc={};function BI(s,e=!0){if(pc[s])return pc[s];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let n=0;n<t.length;n++){var r;if($u(t[n],"audio",e))return pc[s]=t[n],t[n];if(t[n]==="mp3"&&(r=rn(e))!=null&&r.isTypeSupported("audio/mpeg"))return""}return s}const VI=/flac|opus|mp4a\.40\.34/i;function rl(s,e=!0){return s.replace(VI,t=>BI(t.toLowerCase(),e))}function GI(s,e){const t=[];if(s){const r=s.split(",");for(let n=0;n<r.length;n++)Fu(r[n],"video")||t.push(r[n])}return e&&t.push(e),t.join(",")}function Ao(s,e){if(s&&(s.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(s)!==-1)&&(im(s,"audio")||im(s,"video")))return s;if(e){const t=e.split(",");if(t.length>1){if(s){for(let r=t.length;r--;)if(t[r].substring(0,4)===s.substring(0,4))return t[r]}return t[0]}}return e||s}function im(s,e){return Fu(s,e)&&$u(s,e)}function zI(s){const e=s.split(",");for(let t=0;t<e.length;t++){const r=e[t].split(".");r.length>2&&r[0]==="avc1"&&(e[t]=`avc1.${parseInt(r[1]).toString(16)}${("000"+parseInt(r[2]).toString(16)).slice(-4)}`)}return e.join(",")}function qI(s){if(s.startsWith("av01.")){const e=s.split("."),t=["0","111","01","01","01","0"];for(let r=e.length;r>4&&r<10;r++)e[r]=t[r-4];return e.join(".")}return s}function am(s){const e=rn(s)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function _d(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const HI={supported:!0,powerEfficient:!0,smooth:!0},KI={supported:!1,smooth:!1,powerEfficient:!1},oy={supported:!0,configurations:[],decodingInfoResults:[HI]};function ly(s,e){return{supported:!1,configurations:e,decodingInfoResults:[KI],error:s}}function WI(s,e,t,r,n,i){const o=s.videoCodec,l=s.audioCodec?s.audioGroups:null,d=i==null?void 0:i.audioCodec,c=i==null?void 0:i.channels,u=c?parseInt(c):d?1/0:2;let h=null;if(l!=null&&l.length)try{l.length===1&&l[0]?h=e.groups[l[0]].channels:h=l.reduce((f,m)=>{if(m){const p=e.groups[m];if(!p)throw new Error(`Audio track group ${m} not found`);Object.keys(p.channels).forEach(x=>{f[x]=(f[x]||0)+p.channels[x]})}return f},{2:0})}catch{return!0}return o!==void 0&&(o.split(",").some(f=>Cl(f))||s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(r,30)||s.videoRange!=="SDR"&&s.videoRange!==t||s.bitrate>Math.max(n,8e6))||!!h&&xe(u)&&Object.keys(h).some(f=>parseInt(f)>u)}function cy(s,e,t,r={}){const n=s.videoCodec;if(!n&&!s.audioCodec||!t)return Promise.resolve(oy);const i=[],o=YI(s),l=o.length,d=XI(s,e,l>0),c=d.length;for(let u=l||1*c||1;u--;){const h={type:"media-source"};if(l&&(h.video=o[u%l]),c){h.audio=d[u%c];const f=h.audio.bitrate;h.video&&f&&(h.video.bitrate-=f)}i.push(h)}if(n){const u=navigator.userAgent;if(n.split(",").some(h=>Cl(h))&&ay())return Promise.resolve(ly(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),i))}return Promise.all(i.map(u=>{const h=JI(u);return r[h]||(r[h]=t.decodingInfo(u))})).then(u=>({supported:!u.some(h=>!h.supported),configurations:i,decodingInfoResults:u})).catch(u=>({supported:!1,configurations:i,decodingInfoResults:[],error:u}))}function YI(s){var e;const t=(e=s.videoCodec)==null?void 0:e.split(","),r=dy(s),n=s.width||640,i=s.height||480,o=s.frameRate||30,l=s.videoRange.toLowerCase();return t?t.map(d=>{const c={contentType:Ta(qI(d),"video"),width:n,height:i,bitrate:r,framerate:o};return l!=="sdr"&&(c.transferFunction=l),c}):[]}function XI(s,e,t){var r;const n=(r=s.audioCodec)==null?void 0:r.split(","),i=dy(s);return n&&s.audioGroups?s.audioGroups.reduce((o,l)=>{var d;const c=l?(d=e.groups[l])==null?void 0:d.tracks:null;return c?c.reduce((u,h)=>{if(h.groupId===l){const f=parseFloat(h.channels||"");n.forEach(m=>{const p={contentType:Ta(m,"audio"),bitrate:t?QI(m,i):i};f&&(p.channels=""+f),u.push(p)})}return u},o):o},[]):[]}function QI(s,e){if(e<=1)return 1;let t=128e3;return s==="ec-3"?t=768e3:s==="ac-3"&&(t=64e4),Math.min(e/2,t)}function dy(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function JI(s){let e="";const{audio:t,video:r}=s;if(r){const n=_d(r.contentType);e+=`${n}_r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||"sd"}_${Math.ceil(r.bitrate/1e5)}`}if(t){const n=_d(t.contentType);e+=`${r?"_":""}${n}_c${t.channels}`}return e}const wd=["NONE","TYPE-0","TYPE-1",null];function ZI(s){return wd.indexOf(s)>-1}const nl=["SDR","PQ","HLG"];function eC(s){return!!s&&nl.indexOf(s)>-1}var ko={No:"",Yes:"YES",v2:"v2"};function om(s){const{canSkipUntil:e,canSkipDateRanges:t,age:r}=s,n=r<e/2;return e&&n?t?ko.v2:ko.Yes:ko.No}class lm{constructor(e,t,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=r}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class Aa{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(r=>!!r).map(r=>r.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const r=(t=e.supplemental)==null?void 0:t.videoCodec;r&&r!==e.videoCodec&&(this.codecSet+=`,${r.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return cm(this._audioGroups,e)}hasSubtitleGroup(e){return cm(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let r=this._audioGroups;r||(r=this._audioGroups=[]),r.indexOf(t)===-1&&r.push(t)}else if(e==="text"){let r=this._subtitleGroups;r||(r=this._subtitleGroups=[]),r.indexOf(t)===-1&&r.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function cm(s,e){return!e||!s?!1:s.indexOf(e)!==-1}function tC(){if(typeof matchMedia=="function"){const s=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(s.media!==e.media)return s.matches===!0}return!1}function sC(s,e){let t=!1,r=[];if(s&&(t=s!=="SDR",r=[s]),e){r=e.allowedVideoRanges||nl.slice(0);const n=r.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:n&&tC(),t||(r=["SDR"])}return{preferHDR:t,allowedVideoRanges:r}}const rC=s=>{const e=new WeakSet;return(t,r)=>{if(s&&(r=s(t,r)),typeof r=="object"&&r!==null){if(e.has(r))return;e.add(r)}return r}},Rt=(s,e)=>JSON.stringify(s,rC(e));function nC(s,e,t,r,n){const i=Object.keys(s),o=r==null?void 0:r.channels,l=r==null?void 0:r.audioCodec,d=n==null?void 0:n.videoCodec,c=o&&parseInt(o)===2;let u=!1,h=!1,f=1/0,m=1/0,p=1/0,x=1/0,y=0,v=[];const{preferHDR:_,allowedVideoRanges:b}=sC(e,n);for(let I=i.length;I--;){const j=s[i[I]];u||(u=j.channels[2]>0),f=Math.min(f,j.minHeight),m=Math.min(m,j.minFramerate),p=Math.min(p,j.minBitrate),b.filter(k=>j.videoRanges[k]>0).length>0&&(h=!0)}f=xe(f)?f:0,m=xe(m)?m:0;const w=Math.max(1080,f),T=Math.max(30,m);p=xe(p)?p:t,t=Math.max(p,t),h||(e=void 0);const A=i.length>1;return{codecSet:i.reduce((I,j)=>{const R=s[j];if(j===I)return I;if(v=h?b.filter(k=>R.videoRanges[k]>0):[],A){if(R.minBitrate>t)return ar(j,`min bitrate of ${R.minBitrate} > current estimate of ${t}`),I;if(!R.hasDefaultAudio)return ar(j,"no renditions with default or auto-select sound found"),I;if(l&&j.indexOf(l.substring(0,4))%5!==0)return ar(j,`audio codec preference "${l}" not found`),I;if(o&&!c){if(!R.channels[o])return ar(j,`no renditions with ${o} channel sound found (channels options: ${Object.keys(R.channels)})`),I}else if((!l||c)&&u&&R.channels[2]===0)return ar(j,"no renditions with stereo sound found"),I;if(R.minHeight>w)return ar(j,`min resolution of ${R.minHeight} > maximum of ${w}`),I;if(R.minFramerate>T)return ar(j,`min framerate of ${R.minFramerate} > maximum of ${T}`),I;
vendor: 3,865 bytes, line 661
661if(!v.some(k=>R.videoRanges[k]>0))return ar(j,`no variants with VIDEO-RANGE of ${Rt(v)} found`),I;if(d&&j.indexOf(d.substring(0,4))%5!==0)return ar(j,`video codec preference "${d}" not found`),I;if(R.maxScore<y)return ar(j,`max score of ${R.maxScore} < selected max of ${y}`),I}return I&&(sl(j)>=sl(I)||R.fragmentError>s[I].fragmentError)?I:(x=R.minIndex,y=R.maxScore,j)},void 0),videoRanges:v,preferHDR:_,minFramerate:m,minBitrate:p,minIndex:x}}function ar(s,e){vt.log(`[abr] start candidates with "${s}" ignored because ${e}`)}function uy(s){return s.reduce((e,t)=>{let r=e.groups[t.groupId];r||(r=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(t);const n=t.channels||"2";return r.channels[n]=(r.channels[n]||0)+1,r.hasDefault=r.hasDefault||t.default,r.hasAutoSelect=r.hasAutoSelect||t.autoselect,r.hasDefault&&(e.hasDefaultAudio=!0),r.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function iC(s,e,t,r){return s.slice(t,r+1).reduce((n,i,o)=>{if(!i.codecSet)return n;const l=i.audioGroups;let d=n[i.codecSet];d||(n[i.codecSet]=d={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:o,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!l,fragmentError:0}),d.minBitrate=Math.min(d.minBitrate,i.bitrate);const c=Math.min(i.height,i.width);return d.minHeight=Math.min(d.minHeight,c),d.minFramerate=Math.min(d.minFramerate,i.frameRate),d.minIndex=Math.min(d.minIndex,o),d.maxScore=Math.max(d.maxScore,i.score),d.fragmentError+=i.fragmentError,d.videoRanges[i.videoRange]=(d.videoRanges[i.videoRange]||0)+1,l&&l.forEach(u=>{if(!u)return;const h=e.groups[u];h&&(d.hasDefaultAudio=d.hasDefaultAudio||e.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(h.channels).forEach(f=>{d.channels[f]=(d.channels[f]||0)+h.channels[f]}))}),n},{})}function dm(s){if(!s)return s;const{lang:e,assocLang:t,characteristics:r,channels:n,audioCodec:i}=s;return{lang:e,assocLang:t,characteristics:r,channels:n,audioCodec:i}}function fr(s,e,t){if("attrs"in s){const r=e.indexOf(s);if(r!==-1)return r}for(let r=0;r<e.length;r++){const n=e[r];if(Sn(s,n,t))return r}return-1}function Sn(s,e,t){const{groupId:r,name:n,lang:i,assocLang:o,default:l}=s,d=s.forced;return(r===void 0||e.groupId===r)&&(n===void 0||e.name===n)&&(i===void 0||aC(i,e.lang))&&(i===void 0||e.assocLang===o)&&(l===void 0||e.default===l)&&(d===void 0||e.forced===d)&&(!("characteristics"in s)||oC(s.characteristics||"",e.characteristics))&&(t===void 0||t(s,e))}function aC(s,e="--"){return s.length===e.length?s===e:s.startsWith(e)||e.startsWith(s)}function oC(s,e=""){const t=s.split(","),r=e.split(",");return t.length===r.length&&!t.some(n=>r.indexOf(n)===-1)}function vn(s,e){const{audioCodec:t,channels:r}=s;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(r===void 0||r===(e.channels||"2"))}function lC(s,e,t,r,n){const i=e[r],l=e.reduce((f,m,p)=>{const x=m.uri;return(f[x]||(f[x]=[])).push(p),f},{})[i.uri];l.length>1&&(r=Math.max.apply(Math,l));const d=i.videoRange,c=i.frameRate,u=i.codecSet.substring(0,4),h=um(e,r,f=>{if(f.videoRange!==d||f.frameRate!==c||f.codecSet.substring(0,4)!==u)return!1;const m=f.audioGroups,p=t.filter(x=>!m||m.indexOf(x.groupId)!==-1);return fr(s,p,n)>-1});return h>-1?h:um(e,r,f=>{const m=f.audioGroups,p=t.filter(x=>!m||m.indexOf(x.groupId)!==-1);return fr(s,p,n)>-1})}function um(s,e,t){for(let r=e;r>-1;r--)if(t(s[r]))return r;for(let r=e+1;r<s.length;r++)if(t(s[r]))return r;return-1}function il(s,e){var t;return!!s&&s!==((t=e.loadLevelObj)==null?void 0:t.uri)}class cC extends Hs{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.co
vendor: 8,083 bytes, lines 661-671
661decTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var r;const{fragCurrent:n,partCurrent:i,hls:o}=this,{autoLevelEnabled:l,media:d}=o;if(!n||!d)return;const c=performance.now(),u=i?i.stats:n.stats,h=i?i.duration:n.duration,f=c-u.loading.start,m=o.minAutoLevel,p=n.level,x=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||p<=m){this.clearTimer(),this._nextAutoLevel=-1;return}if(!l)return;const y=x>-1&&x!==p,v=!!t||y;if(!v&&(d.paused||!d.playbackRate||!d.readyState))return;const _=o.mainForwardBufferInfo;if(!v&&_===null)return;const b=this.bwEstimator.getEstimateTTFB(),w=Math.abs(d.playbackRate);if(f<=Math.max(b,1e3*(h/(w*2))))return;const T=_?_.len/w:0,A=u.loading.first?u.loading.first-u.loading.start:-1,S=u.loaded&&A>-1,I=this.getBwEstimate(),j=o.levels,R=j[p],k=Math.max(u.loaded,Math.round(h*(n.bitrate||R.averageBitrate)/8));let D=S?f-A:f;D<1&&S&&(D=Math.min(f,u.loaded*8/I));const Y=S?u.loaded*1e3/D:0,q=b/1e3,X=Y?(k-u.loaded)/Y:k*8/I+q;if(X<=T)return;const F=Y?Y*8:I,P=((r=(t==null?void 0:t.details)||this.hls.latestLevelDetails)==null?void 0:r.live)===!0,N=this.hls.config.abrBandWidthUpFactor;let O=Number.POSITIVE_INFINITY,$;for($=p-1;$>m;$--){const ee=j[$].maxBitrate,ce=!j[$].details||P;if(O=this.getTimeToLoadFrag(q,F,h*ee,ce),O<Math.min(T,h+q))break}if(O>=X||O>h*10)return;S?this.bwEstimator.sample(f-Math.min(b,A),u.loaded):this.bwEstimator.sampleTTFB(f);const B=j[$].maxBitrate;this.getBwEstimate()*N>B&&this.resetEstimator(B);const U=this.findBestLevel(B,m,$,0,T,1,1);U>-1&&($=U),this.warn(`Fragment ${n.sn}${i?" part "+i.index:""} of level ${p} is loading too slowly;
662      Fragment duration: ${n.duration.toFixed(3)}
663      Time to underbuffer: ${T.toFixed(3)} s
664      Estimated load time for current fragment: ${X.toFixed(3)} s
665      Estimated load time for down switch fragment: ${O.toFixed(3)} s
666      TTFB estimate: ${A|0} ms
667      Current BW estimate: ${xe(I)?I|0:"Unknown"} bps
668      New BW estimate: ${this.getBwEstimate()|0} bps
669      Switching to level ${$} @ ${B|0} bps`),o.nextLoadLevel=o.nextAutoLevel=$,this.clearTimer();const K=()=>{if(this.clearTimer(),this.fragCurrent===n&&this.hls.loadLevel===$&&$>0){const ee=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${$>0?"and switching down":""}
670      Fragment duration: ${n.duration.toFixed(3)} s
671      Time to underbuffer: ${ee.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,$>m){let ce=this.findBestLevel(this.hls.levels[m].bitrate,m,$,0,ee,1,1);ce===-1&&(ce=m),this.hls.nextLoadLevel=this.hls.nextAutoLevel=ce,this.resetEstimator(this.hls.levels[ce].bitrate)}}};y||X>O*2?K():this.timer=self.setInterval(K,O*1e3),o.trigger(E.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:i,stats:u})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new mI(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(E.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const r=t.frag;if(!this.ignoreFragment(r)){if(!r.bitrateTest){var n;this.fragCurrent=r,this.partCurrent=(n=t.part)!=null?n:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case z.BUFFER_ADD_CODEC_ERROR:case z.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case z.FRAG_LOAD_TIMEOUT:{const r=t.frag,{fragCurrent:n,partCurrent:i}=this;if(r&&n&&r.sn===n.sn&&r.level===n.level){const o=performance.now(),l=i?i.stats:r.stats,d=o-l.loading.start,c=l.loading.first?l.loading.first-l.loading.start:-1;if(l.loaded&&c>-1){const h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(d-Math.min(h,c),l.loaded)}else this.bwEstimator.sampleTTFB(d)}break}}}getTimeToLoadFrag(e,t,r,n){const i=e+r/t,o=n?e+this.lastLevelLoadSec:0;return i+o}onLevelLoaded(e,t){const r=this.hls.config,{loading:n}=t.stats,i=n.end-n.first;xe(i)&&(this.lastLevelLoadSec=i/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:r}){const n=r?r.stats:t.stats;if(t.type===we.MAIN&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const i=r?r.duration:t.duration,o=this.hls.levels[t.level],l=(o.loaded?o.loaded.bytes:0)+n.loaded,d=(o.loaded?o.loaded.duration:0)+i;o.loaded={bytes:l,duration:d},o.realBitrate=Math.round(8*l/d)}if(t.bitrateTest){const i={stats:n,frag:t,part:r,id:t.type};this.onFragBuffered(E.FRAG_BUFFERED,i),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:r,part:n}=t,i=n!=null&&n.stats.loaded?n.stats:r.stats;if(i.aborted||this.ignoreFragment(r))return;const o=i.parsing.end-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,i.loaded),i.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=o/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==we.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,r=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,i=this.findBestLevel(r,t,e,0,n,1,1);if(i>-1)return i;const o=this.hls.firstLevel,l=Math.min(Math.max(o,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${l}`),l}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,r=this.bwEstimator.canEstimate(),n=this.lastLoadedFragLevel>-1;if(e!==-1&&(!r||!n||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const i=r&&n?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const o=this.hls.levels;if(o.length>Math.max(e,i)&&o[e].loadError<=o[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}
671_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:r}=this;if(r.levels.length<=1)return r.loadLevel;const{maxAutoLevel:n,config:i,minAutoLevel:o}=r,l=t?t.duration:e?e.duration:0,d=this.getBwEstimate(),c=this.getStarvationDelay();let u=i.abrBandWidthFactor,h=i.abrBandWidthUpFactor;if(c){const y=this.findBestLevel(d,o,n,c,0,u,h);if(y>=0)return this.rebufferNotice=-1,y}let f=l?Math.min(l,i.maxStarvationDelay):i.maxStarvationDelay;if(!c){const y=this.bitrateTestDelay;y&&(f=(l?Math.min(l,i.maxLoadingDelay):i.maxLoadingDelay)-y,this.info(`bitrate test took ${Math.round(1e3*y)}ms, set first fragment max fetchDuration to ${Math.round(1e3*f)} ms`),u=h=1)}const m=this.findBestLevel(d,o,n,c,f,u,h);if(this.rebufferNotice!==m&&(this.rebufferNotice=m,this.info(`${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${m}`)),m>-1)return m;const p=r.levels[o],x=r.loadLevelObj;return x&&(p==null?void 0:p.bitrate)<x.bitrate?o:r.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const r=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/r}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,r,n,i,o,l){var d;const c=n+i,u=this.lastLoadedFragLevel,h=u===-1?this.hls.firstLevel:u,{fragCurrent:f,partCurrent:m}=this,{levels:p,allAudioTracks:x,loadLevel:y,config:v}=this.hls;if(p.length===1)return 0;const _=p[h],b=!!((d=this.hls.latestLevelDetails)!=null&&d.live),w=y===-1||u===-1;let T,A="SDR",S=(_==null?void 0:_.frameRate)||0;const{audioPreference:I,videoPreference:j}=v,R=this.audioTracksByGroup||(this.audioTracksByGroup=uy(x));let k=-1;if(w){if(this.firstSelection!==-1)return this.firstSelection;const F=this.codecTiers||(this.codecTiers=iC(p,R,t,r)),P=nC(F,A,e,I,j),{codecSet:N,videoRanges:O,minFramerate:$,minBitrate:B,minIndex:U,preferHDR:K}=P;k=U,T=N,A=K?O[O.length-1]:O[0],S=$,e=Math.max(e,B),this.log(`picked start tier ${Rt(P)}`)}else T=_==null?void 0:_.codecSet,A=_==null?void 0:_.videoRange;const D=m?m.duration:f?f.duration:0,Y=this.bwEstimator.getEstimateTTFB()/1e3,q=[];for(let F=r;F>=t;F--){var X;const P=p[F],N=F>h;if(!P)continue;if(v.useMediaCapabilities&&!P.supportedResult&&!P.supportedPromise){const ce=navigator.mediaCapabilities;typeof(ce==null?void 0:ce.decodingInfo)=="function"&&WI(P,R,A,S,e,I)?(P.supportedPromise=cy(P,R,ce,this.supportedCache),P.supportedPromise.then(Q=>{if(!this.hls)return;P.supportedResult=Q;const re=this.hls.levels,ve=re.indexOf(P);Q.error?this.warn(`MediaCapabilities decodingInfo error: "${Q.error}" for level ${ve} ${Rt(Q)}`):Q.supported?Q.decodingInfoResults.some(Ce=>Ce.smooth===!1||Ce.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ve} not smooth or powerEfficient: ${Rt(Q)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ve} ${Rt(Q)}`),ve>-1&&re.length>1&&(this.log(`Removing unsupported level ${ve}`),this.hls.removeLevel(ve),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Q=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Q}`)})):P.supportedResult=oy}if((T&&P.codecSet!==T||A&&P.videoRange!==A||N&&S>P.frameRate||!N&&S>0&&S<P.frameRate||(X=P.supportedResult)!=null&&(X=X.decodingInfoResults)!=null&&X.some(ce=>ce.smooth===!1))&&(!w||F!==k)){q.push(F);continue}const O=P.details,$=(m?O==null?void 0:O.partTarget:O==null?void 0:O.averagetargetduration)||D;let B;N?B=l*e:B=o*e;const U=D&&n>=D*2&&i===0?P.averageBitrate:P.maxBitrate,K=this.getTimeToLoadFrag(Y,B,U*$,O===void 0);if(B>=U&&(F===u||P.loadError===0&&P.fragmentError===0)&&(K<=Y||!xe(K)||b&&!this.bitrateTestDelay||K<c)){const ce=this.forcedAutoLevel;return F!==y&&(ce===-1||ce!==y)&&(q.length&&this.trace(`Skipped level(s) ${q.join(",")} of ${r} max with CODECS and VIDEO-RANGE:"${p[q[0]].codecs}" ${p[q[0]].videoRange}; not compatible with "${T}" ${A}`),this.info(`switch candidate:${h}->${F} adjustedbw(${Math.round(B)})-bitrate=${Math.round(B-U)} ttfb:${Y.toFixed(1)} avgDuration:${$.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${K.toFixed(1)}
671 firstSelection:${w} codecSet:${P.codecSet} videoRange:${P.videoRange} hls.loadLevel:${y}`)),w&&(this.firstSelection=F),F}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:r}=this.hls;return Math.min(Math.max(e,r),t)}}const hy={search:function(s,e){let t=0,r=s.length-1,n=null,i=null;for(;t<=r;){n=(t+r)/2|0,i=s[n];const o=e(i);if(o>0)t=n+1;else if(o<0)r=n-1;else return i}return null}};function dC(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!xe(e))return null;const r=s[0].programDateTime;if(e<(r||0))return null;const n=s[s.length-1].endProgramDateTime;if(e>=(n||0))return null;for(let i=0;i<s.length;++i){const o=s[i];if(hC(e,t,o))return o}return null}function kn(s,e,t=0,r=0,n=.005){let i=null;if(s){i=e[1+s.sn-e[0].sn]||null;const l=s.endDTS-t;l>0&&l<15e-7&&(t+=15e-7),i&&s.level!==i.level&&i.end<=s.end&&(i=e[2+s.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(i=e[0]);if(i&&((!s||s.level===i.level)&&hm(t,r,i)===0||uC(i,s,Math.min(n,r))))return i;const o=hy.search(e,hm.bind(null,t,r));return o&&(o!==s||!i)?o:i}function uC(s,e,t){if(e&&e.start===0&&e.level<s.level&&(e.endPTS||0)>0){const r=e.tagList.reduce((n,i)=>(i[0]==="INF"&&(n+=parseFloat(i[1])),n),t);return s.start<=r}return!1}function hm(s=0,e=0,t){if(t.start<=s&&t.start+t.duration>s)return 0;const r=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-r<=s?1:t.start-r>s&&t.start?-1:0}function hC(s,e,t){const r=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-r>s}function fy(s,e,t){if(s&&s.startCC<=e&&s.endCC>=e){let r=s.fragments;const{fragmentHint:n}=s;n&&(r=r.concat(n));let i;return hy.search(r,o=>o.cc<e?1:o.cc>e?-1:(i=o,o.end<=t?1:o.start>t?-1:0)),i||null}return null}function al(s){switch(s.details){case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_TIMEOUT:case z.LEVEL_LOAD_TIMEOUT:case z.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function my(s){return s.details.startsWith("key")}function py(s){return my(s)&&!!s.frag&&!s.frag.decryptdata}function fm(s,e){const t=al(e);return s.default[`${t?"timeout":"error"}Retry`]}function Uu(s,e){const t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function mm(s){return yt(yt({},s),{errorRetry:null,timeoutRetry:null})}function ol(s,e,t,r){if(!s)return!1;const n=r==null?void 0:r.code,i=e<s.maxNumRetry&&(fC(n)||!!t);return s.shouldRetry?s.shouldRetry(s,e,t,r,i):i}function fC(s){return Ed(s)||!!s&&(s<400||s>499)}function Ed(s){return s===0&&navigator.onLine===!1}var os={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Is={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class mC extends Hs{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(E.ERROR,this.onError,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(E.ERROR,this.onError,this),e.off(E.ERROR,this.onErrorOut,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===we.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,r=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||r===-1?t.loadLevel:r}variantHasKey(e,t){if(e){var r;if((r=e.details)!=null&&r.hasKey(t))return!0;const n=e.audioGroups;if(n)return this.hls.allAudioTracks.filter(o=>n.indexOf(o.groupId)>=0).some(o=>{var l;return(l=o.details)==null?void 0:l.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var r;if(t.fatal)return;const n=this.hls,i=t.context;switch(t.details){case z.FRAG_LOAD_ERROR:case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_ERROR:case z.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case z.FRAG_PARSING_ERROR:if((r=t.frag)!=null&&r.gap){t.errorAction=hi();return}case z.FRAG_GAP:case z.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=os.SendAlternateToPenaltyBox;return}case z.LEVEL_EMPTY_ERROR:case z.LEVEL_PARSING_ERROR:{var o;const d=t.parent===we.MAIN?t.level:n.loadLevel;t.details===z.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(o=o.levelDetails)!=null&&o.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,d):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,d))}return;case z.LEVEL_LOAD_ERROR:case z.LEVEL_LOAD_TIMEOUT:typeof(i==null?void 0:i.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level));return;case z.AUDIO_TRACK_LOAD_ERROR:case z.AUDIO_TRACK_LOAD_TIMEOUT:case z.SUBTITLE_LOAD_ERROR:case z.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const d=n.loadLevelObj;if(d&&(i.type===tt.AUDIO_TRACK&&d.hasAudioGroup(i.groupId)||i.type===tt.SUBTITLE_TRACK&&d.hasSubtitleGroup(i.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=os.SendAlternateToPenaltyBox,t.errorAction.flags=Is.MoveAllAlternatesMatchingHost;return}}return;case z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:os.SendAlternateToPenaltyBox,flags:Is.MoveAllAlternatesMatchingHDCP};return;case z.KEY_SYSTEM_SESSION_UPDATE_FAILED:case z.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case z.KEY_SYSTEM_NO_SESSION:t.errorAction={action:os.SendAlternateToPenaltyBox,flags:Is.MoveAllAlternatesMatchingKey};return;
vendor: 10,876 bytes, line 671
671case z.BUFFER_ADD_CODEC_ERROR:case z.REMUX_ALLOC_ERROR:case z.BUFFER_APPEND_ERROR:if(!t.errorAction){var l;t.errorAction=this.getLevelSwitchAction(t,(l=t.level)!=null?l:n.loadLevel)}return;case z.INTERNAL_EXCEPTION:case z.BUFFER_APPENDING_ERROR:case z.BUFFER_FULL_ERROR:case z.LEVEL_SWITCH_ERROR:case z.BUFFER_STALLED_ERROR:case z.BUFFER_SEEK_OVER_HOLE:case z.BUFFER_NUDGE_ON_STALL:t.errorAction=hi();return}t.type===Re.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=hi())}getPlaylistRetryOrSwitchAction(e,t){const r=this.hls,n=fm(r.config.playlistLoadPolicy,e),i=this.playlistError++;if(ol(n,i,al(e),e.response))return{action:os.RetryRequest,flags:Is.None,retryConfig:n,retryCount:i};const l=this.getLevelSwitchAction(e,t);return n&&(l.retryConfig=n,l.retryCount=i),l}getFragRetryOrSwitchAction(e){const t=this.hls,r=this.getVariantLevelIndex(e.frag),n=t.levels[r],{fragLoadPolicy:i,keyLoadPolicy:o}=t.config,l=fm(my(e)?o:i,e),d=t.levels.reduce((u,h)=>u+h.fragmentError,0);if(n&&(e.details!==z.FRAG_GAP&&n.fragmentError++,!py(e)&&ol(l,d,al(e),e.response)))return{action:os.RetryRequest,flags:Is.None,retryConfig:l,retryCount:d};const c=this.getLevelSwitchAction(e,r);return l&&(c.retryConfig=l,c.retryCount=d),c}getLevelSwitchAction(e,t){const r=this.hls;t==null&&(t=r.loadLevel);const n=this.hls.levels[t];if(n){var i,o;const c=e.details;n.loadError++,c===z.BUFFER_APPEND_ERROR&&n.fragmentError++;let u=-1;const{levels:h,loadLevel:f,minAutoLevel:m,maxAutoLevel:p}=r;!r.autoLevelEnabled&&!r.config.preserveManualLevelOnError&&(r.loadLevel=-1);const x=(i=e.frag)==null?void 0:i.type,v=(x===we.AUDIO&&c===z.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(c===z.BUFFER_ADD_CODEC_ERROR||c===z.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:A})=>n.audioCodec!==A),b=e.sourceBufferName==="video"&&(c===z.BUFFER_ADD_CODEC_ERROR||c===z.BUFFER_APPEND_ERROR)&&h.some(({codecSet:A,audioCodec:S})=>n.codecSet!==A&&n.audioCodec===S),{type:w,groupId:T}=(o=e.context)!=null?o:{};for(let A=h.length;A--;){const S=(A+f)%h.length;if(S!==f&&S>=m&&S<=p&&h[S].loadError===0){var l,d;const I=h[S];if(c===z.FRAG_GAP&&x===we.MAIN&&e.frag){const j=h[S].details;if(j){const R=kn(e.frag,j.fragments,e.frag.start);if(R!=null&&R.gap)continue}}else{if(w===tt.AUDIO_TRACK&&I.hasAudioGroup(T)||w===tt.SUBTITLE_TRACK&&I.hasSubtitleGroup(T))continue;if(x===we.AUDIO&&(l=n.audioGroups)!=null&&l.some(j=>I.hasAudioGroup(j))||x===we.SUBTITLE&&(d=n.subtitleGroups)!=null&&d.some(j=>I.hasSubtitleGroup(j))||v&&n.audioCodec===I.audioCodec||b&&n.codecSet===I.codecSet||!v&&n.codecSet!==I.codecSet)continue}u=S;break}}if(u>-1&&r.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:os.SendAlternateToPenaltyBox,flags:Is.None,nextAutoLevel:u}}return{action:os.SendAlternateToPenaltyBox,flags:Is.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var r;switch((r=t.errorAction)==null?void 0:r.action){case os.DoNothing:break;case os.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==z.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,r=e.errorAction;if(!r)return;const{flags:n}=r,i=r.nextAutoLevel;switch(n){case Is.None:this.switchLevel(e,i);break;case Is.MoveAllAlternatesMatchingHDCP:{const d=this.getVariantLevelIndex(e.frag),c=t.levels[d],u=c==null?void 0:c.attrs["HDCP-LEVEL"];if(r.hdcpLevel=u,u==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(u){t.maxHdcpLevel=wd[wd.indexOf(u)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Is.MoveAllAlternatesMatchingKey:{const d=e.decryptdata;if(d){const c=this.hls.levels,u=c.length;for(let f=u;f--;)if(this.variantHasKey(c[f],d)){var o,l;this.log(`Banned key found in level ${f} (${c[f].bitrate}bps) or audio group "${(o=c[f].audioGroups)==null?void 0:o.join(",")}" (${(l=e.frag)==null?void 0:l.type} fragment) ${ls(d.keyId||[])}`),c[f].fragmentError++,c[f].loadError++,this.log(`Removing level ${f} with key error (${e.error})`),this.hls.removeLevel(f)}const h=e.frag;if(this.hls.levels.length<u)r.resolved=!0;else if(h&&h.type!==we.MAIN){const f=h.decryptdata;f&&!d.matches(f)&&(r.resolved=!0)}}break}}r.resolved||this.switchLevel(e,i)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===z.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const r=_d(e.mimeType),n=this.hls.levels;for(let i=n.length;i--;)n[i][`${e.sourceBufferName}Codec`]===r&&(this.log(`Removing level ${i} for ${e.details} ("${r}" not supported)`),this.hls.removeLevel(i))}}}function hi(s){const e={action:os.DoNothing,flags:Is.None};return s&&(e.resolved=!0),e}var ss={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class pC{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const r=this.activePartLists[t];if(r)for(let n=r.length;n--;){const i=r[n];if(!i)break;if(i.start<=e&&e<=i.end&&i.loaded)return i}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,r){const{fragments:n}=this,i=Object.keys(n);for(let o=i.length;o--;){const l=n[i[o]];if((l==null?void 0:l.body.type)===t&&(!r||l.buffered)){const d=l.body;if(d.start<=e&&e<=d.end)return d}}return null}detectEvictedFragments(e,t,r,n,i){this.timeRanges&&(this.timeRanges[e]=t);const o=(n==null?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(l=>{const d=this.fragments[l];if(!d||o>=d.body.sn)return;if(!d.buffered&&(!d.loaded||i)){d.body.type===r&&this.removeFragment(d.body);return}const c=d.range[e];if(c){if(c.time.length===0){this.removeFragment(d.body);return}c.time.some(u=>{const h=!this.isTimeBuffered(u.startPTS,u.endPTS,t);return h&&this.removeFragment(d.body),h})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const r=e.frag,n=Hn(r),i=this.fragments[n];if(!i||i.buffered&&r.gap)return;const o=!r.relurl;Object.keys(t).forEach(l=>{const d=r.elementaryStreams[l];if(!d)return;const c=t[l],u=o||d.partial===!0;i.range[l]=this.getBufferedTimes(r,e.part,u,c)}),i.loaded=null,Object.keys(i.range).length?(this.bufferedEnd(i,r),to(i)||this.removeParts(r.sn-1,r.type)):this.removeFragment(i.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const r=this.activePartLists[t];r&&(this.activePartLists[t]=pm(r,n=>n.fragment.sn>=e))}fragBuffered(e,t){const r=Hn(e);let n=this.fragments[r];!n&&t&&(n=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,this.bufferedEnd(n,e))}getBufferedTimes(e,t,r,n){const i={time:[],partial:r},o=e.start,l=e.end,d=e.minEndPTS||l,c=e.maxStartPTS||o;for(let u=0;u<n.length;u++){const h=n.start(u)-this.bufferPadding,f=n.end(u)+this.bufferPadding;if(c>=h&&d<=f){i.time.push({startPTS:Math.max(o,n.start(u)),endPTS:Math.min(l,n.end(u))});break}else if(o<f&&l>h){const m=Math.max(o,n.start(u)),p=Math.min(l,n.end(u));p>m&&(i.partial=!0,i.time.push({startPTS:m,endPTS:p}))}else if(l<=h)break}return i}getPartialFragment(e){let t=null,r,n,i,o=0;const{bufferPadding:l,fragments:d}=this;return Object.keys(d).forEach(c=>{const u=d[c];u&&to(u)&&(n=u.body.start-l,i=u.body.end+l,e>=n&&e<=i&&(r=Math.min(e-n,i-e),o<=r&&(t=u.body,o=r)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||to(t))}getState(e){const t=Hn(e),r=this.fragments[t];return r?r.buffered?to(r)?ss.PARTIAL:ss.OK:ss.APPENDING:ss.NOT_LOADED}isTimeBuffered(e,t,r){let n,i;for(let o=0;o<r.length;o++){if(n=r.start(o)-this.bufferPadding,i=r.end(o)+this.bufferPadding,e>=n&&t<=i)return!0;if(t<=n)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const r=t.frag,n=t.part?null:t,i=Hn(r);this.fragments[i]={body:r,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:r,part:n,timeRanges:i,type:o}=t;if(r.sn==="initSegment")return;const l=r.type;if(n){let c=this.activePartLists[l];c||(this.activePartLists[l]=c=[]),c.push(n)}this.timeRanges=i;const d=i[o];this.detectEvictedFragments(o,d,l,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Hn(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,r=Object.keys(t);if(!e)return r.length>0;for(let n=r.length;n--;){const i=t[r[n]];if((i==null?void 0:i.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,r,n,i){n&&!this.hasGaps||Object.keys(this.fragments).forEach(o=>{const l=this.fragments[o];if(!l)return;const d=l.body;d.type!==r||n&&!d.gap||d.start<t&&d.end>e&&(l.buffered||i)&&this.removeFragment(d)})}removeFragment(e){const t=Hn(e);e.clearElementaryStreamInfo();const r=this.activePartLists[e.type];if(r){const n=e.sn;this.activePartLists[e.type]=pm(r,i=>i.fragment.sn!==n)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(r=>r.clearElementaryStreamInfo())}}function to(s){var e,t,r;return s.buffered&&!!(s.body.gap||(e=s.range.video)!=null&&e.partial||(t=s.range.audio)!=null&&t.partial||(r=s.range.audiovideo)!=null&&r.partial)}function Hn(s){return`${s.type}_${s.level}_${s.sn}`}function pm(s,e){return s.filter(t=>{const r=e(t);return r||t.clearElementaryStreamInfo(),r})}
vendor: 19,850 bytes, line 671
671var nn={cbc:0,ctr:1};class gC{constructor(e,t,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=r}decrypt(e,t){switch(this.aesMode){case nn.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case nn.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function xC(s){const e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?s.slice(0,e-t):s}class yC{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),r=new Uint32Array(4);for(let n=0;n<4;n++)r[n]=t.getUint32(n*4);return r}initTable(){const e=this.sBox,t=this.invSBox,r=this.subMix,n=r[0],i=r[1],o=r[2],l=r[3],d=this.invSubMix,c=d[0],u=d[1],h=d[2],f=d[3],m=new Uint32Array(256);let p=0,x=0,y=0;for(y=0;y<256;y++)y<128?m[y]=y<<1:m[y]=y<<1^283;for(y=0;y<256;y++){let v=x^x<<1^x<<2^x<<3^x<<4;v=v>>>8^v&255^99,e[p]=v,t[v]=p;const _=m[p],b=m[_],w=m[b];let T=m[v]*257^v*16843008;n[p]=T<<24|T>>>8,i[p]=T<<16|T>>>16,o[p]=T<<8|T>>>24,l[p]=T,T=w*16843009^b*65537^_*257^p*16843008,c[v]=T<<24|T>>>8,u[v]=T<<16|T>>>16,h[v]=T<<8|T>>>24,f[v]=T,p?(p=_^m[m[m[w^_]]],x^=m[m[x]]):p=x=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let r=!0,n=0;for(;n<t.length&&r;)r=t[n]===this.key[n],n++;if(r)return;this.key=t;const i=this.keySize=t.length;if(i!==4&&i!==6&&i!==8)throw new Error("Invalid aes key size="+i);const o=this.ksRows=(i+6+1)*4;let l,d;const c=this.keySchedule=new Uint32Array(o),u=this.invKeySchedule=new Uint32Array(o),h=this.sBox,f=this.rcon,m=this.invSubMix,p=m[0],x=m[1],y=m[2],v=m[3];let _,b;for(l=0;l<o;l++){if(l<i){_=c[l]=t[l];continue}b=_,l%i===0?(b=b<<8|b>>>24,b=h[b>>>24]<<24|h[b>>>16&255]<<16|h[b>>>8&255]<<8|h[b&255],b^=f[l/i|0]<<24):i>6&&l%i===4&&(b=h[b>>>24]<<24|h[b>>>16&255]<<16|h[b>>>8&255]<<8|h[b&255]),c[l]=_=(c[l-i]^b)>>>0}for(d=0;d<o;d++)l=o-d,d&3?b=c[l]:b=c[l-4],d<4||l<=4?u[d]=b:u[d]=p[h[b>>>24]]^x[h[b>>>16&255]]^y[h[b>>>8&255]]^v[h[b&255]],u[d]=u[d]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,r){const n=this.keySize+6,i=this.invKeySchedule,o=this.invSBox,l=this.invSubMix,d=l[0],c=l[1],u=l[2],h=l[3],f=this.uint8ArrayToUint32Array_(r);let m=f[0],p=f[1],x=f[2],y=f[3];const v=new Int32Array(e),_=new Int32Array(v.length);let b,w,T,A,S,I,j,R,k,D,Y,q,X,F;const P=this.networkToHostOrderSwap;for(;t<v.length;){for(k=P(v[t]),D=P(v[t+1]),Y=P(v[t+2]),q=P(v[t+3]),S=k^i[0],I=q^i[1],j=Y^i[2],R=D^i[3],X=4,F=1;F<n;F++)b=d[S>>>24]^c[I>>16&255]^u[j>>8&255]^h[R&255]^i[X],w=d[I>>>24]^c[j>>16&255]^u[R>>8&255]^h[S&255]^i[X+1],T=d[j>>>24]^c[R>>16&255]^u[S>>8&255]^h[I&255]^i[X+2],A=d[R>>>24]^c[S>>16&255]^u[I>>8&255]^h[j&255]^i[X+3],S=b,I=w,j=T,R=A,X=X+4;b=o[S>>>24]<<24^o[I>>16&255]<<16^o[j>>8&255]<<8^o[R&255]^i[X],w=o[I>>>24]<<24^o[j>>16&255]<<16^o[R>>8&255]<<8^o[S&255]^i[X+1],T=o[j>>>24]<<24^o[R>>16&255]<<16^o[S>>8&255]<<8^o[I&255]^i[X+2],A=o[R>>>24]<<24^o[S>>16&255]<<16^o[I>>8&255]<<8^o[j&255]^i[X+3],_[t]=P(b^m),_[t+1]=P(A^p),_[t+2]=P(T^x),_[t+3]=P(w^y),m=k,p=D,x=Y,y=q,t=t+4}return _.buffer}}class vC{constructor(e,t,r){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=r}expandKey(){const e=bC(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function bC(s){switch(s){case nn.cbc:return"AES-CBC";case nn.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${s}`)}}const _C=16;class Bu{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const r=self.crypto;r&&(this.subtle=r.subtle||r.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const r=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?xC(r):r}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,r,n){return this.useSoftware?new Promise((i,o)=>{const l=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(l,t,r,n);const d=this.flush();d?i(d.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,r,n)}softwareDecrypt(e,t,r,n){const{currentIV:i,currentResult:o,remainderData:l}=this;if(n!==nn.cbc||t.byteLength!==16)return vt.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),l&&(e=zs(l,e),this.remainderData=null);const d=this.getValidChunk(e);if(!d.length)return null;i&&(r=i);let c=this.softwareDecrypter;c||(c=this.softwareDecrypter=new yC),c.expandKey(t);const u=o;return this.currentResult=c.decrypt(d.buffer,0,r),this.currentIV=d.slice(-16).buffer,u||null}webCryptoDecrypt(e,t,r,n){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,r,n));this.key=t,this.fastAesKey=new vC(this.subtle,t,n)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new gC(this.subtle,new Uint8Array(r),n).decrypt(e.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(vt.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(e,t,r,n)))}onWebCryptoError(e,t,r,n){const i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r,n);const o=this.flush();if(o)return o.buffer}throw new Error("WebCrypto"+(i?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const r=e.length-e.length%_C;return r!==e.length&&(t=e.slice(0,r),this.remainderData=e.slice(r)),t}logOnce(e){this.logEnabled&&(vt.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const gm=Math.pow(2,17);class wC{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const r=e.url;if(!r)return Promise.reject(new jr({type:Re.NETWORK_ERROR,details:z.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();const n=this.config,i=n.fLoader,o=n.loader;return new Promise((l,d)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(p=>p[0]==="GAP")){d(ym(e));return}else e.gap=!1;const c=this.loader=i?new i(n):new o(n),u=xm(e);e.loader=c;const h=mm(n.fragLoadPolicy.default),f={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:gm};e.stats=c.stats;const m={onSuccess:(p,x,y,v)=>{this.resetLoader(e,c);let _=p.data;y.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(_.slice(0,16)),_=_.slice(16)),l({frag:e,part:null,payload:_,networkDetails:v})},onError:(p,x,y,v)=>{this.resetLoader(e,c),d(new jr({type:Re.NETWORK_ERROR,details:z.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:yt({url:r,data:void 0},p),error:new Error(`HTTP Error ${p.code} ${p.text}`),networkDetails:y,stats:v}))},onAbort:(p,x,y)=>{this.resetLoader(e,c),d(new jr({type:Re.NETWORK_ERROR,details:z.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:y,stats:p}))},onTimeout:(p,x,y)=>{this.resetLoader(e,c),d(new jr({type:Re.NETWORK_ERROR,details:z.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:y,stats:p}))}};t&&(m.onProgress=(p,x,y,v)=>t({frag:e,part:null,payload:y,networkDetails:v})),c.load(u,f,m)})}loadPart(e,t,r){this.abort();const n=this.config,i=n.fLoader,o=n.loader;return new Promise((l,d)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){d(ym(e,t));return}const c=this.loader=i?new i(n):new o(n),u=xm(e,t);e.loader=c;const h=mm(n.fragLoadPolicy.default),f={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:gm};t.stats=c.stats,c.load(u,f,{onSuccess:(m,p,x,y)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:m.data,networkDetails:y};r(v),l(v)},onError:(m,p,x,y)=>{this.resetLoader(e,c),d(new jr({type:Re.NETWORK_ERROR,details:z.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:yt({url:u.url,data:void 0},m),error:new Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:x,stats:y}))},onAbort:(m,p,x)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),d(new jr({type:Re.NETWORK_ERROR,details:z.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:x,stats:m}))},onTimeout:(m,p,x)=>{this.resetLoader(e,c),d(new jr({type:Re.NETWORK_ERROR,details:z.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:x,stats:m}))}})})}updateStatsFromPart(e,t){const r=e.stats,n=t.stats,i=n.total;if(r.loaded+=n.loaded,i){const d=Math.round(e.duration/t.duration),c=Math.min(Math.round(r.loaded/i),d),h=(d-c)*Math.round(r.loaded/c);r.total=r.loaded+h}else r.total=Math.max(r.loaded,r.total);const o=r.loading,l=n.loading;o.start?o.first+=l.first-l.start:(o.start=l.start,o.first=l.first),o.end=l.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function xm(s,e=null){const t=e||s,r={frag:s,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},n=t.byteRangeStartOffset,i=t.byteRangeEndOffset;if(xe(n)&&xe(i)){var o;let l=n,d=i;if(s.sn==="initSegment"&&EC((o=s.decryptdata)==null?void 0:o.method)){const c=i-n;c%16&&(d=i+(16-c%16)),n!==0&&(r.resetIV=!0,l=n-16)}r.rangeStart=l,r.rangeEnd=d}return r}function ym(s,e){const t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),r={type:Re.MEDIA_ERROR,details:z.FRAG_GAP,fatal:!1,frag:s,error:t,networkDetails:null};return e&&(r.part=e),(e||s).stats.aborted=!0,new jr(r)}function EC(s){return s==="AES-128"||s==="AES-256"}class jr extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class gy extends Hs{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Vu{constructor(e,t,r,n=0,i=-1,o=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=so(),this.buffering={audio:so(),video:so(),audiovideo:so()},this.level=e,this.sn=t,this.id=r,this.size=n,this.part=i,this.partial=o}}function so(){return{start:0,executeStart:0,executeEnd:0,end:0}}const vm={length:0,start:()=>0,end:()=>0};class Ue{static isBuffered(e,t){if(e){const r=Ue.getBuffered(e);for(let n=r.length;n--;)if(t>=r.start(n)&&t<=r.end(n))return!0}return!1}static bufferedRanges(e){if(e){const t=Ue.getBuffered(e);return Ue.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let r=0;r<e.length;r++)t.push({start:e.start(r),end:e.end(r)});return t}static bufferInfo(e,t,r){if(e){const n=Ue.bufferedRanges(e);if(n.length)return Ue.bufferedInfo(n,t,r)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,r){t=Math.max(0,t),e.length>1&&e.sort((u,h)=>u.start-h.start||h.end-u.end);let n=-1,i=[];if(r)for(let u=0;u<e.length;u++){t>=e[u].start&&t<=e[u].end&&(n=u);const h=i.length;if(h){const f=i[h-1].end;e[u].start-f<r?e[u].end>f&&(i[h-1].end=e[u].end):i.push(e[u])}else i.push(e[u])}else i=e;let o=0,l,d=t,c=t;for(let u=0;u<i.length;u++){const h=i[u].start,f=i[u].end;if(n===-1&&t>=h&&t<=f&&(n=u),t+r>=h&&t<f)d=h,c=f,o=c-t;else if(t+r<h){l=h;break}}return{len:o,start:d||0,end:c||0,nextStart:l,buffered:e,bufferedIndex:n}}static getBuffered(e){try{return e.buffered||vm}catch(t){return vt.log("failed to get media.buffered",t),vm}}}const xy=/\{\$([a-zA-Z0-9-_]+)\}/g;function bm(s){return xy.test(s)}function Sd(s,e){if(s.variableList!==null||s.hasVariableRefs){const t=s.variableList;return e.replace(xy,r=>{const n=r.substring(2,r.length-1),i=t==null?void 0:t[n];return i===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),r):i})}return e}function _m(s,e,t){let r=s.variableList;r||(s.variableList=r={});let n,i;if("QUERYPARAM"in e){n=e.QUERYPARAM;try{const o=new self.URL(t).searchParams;if(o.has(n))i=o.get(n);else throw new Error(`"${n}" does not match any query parameter in URI: "${t}"`)}catch(o){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${o.message}`))}}else n=e.NAME,i=e.VALUE;n in r?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):r[n]=i||""}function SC(s,e,t){const r=e.IMPORT;if(t&&r in t){let n=s.variableList;n||(s.variableList=n={}),n[r]=t[r]}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}const TC=/^(\d+)x(\d+)$/,wm=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Dt{constructor(e,t){typeof e=="string"&&(e=Dt.parseAttrList(e,t)),Tt(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const r=new Uint8Array(t.length/2);for(let n=0;n<t.length/2;n++)r[n]=parseInt(t.slice(n*2,n*2+2),16);return r}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const r=this[e];return r?parseFloat(r):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const r=this[e];return(r?r.split(/[ ,]+/):[]).reduce((n,i)=>(n[i.toLowerCase()]=!0,n),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=TC.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let r;const n={},i='"';for(wm.lastIndex=0;(r=wm.exec(e))!==null;){const o=r[1].trim();let l=r[2];const d=l.indexOf(i)===0&&l.lastIndexOf(i)===l.length-1;let c=!1;if(d)l=l.slice(1,-1);else switch(o){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":c=!0}if(t&&(d||c))l=Sd(t,l);else if(!c&&!d)switch(o){case"CLOSED-CAPTIONS":if(l==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":vt.warn(`${e}: attribute ${o} is missing quotes`)}n[o]=l}return n}}const AC="com.apple.hls.interstitial";function kC(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function RC(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class yy{constructor(e,t,r=0){var n;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(n=t==null?void 0:t.tagOrder)!=null?n:r,t){const i=t.attr;for(const o in i)if(Object.prototype.hasOwnProperty.call(e,o)&&e[o]!==i[o]){vt.warn(`DATERANGE tag attribute: "${o}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=o;break}e=Tt(new Dt({}),i,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const i=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);xe(i.getTime())&&(this._endDate=i)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(vt.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(xe(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===AC}get isValid(){return!!this.id&&!this._badValueForSameId&&xe(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const jC=10;class IC{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.drift
vendor: 67,126 bytes, lines 671-676
671StartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&r>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let r=t.decryptdata;return r||(t.setKeyFormat(e.keyFormat),r=t.decryptdata),!!r&&e.matches(r)})}get hasProgramDateTime(){return this.fragments.length?xe(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||jC}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let r=e.length;r--;)if(e[r].index>t)return e[r].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function ll(s,e){return s.length===e.length?!s.some((t,r)=>t!==e[r]):!1}function Em(s,e){return!s&&!e?!0:!s||!e?!1:ll(s,e)}function fi(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function Gu(s){switch(s){case"AES-128":case"AES-256":return nn.cbc;case"AES-256-CTR":return nn.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function zu(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function Td(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}function CC(s){const e=Td(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function vy(s){const e=function(r,n,i){const o=r[n];r[n]=r[i],r[i]=o};e(s,0,3),e(s,1,2),e(s,4,5),e(s,6,7)}function by(s){const e=s.split(":");let t=null;if(e[0]==="data"&&e.length===2){const r=e[1].split(";"),n=r[r.length-1].split(",");if(n.length===2){const i=n[0]==="base64",o=n[1];i?(r.splice(-1,1),t=zu(o)):t=CC(o)}}return t}const cl=typeof self<"u"?self:void 0;var Ft={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},cs={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Ro(s){switch(s){case cs.FAIRPLAY:return Ft.FAIRPLAY;case cs.PLAYREADY:return Ft.PLAYREADY;case cs.WIDEVINE:return Ft.WIDEVINE;case cs.CLEARKEY:return Ft.CLEARKEY}}function gc(s){switch(s){case Ft.FAIRPLAY:return cs.FAIRPLAY;case Ft.PLAYREADY:return cs.PLAYREADY;case Ft.WIDEVINE:return cs.WIDEVINE;case Ft.CLEARKEY:return cs.CLEARKEY}}function Qi(s){const{drmSystems:e,widevineLicenseUrl:t}=s,r=e?[Ft.FAIRPLAY,Ft.WIDEVINE,Ft.PLAYREADY,Ft.CLEARKEY].filter(n=>!!e[n]):[];return!r[Ft.WIDEVINE]&&t&&r.push(Ft.WIDEVINE),r}const _y=function(s){return cl!=null&&(s=cl.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function NC(s,e,t,r){let n;switch(s){case Ft.FAIRPLAY:n=["cenc","sinf"];break;case Ft.WIDEVINE:case Ft.PLAYREADY:n=["cenc"];break;case Ft.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return LC(n,e,t,r)}function LC(s,e,t,r){return[{initDataTypes:s,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:e.map(i=>({contentType:`audio/mp4; codecs=${i}`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:t.map(i=>({contentType:`video/mp4; codecs=${i}`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}))}]}function PC(s){var e;return!!s&&(s.sessionType==="persistent-license"||!!((e=s.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function wy(s){const e=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),r=t.substring(t.indexOf("<"),t.length),o=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(o){const l=o.childNodes[0]?o.childNodes[0].nodeValue:o.getAttribute("VALUE");if(l){const d=zu(l).subarray(0,16);return vy(d),d}}return null}let Kn={};class Zr{static clearKeyUriToKeyIdMap(){Kn={}}static setKeyIdForUri(e,t){Kn[e]=t}static addKeyIdForUri(e){const t=Object.keys(Kn).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,t),Kn[e]=r,r}constructor(e,t,r,n=[1],i=null,o){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=r,this.keyFormatVersions=n,this.iv=i,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!fi(e),o!=null&&o.startsWith("0x")&&(this.keyId=new Uint8Array(Xx(o)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&ll(e.keyFormatVersions,this.keyFormatVersions)&&Em(e.iv,this.iv)&&Em(e.keyId,this.keyId)}isSupported(){if(this.method){if(fi(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case cs.FAIRPLAY:case cs.WIDEVINE:case cs.PLAYREADY:case cs.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(fi(this.method)){let i=this.iv;return i||(typeof e!="number"&&(vt.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),i=OC(e)),new Zr(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){const i=Kn[this.uri];if(i&&!ll(this.keyId,i)&&Zr.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const r=by(this.uri);if(r)switch(this.keyFormat){case cs.WIDEVINE:if(this.pssh=r,!this.keyId){const i=$I(r.buffer);if(i.length){var n;const o=i[0];this.keyId=(n=o.kids)!=null&&n.length?o.kids[0]:null}}this.keyId||(this.keyId=Sm(t));break;case cs.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=FI(i,null,r),this.keyId=wy(r);break}default:{let i=r.subarray(0,16);if(i.length!==16){const o=new Uint8Array(16);o.set(i,16-i.length),i=o}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i;i=DC(t),i||(i=Sm(t),i||(i=Kn[this.uri])),i&&(this.keyId=i,Zr.setKeyIdForUri(this.uri,i))}return this}}function DC(s){const e=s==null?void 0:s[cs.WIDEVINE];return e?e.keyId:null}function Sm(s){const e=s==null?void 0:s[cs.PLAYREADY];if(e){const t=by(e.uri);if(t)return wy(t)}return null}function OC(s){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}const Tm=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Am=/#EXT-X-MEDIA:(.*)/g,MC=/^#EXT(?:INF|-X-TARGETDURATION):/m,xc=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),FC=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class mr{static findGroup(e,t){for(let r=0;r<e.length;r++){const n=e[r];if(n.id===t)return n}}static resolve(e,t){return Du.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return MC.test(e)}static parseMasterPlaylist(e,t){const r=bm(e),n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:r},i=[];if(Tm.lastIndex=0,!e.startsWith("#EXTM3U"))return n.playlistParsingError=new Error("no EXTM3U delimiter"),n;let o;for(;(o=Tm.exec(e))!=null;)if(o[1]){var l;const c=new Dt(o[1],n),u=Sd(n,o[2]),h={attrs:c,bitrate:c.decimalInteger("BANDWIDTH")||c.decimalInteger("AVERAGE-BANDWIDTH"),name:c.NAME,url:mr.resolve(u,t)},f=c.decimalResolution("RESOLUTION");f&&(h.width=f.width,h.height=f.height),jm(c.CODECS,h);const m=c["SUPPLEMENTAL-CODECS"];m&&(h.supplemental={},jm(m,h.supplemental)),(l=h.unknownCodecs)!=null&&l.length||i.push(h),n.levels.push(h)}else if(o[3]){const c=o[3],u=o[4];switch(c){case"SESSION-DATA":{const h=new Dt(u,n),f=h["DATA-ID"];f&&(n.sessionData===null&&(n.sessionData={}),n.sessionData[f]=h);break}case"SESSION-KEY":{const h=km(u,t,n);h.encrypted&&h.isSupported()?(n.sessionKeys===null&&(n.sessionKeys=[]),n.sessionKeys.push(h)):vt.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const h=new Dt(u,n);_m(n,h,t)}break}case"CONTENT-STEERING":{const h=new Dt(u,n);n.contentSteering={uri:mr.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{n.startTimeOffset=Rm(u);break}}}const d=i.length>0&&i.length<n.levels.length;return n.levels=d?i:n.levels,n.levels.length===0&&(n.playlistParsingError=new Error("no levels found in manifest")),n}static parseMasterPlaylistMedia(e,t,r){let n;const i={},o=r.levels,l={AUDIO:o.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:o.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let d=0;for(Am.lastIndex=0;(n=Am.exec(e))!==null;){const c=new Dt(n[1],r),u=c.TYPE;if(u){const h=l[u],f=i[u]||[];i[u]=f;const m=c.LANGUAGE,p=c["ASSOC-LANGUAGE"],x=c.CHANNELS,y=c.CHARACTERISTICS,v=c["INSTREAM-ID"],_={attrs:c,bitrate:0,id:d++,groupId:c["GROUP-ID"]||"",name:c.NAME||m||"",type:u,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:m,url:c.URI?mr.resolve(c.URI,t):""};if(p&&(_.assocLang=p),x&&(_.channels=x),y&&(_.characteristics=y),v&&(_.instreamId=v),h!=null&&h.length){const b=mr.findGroup(h,_.groupId)||h[0];Im(_,b,"audioCodec"),Im(_,b,"textCodec")}f.push(_)}}return i}static parseLevelPlaylist(e,t,r,n,i,o){var l;const d={url:t},c=new IC(t),u=c.fragments,h=[];let f=null,m=0,p=0,x=0,y=0,v=0,_=null,b=new fc(n,d),w,T,A,S=-1,I=!1,j=null,R;if(xc.lastIndex=0,c.m3u8=e,c.hasVariableRefs=bm(e),((l=xc.exec(e))==null?void 0:l[0])!=="#EXTM3U")return c.playlistParsingError=new Error("Missing format identifier #EXTM3U"),c;for(;(w=xc.exec(e))!==null;){I&&(I=!1,b=new fc(n,d),b.playlistOffset=x,b.setStart(x),b.sn=m,b.cc=y,v&&(b.bitrate=v),b.level=r,f&&(b.initSegment=f,f.rawProgramDateTime&&(b.rawProgramDateTime=f.rawProgramDateTime,f.rawProgramDateTime=null),j&&(b.setByteRange(j),j=null)));const q=w[1];if(q){b.duration=parseFloat(q);const X=(" "+w[2]).slice(1);b.title=X||null,b.tagList.push(X?["INF",q,X]:["INF",q])}else if(w[3]){if(xe(b.duration)){b.playlistOffset=x,b.setStart(x),A&&Nm(b,A,c),b.sn=m,b.level=r,b.cc=y,u.push(b);const X=(" "+w[3]).slice(1);b.relurl=Sd(c,X),Ad(b,_,h),_=b,x+=b.duration,m++,p=0,I=!0}}else{if(w=w[0].match(FC),!w){vt.warn("No matches on slow regex match for level playlist!");continue}for(T=1;T<w.length&&w[T]===void 0;T++);const X=(" "+w[T]).slice(1),F=(" "+w[T+1]).slice(1),P=w[T+2]?(" "+w[T+2]).slice(1):null;switch(X){case"BYTERANGE":_?b.setByteRange(F,_):b.setByteRange(F);break;case"PROGRAM-DATE-TIME":b.rawProgramDateTime=F,b.tagList.push(["PROGRAM-DATE-TIME",F]),S===-1&&(S=u.length);break;case"PLAYLIST-TYPE":c.type&&Tr(c,X,w),c.type=F.toUpperCase();break;case"MEDIA-SEQUENCE":c.startSN!==0?Tr(c,X,w):u.length>0&&Lm(c,X,w),m=c.startSN=parseInt(F);break;case"SKIP":{c.skippedSegments&&Tr(c,X,w);const N=new Dt(F,c),O=N.decimalInteger("SKIPPED-SEGMENTS");if(xe(O)){c.skippedSegments+=O;for(let B=O;B--;)u.push(null);m+=O}const $=N.enumeratedString("RECENTLY-REMOVED-DATERANGES");$&&(c.recentlyRemovedDateranges=(c.recentlyRemovedDateranges||[]).concat($.split("	")));break}case"TARGETDURATION":c.targetduration!==0&&Tr(c,X,w),c.targetduration=Math.max(parseInt(F),1);break;case"VERSION":c.version!==null&&Tr(c,X,w),c.version=parseInt(F);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":c.live||Tr(c,X,w),c.live=!1;break;case"#":(F||P)&&b.tagList.push(P?[F,P]:[F]);break;case"DISCONTINUITY":y++,b.tagList.push(["DIS"]);break;case"GAP":b.gap=!0,b.tagList.push([X]);break;case"BITRATE":b.tagList.push([X,F]),v=parseInt(F)*1e3,xe(v)?b.bitrate=v:v=0;break;case"DATERANGE":{const N=new Dt(F,c),O=new yy(N,c.dateRanges[N.ID],c.dateRangeTagCount);c.dateRangeTagCount++,O.isValid||c.skippedSegments?c.dateRanges[O.id]=O:vt.warn(`Ignoring invalid DATERANGE tag: "${F}"`),b.tagList.push(["EXT-X-DATERANGE",F]);break}case"DEFINE":{{const N=new Dt(F,c);"IMPORT"in N?SC(c,N,o):_m(c,N,t)}break}case"DISCONTINUITY-SEQUENCE":c.startCC!==0?Tr(c,X,w):u.length>0&&Lm(c,X,w),c.startCC=y=parseInt(F);break;case"KEY":{const N=km(F,t,c);if(N.isSupported()){if(N.method==="NONE"){A=void 0;break}A||(A={});const O=A[N.keyFormat];O!=null&&O.matches(N)||(O&&(A=Tt({},A)),A[N.keyFormat]=N)}else vt.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${F}"`);break}case"START":c.startTimeOffset=Rm(F);break;case"MAP":{const N=new Dt(F,c);if(b.duration){const O=new fc(n,d);Cm(O,N,r,A),f=O,b.initSegment=f,f.rawProgramDateTime&&!b.rawProgramDateTime&&(b.rawProgramDateTime=f.rawProgramDateTime)}else{const O=b.byteRangeEndOffset;if(O){const $=b.byteRangeStartOffset;j=`${O-$}@${$}`}else j=null;Cm(b,N,r,A),f=b,I=!0}f.cc=y;break}case"SERVER-CONTROL":{R&&Tr(c,X,w),R=new Dt(F),c.canBlockReload=R.bool("CAN-BLOCK-RELOAD"),c.canSkipUntil=R.optionalFloat("CAN-SKIP-UNTIL",0),c.canSkipDateRanges=c.canSkipUntil>0&&R.bool("CAN-SKIP-DATERANGES"),c.partHoldBack=R.optionalFloat("PART-HOLD-BACK",0),c.holdBack=R.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{c.partTarget&&Tr(c,X,w);const N=new Dt(F);c.partTarget=N.decimalFloatingPoint("PART-TARGET");break}case"PART":{let N=c.partList;N||(N=c.partList=[]);const O=p>0?N[N.length-1]:void 0,$=p++,B=new Dt(F,c),U=new SI(B,b,d,$,O);N.push(U),b.duration+=U.duration;break}case"PRELOAD-HINT":{const N=new Dt(F,c);c.preloadHint=N;break}case"RENDITION-REPORT":{const N=new Dt(F,c);c.renditionReports=c.renditionReports||[],c.renditionReports.push(N);break}default:vt.warn(`line parsed but not handled: ${w}`);break}}}_&&!_.relurl?(u.pop(),x-=_.duration,c.partList&&(c.fragmentHint=_)):c.partList&&(Ad(b,_,h),b.cc=y,c.fragmentHint=b,A&&Nm(b,A,c)),c.targetduration||(c.playlistParsingError=new Error("Missing Target Duration"));const k=u.length,D=u[0],Y=u[k-1];if(x+=c.skippedSegments*c.targetduration,x>0&&k&&Y){c.averagetargetduration=x/k;const q=Y.sn;c.endSN=q!=="initSegment"?q:0,c.live||(Y.endList=!0),S>0&&(UC(u,S),D&&h.unshift(D))}return c.fragmentHint&&(x+=c.fragmentHint.duration),c.totalduration=x,h.length&&c.dateRangeTagCount&&D&&Ey(h,c),c.endCC=y,c}}function Ey(s,e){let t=s.length;if(!t)if(e.hasProgramDateTime){const l=e.fragments[e.fragments.length-1];s.push(l),t++}else return;const r=s[t-1],n=e.live?1/0:e.totalduration,i=Object.keys(e.dateRanges);for(let l=i.length;l--;){const d=e.dateRanges[i[l]],c=d.startDate.getTime();d.tagAnchor=r.ref;for(let u=t;u--;){var o;if(((o=s[u])==null?void 0:o.sn)<e.startSN)break;const h=$C(e,c,s,u,n);if(h!==-1){d.tagAnchor=e.fragments[h].ref;break}}}}function $C(s,e,t,r,n){const i=t[r];if(i){const l=i.programDateTime;if(e>=l||r===0){var o;const d=(((o=t[r+1])==null?void 0:o.start)||n)-i.start;if(e<=l+d*1e3){const c=t[r].sn-s.startSN;if(c<0)return-1;const u=s.fragments;if(u.length>t.length){const f=(t[r+1]||u[u.length-1]).sn-s.startSN;for(let m=f;m>c;m--){const p=u[m].programDateTime;if(e>=p&&e<p+u[m].duration*1e3)return m}}return c}}}return-1}function km(s,e,t){var r,n;const i=new Dt(s,t),o=(r=i.METHOD)!=null?r:"",l=i.URI,d=i.hexadecimalInteger("IV"),c=i.KEYFORMATVERSIONS,u=(n=i.KEYFORMAT)!=null?n:"identity";l&&i.IV&&!d&&vt.error(`Invalid IV: ${i.IV}`);const h=l?mr.resolve(l,e):"",f=(c||"1").split("/").map(Number).filter(Number.isFinite);return new Zr(o,h,u,f,d,i.KEYID)}function Rm(s){const t=new Dt(s).decimalFloatingPoint("TIME-OFFSET");return xe(t)?t:null}function jm(s,e){let t=(s||"").split(/[ ,]+/).filter(r=>r);["video","audio","text"].forEach(r=>{const n=t.filter(i=>Fu(i,r));n.length&&(e[`${r}Codec`]=n.map(i=>i.split("/")[0]).join(","),t=t.filter(i=>n.indexOf(i)===-1))}),e.unknownCodecs=t}function Im(s,e,t){const r=e[t];r&&(s[t]=r)}function UC(s,e){let t=s[e];for(let r=e;r--;){const n=s[r];if(!n)return;n.programDateTime=t.programDateTime-n.duration*1e3,t=n}}function Ad(s,e,t){s.rawProgramDateTime?t.push(s):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime)}function Cm(s,e,t,r){s.relurl=e.URI,e.BYTERANGE&&s.setByteRange(e.BYTERANGE),s.level=t,s.sn="initSegment",r&&(s.levelkeys=r),s.initSegment=null}function Nm(s,e,t){s.levelkeys=e;const{encryptedFragments:r}=t;(!r.length||r[r.length-1].levelkeys!==e)&&Object.keys(e).some(n=>e[n].isCommonEncryption)&&r.push(s)}function Tr(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function Lm(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function yc(s,e){const t=e.startPTS;if(xe(t)){let r=0,n;e.sn>s.sn?(r=t-s.start,n=s):(r=s.start-t,n=e),n.duration!==r&&n.setDuration(r)}else e.sn>s.sn?s.cc===e.cc&&s.minEndPTS?e.setStart(s.start+(s.minEndPTS-s.start)):e.setStart(s.start+s.duration):e.setStart(Math.max(s.start-e.duration,0))}function Sy(s,e,t,r,n,i,o){r-t<=0&&(o.warn("Fragment should have a positive duration",e),r=t+e.duration,i=n+e.duration);let d=t,c=r;const u=e.startPTS,h=e.endPTS;if(xe(u)){const v=Math.abs(u-t);s&&v>s.totalduration?o.warn(`media timestamps and playlist times differ by ${v}s for level ${e.level} ${s.url}`):xe(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,d=Math.max(t,u),t=Math.min(t,u),n=e.startDTS!==void 0?Math.min(n,e.startDTS):n,c=Math.min(r,h),r=Math.max(r,h),i=e.endDTS!==void 0?Math.max(i,e.endDTS):i}const f=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(r-e.start),e.startPTS=t,e.maxStartPTS=d,e.startDTS=n,e.endPTS=r,e.minEndPTS=c,e.endDTS=i;const m=e.sn;if(!s||m<s.startSN||m>s.endSN)return 0;let p;const x=m-s.startSN,y=s.fragments;for(y[x]=e,p=x;p>0;p--)yc(y[p],y[p-1]);for(p=x;p<y.length-1;p++)yc(y[p],y[p+1]);return s.fragmentHint&&yc(y[y.length-1],s.fragmentHint),s.PTSKnown=s.alignedSliding=!0,f}function BC(s,e,t){if(s===e)return;let r=null;const n=s.fragments;for(let u=n.length-1;u>=0;u--){const h=n[u].initSegment;if(h){r=h;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let i;zC(s,e,(u,h,f,m)=>{if((!e.startCC||e.skippedSegments)&&h.cc!==u.cc){const p=u.cc-h.cc;for(let x=f;x<m.length;x++)m[x].cc+=p;e.endCC=m[m.length-1].cc}xe(u.startPTS)&&xe(u.endPTS)&&(h.setStart(h.startPTS=u.startPTS),h.startDTS=u.startDTS,h.maxStartPTS=u.maxStartPTS,h.endPTS=u.endPTS,h.endDTS=u.endDTS,h.minEndPTS=u.minEndPTS,h.setDuration(u.endPTS-u.startPTS),h.duration&&(i=h),e.PTSKnown=e.alignedSliding=!0),u.hasStreams&&(h.elementaryStreams=u.elementaryStreams),h.loader=u.loader,u.hasStats&&(h.stats=u.stats),u.initSegment&&(h.initSegment=u.initSegment,r=u.initSegment)});const o=e.fragments,l=e.fragmentHint?o.concat(e.fragmentHint):o;if(r&&l.forEach(u=>{var h;u&&(!u.initSegment||u.initSegment.relurl===((h=r)==null?void 0:h.relurl))&&(u.initSegment=r)}),e.skippedSegments){if(e.deltaUpdateFailed=o.some(u=>!u),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let u=e.skippedSegments;u--;)o.shift();e.startSN=o[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=VC(s.dateRanges,e,t));const u=s.fragments.filter(h=>h.rawProgramDateTime);if(s.hasProgramDateTime&&!e.hasProgramDateTime)for(let h=1;h<l.length;h++)l[h].programDateTime===null&&Ad(l[h],l[h-1],u);Ey(u,e)}e.endCC=o[o.length-1].cc}if(!e.startCC){var d;const u=ky(s,e.startSN-1);e.startCC=(d=u==null?void 0:u.cc)!=null?d:o[0].cc}GC(s.partList,e.partList,(u,h)=>{h.elementaryStreams=u.elementaryStreams,h.stats=u.stats}),i?Sy(e,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,t):Ty(s,e),o.length&&(e.totalduration=e.edge-o[0].start),e.driftStartTime=s.driftStartTime,e.driftStart=s.driftStart;const c=e.advancedDateTime;if(e.advanced&&c){const u=e.edge;e.driftStart||(e.driftStartTime=c,e.driftStart=u),e.driftEndTime=c,e.driftEnd=u}else e.driftEndTime=s.driftEndTime,e.driftEnd=s.driftEnd,e.advancedDateTime=s.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=s.requestScheduled)}function VC(s,e,t){const{dateRanges:r,recentlyRemovedDateranges:n}=e,i=Tt({},s);n&&n.forEach(d=>{delete i[d]});const l=Object.keys(i).length;return l?(Object.keys(r).forEach(d=>{const c=i[d],u=new yy(r[d].attr,c);u.isValid?(i[d]=u,c||(u.tagOrder+=l)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Rt(r[d].attr)}"`)}),i):r}function GC(s,e,t){if(s&&e){let r=0;for(let n=0,i=s.length;n<=i;n++){const o=s[n],l=e[n+r];o&&l&&o.index===l.index&&o.fragment.sn===l.fragment.sn?t(o,l):r--}}}function zC(s,e,t){const r=e.skippedSegments,n=Math.max(s.startSN,e.startSN)-e.startSN,i=(s.fragmentHint?1:0)+(r?e.endSN:Math.min(s.endSN,e.endSN))-e.startSN,o=e.startSN-s.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,d=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let c=n;c<=i;c++){const u=d[o+c];let h=l[c];if(r&&!h&&u&&(h=e.fragments[c]=u),u&&h){t(u,h,c,l);const f=u.relurl,m=h.relurl;if(f&&qC(f,m)){e.playlistParsingError=Pm(`media sequence mismatch ${h.sn}:`,s,e,u,h);return}else if(u.cc!==h.cc){e.playlistParsingError=Pm(`discontinuity sequence mismatch (${u.cc}!=${h.cc})`,s,e,u,h);return}}}}function Pm(s,e,t,r,n){return new Error(`${s} ${n.url}
672Playlist starting @${e.startSN}
673${e.m3u8}
674
675Playlist starting @${t.startSN}
676${t.m3u8}`)}function Ty(s,e,t=!0){const r=e.startSN+e.skippedSegments-s.startSN,n=s.fragments,i=r>=0;let o=0;if(i&&r<n.length)o=n[r].start;else if(i&&e.startSN===s.endSN+1)o=s.fragmentEnd;else if(i&&t)o=s.fragmentStart+r*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=s.fragmentStart;else return;kd(e,o)}function kd(s,e){if(e){const t=s.fragments;for(let r=s.skippedSegments;r<t.length;r++)t[r].addStart(e);s.fragmentHint&&s.fragmentHint.addStart(e)}}function Ay(s,e=1/0){let t=1e3*s.targetduration;if(s.updated){const r=s.fragments;if(r.length&&t*4>e){const i=r[r.length-1].duration*1e3;i<t&&(t=i)}}else t/=2;return Math.round(t)}function ky(s,e,t){if(!s)return null;let r=s.fragments[e-s.startSN];return r||(r=s.fragmentHint,r&&r.sn===e)?r:e<s.startSN&&t&&t.sn===e?t:null}function Dm(s,e,t){return s?Ry(s.partList,e,t):null}function Ry(s,e,t){if(s)for(let r=s.length;r--;){const n=s[r];if(n.index===t&&n.fragment.sn===e)return n}return null}function jy(s){s.forEach((e,t)=>{var r;(r=e.details)==null||r.fragments.forEach(n=>{n.level=t,n.initSegment&&(n.initSegment.level=t)})})}function qC(s,e){return s!==e&&e?Om(s)!==Om(e):!1}function Om(s){return s.replace(/\?[^?]*$/,"")}function oa(s,e){for(let r=0,n=s.length;r<n;r++){var t;if(((t=s[r])==null?void 0:t.cc)===e)return s[r]}return null}function HC(s,e){return!!(s&&e.startCC<s.endCC&&e.endCC>s.startCC)}function Mm(s,e){const t=s.start+e;s.startPTS=t,s.setStart(t),s.endPTS=t+s.duration}function Iy(s,e){const t=e.fragments;for(let r=0,n=t.length;r<n;r++)Mm(t[r],s);e.fragmentHint&&Mm(e.fragmentHint,s),e.alignedSliding=!0}function KC(s,e){s&&(Cy(e,s),e.alignedSliding||dl(e,s),!e.alignedSliding&&!e.skippedSegments&&Ty(s,e,!1))}function Cy(s,e){if(!HC(e,s))return;const t=Math.min(e.endCC,s.endCC),r=oa(e.fragments,t),n=oa(s.fragments,t);if(!r||!n)return;vt.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const i=r.start-n.start;Iy(i,s)}function dl(s,e){if(!s.hasProgramDateTime||!e.hasProgramDateTime)return;const t=s.fragments,r=e.fragments;if(!t.length||!r.length)return;let n,i;const o=Math.min(e.endCC,s.endCC);e.startCC<o&&s.startCC<o&&(n=oa(r,o),i=oa(t,o)),(!n||!i)&&(n=r[Math.floor(r.length/2)],i=oa(t,n.cc)||t[Math.floor(t.length/2)]);const l=n.programDateTime,d=i.programDateTime;if(!l||!d)return;const c=(d-l)/1e3-(i.start-n.start);Iy(c,s)}function ys(s,e,t){ws(s,e,t),s.addEventListener(e,t)}function ws(s,e,t){s.removeEventListener(e,t)}const WC={toString:function(s){let e="";const t=s.length;for(let r=0;r<t;r++)e+=`[${s.start(r).toFixed(3)}-${s.end(r).toFixed(3)}]`;return e}},te={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class qu extends gy{constructor(e,t,r,n,i){super(n,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=te.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:o,fragCurrent:l,media:d,mediaBuffer:c,state:u}=this,h=d?d.currentTime:0,f=Ue.bufferInfo(c||d,h,o.maxBufferHole),m=!f.len;if(this.log(`Media seeking to ${xe(h)?h.toFixed(3):h}, state: ${u}, ${m?"out of":"in"} buffer`),this.state===te.ENDED)this.resetLoadingState();else if(l){const p=o.maxFragLookUpTolerance,x=l.start-p,y=l.start+l.duration+p;if(m||y<f.start||x>f.end){const v=h>y;(h<x||v)&&(v&&l.loader&&(this.log(`Cancelling fragment load for seek (sn: ${l.sn})`),l.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(d){this.fragmentTracker.removeFragmentsInRange(h,1/0,this.playlistType,!0);const p=this.lastCurrentTime;if(h>p&&(this.lastCurrentTime=h),!this.loadingParts){const x=Math.max(f.end,h),y=this.shouldLoadParts(this.getLevelDetails(),x);y&&(this.log(`LL-Part loading ON after seeking to ${h.toFixed(2)} with buffer @${x.toFixed(2)}`),this.loadingParts=y)}}this.hls.hasEnoughToStart||(this.log(`Setting ${m?"startPosition":"nextLoadPosition"} to ${h} for seek without enough to start`),this.nextLoadPosition=h,m&&(this.startPosition=h)),m&&this.state===te.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=i,this.hls=e,this.fragmentLoader=new wC(e.config),this.keyLoader=r,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Bu(e.config)}registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===te.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=te.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const r=e.end||0,n=this.config.timelineOffset||0;if(r<=n)return!1;const i=e.buffered;this.config.maxBufferHole&&i&&i.length>1&&(e=Ue.bufferedInfo(i,e.start,0));const o=e.nextStart;if(o&&o>n&&o<t.edge||this.media.currentTime<e.start)return!1;const d=t.partList;if(d!=null&&d.length){const u=d[d.length-1];return Ue.isBuffered(this.media,u.start+u.duration/2)}const c=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(c)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const r=this.media=this.mediaBuffer=t.media;ys(r,"seeking",this.onMediaSeeking),ys(r,"ended",this.onMediaEnded);const n=this.config;this.levels&&n.autoStartLoad&&this.state===te.STOPPED&&this.startLoad(n.startPosition)}onMediaDetaching(e,t){const r=!!t.transferMedia,n=this.media;if(n!==null){if(n.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),ws(n,"seeking",this.onMediaSeeking),ws(n,"ended",this.onMediaEnded),this.keyLoader&&!r&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,r){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=te.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,r){this.startFragRequested=!0,this._loadFragForPlayback(e,t,r)}_loadFragForPlayback(e,t,r){const n=i=>{const o=i.frag;if(this.fragContextChanged(o)){this.warn(`${o.type} sn: ${o.sn}${i.part?" part: "+i.part.index:""} of ${this.fragInfo(o,!1,i.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(o);return}o.stats.chunkCount++,this._handleFragmentLoadProgress(i)};this._doFragLoad(e,t,r,n).then(i=>{if(!i)return;const o=this.state,l=i.frag;if(this.fragContextChanged(l)){(o===te.FRAG_LOADING||!this.fragCurrent&&o===te.PARSING)&&(this.fragmentTracker.removeFragment(l),this.state=te.IDLE);return}"payload"in i&&(this.log(`Loaded ${l.type} sn: ${l.sn} of ${this.playlistLabel()} ${l.level}`),this.hls.trigger(E.FRAG_LOADED,i)),this._handleFragmentLoadComplete(i)}).catch(i=>{this.state===te.STOPPED||this.state===te.ERROR||(this.warn(`Frag error: ${(i==null?void 0:i.message)||i}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:r}=this;if(r.getState(e)===ss.APPENDING){const i=e.type,o=this.getFwdBufferInfo(this.mediaBuffer,i),l=Math.max(e.duration,o?o.len:this.config.maxBufferLength),d=this.backtrackFragment;((d?e.sn-d.sn:0)===1||this.reduceMaxBufferLength(l,e.duration))&&r.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===ss.PARTIAL&&r.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,r=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:r};this.hls.trigger(E.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(r=>{const n=r==null?void 0:r.frag;if(!n||this.fragContextChanged(n)||!this.levels)throw new Error("init load aborted");return r}).then(r=>{const{hls:n}=this,{frag:i,payload:o}=r,l=i.decryptdata;if(o&&o.byteLength>0&&l!=null&&l.key&&l.iv&&fi(l.method)){const d=self.performance.now();return this.decrypter.decrypt(new Uint8Array(o),l.key.buffer,l.iv.buffer,Gu(l.method)).catch(c=>{throw n.trigger(E.ERROR,{type:Re.MEDIA_ERROR,details:z.FRAG_DECRYPT_ERROR,fatal:!1,error:c,reason:c.message,frag:i}),c}).then(c=>{const u=self.performance.now();return n.trigger(E.FRAG_DECRYPTED,{frag:i,payload:c,stats:{tstart:d,tdecrypt:u}}),r.payload=c,this.completeInitSegmentLoad(r)})}return this.completeInitSegmentLoad(r)}).catch(r=>{this.state===te.STOPPED||this.state===te.ERROR||(this.warn(r),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const r=e.frag.stats;this.state!==te.STOPPED&&(this.state=te.IDLE),e.frag.data=new Uint8Array(e.payload),r.parsing.start=r.buffering.start=self.performance.now(),r.parsing.end=r.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var r,n;const i=e.tracks;if(i&&!t.encrypted&&((r=i.audio)!=null&&r.encrypted||(n=i.video)!=null&&n.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const o=this.media,l=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${o?"attached mediaKeys: "+o.mediaKeys:"detached"})`);return this.warn(l.message),!o||o.mediaKeys?!1:(this.hls.trigger(E.ERROR,{type:Re.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_KEYS,fatal:!1,error:l,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${r?WC.toString(Ue.getBuffered(r)):"(detached)"})`),zt(e)){var n;if(e.type!==we.SUBTITLE){const o=e.elementaryStreams;if(!Object.keys(o).some(l=>!!o[l])){this.state=te.IDLE;return}}const i=(n=this.levels)==null?void 0:n[e.level];i!=null&&i.fragmentError&&(this.log(`Resetting level fragment error count of ${i.fragmentError} on frag buffered`),i.fragmentError=0)}this.state=te.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:r,part:n,partsLoaded:i}=e,o=!i||i.length===0||i.some(d=>!d),l=new Vu(r.level,r.sn,r.stats.chunkCount+1,0,n?n.index:-1,!o);t.flush(l)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,r=null,n){var i;this.fragCurrent=e;const o=t.details;if(!this.levels||!o)throw new Error(`frag load aborted, missing level${o?"":" detail"}s`);let l=null;if(e.encrypted&&!((i=e.decryptdata)!=null&&i.key)){if(this.log(`Loading key for ${e.sn} of [${o.startSN}-${o.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=te.KEY_LOADING,this.fragCurrent=e,l=this.keyLoader.load(e).then(f=>{if(!this.fragContextChanged(f.frag))return this.hls.trigger(E.KEY_LOADED,f),this.state===te.KEY_LOADING&&(this.state=te.IDLE),f}),this.hls.trigger(E.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(l=this.keyLoader.loadClear(e,o.encryptedFragments,this.startFragRequested),l&&this.log("[eme] blocking frag load until media-keys acquired"));const d=this.fragPrevious;if(zt(e)&&(!d||e.sn!==d.sn)){const f=this.shouldLoadParts(t.details,e.end);f!==this.loadingParts&&(this.log(`LL-Part loading ${f?"ON":"OFF"} loading sn ${d==null?void 0:d.sn}->${e.sn}`),this.loadingParts=f)}if(r=Math.max(e.start,r||0),this.loadingParts&&zt(e)){const f=o.partList;if(f&&n){r>o.fragmentEnd&&o.fragmentHint&&(e=o.fragmentHint);const m=this.getNextPart(f,e,r);if(m>-1){const p=f[m];e=this.fragCurrent=p.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${p.index} (${m}/${f.length-1}) of ${this.fragInfo(e,!1,p)}) cc: ${e.cc} [${o.startSN}-${o.endSN}], target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=p.start+p.duration,this.state=te.FRAG_LOADING;let x;return l?x=l.then(y=>!y||this.fragContextChanged(y.frag)?null:this.doFragPartsLoad(e,p,t,n)).catch(y=>this.handleFragLoadError(y)):x=this.doFragPartsLoad(e,p,t,n).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(E.FRAG_LOADING,{frag:e,part:p,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):x}else if(!e.url||this.loadedEndOfParts(f,r))return Promise.resolve(null)}}if(zt(e)&&this.loadingParts){var c;this.log(`LL-Part loading OFF after next part miss @${r.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(c=o.partList)==null?void 0:c.filter(f=>f.loaded).map(f=>`[${f.start}-${f.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+o.startSN+"-"+o.endSN+"]"}, target: ${parseFloat(r.toFixed(3))}`),xe(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=te.FRAG_LOADING;const u=this.config.progressive&&e.type!==we.SUBTITLE;let h;return u&&l?h=l.then(f=>!f||this.fragContextChanged(f.frag)?null:this.fragmentLoader.load(e,n)).catch(f=>this.handleFragLoadError(f)):h=Promise.all([this.fragmentLoader.load(e,u?n:void 0),l]).then(([f])=>(!u&&n&&n(f),f)).catch(f=>this.handleFragLoadError(f)),this.hls.trigger(E.FRAG_LOADING,{frag:e,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(e,t,r,n){return new Promise((i,o)=>{var l;const d=[],c=(l=r.details)==null?void 0:l.partList,u=h=>{this.fragmentLoader.loadPart(e,h,n).then(f=>{d[h.index]=f;const m=f.part;this.hls.trigger(E.FRAG_LOADED,f);const p=Dm(r.details,e.sn,h.index+1)||Ry(c,e.sn,h.index+1);if(p)u(p);else return i({frag:e,part:m,partsLoaded:d})}).catch(o)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===z.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===Re.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(E.ERROR,t)}else this.hls.trigger(E.ERROR,{type:Re.OTHER_ERROR,details:z.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==te.PARSING){!this.fragCurrent&&this.state!==te.STOPPED&&this.state!==te.ERROR&&(this.state=te.IDLE);return}const{frag:r,part:n,level:i}=t,o=self.performance.now();r.stats.parsing.end=o,n&&(n.stats.parsing.end=o);const l=this.getLevelDetails(),c=l&&r.sn>l.endSN||this.shouldLoadParts(l,r.end);c!==this.loadingParts&&(this.log(`LL-Part loading ${c?"ON":"OFF"} after parsing segment ending @${r.end.toFixed(2)}`),this.loadingParts=c),this.updateLevelTiming(r,n,i,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var r;const i=e.partList[0];if(i.fragment.type===we.SUBTITLE)return!1;const o=i.end+(((r=e.fragmentHint)==null?void 0:r.duration)||0);if(t>=o){var n;if((this.hls.hasEnoughToStart?((n=this.media)==null?void 0:n.currentTime)||this.lastCurrentTime:this.getLoadPosition())>i.start-i.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:r}=this,{level:n,sn:i,part:o}=e;if(!(t!=null&&t[n]))return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const l=t[n],d=l.details,c=o>-1?Dm(d,i,o):null,u=c?c.fragment:ky(d,i,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:c,level:l}):null}bufferFragmentData(e,t,r,n,i){if(this.state!==te.PARSING)return;const{data1:o,data2:l}=e;let d=o;if(l&&(d=zs(o,l)),!d.length)return;const c=this.initPTS[t.cc],u=c?-c.baseTime/c.timescale:void 0,h={type:e.type,frag:t,part:r,chunkMeta:n,offset:u,parent:t.type,data:d};if(this.hls.trigger(E.BUFFER_APPENDING,h),e.dropped&&e.independent&&!r){if(i)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Ue.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const r=t.currentTime,n=Ue.bufferInfo(t,r,0),i=e.duration,o=Math.min(this.config.maxFragLookUpTolerance*2,i*.25),l=Math.max(Math.min(e.start-o,n.end-o),r+o);e.start-l>o&&this.flushMainBuffer(l,e.start)}getFwdBufferInfo(e,t){var r;const n=this.getLoadPosition();if(!xe(n))return null;const o=this.lastCurrentTime>n||(r=this.media)!=null&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,o)}getFwdBufferInfoAtPos(e,t,r,n){const i=Ue.bufferInfo(e,t,n);if(i.len===0&&i.nextStart!==void 0){const o=this.fragmentTracker.getBufferedFrag(t,r);if(o&&(i.nextStart<=o.end||o.gap)){const l=Math.max(Math.min(i.nextStart,o.end)-t,n);return Ue.bufferInfo(e,t,l)}}return i}getMaxBufferLength(e){const{config:t}=this;let r;return e?r=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):r=t.maxBufferLength,Math.min(r,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const r=this.config,n=Math.max(Math.min(e-t,r.maxBufferLength),t),i=Math.max(e-t*3,r.maxMaxBufferLength/2,n);return i>=n?(r.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0):!1}getAppendedFrag(e,t=we.MAIN){const r=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return r&&"fragment"in r?r.fragment:r}getNextFragment(e,t){const r=t.fragments,n=r.length;if(!n)return null;const{config:i}=this,o=r[0].start,l=i.lowLatencyMode&&!!t.partList;let d=null;if(t.live){const h=i.initialLiveManifestSize;if(n<h)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${h})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<o){var c;l&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),d=this.getInitialLiveFragment(t);const f=this.hls.startPosition,m=this.hls.liveSyncPosition,p=d?(f!==-1&&f>=o?f:m)||d.start:e;this.log(`Setting startPosition to ${p} to match start frag at live edge. mainStart: ${f} liveSyncPosition: ${m} frag.start: ${(c=d)==null?void 0:c.start}`),this.startPosition=this.nextLoadPosition=p}}else e<=o&&(d=r[0]);if(!d){const h=this.loadingParts?t.partEnd:t.fragmentEnd;d=this.getFragmentAtPosition(e,h,t)}let u=this.filterReplacedPrimary(d,t);if(!u&&d){const h=d.sn-t.startSN;u=this.filterReplacedPrimary(r[h+1]||null,t)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(e,t){const r=this.fragmentTracker.getState(e);return(r===ss.OK||r===ss.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,r,n,i){let o=null;if(e.gap&&(o=this.getNextFragment(this.nextLoadPosition,t),o&&!o.gap&&r.nextStart)){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,n,0);if(l!==null&&r.len+l.len>=i){const d=o.sn;return this.loopSn!==d&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${d}`),this.loopSn=d),null}}return this.loopSn=void 0,o}get primaryPrefetch(){if(Fm(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Fm(this.config)&&e.type!==we.SUBTITLE){const r=this.hls.interstitialsManager,n=r==null?void 0:r.bufferingItem;if(n){const o=n.event;if(o){if(o.appendInPlace||Math.abs(e.start-n.start)>1||n.start===0)return null}else if(e.end<=n.start&&(t==null?void 0:t.live)===!1||e.start>n.end&&n.nextEvent&&(n.nextEvent.appendInPlace||e.start-n.end>1))return null}const i=r==null?void 0:r.playerQueue;if(i)for(let o=i.length;o--;){const l=i[o].interstitial;if(l.appendInPlace&&e.start>=l.startTime&&e.end<=l.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,r){let n=-1,i=!1,o=!0;for(let l=0,d=e.length;l<d;l++){const c=e[l];if(o=o&&!c.independent,n>-1&&r<c.start)break;const u=c.loaded;u?n=-1:(i||(c.independent||o)&&c.fragment===t)&&(c.fragment!==t&&this.warn(`Need buffer at ${r} but next unloaded part starts at ${c.start}`),n=l),i=u}return n}loadedEndOfParts(e,t){let r;for(let n=e.length;n--;){if(r=e[n],!r.loaded)return!1;if(t>r.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,r=this.fragPrevious;let n=null;if(r){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`),n=dC(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const i=r.sn+1;if(i>=e.startSN&&i<=e.endSN){const o=t[i-e.startSN];r.cc===o.cc&&(n=o,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=fy(e,r.cc,r.end),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const i=this.hls.liveSyncPosition;i!==null&&(n=this.getFragmentAtPosition(i,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,r){const{config:n}=this;let{fragPrevious:i}=this,{fragments:o,endSN:l}=r;const{fragmentHint:d}=r,{maxFragLookUpTolerance:c}=n,u=r.partList,h=!!(this.loadingParts&&u!=null&&u.length&&d);h&&!this.bitrateTest&&u[u.length-1].fragment.sn===d.sn&&(o=o.concat(d),l=d.sn);let f;if(e<t){var m;const x=e<this.lastCurrentTime||e>t-c||(m=this.media)!=null&&m.paused||!this.startFragRequested?0:c;f=kn(i,o,e,x)}else f=o[o.length-1];if(f){const p=f.sn-r.startSN,x=this.fragmentTracker.getState(f);if((x===ss.OK||x===ss.PARTIAL&&f.gap)&&(i=f),i&&f.sn===i.sn&&(!h||u[0].fragment.sn>f.sn||!r.live)&&f.level===i.level){const v=o[p+1];f.sn<l&&this.fragmentTracker.getState(v)!==ss.OK?f=v:f=null}}return f}alignPlaylists(e,t,r){const n=e.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;const i=e.fragmentStart,o=!t,l=e.alignedSliding&&xe(i);if(o||!l&&!i){KC(r,e);const d=e.fragmentStart;return this.log(`Live playlist sliding: ${d.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${n}`),d}return i}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let r=this.startPosition;r<t&&(r=-1);const n=this.timelineOffset;if(r===-1){const i=this.startTimeOffset!==null,o=i?this.startTimeOffset:e.startTimeOffset;o!==null&&xe(o)?(r=t+o,o<0&&(r+=e.edge),r=Math.min(Math.max(t,r),t+e.totalduration),this.log(`Setting startPosition to ${r} for start time offset ${o} found in ${i?"multivariant":"media"} playlist`),this.startPosition=r):e.live?(r=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${r}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=r=0),this.lastCurrentTime=r+n}this.nextLoadPosition=r+n}getLoadPosition(){var e;const{media:t}=this;let r=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?r=t.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&zt(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==te.FRAG_LOADING_WAITING_RETRY)&&(this.state=te.IDLE)}onFragmentOrKeyLoadError(e,t){var r;if(t.chunkMeta&&!t.frag){const v=this.getCurrentContext(t.chunkMeta);v&&(t.frag=v.frag)}const n=t.frag;if(!n||n.type!==e||!this.levels)return;if(this.fragContextChanged(n)){var i;this.warn(`Frag load error must match current frag to retry ${n.url} > ${(i=this.fragCurrent)==null?void 0:i.url}`);return}const o=t.details===z.FRAG_GAP;o&&this.fragmentTracker.fragBuffered(n,!0);const l=t.errorAction;if(!l){this.state=te.ERROR;return}const{action:d,flags:c,retryCount:u=0,retryConfig:h}=l,f=!!h,m=f&&d===os.RetryRequest,p=f&&!l.resolved&&c===Is.MoveAllAlternatesMatchingHost,x=(r=this.hls.latestLevelDetails)==null?void 0:r.live;if(!m&&p&&zt(n)&&!n.endList&&x&&!py(t))this.resetFragmentErrors(e),this.treatAsGap(n),l.resolved=!0;else if((m||p)&&u<h.maxNumRetry){var y;const v=Ed((y=t.response)==null?void 0:y.code),_=Uu(h,u);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+_,this.state=te.FRAG_LOADING_WAITING_RETRY,l.resolved=!0,v){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${t.details}, retrying loading ${u+1}/${h.maxNumRetry} in ${_}ms`)}else if(h)if(this.resetFragmentErrors(e),u<h.maxNumRetry)!o&&d!==os.RemoveAlternatePermanently&&(l.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${u})`);return}else d===os.SendAlternateToPenaltyBox?this.state=te.WAITING_LEVEL:this.state=te.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,r=t===1/0;(!t||e>=t||r&&!Ed(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=te.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===te.PARSING||this.state===te.PARSED){const t=e.frag,r=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,r),i=n&&n.len>.5;i&&this.reduceMaxBufferLength(n.len,(t==null?void 0:t.duration)||10);const o=!i;return o&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${r} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),o}return!1}resetFragmentErrors(e){e===we.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==te.STOPPED&&(this.state=te.IDLE)}afterBufferFlushed(e,t,r){if(!e)return;const n=Ue.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,r),this.state===te.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==te.STOPPED&&(this.state=te.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,r,n){const i=r.details;if(!i){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((d,c)=>{const u=e.elementaryStreams[c];if(u){const h=u.endPTS-u.startPTS;if(h<=0)return this.warn(`Could not parse fragment ${e.sn} ${c} duration reliably (${h})`),d||!1;const f=n?0:Sy(i,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger(E.LEVEL_PTS_UPDATED,{details:i,level:r,drift:f,type:c,frag:e,start:u.startPTS,end:u.endPTS}),!0}return d},!1)){var l;const d=((l=this.transmuxer)==null?void 0:l.error)===null;if((r.fragmentError===0||d&&(r.fragmentError<2||e.endList))&&this.treatAsGap(e,r),d){const c=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(c.message),this.hls.trigger(E.ERROR,{type:Re.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!1,error:c,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=te.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(E.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===we.MAIN?"level":"track"}fragInfo(e,t=!0,r){var n,i;return`${this.playlistLabel()} ${e.level} (${r?"part":"frag"}:[${((n=t&&!r?e.startPTS:(r||e).start)!=null?n:NaN).toFixed(3)}-${((i=t&&!r?e.endPTS:(r||e).end)!=null?i:NaN).toFixed(3)}]${r&&e.type==="main"?"INDEPENDENT="+(r.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function Fm(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class Ny{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let r;if(e.length)e.length===1?r=e[0]:r=YC(e,t);else return new Uint8Array(0);return this.reset(),r}reset(){this.chunks.length=0,this.dataLength=0}}function YC(s,e){const t=new Uint8Array(e);let r=0;for(let n=0;n<s.length;n++){const i=s[n];t.set(i,r),r+=i.length}return t}var vc={exports:{}},$m;function XC(){return $m||($m=1,function(s){var e=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function n(d,c,u){this.fn=d,this.context=c,this.once=u||!1}function i(d,c,u,h,f){if(typeof u!="function")throw new TypeError("The listener must be a function");var m=new n(u,h||d,f),p=t?t+c:c;return d._events[p]?d._events[p].fn?d._events[p]=[d._events[p],m]:d._events[p].push(m):(d._events[p]=m,d._eventsCount++),d}function o(d,c){--d._eventsCount===0?d._events=new r:delete d._events[c]}function l(){this._events=new r,this._eventsCount=0}l.prototype.eventNames=function(){var c=[],u,h;if(this._eventsCount===0)return c;for(h in u=this._events)e.call(u,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},l.prototype.listeners=function(c){var u=t?t+c:c,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var f=0,m=h.length,p=new Array(m);f<m;f++)p[f]=h[f].fn;return p},l.prototype.listenerCount=function(c){var u=t?t+c:c,h=this._events[u];return h?h.fn?1:h.length:0},l.prototype.emit=function(c,u,h,f,m,p){var x=t?t+c:c;if(!this._events[x])return!1;var y=this._events[x],v=arguments.length,_,b;if(y.fn){switch(y.once&&this.removeListener(c,y.fn,void 0,!0),v){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,u),!0;case 3:return y.fn.call(y.context,u,h),!0;case 4:return y.fn.call(y.context,u,h,f),!0;case 5:return y.fn.call(y.context,u,h,f,m),!0;case 6:return y.fn.call(y.context,u,h,f,m,p),!0}for(b=1,_=new Array(v-1);b<v;b++)_[b-1]=arguments[b];y.fn.apply(y.context,_)}else{var w=y.length,T;for(b=0;b<w;b++)switch(y[b].once&&this.removeListener(c,y[b].fn,void 0,!0),v){case 1:y[b].fn.call(y[b].context);break;case 2:y[b].fn.call(y[b].context,u);break;case 3:y[b].fn.call(y[b].context,u,h);break;case 4:y[b].fn.call(y[b].context,u,h,f);break;default:if(!_)for(T=1,_=new Array(v-1);T<v;T++)_[T-1]=arguments[T];y[b].fn.apply(y[b].context,_)}}return!0},l.prototype.on=function(c,u,h){return i(this,c,u,h,!1)},l.prototype.once=function(c,u,h){return i(this,c,u,h,!0)},l.prototype.removeListener=function(c,u,h,f){var m=t?t+c:c;if(!this._events[m])return this;if(!u)return o(this,m),this;var p=this._events[m];if(p.fn)p.fn===u&&(!f||p.once)&&(!h||p.context===h)&&o(this,m);else{for(var x=0,y=[],v=p.length;x<v;x++)(p[x].fn!==u||f&&!p[x].once||h&&p[x].context!==h)&&y.push(p[x]);y.length?this._events[m]=y.length===1?y[0]:y:o(this,m)}return this},l.prototype.removeAllListeners=function(c){var u;return c?(u=t?t+c:c,this._events[u]&&o(this,u)):(this._events=new r,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=t,l.EventEmitter=l,s.exports=l}(vc)),vc.exports}var QC=XC(),Hu=wI(QC);const ka="1.6.15",Ti={};function JC(){return typeof __HLS_WORKER_BUNDLE__=="function"}function ZC(){const s=Ti[ka];if(s)return s.clientCount++,s;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),n={worker:new self.Worker(t),objectURL:t,clientCount:1};return Ti[ka]=n,n}function eN(s){const e=Ti[s];if(e)return e.clientCount++,e;const t=new self.URL(s,self.location.href).href,n={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Ti[s]=n,n}function tN(s){const e=Ti[s||ka];if(e&&e.clientCount--===1){const{worker:r,objectURL:n}=e;delete Ti[s||ka],n&&self.URL.revokeObjectURL(n),r.terminate()}}function Ly(s,e){return e+10<=s.length&&s[e]===51&&s[e+1]===68&&s[e+2]===73&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128}function Ku(s,e){return e+10<=s.length&&s[e]===73&&s[e+1]===68&&s[e+2]===51&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128}function Nl(s,e){let t=0;return t=(s[e]&127)<<21,t|=(s[e+1]&127)<<14,t|=(s[e+2]&127)<<7,t|=s[e+3]&127,t}function Ra(s,e){const t=e;let r=0;for(;Ku(s,e);){r+=10;const n=Nl(s,e+6);r+=n,Ly(s,e+10)&&(r+=10),e+=r}if(r>0)return s.subarray(t,t+r)}function sN(s,e,t,r){const n=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],i=e[t+2],o=i>>2&15;if(o>12){const m=new Error(`invalid ADTS sampling index:${o}`);s.emit(E.ERROR,E.ERROR,{type:Re.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!0,error:m,reason:m.message});return}const l=(i>>6&3)+1,d=e[t+3]>>6&3|(i&1)<<2,c="mp4a.40."+l,u=n[o];let h=o;(l===5||l===29)&&(h-=3);const f=[l<<3|(h&14)>>1,(h&1)<<7|d<<3];return vt.log(`manifest codec:${r}, parsed codec:${c}, channels:${d}, rate:${u} (ADTS object type:${l} sampling index:${o})`),{config:f,samplerate:u,channelCount:d,codec:c,parsedCodec:c,manifestCodec:r}}function Py(s,e){return s[e]===255&&(s[e+1]&246)===240}function Dy(s,e){return s[e+1]&1?7:9}function Wu(s,e){return(s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function rN(s,e){return e+5<s.length}function ul(s,e){return e+1<s.length&&Py(s,e)}function nN(s,e){return rN(s,e)&&Py(s,e)&&Wu(s,e)<=s.length-e}function iN(s,e){if(ul(s,e)){const t=Dy(s,e);if(e+t>=s.length)return!1;const r=Wu(s,e);if(r<=t)return!1;const n=e+r;return n===s.length||ul(s,n)}return!1}function Oy(s,e,t,r,n){if(!s.samplerate){const i=sN(e,t,r,n);if(!i)return;Tt(s,i)}}function My(s){return 1024*9e4/s}function aN(s,e){const t=Dy(s,e);if(e+t<=s.length){const r=Wu(s,e)-t;if(r>0)return{headerLength:t,frameLength:r}}}function Fy(s,e,t,r,n){const i=My(s.samplerate),o=r+n*i,l=aN(e,t);let d;if(l){const{frameLength:h,headerLength:f}=l,m=f+h,p=Math.max(0,t+m-e.length);p?(d=new Uint8Array(m-f),d.set(e.subarray(t+f,e.length),0)):d=e.subarray(t+f,t+m);const x={unit:d,pts:o};return p||s.samples.push(x),{sample:x,length:m,missing:p}}const c=e.length-t;return d=new Uint8Array(c),d.set(e.subarray(t,e.length),0),{sample:{unit:d,pts:o},length:c,missing:-1}}function oN(s,e){return Ku(s,e)&&Nl(s,e+6)+10<=s.length-e}function lN(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function bc(s,e=0,t=1/0){return cN(s,e,t,Uint8Array)}function cN(s,e,t,r){const n=dN(s);let i=1;"BYTES_PER_ELEMENT"in r&&(i=r.BYTES_PER_ELEMENT);const o=uN(s)?s.byteOffset:0,l=(o+s.byteLength)/i,d=(o+e)/i,c=Math.floor(Math.max(0,Math.min(d,l))),u=Math.floor(Math.min(c+Math.max(t,0),l));return new r(n,c,u-c)}function dN(s){return s instanceof ArrayBuffer?s:s.buffer}function uN(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function hN(s){const e={key:s.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(s.size<2)return;if(s.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const r=s.data.subarray(1).indexOf(0);if(r===-1)return;const n=Os(bc(s.data,1,r)),i=s.data[2+r],o=s.data.subarray(3+r).indexOf(0);if(o===-1)return;const l=Os(bc(s.data,3+r,o));let d;return n==="-->"?d=Os(bc(s.data,4+r+o)):d=lN(s.data.subarray(4+r+o)),e.mimeType=n,e.pictureType=i,e.description=l,e.data=d,e}function fN(s){if(s.size<2)return;const e=Os(s.data,!0),t=new Uint8Array(s.data.subarray(e.length+1));return{key:s.type,info:e,data:t.buffer}}function mN(s){if(s.size<2)return;if(s.type==="TXXX"){let t=1;const r=Os(s.data.subarray(t),!0);t+=r.length+1;const n=Os(s.data.subarray(t));return{key:s.type,info:r,data:n}}const e=Os(s.data.subarray(1));return{key:s.type,info:"",data:e}}function pN(s){if(s.type==="WXXX"){if(s.size<2)return;let t=1;const r=Os(s.data.subarray(t),!0);t+=r.length+1;const n=Os(s.data.subarray(t));return{key:s.type,info:r,data:n}}const e=Os(s.data);return{key:s.type,info:"",data:e}}function gN(s){return s.type==="PRIV"?fN(s):s.type[0]==="W"?pN(s):s.type==="APIC"?hN(s):mN(s)}function xN(s){const e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=Nl(s,4),r=10;return{type:e,size:t,data:s.subarray(r,r+t)}}const ro=10,yN=10;function $y(s){let e=0;const t=[];for(;Ku(s,e);){const r=Nl(s,e+6);s[e+5]>>6&1&&(e+=ro),e+=ro;const n=e+r;for(;e+yN<n;){const i=xN(s.subarray(e)),o=gN(i);o&&t.push(o),e+=i.size+ro}Ly(s,e)&&(e+=ro)}return t}function Uy(s){return s&&s.key==="PRIV"&&s.info==="com.apple.streaming.transportStreamTimestamp"}function vN(s){if(s.data.byteLength===8){const e=new Uint8Array(s.data),t=e[3]&1;let r=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return r/=45,t&&(r+=4772185884e-2),Math.round(r)}}function Yu(s){const e=$y(s);for(let t=0;t<e.length;t++){const r=e[t];if(Uy(r))return vN(r)}}let Ns=function(s){return s.audioId3="org.id3",s.dateRange="com.apple.quicktime.HLS",s.emsg="https://aomedia.org/emsg/ID3",s.misbklv="urn:misb:KLV:bin:1910.1",s}({});function ur(s="",e=9e4){return{type:s,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Xu{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,r,n){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,r){}demux(e,t){this.cachedData&&(e=zs(this.cachedData,e),this.cachedData=null);let r=Ra(e,0),n=r?r.length:0,i;const o=this._audioTrack,l=this._id3Track,d=r?Yu(r):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&xe(d))&&(this.basePTS=bN(d,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),r&&r.length>0&&l.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Ns.audioId3,duration:Number.POSITIVE_INFINITY});n<c;){if(this.canParse(e,n)){const u=this.appendFrame(o,e,n);u?(this.frameIndex++,this.lastPTS=u.sample.pts,n+=u.length,i=n):n=c}else oN(e,n)?(r=Ra(e,n),l.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Ns.audioId3,duration:Number.POSITIVE_INFINITY}),n+=r.length,i=n):n++;if(n===c&&i!==c){const u=e.slice(i);this.cachedData?this.cachedData=zs(this.cachedData,u):this.cachedData=u}}return{audioTrack:o,videoTrack:ur(),id3Track:l,textTrack:ur()}}demuxSampleAes(e,t,r){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:ur(),id3Track:this._id3Track,textTrack:ur()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const bN=(s,e,t)=>{if(xe(s))return s*90;const r=t?t.baseTime*9e4/t.timescale:0;return e*9e4+r};let no=null;const _N=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],wN=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],EN=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],SN=[0,1,1,4];function By(s,e,t,r,n){if(t+24>e.length)return;const i=Vy(e,t);if(i&&t+i.frameLength<=e.length){const o=i.samplesPerFrame*9e4/i.sampleRate,l=r+n*o,d={unit:e.subarray(t,t+i.frameLength),pts:l,dts:l};return s.config=[],s.channelCount=i.channelCount,s.samplerate=i.sampleRate,s.samples.push(d),{sample:d,length:i.frameLength,missing:0}}}function Vy(s,e){const t=s[e+1]>>3&3,r=s[e+1]>>1&3,n=s[e+2]>>4&15,i=s[e+2]>>2&3;if(t!==1&&n!==0&&n!==15&&i!==3){const o=s[e+2]>>1&1,l=s[e+3]>>6,d=t===3?3-r:r===3?3:4,c=_N[d*14+n-1]*1e3,h=wN[(t===3?0:t===2?1:2)*3+i],f=l===3?1:2,m=EN[t][r],p=SN[r],x=m*8*p,y=Math.floor(m*c/h+o)*p;if(no===null){const b=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);no=b?parseInt(b[1]):0}return!!no&&no<=87&&r===2&&c>=224e3&&l===0&&(s[e+3]=s[e+3]|128),{sampleRate:h,channelCount:f,frameLength:y,samplesPerFrame:x}}}function Qu(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function Gy(s,e){return e+1<s.length&&Qu(s,e)}function TN(s,e){return Qu(s,e)&&4<=s.length-e}function zy(s,e){if(e+1<s.length&&Qu(s,e)){const r=Vy(s,e);let n=4;r!=null&&r.frameLength&&(n=r.frameLength);const i=e+n;return i===s.length||Gy(s,i)}return!1}class AN extends Xu{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const r=Ra(e,0);let n=(r==null?void 0:r.length)||0;
vendor: 4,099 bytes, line 676
676if(zy(e,n))return!1;for(let i=e.length;n<i;n++)if(iN(e,n))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return nN(e,t)}appendFrame(e,t,r){Oy(e,this.observer,t,r,e.manifestCodec);const n=Fy(e,t,r,this.basePTS,this.frameIndex);if(n&&n.missing===0)return n}}const qy=(s,e)=>{let t=0,r=5;e+=r;const n=new Uint32Array(1),i=new Uint32Array(1),o=new Uint8Array(1);for(;r>0;){o[0]=s[e];const l=Math.min(r,8),d=8-l;i[0]=4278190080>>>24+d<<d,n[0]=(o[0]&i[0])>>d,t=t?t<<l|n[0]:n[0],e+=1,r-=l}return t};class kN extends Xu{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,n),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,r){const n=Hy(e,t,r,this.basePTS,this.frameIndex);if(n!==-1)return{sample:e.samples[e.samples.length-1],length:n,missing:0}}static probe(e){if(!e)return!1;const t=Ra(e,0);if(!t)return!1;const r=t.length;return e[r]===11&&e[r+1]===119&&Yu(t)!==void 0&&qy(e,r)<16}}function Hy(s,e,t,r,n){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const i=e[t+4]>>6;if(i>=3)return-1;const l=[48e3,44100,32e3][i],d=e[t+4]&63,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][d*3+i]*2;if(t+u>e.length)return-1;const h=e[t+6]>>5;let f=0;h===2?f+=2:(h&1&&h!==1&&(f+=2),h&4&&(f+=2));const m=(e[t+6]<<8|e[t+7])>>12-f&1,x=[2,1,2,3,3,4,4,5][h]+m,y=e[t+5]>>3,v=e[t+5]&7,_=new Uint8Array([i<<6|y<<1|v>>2,(v&3)<<6|h<<3|m<<2|d>>4,d<<4&224]),b=1536/l*9e4,w=r+n*b,T=e.subarray(t,t+u);return s.config=_,s.channelCount=x,s.samplerate=l,s.samples.push({unit:T,pts:w}),u}class RN extends Xu{resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Ra(e,0);let r=(t==null?void 0:t.length)||0;if(t&&e[r]===11&&e[r+1]===119&&Yu(t)!==void 0&&qy(e,r)<=16)return!1;for(let n=e.length;r<n;r++)if(zy(e,r))return vt.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return TN(e,t)}appendFrame(e,t,r){if(this.basePTS!==null)return By(e,t,r,this.basePTS,this.frameIndex)}}const jN=/\/emsg[-/]ID3/i;class IN{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,r,n){const i=this.videoTrack=ur("video",1),o=this.audioTrack=ur("audio",1),l=this.txtTrack=ur("text",1);if(this.id3Track=ur("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const d=sy(e);if(d.video){const{id:c,timescale:u,codec:h,supplemental:f}=d.video;i.id=c,i.timescale=l.timescale=u,i.codec=h,i.supplemental=f}if(d.audio){const{id:c,timescale:u,codec:h}=d.audio;o.id=c,o.timescale=u,o.codec=h}l.id=Zx.text,i.sampleDuration=0,i.duration=o.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return kI(e)}demux(e,t){this.timeOffset=t;let r=e;const n=this.videoTrack,i=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=zs(this.remainderData,e));const l=PI(r);this.remainderData=l.remainder,n.samples=l.valid||new Uint8Array}else n.samples=r;const o=this.extractID3Track(n,t);return i.samples=rm(t,n),{videoTrack:n,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(t,this.timeOffset);
vendor: 4,337 bytes, line 676
676return r.samples=rm(e,t),{videoTrack:t,audioTrack:ur(),id3Track:n,textTrack:ur()}}extractID3Track(e,t){const r=this.id3Track;if(e.samples.length){const n=Ze(e.samples,["emsg"]);n&&n.forEach(i=>{const o=OI(i);if(jN.test(o.schemeIdUri)){const l=Um(o,t);let d=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;d<=.001&&(d=Number.POSITIVE_INFINITY);const c=o.payload;r.samples.push({data:c,len:c.byteLength,dts:l,pts:l,type:Ns.emsg,duration:d})}else if(this.config.enableEmsgKLVMetadata&&o.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const l=Um(o,t);r.samples.push({data:o.payload,len:o.payload.byteLength,dts:l,pts:l,type:Ns.misbklv,duration:Number.POSITIVE_INFINITY})}})}return r}demuxSampleAes(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function Um(s,e){return xe(s.presentationTime)?s.presentationTime/s.timeScale:e+s.presentationTimeDelta/s.timeScale}class CN{constructor(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new Bu(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,nn.cbc)}decryptAacSample(e,t,r){const n=e[t].unit;if(n.length<=16)return;const i=n.subarray(16,n.length-n.length%16),o=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(o).then(l=>{const d=new Uint8Array(l);n.set(d,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,r)}).catch(r)}decryptAacSamples(e,t,r){for(;;t++){if(t>=e.length){r();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,r=new Int8Array(t);let n=0;for(let i=32;i<e.length-16;i+=160,n+=16)r.set(e.subarray(i,i+16),n);return r}getAvcDecryptedUnit(e,t){const r=new Uint8Array(t);let n=0;for(let i=32;i<e.length-16;i+=160,n+=16)e.set(r.subarray(n,n+16),i);return e}decryptAvcSample(e,t,r,n,i){const o=iy(i.data),l=this.getAvcEncryptedData(o);this.decryptBuffer(l.buffer).then(d=>{i.data=this.getAvcDecryptedUnit(o,d),this.decrypter.isSync()||this.decryptAvcSamples(e,t,r+1,n)}).catch(n)}decryptAvcSamples(e,t,r,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length){n();return}const i=e[t].units;for(;!(r>=i.length);r++){const o=i[r];if(!(o.data.length<=48||o.type!==1&&o.type!==5)&&(this.decryptAvcSample(e,t,r,n,o),!this.decrypter.isSync()))return}}}}class Ky{constructor(){this.VideoSample=null}createVideoSample(e,t,r){return{key:e,frame:!1,pts:t,dts:r,units:[],length:0}}getLastNalUnit(e){var t;let r=this.VideoSample,n;if((!r||r.units.length===0)&&(r=e[e.length-1]),(t=r)!=null&&t.units){const i=r.units;n=i[i.length-1]}return n}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const r=t.samples,n=r.length;if(n){const i=r[n-1];e.pts=i.pts,e.dts=i.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,r){const n=t.byteLength;let i=e.naluState||0;const o=i,l=[];let d=0,c,u,h,f=-1,m=0;for(i===-1&&(f=0,m=this.getNALuType(t,0),i=0,d=1);d<n;){if(c=t[d++],!i){i=c?0:1;continue}if(i===1){i=c?0:2;continue}if(!c)i=3;else if(c===1){if(u=d-i-1,f>=0){const p={data:t.subarray(f,u),type:m};l.push(p)}else{const p=this.getLastNalUnit(e.samples);p&&(o&&d<=4-o&&p.state&&(p.data=p.data.subarray(0,p.data.byteLength-o)),u>0&&(p.data=zs(p.data,t.subarray(0,u)),p.state=0))}d<n?(h=this.getNALuType(t,d),f=d,m=h,i=0):i=-1}else i=0}if(f>=0&&i>=0){const p={data:t.subarray(f,n),type:m,state:i};l.push(p)}if(l.length===0){const p=this.getLastNalUnit(e.samples);p&&(p.data=zs(p.data,t))}return e.naluState=i,l}}class la{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,r=e.byteLength-t,n=new Uint8Array(4),i=Math.min(4,t);if(i===0)throw new Error("no bytes available");n.set(e.subarray(r,r+i)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=i*8,this.bytesAvailable-=i}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>
vendor: 9,141 bytes, line 676
676e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const r=this.word>>>32-t;if(e>32&&vt.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?r<<t|this.readBits(t):r}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class NN extends Ky{parsePES(e,t,r,n){const i=this.parseNALu(e,r.data,n);let o=this.VideoSample,l,d=!1;r.data=null,o&&i.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),i.forEach(c=>{var u,h;switch(c.type){case 1:{let x=!1;l=!0;const y=c.data;if(d&&y.length>4){const v=this.readSliceType(y);(v===2||v===4||v===7||v===9)&&(x=!0)}if(x){var f;(f=o)!=null&&f.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),o.frame=!0,o.key=x;break}case 5:l=!0,(u=o)!=null&&u.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),o.key=!0,o.frame=!0;break;case 6:{l=!0,Mu(c.data,1,r.pts,t.samples);break}case 7:{var m,p;l=!0,d=!0;const x=c.data,y=this.readSPS(x);if(!e.sps||e.width!==y.width||e.height!==y.height||((m=e.pixelRatio)==null?void 0:m[0])!==y.pixelRatio[0]||((p=e.pixelRatio)==null?void 0:p[1])!==y.pixelRatio[1]){e.width=y.width,e.height=y.height,e.pixelRatio=y.pixelRatio,e.sps=[x];const v=x.subarray(1,4);let _="avc1.";for(let b=0;b<3;b++){let w=v[b].toString(16);w.length<2&&(w="0"+w),_+=w}e.codec=_}break}case 8:l=!0,e.pps=[c.data];break;case 9:l=!0,e.audFound=!0,(h=o)!=null&&h.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:l=!0;break;default:l=!1;break}o&&l&&o.units.push(c)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new la(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let r=8,n=8,i;for(let o=0;o<e;o++)n!==0&&(i=t.readEG(),n=(r+i+256)%256),r=n===0?r:n}readSPS(e){const t=new la(e);let r=0,n=0,i=0,o=0,l,d,c;const u=t.readUByte.bind(t),h=t.readBits.bind(t),f=t.readUEG.bind(t),m=t.readBoolean.bind(t),p=t.skipBits.bind(t),x=t.skipEG.bind(t),y=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);u();const _=u();if(h(5),p(3),u(),y(),_===100||_===110||_===122||_===244||_===44||_===83||_===86||_===118||_===128){const I=f();if(I===3&&p(1),y(),y(),p(1),m())for(d=I!==3?8:12,c=0;c<d;c++)m()&&(c<6?v(16,t):v(64,t))}y();const b=f();if(b===0)f();else if(b===1)for(p(1),x(),x(),l=f(),c=0;c<l;c++)x();y(),p(1);const w=f(),T=f(),A=h(1);A===0&&p(1),p(1),m()&&(r=f(),n=f(),i=f(),o=f());let S=[1,1];if(m()&&m())switch(u()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:{S=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((w+1)*16-r*2-n*2),height:(2-A)*(T+1)*16-(A?2:4)*(i+o),pixelRatio:S}}}class LN extends Ky{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,r,n){const i=this.parseNALu(e,r.data,n);let o=this.VideoSample,l,d=!1;r.data=null,o&&i.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),i.forEach(c=>{var u,h;switch(c.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),o.frame=!0,l=!0;break;case 16:case 17:case 18:case 21:if(l=!0,d){var f;(f=o)!=null&&f.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),o.key=!0,o.frame=!0;break;case 19:case 20:l=!0,(u=o)!=null&&u.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),o.key=!0,o.frame=!0;break;case 39:l=!0,Mu(c.data,2,r.pts,t.samples);break;case 32:l=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=Tt(e.params,this.readVPS(c.data)),this.initVPS=c.data),e.vps=[c.data];break;case 33:if(l=!0,d=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],c.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const m=this.readSPS(c.data);e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.codec=m.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const p in m.params)e.params[p]=m.params[p]}this.pushParameterSet(e.sps,c.data,e.vps),o||(o=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),o.key=!0;break;case 34:if(l=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const m=this.readPPS(c.data);for(const p in m)e.params[p]=m[p]}this.pushParameterSet(e.pps,c.data,e.vps)}break;case 35:l=!0,e.audFound=!0,(h=o)!=null&&h.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;default:l=!1;break}o&&l&&o.units.push(c)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}pushParameterSet(e,t,r){(r&&r[0]===this.initVPS||!r&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let r=0;for(let n=0;n<e.byteLength;n++)n>=2&&e[n]===3&&e[n-1]===0&&e[n-2]===0||(t[r]=e[n],r++);return new Uint8Array(t.buffer,0,r)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new la(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const r=t.readBits(3),n=t.readBoolean();return{numTemporalLayers:r+1,temporalIdNested:n}}readSPS(e){const t=new la(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const r=t.readBits(3);t.readBoolean();const n=t.readBits(2),i=t.readBoolean(),o=t.readBits(5),l=t.readUByte(),d=t.readUByte(),c=t.readUByte(),u=t.readUByte(),h=t.readUByte(),f=t.readUByte(),m=t.readUByte(),p=t.readUByte(),x=t.readUByte(),y=t.readUByte(),v=t.readUByte(),_=[],b=[];for(let se=0;se<r;se++)_.push(t.readBoolean()),b.push(t.readBoolean());if(r>0)for(let se=r;se<8;se++)t.readBits(2);for(let se=0;se<r;se++)_[se]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),b[se]&&t.readUByte();t.readUEG();const w=t.readUEG();w==3&&t.skipBits(1);const T=t.readUEG(),A=t.readUEG(),S=t.readBoolean();let I=0,j=0,R=0,k=0;S&&(I+=t.readUEG(),j+=t.readUEG(),R+=t.readUEG(),k+=t.readUEG());const D=t.readUEG(),Y=t.readUEG(),q=t.readUEG(),X=t.readBoolean();for(let se=X?0:r;se<=r;se++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let Be=0;Be<4;Be++)for(let Ke=0;Ke<(Be===3?2:6);Ke++)if(!t.readBoolean())t.readUEG();else{const fe=Math.min(64,1<<4+(Be<<1));Be>1&&t.readEG();for(let et=0;et<fe;et++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const N=t.readUEG();let O=0;for(let se=0;se<N;se++){let Be=!1;if(se!==0&&(Be=t.readBoolean()),Be){se===N&&t.readUEG(),t.readBoolean(),t.readUEG();let Ke=0;for(let Ee=0;Ee<=O;Ee++){const fe=t.readBoolean();let et=!1;fe||(et=t.readBoolean()),(fe||et)&&Ke++}O=Ke}else{const Ke=t.readUEG(),Ee=t.readUEG();O=Ke+Ee;for(let fe=0;fe<Ke;fe++)t.readUEG(),t.readBoolean();for(let fe=0;fe<Ee;fe++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const se=t.readUEG();for(let Be=0;Be<se;Be++){for(let Ke=0;Ke<q+4;Ke++)t.readBits(1);t.readBits(1)}}let B=0,U=1,K=1,ee=!0,ce=1,Q=0;t.readBoolean(),t.readBoolean();let re=!1;if(t.readBoolean()){if(t.readBoolean()){const rt=t.readUByte(),We=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],dt=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];rt>0&&rt<16?(U=We[rt-1],K=dt[rt-1]):rt===255&&(U=t.readBits(16),K=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),re=t.readBoolean(),re&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ce=t.readBits(32),Q=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const dt=t.readBoolean(),pe
vendor: 10,058 bytes, line 676
676=t.readBoolean();let ge=!1;(dt||pe)&&(ge=t.readBoolean(),ge&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),ge&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let be=0;be<=r;be++){ee=t.readBoolean();const ie=ee||t.readBoolean();let Qe=!1;ie?t.readEG():Qe=t.readBoolean();const Ve=Qe?1:t.readUEG()+1;if(dt)for(let It=0;It<Ve;It++)t.readUEG(),t.readUEG(),ge&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(pe)for(let It=0;It<Ve;It++)t.readUEG(),t.readUEG(),ge&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),B=t.readUEG())}let Ce=T,Pe=A;if(S){let se=1,Be=1;w===1?se=Be=2:w==2&&(se=2),Ce=T-se*j-se*I,Pe=A-Be*k-Be*R}const Me=n?["A","B","C"][n]:"",le=l<<24|d<<16|c<<8|u;let oe=0;for(let se=0;se<32;se++)oe=(oe|(le>>se&1)<<31-se)>>>0;let He=oe.toString(16);return o===1&&He==="2"&&(He="6"),{codecString:`hvc1.${Me}${o}.${He}.${i?"H":"L"}${v}.B0`,params:{general_tier_flag:i,general_profile_idc:o,general_profile_space:n,general_profile_compatibility_flags:[l,d,c,u],general_constraint_indicator_flags:[h,f,m,p,x,y],general_level_idc:v,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:Y,min_spatial_segmentation_idc:B,chroma_format_idc:w,frame_rate:{fixed:ee,fps:Q/ce}},width:Ce,height:Pe,pixelRatio:[U,K]}}readPPS(e){const t=new la(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const n=t.readBoolean(),i=t.readBoolean();let o=1;return i&&n?o=0:i?o=3:n&&(o=2),{parallelismType:o}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const rs=188;class Kr{constructor(e,t,r,n){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=r,this.logger=n,this.videoParser=null}static probe(e,t){const r=Kr.syncOffset(e);return r>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),r!==-1}static syncOffset(e){const t=e.length;let r=Math.min(rs*5,t-rs)+1,n=0;for(;n<r;){let i=!1,o=-1,l=0;for(let d=n;d<t;d+=rs)if(e[d]===71&&(t-d===rs||e[d+rs]===71)){if(l++,o===-1&&(o=d,o!==0&&(r=Math.min(o+rs*99,e.length-rs)+1)),i||(i=Rd(e,d)===0),i&&l>1&&(o===0&&l>2||d+rs>r))return o}else{if(l)return-1;break}n++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Zx[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,r,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Kr.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=Kr.createTrack("audio",n),this._id3Track=Kr.createTrack("id3"),this._txtTrack=Kr.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:r}=this;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,r=!1,n=!1){r||(this.sampleAes=null);let i;const o=this._videoTrack,l=this._audioTrack,d=this._id3Track,c=this._txtTrack;let u=o.pid,h=o.pesData,f=l.pid,m=d.pid,p=l.pesData,x=d.pesData,y=null,v=this.pmtParsed,_=this._pmtId,b=e.length;if(this.remainderData&&(e=zs(this.remainderData,e),b=e.length,this.remainderData=null),b<rs&&!n)return this.remainderData=e,{audioTrack:l,videoTrack:o,id3Track:d,textTrack:c};const w=Math.max(0,Kr.syncOffset(e));b-=(b-w)%rs,b<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,b,e.buffer.byteLength-b));let T=0;for(let S=w;S<b;S+=rs)if(e[S]===71){const I=!!(e[S+1]&64),j=Rd(e,S),R=(e[S+3]&48)>>4;let k;if(R>1){if(k=S+5+e[S+4],k===S+rs)continue}else k=S+4;switch(j){case u:I&&(h&&(i=Wn(h,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,c,i,!1)),h={data:[],size:0}),h&&(h.data.push(e.subarray(k,S+rs)),h.size+=S+rs-k);break;case f:if(I){if(p&&(i=Wn(p,this.logger)))switch(l.segmentCodec){case"aac":this.parseAACPES(l,i);break;case"mp3":this.parseMPEGPES(l,i);break;case"ac3":this.parseAC3PES(l,i);break}p={data:[],size:0}}p&&(p.data.push(e.subarray(k,S+rs)),p.size+=S+rs-k);break;case m:I&&(x&&(i=Wn(x,this.logger))&&this.parseID3PES(d,i),x={data:[],size:0}),x&&(x.data.push(e.subarray(k,S+rs)),x.size+=S+rs-k);break;case 0:I&&(k+=e[k]+1),_=this._pmtId=PN(e,k);break;case _:{I&&(k+=e[k]+1);const D=DN(e,k,this.typeSupported,r,this.observer,this.logger);u=D.videoPid,u>0&&(o.pid=u,o.segmentCodec=D.segmentVideoCodec),f=D.audioPid,f>0&&(l.pid=f,l.segmentCodec=D.segmentAudioCodec),m=D.id3Pid,m>0&&(d.pid=m),y!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${S} after unknown PID '${y}'. Backtracking to sync byte @${w} to parse all TS packets.`),y=null,S=w-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=j;break}}else T++;T>0&&jd(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),o.pesData=h,l.pesData=p,d.pesData=x;const A={audioTrack:l,videoTrack:o,id3Track:d,textTrack:c};return n&&this.extractRemainingSamples(A),A}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:r,id3Track:n,textTrack:i}=e,o=r.pesData,l=t.pesData,d=n.pesData;let c;if(o&&(c=Wn(o,this.logger))?(this.readyVideoParser(r.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(r,i,c,!0),r.pesData=null)):r.pesData=o,l&&(c=Wn(l,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,c);break;case"mp3":this.parseMPEGPES(t,c);break;case"ac3":this.parseAC3PES(t,c);break}t.pesData=null}else l!=null&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=l;d&&(c=Wn(d,this.logger))?(this.parseID3PES(n,c),n.pesData=null):n.pesData=d}demuxSampleAes(e,t,r){const n=this.demux(e,r,!0,!this.config.progressive),i=this.sampleAes=new CN(this.observer,this.config,t);return this.decrypt(n,i)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new NN:e==="hevc"&&(this.videoParser=new LN))}decrypt(e,t){return new Promise(r=>{const{audioTrack:n,videoTrack:i}=e;n.samples&&n.segmentCodec==="aac"?t.decryptAacSamples(n.samples,0,()=>{i.samples?t.decryptAvcSamples(i.samples,0,0,()=>{r(e)}):r(e)}):i.samples&&t.decryptAvcSamples(i.samples,0,0,()=>{r(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let r=0;const n=this.aacOverFlow;let i=t.data;if(n){this.aacOverFlow=null;const h=n.missing,f=n.sample.unit.byteLength;if(h===-1)i=zs(n.sample.unit,i);else{const m=f-h;n.sample.unit.set(i.subarray(0,h),m),e.samples.push(n.sample),r=n.missing}}let o,l;for(o=r,l=i.length;o<l-1&&!ul(i,o);o++);if(o!==r){let h;const f=o<l-1;if(f?h=`AAC PES did not start with ADTS header,offset:${o}`:h="No ADTS header found in AAC PES",jd(this.observer,new Error(h),f,this.logger),!f)return}Oy(e,this.observer,i,o,this.audioCodec);let d;if(t.pts!==void 0)d=t.pts;else if(n){const h=My(e.samplerate);d=n.sample.pts+h}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,u;for(;o<l;)if(u=Fy(e,i,o,d,c),o+=u.length,u.missing){this.aacOverFlow=u;break}else for(c++;o<l-1&&!ul(i,o);o++);}parseMPEGPES(e,t){const r=t.data,n=r.length;let i=0,o=0;const l=t.pts;if(l===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;o<n;)if(Gy(r,o)){const d=By(e,r,o,l,i);if(d)o+=d.length,i++;else break}else o++}parseAC3PES(e,t){{const r=t.data,n=t.pts;if(n===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const i=r.length;let o=0,l=0,d;for(;l<i&&(d=Hy(e,r,l,n,o++))>0;)l+=d}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const r=Tt({},t,{type:this._videoTrack?Ns.emsg:Ns.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}}function Rd(s,e){return((s[e+1]&31)<<8)+s[e+2]}function PN(s,e){return(s[e+10]&31)<<8|s[e+11]}function DN(s,e,t,r,n,i){const o={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},l=(s[e+1]&15)<<8|s[e+2],d=e+3+l-4,c=(s[e+10]&15)<<8|s[e+11];for(e+=12+c;e<d;){const u=Rd(s,e),h=(s[e+3]&15)<<8|s[e+4];switch(s[e]){case 207:if(!r){_c("ADTS AAC",i);break}case 15:o.audioPid===-1&&(o.audioPid=u);break;case 21:o.id3Pid===-1&&(o.id3Pid=u);break;case 219:if(!r){_c("H.264",i);break}case 27:o.videoPid===-1&&(o.videoPid=u);break;case 3:case 4:!t.mpeg&&!t.mp3?i.log("MPEG audio found, not supported in this browser"):o.audioPid===-1&&(o.audioPid=u,o.segmentAudioCodec="mp3");break;case 193:if(!r){_c("AC-3",i);break}case 129:t.ac3?o.audioPid===-1&&(o.audioPid=u,o.segmentAudioCodec="ac3"):i.log("AC-3 audio found, not supported in this browser");break;case 6:if(o.audioPid===-1&&h>0){let f=e+5,m=h;for(;m>2;){switch(s[f]){case 106:t.ac3!==!0?i.log("AC-3 audio found, not supported in this browser for now"):(o.audioPid=u,o.segmentAudioCodec="ac3");break}const x=s[f+1]+2;f+=x,m-=x}}break;case 194:case 135:return jd(n,new Error("Unsupported EC-3 in M2TS found"),void 0,i),o;case 36:o.videoPid===-1&&(o.videoPid=u,o.segmentVideoCodec="hevc",i.log("HEVC in M2TS found"));break}e+=h+5}return o}
vendor: 4,463 bytes, line 676
676function jd(s,e,t,r){r.warn(`parsing error: ${e.message}`),s.emit(E.ERROR,E.ERROR,{type:Re.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function _c(s,e){e.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function Wn(s,e){let t=0,r,n,i,o,l;const d=s.data;if(!s||s.size===0)return null;for(;d[0].length<19&&d.length>1;)d[0]=zs(d[0],d[1]),d.splice(1,1);if(r=d[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(n=(r[4]<<8)+r[5],n&&n>s.size-6)return null;const u=r[7];u&192&&(o=(r[9]&14)*536870912+(r[10]&255)*4194304+(r[11]&254)*16384+(r[12]&255)*128+(r[13]&254)/2,u&64?(l=(r[14]&14)*536870912+(r[15]&255)*4194304+(r[16]&254)*16384+(r[17]&255)*128+(r[18]&254)/2,o-l>60*9e4&&(e.warn(`${Math.round((o-l)/9e4)}s delta between PTS and DTS, align them`),o=l)):l=o),i=r[8];let h=i+9;if(s.size<=h)return null;s.size-=h;const f=new Uint8Array(s.size);for(let m=0,p=d.length;m<p;m++){r=d[m];let x=r.byteLength;if(h)if(h>x){h-=x;continue}else r=r.subarray(h),x-=h,h=0;f.set(r,t),t+=x}return n&&(n-=i+3),{data:f,pts:o,dts:l,len:n}}return null}class ON{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const Vr=Math.pow(2,32)-1;class G{static init(){G.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in G.types)G.types.hasOwnProperty(e)&&(G.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);G.HDLR_TYPES={video:t,audio:r};const n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),i=new Uint8Array([0,0,0,0,0,0,0,0]);G.STTS=G.STSC=G.STCO=i,G.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),G.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),G.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),G.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const o=new Uint8Array([105,115,111,109]),l=new Uint8Array([97,118,99,49]),d=new Uint8Array([0,0,0,1]);G.FTYP=G.box(G.types.ftyp,o,d,o,l),G.DINF=G.box(G.types.dinf,G.box(G.types.dref,n))}static box(e,...t){let r=8,n=t.length;const i=n;for(;n--;)r+=t[n].byteLength;const o=new Uint8Array(r);for(o[0]=r>>24&255,o[1]=r>>16&255,o[2]=r>>8&255,o[3]=r&255,o.set(e,4),n=0,r=8;n<i;n++)o.set(t[n],r),r+=t[n].byteLength;return o}static hdlr(e){return G.box(G.types.hdlr,G.HDLR_TYPES[e])}static mdat(e){return G.box(G.types.mdat,e)}static mdhd(e,t){t*=e;const r=Math.floor(t/(Vr+1)),n=Math.floor(t%(Vr+1));return G.box(G.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,r>>24,r>>16&255,r>>8&255,r&255,n>>24,n>>16&255,n>>8&255,n&255,85,196,0,0]))}static mdia(e){return G.box(G.types.mdia,G.mdhd(e.timescale||0,e.duration||0),G.hdlr(e.type),G.minf(e))}static mfhd(e){return G.box(G.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?G.box(G.types.minf,G.box(G.types.smhd,G.SMHD),G.DIN
vendor: 4,221 bytes, line 676
676F,G.stbl(e)):G.box(G.types.minf,G.box(G.types.vmhd,G.VMHD),G.DINF,G.stbl(e))}static moof(e,t,r){return G.box(G.types.moof,G.mfhd(e),G.traf(r,t))}static moov(e){let t=e.length;const r=[];for(;t--;)r[t]=G.trak(e[t]);return G.box.apply(null,[G.types.moov,G.mvhd(e[0].timescale||0,e[0].duration||0)].concat(r).concat(G.mvex(e)))}static mvex(e){let t=e.length;const r=[];for(;t--;)r[t]=G.trex(e[t]);return G.box.apply(null,[G.types.mvex,...r])}static mvhd(e,t){t*=e;const r=Math.floor(t/(Vr+1)),n=Math.floor(t%(Vr+1)),i=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,r>>24,r>>16&255,r>>8&255,r&255,n>>24,n>>16&255,n>>8&255,n&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return G.box(G.types.mvhd,i)}static sdtp(e){const t=e.samples||[],r=new Uint8Array(4+t.length);let n,i;for(n=0;n<t.length;n++)i=t[n].flags,r[n+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return G.box(G.types.sdtp,r)}static stbl(e){return G.box(G.types.stbl,G.stsd(e),G.box(G.types.stts,G.STTS),G.box(G.types.stsc,G.STSC),G.box(G.types.stsz,G.STSZ),G.box(G.types.stco,G.STCO))}static avc1(e){let t=[],r=[],n,i,o;for(n=0;n<e.sps.length;n++)i=e.sps[n],o=i.byteLength,t.push(o>>>8&255),t.push(o&255),t=t.concat(Array.prototype.slice.call(i));for(n=0;n<e.pps.length;n++)i=e.pps[n],o=i.byteLength,r.push(o>>>8&255),r.push(o&255),r=r.concat(Array.prototype.slice.call(i));const l=G.box(G.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(r))),d=e.width,c=e.height,u=e.pixelRatio[0],h=e.pixelRatio[1];return G.box(G.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,d>>8&255,d&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,G.box(G.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),G.box(G.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return G.box(G.types.mp4a,G.audioStsd(e),G.box(G.types.esds,G.esds(e)))}static mp3(e){return G.box(G.types[".mp3"],G.audioStsd(e))}static ac3(e){return G.box(G.types["ac-3"],G.audioStsd(e),G.box(G.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return G.box(G.types.stsd,G.STSD,G.mp4a(e));if(t==="ac3"&&e.config)return G.box(G.types.stsd,G.STSD,G.ac3(e));if(t==="mp3"&&e.codec==="mp3")return G.box(G.types.stsd,G.STSD,G.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return G.box(G.types.stsd,G.STSD,G.avc1(e));if(t==="hevc"&&e.vps)return G.box(G.types.stsd,G.STSD,G.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,r=(e.duration||0)*(e.timescale||0),n=e.width||0,i=e.height||0,o=Math.floor(r/(Vr+1)),l=Math.floor(r%(Vr+1));return G.box(G.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,l>>24,l>>16&255,l>>8&255,l&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,n&255,0,0,i>>8&255,i&255,0,0]))}static traf(e,t){const r=G.sdtp(e),n=e.id,i=Math.floor(t/(Vr+1)),o=Math.floor(t%(Vr+1));return G.box(G.types.traf,G.box(G.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255])),G.box(G.types.tfdt,new Uint8Array([1,0,0,0,i>>24,i>>16&255,i>>8&255,i&255,o>>24,o>>16&255,o>>8&255,o&255])),G.trun(e,r.length+16+20+8+16+8+8),r)}static trak(e){return e.duration=e.duration||4294967295,G.box(G.types.trak,G.tkhd(e),G.mdia(e))}static trex(e){const t=e.id;return G.box(G.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}
vendor: 16,787 bytes, line 676
676static trun(e,t){const r=e.samples||[],n=r.length,i=12+16*n,o=new Uint8Array(i);let l,d,c,u,h,f;for(t+=8+i,o.set([e.type==="video"?1:0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,n&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),l=0;l<n;l++)d=r[l],c=d.duration,u=d.size,h=d.flags,f=d.cts,o.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,f>>>24&255,f>>>16&255,f>>>8&255,f&255],12+16*l);return G.box(G.types.trun,o)}static initSegment(e){G.types||G.init();const t=G.moov(e);return zs(G.FTYP,t)}static hvc1(e){const t=e.params,r=[e.vps,e.sps,e.pps],n=4,i=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),n-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),r.length]);let o=i.length;for(let p=0;p<r.length;p+=1){o+=3;for(let x=0;x<r[p].length;x+=1)o+=2+r[p][x].length}const l=new Uint8Array(o);l.set(i,0),o=i.length;const d=r.length-1;for(let p=0;p<r.length;p+=1){l.set(new Uint8Array([32+p|(p===d?128:0),0,r[p].length]),o),o+=3;for(let x=0;x<r[p].length;x+=1)l.set(new Uint8Array([r[p][x].length>>8,r[p][x].length&255]),o),o+=2,l.set(r[p][x],o),o+=r[p][x].length}const c=G.box(G.types.hvcC,l),u=e.width,h=e.height,f=e.pixelRatio[0],m=e.pixelRatio[1];return G.box(G.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,u>>8&255,u&255,h>>8&255,h&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),c,G.box(G.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),G.box(G.types.pasp,new Uint8Array([f>>24,f>>16&255,f>>8&255,f&255,m>>24,m>>16&255,m>>8&255,m&255])))}}G.types=void 0;G.HDLR_TYPES=void 0;G.STTS=void 0;G.STSC=void 0;G.STCO=void 0;G.STSZ=void 0;G.VMHD=void 0;G.SMHD=void 0;G.STSD=void 0;G.FTYP=void 0;G.DINF=void 0;const Wy=9e4;function Ju(s,e,t=1,r=!1){const n=s*e*t;return r?Math.round(n):n}function MN(s,e,t=1,r=!1){return Ju(s,e,1/t,r)}function Ki(s,e=!1){return Ju(s,1e3,1/Wy,e)}function FN(s,e=1){return Ju(s,Wy,1/e)}function Bm(s){const{baseTime:e,timescale:t,trackId:r}=s;return`${e/t} (${e}/${t}) trackId: ${r}`}const $N=10*1e3,UN=1024,BN=1152,VN=1536;let Yn=null,wc=null;function Vm(s,e,t,r){return{duration:e,size:t,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:s?2:1,isNonSync:s?0:1}}}class jo extends Hs{constructor(e,t,r,n){if(super("mp4-remuxer",n),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=r,this.ISGenerated=!1,Yn===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Yn=o?parseInt(o[1]):0}if(wc===null){const i=navigator.userAgent.match(/Safari\/(\d+)/i);wc=i?parseInt(i[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&Bm(t)} > ${e&&Bm(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const r=e[0].pts,n=e.reduce((i,o)=>{let l=o.pts,d=l-i;return d<-4294967296&&(t=!0,l=Cs(l,r),d=l-i),d>0?i:l},r);return t&&this.debug("PTS rollover detected"),n}remux(e,t,r,n,i,o,l,d){let c,u,h,f,m,p,x=i,y=i;const v=e.pid>-1,_=t.pid>-1,b=t.samples.length,w=e.samples.length>0,T=l&&b>0||b>1;if((!v||w)&&(!_||T)||this.ISGenerated||l){if(this.ISGenerated){var S,I,j,R;const q=this.videoTrackConfig;(q&&(t.width!==q.width||t.height!==q.height||((S=t.pixelRatio)==null?void 0:S[0])!==((I=q.pixelRatio)==null?void 0:I[0])||((j=t.pixelRatio)==null?void 0:j[1])!==((R=q.pixelRatio)==null?void 0:R[1]))||!q&&T||this.nextAudioTs===null&&w)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,i,o));const k=this.isVideoContiguous;let D=-1,Y;if(T&&(D=GN(t.samples),!k&&this.config.forceKeyFrameOnDiscontinuity))if(p=!0,D>0){this.warn(`Dropped ${D} out of ${b} video samples due to a missing keyframe`);const q=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(D),t.dropped+=D,y+=(t.samples[0].pts-q)/t.inputTimeScale,Y=y}else D===-1&&(this.warn(`No keyframe found out of ${b} video samples`),p=!1);if(this.ISGenerated){if(w&&T){const q=this.getVideoStartPts(t.samples),F=(Cs(e.samples[0].pts,q)-q)/t.inputTimeScale;x+=Math.max(0,F),y+=Math.max(0,-F)}if(w){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(e,t,i,o)),u=this.remuxAudio(e,x,this.isAudioContiguous,o,_||T||d===we.AUDIO?y:void 0),T){const q=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(e,t,i,o)),c=this.remuxVideo(t,y,k,q)}}else T&&(c=this.remuxVideo(t,y,k,0));c&&(c.firstKeyFrame=D,c.independent=D!==-1,c.firstKeyFramePTS=Y)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(m=Yy(r,i,this._initPTS,this._initDTS)),n.samples.length&&(f=Xy(n,i,this._initPTS))),{audio:u,video:c,initSegment:h,independent:p,text:f,id3:m}}computeInitPts(e,t,r,n){const i=Math.round(r*t);let o=Cs(e,i);if(o<i+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(i-o)/t} ${n}`);o<i+t;)o+=8589934592;return o-i}generateIS(e,t,r,n){const i=e.samples,o=t.samples,l=this.typeSupported,d={},c=this._initPTS;let u=!c||n,h="audio/mp4",f,m,p,x=-1;if(u&&(f=m=1/0),e.config&&i.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":l.mpeg?(h="audio/mpeg",e.codec=""):l.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}d.audio={id:"audio",container:h,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&l.mpeg?new Uint8Array(0):G.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(x=e.id,p=e.inputTimeScale,!c||p!==c.timescale?f=m=this.computeInitPts(i[0].pts,p,r,"audio"):u=!1)}if(t.sps&&t.pps&&o.length){if(t.timescale=t.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:G.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(x=t.id,p=t.inputTimeScale,!c||p!==c.timescale){const y=this.getVideoStartPts(o),v=Cs(o[0].dts,y),_=this.computeInitPts(v,p,r,"video"),b=this.computeInitPts(y,p,r,"video");m=Math.min(m,_),f=Math.min(f,b)}else u=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(d).length)return this.ISGenerated=!0,u?(c&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${f/p} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${f/p} (${f}/${p}) trackId: ${x}`),this._initPTS={baseTime:f,timescale:p,trackId:x},this._initDTS={baseTime:m,timescale:p,trackId:x}):f=p=void 0,{tracks:d,initPTS:f,timescale:p,trackId:x}}remuxVideo(e,t,r,n){const i=e.inputTimeScale,o=e.samples,l=[],d=o.length,c=this._initPTS,u=c.baseTime*i/c.timescale;let h=this.nextVideoTs,f=8,m=this.videoSampleDuration,p,x,y=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,_=!1;if(!r||h===null){const B=u+t*i,U=o[0].pts-Cs(o[0].dts,o[0].pts);Yn&&h!==null&&Math.abs(B-U-(h+u))<15e3?r=!0:h=B-U-u}const b=h+u;for(let B=0;B<d;B++){const U=o[B];U.pts=Cs(U.pts,b),U.dts=Cs(U.dts,b),U.dts<o[B>0?B-1:B].dts&&(_=!0)}_&&o.sort(function(B,U){const K=B.dts-U.dts,ee=B.pts-U.pts;return K||ee}),p=o[0].dts,x=o[o.length-1].dts;const w=x-p,T=w?Math.round(w/(d-1)):m||e.inputTimeScale/30;if(r){const B=p-b,U=B>T,K=B<-1;if((U||K)&&(U?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ki(B,!0)} ms (${B}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ki(-B,!0)} ms (${B}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!K||b>=o[0].pts||Yn)){p=b;const ee=o[0].pts-B;if(U)o[0].dts=p,o[0].pts=ee;else{let ce=!0;for(let Q=0;Q<o.length&&!(o[Q].dts>ee&&ce);Q++){const re=o[Q].pts;if(o[Q].dts-=B,o[Q].pts-=B,Q<o.length-1){const ve=o[Q+1].pts,Ce=o[Q].pts,Pe=ve<=Ce,Me=ve<=re;ce=Pe==Me}}}this.log(`Video: Initial PTS/DTS adjusted: ${Ki(ee,!0)}/${Ki(p,!0)}, delta: ${Ki(B,!0)} ms`)}}p=Math.max(0,p);let A=0,S=0,I=p;for(let B=0;B<d;B++){const U=o[B],K=U.units,ee=K.length;let ce=0;for(let Q=0;Q<ee;Q++)ce+=K[Q].data.length;S+=ce,A+=ee,U.length=ce,U.dts<I?(U.dts=I,I+=T/4|0||1):I=U.dts,y=Math.min(U.pts,y),v=Math.max(U.pts,v)}x=o[d-1].dts;const j=S+4*A+8;let R;try{R=new Uint8Array(j)}catch(B){this.observer.emit(E.ERROR,E.ERROR,{type:Re.MUX_ERROR,details:z.REMUX_ALLOC_ERROR,fatal:!1,error:B,bytes:j,reason:`fail allocating video mdat ${j}`});return}const k=new DataView(R.buffer);k.setUint32(0,j),R.set(G.types.mdat,4);let D=!1,Y=Number.POSITIVE_INFINITY,q=Number.POSITIVE_INFINITY,X=Number.NEGATIVE_INFINITY,F=Number.NEGATIVE_INFINITY;for(let B=0;B<d;B++){const U=o[B],K=U.units;let ee=0;for(let re=0,ve=K.length;re<ve;re++){const Ce=K[re],Pe=Ce.data,Me=Ce.data.byteLength;k.setUint32(f,Me),f+=4,R.set(Pe,f),f+=Me,ee+=4+Me}let ce;if(B<d-1)m=o[B+1].dts-U.dts,ce=o[B+1].pts-U.pts;else{const re=this.config,ve=B>0?U.dts-o[B-1].dts:T;if(ce=B>0?U.pts-o[B-1].pts:T,re.stretchShortVideoTrack&&this.nextAudioTs!==null){const Ce=Math.floor(re.maxBufferHole*i),Pe=(n?y+n*i:this.nextAudioTs+u)-U.pts;Pe>Ce?(m=Pe-ve,m<0?m=ve:D=!0,this.log(`It is approximately ${Pe/90} ms to the next segment; using duration ${m/90} ms for the last video frame.`)):m=ve}else m=ve}const Q=Math.round(U.pts-U.dts);Y=Math.min(Y,m),X=Math.max(X,m),q=Math.min(q,ce),F=Math.max(F,ce),l.push(Vm(U.key,m,ee,Q))}if(l.length){if(Yn){if(Yn<70){const B=l[0].flags;B.dependsOn=2,B.isNonSync=0}}else if(wc&&F-q<X-Y&&T/X<.025&&l[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let B=p;for(let U=0,K=l.length;U<K;U++){const ee=B+l[U].duration,ce=B+l[U].cts;if(U<K-1){const Q=ee+l[U+1].cts;l[U].duration=Q-ce}else l[U].duration=U?l[U-1].duration:T;l[U].cts=0,B=ee}}}m=D||!m?T:m;const P=x+m;this.nextVideoTs=h=P-u,this.videoSampleDuration=m,this.isVideoContiguous=!0;const $={data1:G.moof(e.sequenceNumber++,p,Tt(e,{samples:l})),data2:R,startPTS:(y-u)/i,endPTS:(v+m-u)/i,startDTS:(p-u)/i,endDTS:h/i,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:e.dropped};return e.samples=[],e.dropped=0,$}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return BN;case"ac3":return VN;default:return UN}}remuxAudio(e,t,r,n,i){const o=e.inputTimeScale,l=e.samplerate?e.samplerate:o,d=o/l,c=this.getSamplesPerFrame(e),u=c*d,h=this._initPTS,f=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,m=[],p=i!==void 0;let x=e.samples,y=f?0:8,v=this.nextAudioTs||-1;const _=h.baseTime*o/h.timescale,b=_+t*o;if(this.isAudioContiguous=r=r||x.length&&v>0&&(n&&Math.abs(b-(v+_))<9e3||Math.abs(Cs(x[0].pts,b)-(v+_))<20*u),x.forEach(function(F){F.pts=Cs(F.pts,b)}),!r||v<0){const F=x.length;if(x=x.filter(P=>P.pts>=0),F!==x.length&&this.warn(`Removed ${x.length-F} of ${F} samples (initPTS ${_} / ${o})`),!x.length)return;i===0?v=0:n&&!p?v=Math.max(0,b-_):v=x[0].pts-_}if(e.segmentCodec==="aac"){const F=this.config.maxAudioFramesDrift;for(let P=0,N=v+_;P<x.length;P++){const O=x[P],$=O.pts,B=$-N,U=Math.abs(1e3*B/o);if(B<=-F*u&&p)P===0&&(this.warn(`Audio frame @ ${($/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*B/o)} ms.`),this.nextAudioTs=v=$-_,N=$);else if(B>=F*u&&U<$N&&p){let K=Math.round(B/u);for(N=$-K*u;N<0&&K&&u;)K--,N+=u;P===0&&(this.nextAudioTs=v=N-_),this.warn(`Injecting ${K} audio frames @ ${((N-_)/o).toFixed(3)}s due to ${Math.round(1e3*B/o)} ms gap.`);for(let ee=0;ee<K;ee++){let ce=ON.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);ce||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),ce=O.unit.subarray()),x.splice(P,0,{unit:ce,pts:N}),N+=u,P++}}O.pts=N,N+=u}}let w=null,T=null,A,S=0,I=x.length;for(;I--;)S+=x[I].unit.byteLength;for(let F=0,P=x.length;F<P;F++){const N=x[F],O=N.unit;let $=N.pts;if(T!==null){const U=m[F-1];U.duration=Math.round(($-T)/d)}else if(r&&e.segmentCodec==="aac"&&($=v+_),w=$,S>0){S+=y;try{A=new Uint8Array(S)}catch(U){this.observer.emit(E.ERROR,E.ERROR,{type:Re.MUX_ERROR,details:z.REMUX_ALLOC_ERROR,fatal:!1,error:U,bytes:S,reason:`fail allocating audio mdat ${S}`});return}f||(new DataView(A.buffer).setUint32(0,S),A.set(G.types.mdat,4))}else return;A.set(O,y);const B=O.byteLength;y+=B,m.push(Vm(!0,c,B,0)),T=$}const j=m.length;if(!j)return;const R=m[m.length-1];v=T-_,this.nextAudioTs=v+d*R.duration;const k=f?new Uint8Array(0):G.moof(e.sequenceNumber++,w/d,Tt({},e,{samples:m}));e.samples=[];const D=(w-_)/o,Y=this.nextAudioTs/o,X={data1:k,data2:A,startPTS:D,endPTS:Y,startDTS:D,endDTS:Y,type:"audio",hasAudio:!0,hasVideo:!1,nb:j};return this.isAudioContiguous=!0,X}}function Cs(s,e){let t;if(e===null)return s;for(e<s?t=-8589934592:t=8589934592;Math.abs(s-e)>4294967296;)s+=t;return s}function GN(s){for(let e=0;e<s.length;e++)if(s[e].key)return e;return-1}function Yy(s,e,t,r){const n=s.samples.length;if(!n)return;const i=s.inputTimeScale;for(let l=0;l<n;l++){const d=s.samples[l];d.pts=Cs(d.pts-t.baseTime*i/t.timescale,e*i)/i,d.dts=Cs(d.dts-r.baseTime*i/r.timescale,e*i)/i}const o=s.samples;return s.samples=[],{samples:o}}function Xy(s,e,t){const r=s.samples.length;if(!r)return;const n=s.inputTimeScale;for(let o=0;o<r;o++){const l=s.samples[o];l.pts=Cs(l.pts-t.baseTime*n/t.timescale,e*n)/n}s.samples.sort((o,l)=>o.pts-l.pts);const i=s.samples;return s.samples=[],{samples:i}}class zN extends Hs{constructor(e,t,r,n){super("passthrough-remuxer",n),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,r,n){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment(e,n),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:r,videoCodec:n}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:i,video:o}=this.initData=sy(e);if(t)CI(e,t);else{const d=i||o;d!=null&&d.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${d.codec}")!`)}i&&(r=Gm(i,kt.AUDIO,this)),o&&(n=Gm(o,kt.VIDEO,this));const l={};i&&o?l.audiovideo={container:"video/mp4",codec:r+","+n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:i?l.audio={container:"audio/mp4",codec:r,encrypted:i.encrypted,initSegment:e,id:"audio"}:o?l.video={container:"video/mp4",codec:n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l}remux(e,t,r,n,i,o){var l,d;let{initPTS:c,lastEndTime:u}=this;const h={audio:void 0,video:void 0,text:n,id3:r,initSegment:void 0};xe(u)||(u=this.lastEndTime=i||0);const f=t.samples;if(!f.length)return h;const m={initPTS:void 0,timescale:void 0,trackId:void 0};let p=this.initData;if((l=p)!=null&&l.length||(this.generateInitSegment(f),p=this.initData),!((d=p)!=null&&d.length))return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(m.tracks=this.initTracks,this.emitInitSegment=!1);const x=LI(f,p,this),y=p.audio?x[p.audio.id]:null,v=p.video?x[p.video.id]:null,_=io(v,1/0),b=io(y,1/0),w=io(v,0,!0),T=io(y,0,!0);let A=i,S=0;const I=y&&(!v||!c&&b<_||c&&c.trackId===p.audio.id),j=I?y:v;if(j){const N=j.timescale,O=j.start-i*N,$=I?p.audio.id:p.video.id;A=j.start/N,S=I?T-b:w-_,(o||!c)&&(qN(c,A,i,S)||N!==c.timescale)&&(c&&this.warn(`Timestamps at playlist time: ${o?"":"~"}${i} ${O/N}
vendor: 14,262 bytes, lines 676-682
676 != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${A-i} (${O}/${N}) trackId: ${$}`),c=null,m.initPTS=O,m.timescale=N,m.trackId=$)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${i}`);c?(m.initPTS=c.baseTime,m.timescale=c.timescale,m.trackId=c.trackId):((!m.timescale||m.trackId===void 0||m.initPTS===void 0)&&(this.warn("Could not set initPTS"),m.initPTS=A,m.timescale=1,m.trackId=-1),this.initPTS=c={baseTime:m.initPTS,timescale:m.timescale,trackId:m.trackId});const R=A-c.baseTime/c.timescale,k=R+S;S>0?this.lastEndTime=k:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const D=!!p.audio,Y=!!p.video;let q="";D&&(q+="audio"),Y&&(q+="video");const X=(p.audio?p.audio.encrypted:!1)||(p.video?p.video.encrypted:!1),F={data1:f,startPTS:R,startDTS:R,endPTS:k,endDTS:k,type:q,hasAudio:D,hasVideo:Y,nb:1,dropped:0,encrypted:X};h.audio=D&&!Y?F:void 0,h.video=Y?F:void 0;const P=v==null?void 0:v.sampleCount;if(P){const N=v.keyFrameIndex,O=N!==-1;F.nb=P,F.dropped=N===0||this.isVideoContiguous?0:O?N:P,F.independent=O,F.firstKeyFrame=N,O&&v.keyFrameStart&&(F.firstKeyFramePTS=(v.keyFrameStart-c.baseTime)/c.timescale),this.isVideoContiguous||(h.independent=O),this.isVideoContiguous||(this.isVideoContiguous=O),F.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${N}/${P} dropped: ${F.dropped} start: ${F.firstKeyFramePTS||"NA"}`)}return h.initSegment=m,h.id3=Yy(r,i,c,c),n.samples.length&&(h.text=Xy(n,i,c)),h}}function io(s,e,t=!1){return(s==null?void 0:s.start)!==void 0?(s.start+(t?s.duration:0))/s.timescale:e}function qN(s,e,t,r){if(s===null)return!0;const n=Math.max(r,1),i=e-s.baseTime/s.timescale;return Math.abs(i-t)>n}function Gm(s,e,t){const r=s.codec;return r&&r.length>4?r:e===kt.AUDIO?r==="ec-3"||r==="ac-3"||r==="alac"?r:r==="fLaC"||r==="Opus"?rl(r,!1):(t.warn(`Unhandled audio codec "${r}" in mp4 MAP`),r||"mp4a"):(t.warn(`Unhandled video codec "${r}" in mp4 MAP`),r||"avc1")}let Ir;try{Ir=self.performance.now.bind(self.performance)}catch{Ir=Date.now}const Io=[{demux:IN,remux:zN},{demux:Kr,remux:jo},{demux:AN,remux:jo},{demux:RN,remux:jo}];Io.splice(2,0,{demux:kN,remux:jo});class zm{constructor(e,t,r,n,i,o){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=r,this.id=i,this.logger=o}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,r,n){const i=r.transmuxing;i.executeStart=Ir();let o=new Uint8Array(e);const{currentTransmuxState:l,transmuxConfig:d}=this;n&&(this.currentTransmuxState=n);const{contiguous:c,discontinuity:u,trackSwitch:h,accurateTimeOffset:f,timeOffset:m,initSegmentChange:p}=n||l,{audioCodec:x,videoCodec:y,defaultInitPts:v,duration:_,initSegmentData:b}=d,w=HN(o,t);if(w&&fi(w.method)){const I=this.getDecrypter(),j=Gu(w.method);if(I.isSync()){let R=I.softwareDecrypt(o,w.key.buffer,w.iv.buffer,j);if(r.part>-1){const D=I.flush();R=D&&D.buffer}if(!R)return i.executeEnd=Ir(),Ec(r);o=new Uint8Array(R)}else return this.asyncResult=!0,this.decryptionPromise=I.webCryptoDecrypt(o,w.key.buffer,w.iv.buffer,j).then(R=>{const k=this.push(R,null,r);return this.decryptionPromise=null,k}),this.decryptionPromise}const T=this.needsProbing(u,h);if(T){const I=this.configureTransmuxer(o);if(I)return this.logger.warn(`[transmuxer] ${I.message}`),this.observer.emit(E.ERROR,E.ERROR,{type:Re.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),i.executeEnd=Ir(),Ec(r)}(u||h||p||T)&&this.resetInitSegment(b,x,y,_,t),(u||p||T)&&this.resetInitialTimestamp(v),c||this.resetContiguity();const A=this.transmux(o,w,m,f,r);this.asyncResult=ja(A);const S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,i.executeEnd=Ir(),A}flush(e){const t=e.transmuxing;t.executeStart=Ir();const{decrypter:r,currentTransmuxState:n,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then(()=>this.flush(e));const o=[],{timeOffset:l}=n;if(r){const h=r.flush();h&&o.push(this.push(h.buffer,null,e))}const{demuxer:d,remuxer:c}=this;if(!d||!c){t.executeEnd=Ir();const h=[Ec(e)];return this.asyncResult?Promise.resolve(h):h}const u=d.flush(l);return ja(u)?(this.asyncResult=!0,u.then(h=>(this.flushRemux(o,h,e),o))):(this.flushRemux(o,u,e),this.asyncResult?Promise.resolve(o):o)}flushRemux(e,t,r){const{audioTrack:n,videoTrack:i,id3Track:o,textTrack:l}=t,{accurateTimeOffset:d,timeOffset:c}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${r.sn}${r.part>-1?" part: "+r.part:""} of ${this.id===we.MAIN?"level":"track"} ${r.level}`);const u=this.remuxer.remux(n,i,o,l,c,d,!0,this.id);e.push({remuxResult:u,chunkMeta:r}),r.transmuxing.executeEnd=Ir()}resetInitialTimestamp(e){const{demuxer:t,remuxer:r}=this;!t||!r||(t.resetTimeStamp(e),r.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,r,n,i){const{demuxer:o,remuxer:l}=this;!o||!l||(o.resetInitSegment(e,t,r,n),l.resetInitSegment(e,t,r,i))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,r,n,i){let o;return t&&t.method==="SAMPLE-AES"?o=this.transmuxSampleAes(e,t,r,n,i):o=this.transmuxUnencrypted(e,r,n,i),o}transmuxUnencrypted(e,t,r,n){const{audioTrack:i,videoTrack:o,id3Track:l,textTrack:d}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,o,l,d,t,r,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,r,n,i){return this.demuxer.demuxSampleAes(e,t,r).then(o=>({remuxResult:this.remuxer.remux(o.audioTrack,o.videoTrack,o.id3Track,o.textTrack,r,n,!1,this.id),chunkMeta:i}))}configureTransmuxer(e){const{config:t,observer:r,typeSupported:n}=this;let i;for(let h=0,f=Io.length;h<f;h++){var o;if((o=Io[h].demux)!=null&&o.probe(e,this.logger)){i=Io[h];break}}if(!i)return new Error("Failed to find demuxer by probing fragment data");const l=this.demuxer,d=this.remuxer,c=i.remux,u=i.demux;(!d||!(d instanceof c))&&(this.remuxer=new c(r,t,n,this.logger)),(!l||!(l instanceof u))&&(this.demuxer=new u(r,t,n,this.logger),this.probe=u.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Bu(this.config)),e}}function HN(s,e){let t=null;return s.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const Ec=s=>({remuxResult:{},chunkMeta:s});function ja(s){return"then"in s&&s.then instanceof Function}class KN{constructor(e,t,r,n,i){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=r,this.duration=n,this.defaultInitPts=i||null}}class WN{constructor(e,t,r,n,i,o){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=r,this.trackSwitch=n,this.timeOffset=i,this.initSegmentChange=o}}let qm=0;class Qy{constructor(e,t,r,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=qm++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=d=>{const c=d.data,u=this.hls;if(!(!u||!(c!=null&&c.event)||c.instanceNo!==this.instanceNo))switch(c.event){case"init":{var h;const f=(h=this.workerContext)==null?void 0:h.objectURL;f&&self.URL.revokeObjectURL(f);break}case"transmuxComplete":{this.handleTransmuxComplete(c.data);break}case"flush":{this.onFlush(c.data);break}case"workerLog":{u.logger[c.data.logType]&&u.logger[c.data.logType](c.data.message);break}default:{c.data=c.data||{},c.data.frag=this.frag,c.data.part=this.part,c.data.id=this.id,u.trigger(c.event,c.data);break}}},this.onWorkerError=d=>{if(!this.hls)return;const c=new Error(`${d.message}  (${d.filename}:${d.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(E.ERROR,{type:Re.OTHER_ERROR,details:z.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:c})};const i=e.config;this.hls=e,this.id=t,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=r,this.onFlush=n;const o=(d,c)=>{c=c||{},c.frag=this.frag||void 0,d===E.ERROR&&(c=c,c.parent=this.id,c.part=this.part,this.error=c.error),this.hls.trigger(d,c)};this.observer=new Hu,this.observer.on(E.FRAG_DECRYPTED,o),this.observer.on(E.ERROR,o);const l=am(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const d=this.hls.logger;if(i.workerPath||JC()){try{i.workerPath?(d.log(`loading Web Worker ${i.workerPath} for "${t}"`),this.workerContext=eN(i.workerPath)):(d.log(`injecting Web Worker for "${t}"`),this.workerContext=ZC());const{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:l,id:t,config:Rt(i)})}catch(u){d.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new zm(this.observer,l,i,"",t,e.logger)}return}}this.transmuxer=new zm(this.observer,l,i,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=qm++;const t=this.hls.config,r=am(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,id:this.id,config:Rt(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),tN(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,r,n,i,o,l,d,c,u){var h,f;c.transmuxing.start=self.performance.now();const{instanceNo:m,transmuxer:p}=this,x=o?o.start:i.start,y=i.decryptdata,v=this.frag,_=!(v&&i.cc===v.cc),b=!(v&&c.level===v.level),w=v?c.sn-v.sn:-1,T=this.part?c.part-this.part.index:-1,A=w===0&&c.id>1&&c.id===(v==null?void 0:v.stats.chunkCount),S=!b&&(w===1||w===0&&(T===1||A&&T<=0)),I=self.performance.now();(b||w||i.stats.parsing.start===0)&&(i.stats.parsing.start=I),o&&(T||!S)&&(o.stats.parsing.start=I);const j=!(v&&((h=i.initSegment)==null?void 0:h.url)===((f=v.initSegment)==null?void 0:f.url)),R=new WN(_,S,d,b,x,j);if(!S||_||j){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${c.sn}${c.part>-1?" part: "+c.part:""} ${this.id===we.MAIN?"level":"track"}: ${c.level} id: ${c.id}
677        discontinuity: ${_}
678        trackSwitch: ${b}
679        contiguous: ${S}
680        accurateTimeOffset: ${d}
681        timeOffset: ${x}
682        initSegmentChange: ${j}`);const k=new KN(r,n,t,l,u);this.configureTransmuxer(k)}if(this.frag=i,this.part=o,this.workerContext)this.workerContext.worker.postMessage({instanceNo:m,cmd:"demux",data:e,decryptdata:y,chunkMeta:c,state:R},e instanceof ArrayBuffer?[e]:[]);else if(p){const k=p.push(e,y,c,R);ja(k)?k.then(D=>{this.handleTransmuxComplete(D)}).catch(D=>{this.transmuxerError(D,c,"transmuxer-interface push error")}):this.handleTransmuxComplete(k)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:r}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(r){const n=r.flush(e);ja(n)?n.then(i=>{this.handleFlushResult(i,e)}).catch(i=>{this.transmuxerError(i,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}transmuxerError(e,t,r){this.hls&&(this.error=e,this.hls.trigger(E.ERROR,{type:Re.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:r}))}handleFlushResult(e,t){e.forEach(r=>{this.handleTransmuxComplete(r)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:r}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):r&&r.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const Hm=100;class YN extends qu{constructor(e,t,r){super(e,t,r,"audio-stream-controller",we.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.AU
vendor: 15,772 bytes, line 682
682DIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:r,initPTS:n,timescale:i,trackId:o}){if(r===we.MAIN){const l=t.cc,d=this.fragCurrent;if(this.initPTS[l]={baseTime:n,timescale:i,trackId:o},this.log(`InitPTS for cc: ${l} found from main: ${n/i} (${n}/${i}) trackId: ${o}`),this.mainAnchor=t,this.state===te.WAITING_INIT_PTS){const c=this.waitingData;(!c&&!this.loadingParts||c&&c.frag.cc!==l)&&this.syncWithAnchor(t,c==null?void 0:c.frag)}else!this.hls.hasEnoughToStart&&d&&d.cc!==l?(d.abortRequests(),this.syncWithAnchor(t,d)):this.state===te.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var r;const n=((r=this.mainFragLoading)==null?void 0:r.frag)||null;if(t&&(n==null?void 0:n.cc)===t.cc)return;const i=(n||e).cc,o=this.getLevelDetails(),l=this.getLoadPosition(),d=fy(o,i,l);d&&(this.log(`Syncing with main frag at ${d.start} cc ${d.cc}`),this.startFragRequested=!1,this.nextLoadPosition=d.start,this.resetLoadingState(),this.state===te.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=te.STOPPED;return}const r=this.lastCurrentTime;this.stopLoad(),this.setInterval(Hm),r>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r,this.state=te.IDLE):this.state=te.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case te.IDLE:this.doTickIdle();break;case te.WAITING_TRACK:{const{levels:e,trackId:t}=this,r=e==null?void 0:e[t],n=r==null?void 0:r.details;if(n&&!this.waitForLive(r)){if(this.waitForCdnTuneIn(n))break;this.state=te.WAITING_INIT_PTS}break}case te.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case te.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:r,cache:n,complete:i}=e,o=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=te.FRAG_LOADING;const l=n.flush().buffer,d={frag:t,part:r,payload:l,networkDetails:null};this._handleFragmentLoadProgress(d),i&&super._handleFragmentLoadComplete(d)}else o&&o.cc!==e.frag.cc&&this.syncWithAnchor(o,e.frag)}else this.state=te.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:r,media:n,trackId:i}=this,o=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!o.startFragPrefetch)||!(r!=null&&r[i]))return;const l=r[i],d=l.details;if(!d||this.waitForLive(l)||this.waitForCdnTuneIn(d)){this.state=te.WAITING_TRACK,this.startFragRequested=!1;return}const c=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&c&&(this.bufferFlushed=!1,this.afterBufferFlushed(c,kt.AUDIO,we.AUDIO));const u=this.getFwdBufferInfo(c,we.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,d)){t.trigger(E.BUFFER_EOS,{type:"audio"}),this.state=te.ENDED;return}const h=u.len,f=t.maxBufferLength,m=d.fragments,p=m[0].start,x=this.getLoadPosition(),y=this.flushing?x:u.end;if(this.switchingTrack&&n){const b=x;d.PTSKnown&&b<p&&(u.end>p||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=p+.05)}if(h>=f&&!this.switchingTrack&&y<m[m.length-1].start)return;let v=this.getNextFragment(y,d);if(v&&this.isLoopLoading(v,y)&&(v=this.getNextFragmentLoopLoading(v,d,u,we.MAIN,f)),!v){this.bufferFlushed=!0;return}let _=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&_&&zt(v)&&!v.endList&&(!d.live||!this.loadingParts&&y<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(_)===ss.OK&&(this.mainFragLoading=_=null),_&&zt(_))){if(v.start>_.end){const w=this.fragmentTracker.getFragAtPos(y,we.MAIN);w&&w.end>_.end&&(_=w,this.mainFragLoading={frag:w,targetBufferTime:null})}if(v.start>_.end)return}this.loadFragment(v,l,y)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(r=>new Aa(r))}onAudioTrackSwitching(e,t){const r=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),r?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==te.STOPPED&&(this.setInterval(Hm),this.state=te.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const r=this.cachedTrackLoadedData;r&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(E.AUDIO_TRACK_LOADED,r))}onAudioTrackLoaded(e,t){var r;const{levels:n}=this,{details:i,id:o,groupId:l,track:d}=t;if(!n){this.warn(`Audio tracks reset while loading track ${o} "${d.name}" of "${l}"`);return}const c=this.mainDetails;if(!c||i.endCC>c.endCC||c.expired){this.cachedTrackLoadedData=t,this.state!==te.STOPPED&&(this.state=te.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${o} "${d.name}" of "${l}" loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""},duration:${i.totalduration}`);const u=n[o];let h=0;if(i.live||(r=u.details)!=null&&r.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;if(u.details){var f;h=this.alignPlaylists(i,u.details,(f=this.levelLastLoaded)==null?void 0:f.details)}i.alignedSliding||(Cy(i,c),i.alignedSliding||dl(i,c),h=i.fragmentStart)}u.details=i,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(c,h),this.hls.trigger(E.AUDIO_TRACK_UPDATED,{details:i,id:o,groupId:t.groupId}),this.state===te.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=te.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const r=e.frag,{part:n,payload:i}=e,{config:o,trackId:l,levels:d}=this;if(!d){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);return}const c=d[l];if(!c){this.warn("Audio track is undefined on fragment load progress");return}const u=c.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(r.start);return}const h=o.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let f=this.transmuxer;f||(f=this.transmuxer=new Qy(this.hls,we.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const m=this.initPTS[r.cc],p=(t=r.initSegment)==null?void 0:t.data;if(m!==void 0){const y=n?n.index:-1,v=y!==-1,_=new Vu(r.level,r.sn,r.stats.chunkCount,i.byteLength,y,v);f.push(i,p,h,"",r,n,u.totalduration,!1,_,m)}else{this.log(`Unknown video PTS for cc ${r.cc}, waiting for video PTS before demuxing audio frag ${r.sn} of [${u.startSN} ,${u.endSN}],track ${l}`);const{cache:x}=this.waitingData=this.waitingData||{frag:r,part:n,cache:new Ny,complete:!1};x.push(new Uint8Array(i)),this.state!==te.STOPPED&&(this.state=te.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===we.MAIN&&zt(t.frag)&&(this.mainFragLoading=t,this.state===te.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:r,part:n}=t;if(r.type!==we.AUDIO){!this.audioOnly&&r.type===we.MAIN&&!r.elementaryStreams.video&&!r.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${n?" p: "+n.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(zt(r)){this.fragPrevious=r;const i=this.switchingTrack;i&&(this.bufferedTrack=i,this.switchingTrack=null,this.hls.trigger(E.AUDIO_TRACK_SWITCHED,yt({},i)))}this.fragBufferedComplete(r,n),this.media&&this.tick()}onError(e,t){var r;if(t.fatal){this.state=te.ERROR;return}switch(t.details){case z.FRAG_GAP:case z.FRAG_PARSING_ERROR:case z.FRAG_DECRYPT_ERROR:case z.FRAG_LOAD_ERROR:case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_ERROR:case z.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(we.AUDIO,t);break;case z.AUDIO_TRACK_LOAD_ERROR:case z.AUDIO_TRACK_LOAD_TIMEOUT:case z.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===te.WAITING_TRACK&&((r=t.context)==null?void 0:r.type)===tt.AUDIO_TRACK&&(this.state=te.IDLE);break;case z.BUFFER_ADD_CODEC_ERROR:case z.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case z.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case z.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==kt.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==kt.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===te.ENDED&&(this.state=te.IDLE);const r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,t,we.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const r="audio",{hls:n}=this,{remuxResult:i,chunkMeta:o}=e,l=this.getCurrentContext(o);if(!l){this.resetWhenMissingContext(o);return}const{frag:d,part:c,level:u}=l,{details:h}=u,{audio:f,text:m,id3:p,initSegment:x}=i;if(this.fragContextChanged(d)||!h){this.fragmentTracker.removeFragment(d);return}if(this.state=te.PARSING,this.switchingTrack&&f&&this.completeAudioSwitch(this.switchingTrack),x!=null&&x.tracks){const y=d.initSegment||d;if(this.unhandledEncryptionError(x,d))return;this._bufferInitSegment(u,x.tracks,y,o),n.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:r,tracks:x.tracks})}if(f){const{startPTS:y,endPTS:v,startDTS:_,endDTS:b}=f;c&&(c.elementaryStreams[kt.AUDIO]={startPTS:y,endPTS:v,startDTS:_,endDTS:b}),d.setElementaryStreamInfo(kt.AUDIO,y,v,_,b),this.bufferFragmentData(f,d,c,o)}if(p!=null&&(t=p.samples)!=null&&t.length){const y=Tt({id:r,frag:d,details:h},p);n.trigger(E.FRAG_PARSING_METADATA,y)}if(m){const y=Tt({id:r,frag:d,details:h},m);n.trigger(E.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,r,n){if(this.state!==te.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const i=t.audio;i.id=we.AUDIO;const o=e.audioCodec;this.log(`Init audio buffer, container:${i.container}, codecs[level/parsed]=[${o}/${i.codec}]`),o&&o.split(",").length===1&&(i.levelCodec=o),this.hls.trigger(E.BUFFER_CODECS,t);const l=i.initSegment;if(l!=null&&l.byteLength){const d={type:"audio",frag:r,part:null,chunkMeta:n,parent:r.type,data:l};this.hls.trigger(E.BUFFER_APPENDING,d)}this.tickImmediate()}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===ss.NOT_LOADED||n===ss.PARTIAL){var i;if(!zt(e))this._loadInitSegment(e,t);else if((i=t.details)!=null&&i.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=te.WAITING_INIT_PTS;const o=this.mainDetails;o&&o.fragmentStart!==t.details.fragmentStart&&dl(t.details,o)}else super.loadFragment(e,t,r)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:r,assocLang:n,characteristics:i,audioCodec:o,channels:l}=this.bufferedTrack;Sn({name:t,lang:r,assocLang:n,characteristics:i,audioCodec:o,channels:l},e,vn)||(il(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(E.AUDIO_TRACK_SWITCHED,yt({},e))}}class Zu extends Hs{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,r){const n=t==null?void 0:t.renditionReports;if(n){let i=-1;for(let o=0;o<n.length;o++){const l=n[o];let d;try{d=new self.URL(l.URI,t.url).href}catch(c){this.warn(`Could not construct new URL for Rendition Report: ${c}`),d=l.URI||""}if(d===e){i=o;break}else d===e.substring(0,d.length)&&(i=o)}if(i!==-1){const o=n[i],l=parseInt(o["LAST-MSN"])||t.lastPartSn;let d=parseInt(o["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const u=Math.min(t.age-t.partTarget,t.targetduration);d>=0&&u>t.partTarget&&(d+=1)}const c=r&&om(r);return new lm(l,d>=0?d:void 0,c)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(r){this.warn(`Could not construct new URL with HLS Delivery Directives: ${r}`)}return e}playlistLoaded(e,t,r){const{details:n,stats:i}=t,o=self.performance.now(),l=i.loading.first?Math.max(0,o-i.loading.first):0;n.advancedDateTime=Date.now()-l;const d=this.hls.config.timelineOffset;if(d!==n.appliedTimelineOffset){const u=Math.max(d||0,0);n.appliedTimelineOffset=u,n.fragments.forEach(h=>{h.setStart(h.playlistOffset+u)})}if(n.live||r!=null&&r.live){const u="levelInfo"in t?t.levelInfo:t.track;if(n.reloaded(r),r&&n.fragments.length>0){BC(r,n,this);const _=n.playlistParsingError;if(_){this.warn(_);const b=this.hls;if(!b.config.ignorePlaylistParsingErrors){var c;const{networkDetails:w}=t;b.trigger(E.ERROR,{type:Re.NETWORK_ERROR,details:z.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:_,reason:_.message,level:t.level||void 0,parent:(c=n.fragments[0])==null?void 0:c.type,networkDetails:w,stats:i});return}n.playlistParsingError=null}}n.requestScheduled===-1&&(n.requestScheduled=i.loading.start);const h=this.hls.mainForwardBufferInfo,f=h?h.end-h.len:0,m=(n.edge-f)*1e3,p=Ay(n,m);if(n.requestScheduled+p<o?n.requestScheduled=o:n.requestScheduled+=p,this.log(`live playlist ${e} ${n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:n.updated?"UPDATED":"MISSED"}`),!this.canLoad||!n.live)return;let x,y,v;if(n.canBlockReload&&n.endSN&&n.advanced){const _=this.hls.config.lowLatencyMode,b=n.lastPartSn,w=n.endSN,T=n.lastPartIndex,A=T!==-1,S=b===w;A?S?(y=w+1,v=_?0:T):(y=b,v=_?T+1:n.maxPartIndex):y=w+1;const I=n.age,j=I+n.ageHeader;let R=Math.min(j-n.partTarget,n.targetduration*1.5);if(R>0){if(j>n.targetduration*3)this.log(`Playlist last advanced ${I.toFixed(2)}s ago. Omitting segment and part directives.`),y=void 0,v=void 0;else if(r!=null&&r.tuneInGoal&&j-n.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${R} with playlist age: ${n.age}`),R=0;
vendor: 14,089 bytes, lines 682-685
682else{const k=Math.floor(R/n.targetduration);if(y+=k,v!==void 0){const D=Math.round(R%n.targetduration/n.partTarget);v+=D}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${I.toFixed(2)}s goal: ${R} skip sn ${k} to part ${v}`)}n.tuneInGoal=R}if(x=this.getDeliveryDirectives(n,t.deliveryDirectives,y,v),_||!S){n.requestScheduled=o,this.loadingPlaylist(u,x);return}}else(n.canBlockReload||n.canSkipUntil)&&(x=this.getDeliveryDirectives(n,t.deliveryDirectives,y,v));x&&y!==void 0&&n.canBlockReload&&(n.requestScheduled=i.loading.first+Math.max(p-l*2,p/2)),this.scheduleLoading(u,x,n)}else this.clearTimer()}scheduleLoading(e,t,r){const n=r||e.details;if(!n){this.loadingPlaylist(e,t);return}const i=self.performance.now(),o=n.requestScheduled;if(i>=o){this.loadingPlaylist(e,t);return}const l=o-i;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(l)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),l)}getDeliveryDirectives(e,t,r,n){let i=om(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,n=t.part,i=ko.No),new lm(r,n,i)}checkRetry(e){const t=e.details,r=al(e),n=e.errorAction,{action:i,retryCount:o=0,retryConfig:l}=n||{},d=!!n&&!!l&&(i===os.RetryRequest||!n.resolved&&i===os.SendAlternateToPenaltyBox);if(d){var c;if(o>=l.maxNumRetry)return!1;if(r&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${o+1}/${l.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const u=Uu(l,o);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${o+1}/${l.maxNumRetry} after "${t}" in ${u}ms`)}e.levelRetry=!0,n.resolved=!0}return d}}function Jy(s,e){if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(!Ia(s[t].attrs,e[t].attrs))return!1;return!0}function Ia(s,e,t){const r=s["STABLE-RENDITION-ID"];return r&&!t?r===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(n=>s[n]!==e[n])}function Id(s,e){return e.label.toLowerCase()===s.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(s.lang||"").toLowerCase())}class XN extends Zu{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:r,groupId:n,details:i}=t,o=this.tracksInGroup[r];if(!o||o.groupId!==n){this.warn(`Audio track with id:${r} and group:${n} not found in active group ${o==null?void 0:o.groupId}`);return}const l=o.details;o.details=t.details,this.log(`Audio track ${r} "${o.name}" lang:${o.lang} group:${n} loaded [${i.startSN}-${i.endSN}]`),r===this.trackId&&this.playlistLoaded(r,t,l)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const r=t.audioGroups||null,n=this.groupIds;let i=this.currentTrack;if(!r||(n==null?void 0:n.length)!==(r==null?void 0:r.length)||r!=null&&r.some(l=>(n==null?void 0:n.indexOf(l))===-1)){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const l=this.tracks.filter(f=>!r||r.indexOf(f.groupId)!==-1);if(l.length)this.selectDefaultTrack&&!l.some(f=>f.default)&&(this.selectDefaultTrack=!1),l.forEach((f,m)=>{f.id=m});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=l;const d=this.hls.config.audioPreference;if(!i&&d){const f=fr(d,l,vn);if(f>-1)i=l[f];else{const m=fr(d,this.tracks);i=this.tracks[m]}}let c=this.findTrackId(i);c===-1&&i&&(c=this.findTrackId(null));const u={audioTracks:l};this.log(`Updating audio tracks, ${l.length} track(s) found in group(s): ${r==null?void 0:r.join(",")}`),this.hls.trigger(E.AUDIO_TRACKS_UPDATED,u);const h=this.trackId;if(c!==-1&&h===-1)this.setAudioTrack(c);else if(l.length&&h===-1){var o;const f=new Error(`No audio track selected for current audio group-ID(s): ${(o=this.groupIds)==null?void 0:o.join(",")} track count: ${l.length}`);this.warn(f.message),this.hls.trigger(E.ERROR,{type:Re.MEDIA_ERROR,details:z.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}}onError(e,t){t.fatal||!t.context||t.context.type===tt.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){const n=this.currentTrack;if(n&&Sn(e,n,vn))return n;const i=fr(e,this.tracksInGroup,vn);if(i>-1){const o=this.tracksInGroup[i];return this.setAudioTrack(i),o}else if(n){let o=t.loadLevel;o===-1&&(o=t.firstAutoLevel);const l=lC(e,t.levels,r,o,vn);if(l===-1)return null;t.nextLoadLevel=l}if(e.channels||e.audioCodec){const o=fr(e,r);if(o>-1)return r[o]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const r=this.currentTrack,n=t[e],i=n.details&&!n.details.live;if(e===this.trackId&&n===r&&i||(this.log(`Switching to audio-track ${e} "${n.name}" lang:${n.lang} group:${n.groupId} channels:${n.channels}`),this.trackId=e,this.currentTrack=n,this.hls.trigger(E.AUDIO_TRACK_SWITCHING,yt({},n)),i))return;const o=this.switchParams(n.url,r==null?void 0:r.details,n.details);this.loadPlaylist(o)}findTrackId(e){const t=this.tracksInGroup;for(let r=0;r<t.length;r++){const n=t[r];if(!(this.selectDefaultTrack&&!n.default)&&(!e||Sn(e,n,vn)))return r}if(e){const{name:r,lang:n,assocLang:i,characteristics:o,audioCodec:l,channels:d}=e;for(let c=0;c<t.length;c++){const u=t[c];if(Sn({name:r,lang:n,assocLang:i,characteristics:o,audioCodec:l,channels:d},u,vn))return c}for(let c=0;c<t.length;c++){const u=t[c];if(Ia(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c}for(let c=0;c<t.length;c++){const u=t[c];if(Ia(e.attrs,u.attrs,["LANGUAGE"]))return c}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&il(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const r=e.id,n=e.groupId,i=this.getUrlWithDirectives(e.url,t),o=e.details,l=o==null?void 0:o.age;this.log(`Loading audio-track ${r} "${e.name}" lang:${e.lang} group:${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${l&&o.live?" age "+l.toFixed(1)+(o.type&&" "+o.type||""):""} ${i}`),this.hls.trigger(E.AUDIO_TRACK_LOADING,{url:i,id:r,groupId:n,deliveryDirectives:t||null,track:e})}}class QN{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,r){if(this.queues===null||this.tracks===null)return;const n=this.queues[t];n.push(e),n.length===1&&!r&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const r={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(r,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const r={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(r)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const r=(t=e[0])==null?void 0:t.label;(r==="async-blocker"||r==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const n=t[0];try{n.execute()}catch(i){var r;if(n.onError(i),this.queues===null||this.tracks===null)return;const o=(r=this.tracks[e])==null?void 0:r.buffer;o!=null&&o.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
683${this.list("video")}
684${this.list("audio")}
685${this.list("audiovideo")}}`}list(e){var t,r;return(t=this.queues)!=null&&t[e]||(r=this.tracks)!=null&&r[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const r=(t=this.tracks)==null?void 0:t[e],n=r==null?void 0:r.buffer;return n?`SourceBuffer${n.updating?" updating":""}${r.ended?" ended":""}${r.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(r=>r.label).join(", "))||""}}const Km=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Zy="HlsJsTrackRemovedError";class JN extends Error{constructor(e){super(e),this.name=Zy}}class ZN extends Hs{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=r=>{var n;this.hls&&((n=this.mediaSource)==null?void 0:n.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=r=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=r=>{const{media:n,mediaSource:i}=this;r&&this.log("Media source opened"),!(!n||!i)&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(E.MEDIA_ATTACHED,{media:n,mediaSource:i}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:r,_objectUrl:n}=this;r!==n&&this.error(`Media element src was set while attaching MediaSource (${n} > ${r})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=_I(rn(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_APPENDING,this.onBufferAppending,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.BUFFER_EOS,this.onBufferEos,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.FRAG_PARSED,this.onFragParsed,this),e.on(E.FRAG_CHANGED,this.onFragChanged,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_APPENDING,this.onBufferAppending,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_EOS,this.onBufferEos,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.FRAG_PARSED,this.onFragParsed,this),e.off(E.FRAG_CHANGED,this.onFragChanged,this),e.off(E.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const r={};if(this.operationQueue){const i=this.isUpdating();i||this.operationQueue.removeBlockers();const o=this.isQueued();(i||o)&&this.warn(`Transfering MediaSource with${o?" operations in queue":""}${i?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const n=this.transferData;return!this.sourceBufferCount&&n&&n.mediaSource===t?Tt(r,n.tracks):this.sourceBuffers.forEach(i=>{const[o]=i;o&&(r[o]=Tt({},this.tracks[o]),this.removeBuffer(o)),i[0]=i[1]=null}),{media:e,mediaSource:t,tracks:r}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var r;let n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsTotal=n,this.log(`${n}
685 bufferCodec event(s) expected.`),(r=this.transferData)!=null&&r.mediaSource&&this.sourceBufferCount&&n&&this.bufferCreated()}onMediaAttaching(e,t){const r=this.media=t.media;this.transferData=this.overrides=void 0;const n=rn(this.appendSource);if(n){const i=!!t.mediaSource;(i||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const o=this.mediaSource=t.mediaSource||new n;if(this.assignMediaSource(o),i)this._objectUrl=r.src,this.attachTransferred();else{const l=this._objectUrl=self.URL.createObjectURL(o);if(this.appendSource)try{r.removeAttribute("src");const d=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||d&&o instanceof d,Wm(r),eL(r,l),r.load()}catch{r.src=l}else r.src=l}r.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,r;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(r=e.constructor)==null?void 0:r.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const r=this.tracks,n=t.tracks,i=n?Object.keys(n):null,o=i?i.length:0,l=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(n&&i&&o){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
686required tracks: ${Rt(r,(d,c)=>d==="initSegment"?void 0:c)};
687transfer tracks: ${Rt(n,(d,c)=>d==="initSegment"?void 0:c)}}`),!Yx(n,r)){t.mediaSource=null,t.tracks=void 0;const d=e.currentTime,c=this.details,u=Math.max(d,(c==null?void 0:c.fragments[0].start)||0);if(u-d>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${d} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(n)}"->"${Object.keys(r)}") start time: ${u} currentTime: ${d}`),this.onMediaDetaching(E.MEDIA_DETACHING,{}),this.onMediaAttaching(E.MEDIA_ATTACHING,t),e.currentTime=u;return}this.transferData=void 0,i.forEach(d=>{const c=d,u=n[c];if(u){const h=u.buffer;if(h){const f=this.fragmentTracker,m=u.id;if(f.hasFragments(m)||f.hasParts(m)){const y=Ue.getBuffered(h);f.detectEvictedFragments(c,y,m,null,!0)}const p=Sc(c),x=[c,h];this.sourceBuffers[p]=x,h.updating&&this.operationQueue&&this.operationQueue.prependBlocker(c),this.trackSourceBuffer(c,u)}}}),l(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),l()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const r=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:i,_objectUrl:o}=this;if(i){if(this.log(`media source ${r?"transferring":"detaching"}`),r)this.sourceBuffers.forEach(([l])=>{l&&this.removeBuffer(l)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const l=i.readyState==="open";try{const d=i.sourceBuffers;for(let c=d.length;c--;)l&&d[c].abort(),i.removeSourceBuffer(d[c]);l&&i.endOfStream()}catch(d){this.warn(`onMediaDetaching: ${d.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}i.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("sourceended",this._onMediaSourceEnded),i.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(i.removeEventListener("startstreaming",this._onStartStreaming),i.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),r||(o&&self.URL.revokeObjectURL(o),this.mediaSrc===o?(n.removeAttribute("src"),this.appendSource&&Wm(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(E.MEDIA_DETACHED,t)}
vendor: 15,181 bytes, line 687
687onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const r=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),r)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(i){this.warn(`onBufferReset ${e}`,i)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Sc(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new QN(this.tracks)}onBufferCodecs(e,t){var r;const n=this.tracks,i=Object.keys(t);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const o="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),l=!o&&this.sourceBufferCount&&this.media&&i.some(d=>!n[d]);if(o||l){this.warn(`Unsupported transition between "${Object.keys(n)}" and "${i}" SourceBuffers`);return}i.forEach(d=>{var c,u;const h=t[d],{id:f,codec:m,levelCodec:p,container:x,metadata:y,supplemental:v}=h;let _=n[d];const b=(c=this.transferData)==null||(c=c.tracks)==null?void 0:c[d],w=b!=null&&b.buffer?b:_,T=(w==null?void 0:w.pendingCodec)||(w==null?void 0:w.codec),A=w==null?void 0:w.levelCodec;_||(_=n[d]={buffer:void 0,listeners:[],codec:m,supplemental:v,container:x,levelCodec:p,metadata:y,id:f});const S=Ao(T,A),I=S==null?void 0:S.replace(Km,"$1");let j=Ao(m,p);const R=(u=j)==null?void 0:u.replace(Km,"$1");j&&S&&I!==R&&(d.slice(0,5)==="audio"&&(j=rl(j,this.appendSource)),this.log(`switching codec ${T} to ${j}`),j!==(_.pendingCodec||_.codec)&&(_.pendingCodec=j),_.container=x,this.appendChangeType(d,x,j))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((r=t.audio)==null?void 0:r.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const r=this.tracks[t];return e[t]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},e},{})}appendChangeType(e,t,r){const n=`${t};codecs=${r}`,i={label:`change-type=${n}`,execute:()=>{const o=this.tracks[e];if(o){const l=o.buffer;l!=null&&l.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),l.changeType(n),o.codec=r,o.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn(`Failed to change ${e} SourceBuffer type`,o)}};this.append(i,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const r=e.start,n=r+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(r,we.MAIN))==null?void 0:t.gap)===!0)return;const o={label:"block-audio",execute:()=>{var l;const d=this.tracks.video;(this.lastVideoAppendEnd>n||d!=null&&d.buffer&&Ue.isBuffered(d.buffer,n)||((l=this.fragmentTracker.getAppendedFrag(n,we.MAIN))==null?void 0:l.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:l=>{this.warn("Error executing block-audio operation",l)}};this.blockedAudioAppend={op:o,frag:e},this.append(o,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:r}=this,{data:n,type:i,parent:o,frag:l,part:d,chunkMeta:c,offset:u}=t,h=c.buffering[i],{sn:f,cc:m}=l,p=self.performance.now();h.start=p;const x=l.stats.buffering,y=d?d.stats.buffering:null;x.start===0&&(x.start=p),y&&y.start===0&&(y.start=p);const v=r.audio;let _=!1;i==="audio"&&(v==null?void 0:v.container)==="audio/mpeg"&&(_=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const b=r.video,w=b==null?void 0:b.buffer;if(w&&f!=="initSegment"){const S=d||l,I=this.blockedAudioAppend;if(i==="audio"&&o!=="main"&&!this.blockedAudioAppend&&!(b.ending||b.ended)){const R=S.start+S.duration*.05,k=w.buffered,D=this.currentOp("video");!k.length&&!D?this.blockAudio(S):!D&&!Ue.isBuffered(w,R)&&this.lastVideoAppendEnd<R&&this.blockAudio(S)}else if(i==="video"){const j=S.end;if(I){const R=I.frag.start;(j>R||j<this.lastVideoAppendEnd||Ue.isBuffered(w,R))&&this.unblockAudio()}this.lastVideoAppendEnd=j}}const T=(d||l).start,A={label:`append-${i}`,execute:()=>{var S;h.executeStart=self.performance.now();const I=(S=this.tracks[i])==null?void 0:S.buffer;I&&(_?this.updateTimestampOffset(I,T,.1,i,f,m):u!==void 0&&xe(u)&&this.updateTimestampOffset(I,u,1e-6,i,f,m)),this.appendExecutor(n,i)},onStart:()=>{},onComplete:()=>{const S=self.performance.now();h.executeEnd=h.end=S,x.first===0&&(x.first=S),y&&y.first===0&&(y.first=S);const I={};this.sourceBuffers.forEach(([j,R])=>{j&&(I[j]=Ue.getBuffered(R))}),this.appendErrors[i]=0,i==="audio"||i==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(E.BUFFER_APPENDED,{type:i,frag:l,part:d,chunkMeta:c,parent:l.type,timeRanges:I})},onError:S=>{var I;const j={type:Re.MEDIA_ERROR,parent:l.type,details:z.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:l,part:d,chunkMeta:c,error:S,err:S,fatal:!1},R=(I=this.media)==null?void 0:I.error;if(S.code===DOMException.QUOTA_EXCEEDED_ERR||S.name=="QuotaExceededError"||"quota"in S)j.details=z.BUFFER_FULL_ERROR;else if(S.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!R)j.errorAction=hi(!0);else if(S.name===Zy&&this.sourceBufferCount===0)j.errorAction=hi(!0);else{const k=++this.appendErrors[i];this.warn(`Failed ${k}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${R||"no media error"})`),(k>=this.hls.config.appendErrorMaxRetry||R)&&(j.fatal=!0)}this.hls.trigger(E.ERROR,j)}};this.log(`queuing "${i}" append sn: ${f}${d?" p: "+d.index:""} of ${l.type===we.MAIN?"level":"track"} ${l.level} cc: ${m}`),this.append(A,i,this.isPending(this.tracks[i]))}getFlushOp(e,t,r){return this.log(`queuing "${e}" remove ${t}-${r}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,r)},onStart:()=>{},onComplete:()=>{this.hls.trigger(E.BUFFER_FLUSHED,{type:e})},onError:n=>{this.warn(`Failed to remove ${t}-${r} from "${e}" SourceBuffer`,n)}}}onBufferFlushing(e,t){const{type:r,startOffset:n,endOffset:i}=t;r?this.append(this.getFlushOp(r,n,i),r):this.sourceBuffers.forEach(([o])=>{o&&this.append(this.getFlushOp(o,n,i),o)})}onFragParsed(e,t){const{frag:r,part:n}=t,i=[],o=n?n.elementaryStreams:r.elementaryStreams;o[kt.AUDIOVIDEO]?i.push("audiovideo"):(o[kt.AUDIO]&&i.push("audio"),o[kt.VIDEO]&&i.push("video"));const l=()=>{const d=self.performance.now();r.stats.buffering.end=d,n&&(n.stats.buffering.end=d);const c=n?n.stats:r.stats;this.hls.trigger(E.FRAG_BUFFERED,{frag:r,part:n,stats:c,id:r.type})};i.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${r.type} level: ${r.level} sn: ${r.sn}`),this.blockBuffers(l,i).catch(d=>{this.warn(`Fragment buffered callback ${d}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var r;this.sourceBuffers.forEach(([o])=>{if(o){const l=this.tracks[o];(!t.type||t.type===o)&&(l.ending=!0,l.ended||(l.ended=!0,this.log(`${o} buffer reached EOS`)))}});const n=((r=this.overrides)==null?void 0:r.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([o])=>{var l;return o&&!((l=this.tracks[o])!=null&&l.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:o}=this;if(!o||o.readyState!=="open"){o&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${o.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),o.endOfStream(),this.hls.trigger(E.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(E.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===z.BUFFER_APPEND_ERROR&&t.frag){var r;const n=(r=t.errorAction)==null?void 0:r.nextAutoLevel;xe(n)&&n!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:r}=this;if(!r||t===null||!this.sourceBufferCount)return;const n=e.config,i=r.currentTime,o=t.levelTargetDuration,l=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(xe(l)&&l>=0){const c=Math.max(l,o),u=Math.floor(i/o)*o-c;this.flushBackBuffer(i,o,u)}const d=n.frontBufferFlushThreshold;if(xe(d)&&d>0){const c=Math.max(n.maxBufferLength,d),u=Math.max(c,o),h=Math.floor(i/o)*o+u;this.flushFrontBuffer(i,o,h)}}flushBackBuffer(e,t,r){this.sourceBuffers.forEach(([n,i])=>{if(i){const l=Ue.getBuffered(i);if(l.length>0&&r>l.start(0)){var o;this.hls.trigger(E.BACK_BUFFER_REACHED,{bufferEnd:r});const d=this.tracks[n];if((o=this.details)!=null&&o.live)this.hls.trigger(E.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(d!=null&&d.ended){this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:n})}}})}flushFrontBuffer(e,t,r){this.sourceBuffers.forEach(([n,i])=>{if(i){const o=Ue.getBuffered(i),l=o.length;if(l<2)return;const d=o.start(l-1),c=o.end(l-1);if(r>d||e>=d&&e<=c)return;this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:d,endOffset:1/0,type:n})}})}getDurationAndRange(){var e;const{details:t,mediaSource:r}=this;if(!t||!this.media||(r==null?void 0:r.readyState)!=="open")return null;const n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&r.setLiveSeekableRange){const c=Math.max(0,t.fragmentStart),u=Math.max(c,n);return{duration:1/0,start:c,end:u}}return{duration:1/0}}const i=(e=this.overrides)==null?void 0:e.duration;if(i)return xe(i)?{duration:i}:null;const o=this.media.duration,l=xe(r.duration)?r.duration:0;return n>l&&n>o||!xe(o)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:r}){const n=this.mediaSource;!this.media||!n||n.readyState!=="open"||(n.duration!==e&&(xe(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),n.duration=e),t!==void 0&&r!==void 0&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${t}-${r}.`),n.setLiveSeekableRange(t,r)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:r}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Rt(r)}`),this.tracksReady){var n;const i=(n=this.transferData)==null?void 0:n.tracks;i&&Object.keys(i).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,r])=>{if(t){const n=this.tracks[t];e[t]={buffer:r,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}}),this.hls.trigger(E.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(E.ERROR,{type:Re.MEDIA_ERROR,details:z.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:r}=this;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(const i in e){const o=i,l=e[o];if(this.isPending(l)){const d=this.getTrackCodec(l,o),c=`${l.container};codecs=${d}`;l.codec=d,this.log(`creating sourceBuffer(${c})${this.currentOp(o)?" Queued":""} ${Rt(l)}`);try{const u=r.addSourceBuffer(c),h=Sc(o),f=[o,u];t[h]=f,l.buffer=u}catch(u){var n;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(o),(n=this.operationQueue)==null||n.removeBlockers(),delete this.tracks[o],this.hls.trigger(E.ERROR,{type:Re.MEDIA_ERROR,details:z.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:o,mimeType:c,parent:l.id});return}this.trackSourceBuffer(o,l)}}this.bufferCreated()}getTrackCodec(e,t){const r=e.supplemental;let n=e.codec;r&&(t==="video"||t==="audiovideo")&&Sa(r,"video")&&(n=GI(n,r));const i=Ao(n,e.levelCodec);return i?t.slice(0,5)==="audio"?rl(i,this.appendSource):i:""}trackSourceBuffer(e,t){const r=t.buffer;if(!r)return;const n=this.getTrackCodec(t,e);this.tracks[e]={buffer:r,codec:n,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(i,o)=>{const l=o.removedRanges;l!=null&&l.length&&this.hls.trigger(E.BUFFER_FLUSHED,{type:i})})}get mediaSrc(){var e,t;const r=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return r==null?void 0:r.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const r=this.currentOp(e);r&&(r.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var r;const n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(r=this.mediaSource)==null?void 0:r.readyState}`);this.error(`${n}`,t),this.hls.trigger(E.ERROR,{type:Re.MEDIA_ERROR,details:z.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const i=this.currentOp(e);i&&i.onError(n)}updateTimestampOffset(e,t,r,n,i,o){const l=t-e.timestampOffset;Math.abs(l)>=r&&(this.log(`Updating ${n} SourceBuffer timestampOffset to ${t} (sn: ${i} cc: ${o})`),e.timestampOffset=t)}removeExecutor(e,t,r){const{media:n,mediaSource:i}=this,o=this.tracks[e],l=o==null?void 0:o.buffer;if(!n||!i||!l){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const d=xe(n.duration)?n.duration:1/0,c=xe(i.duration)?i.duration:1/0,u=Math.max(0,t),h=Math.min(r,d,c);h>u&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${u},${h}] from the ${e} SourceBuffer`),l.remove(u,h)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const r=this.tracks[t],n=r==null?void 0:r.buffer;if(!n)throw new JN(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);r.ending=!1,r.ended=!1,n.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}
687`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:r}=this,n=t.map(o=>this.appendBlocker(o));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(o=>{r===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var r;const n=(r=this.tracks[t])==null?void 0:r.buffer;!n||n.updating||this.shiftAndExecuteNext(t)})}append(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,r)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,r){const n=this.tracks[e];if(!n)return;const i=n.buffer;if(!i)return;const o=r.bind(this,e);n.listeners.push({event:t,listener:o}),i.addEventListener(t,o)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const r=t.buffer;r&&(t.listeners.forEach(n=>{r.removeEventListener(n.event,n.listener)}),t.listeners.length=0)}}function Wm(s){const e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t)})}function eL(s,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t)}function Sc(s){return s==="audio"?1:0}class eh{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const r=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,r.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&xe(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${r}: ${e[r].height}p@${e[r].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=r,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const r=t.filter((n,i)=>this.isLevelAllowed(n)&&i<=e);return this.clientRect=null,eh.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,!t.width&&!t.height&&(t.width=r.right-r.left||e.
vendor: 4,444 bytes, line 687
687width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(r=>e.bitrate===r.bitrate&&e.width===r.width&&e.height===r.height)}static getMaxLevelByMediaSize(e,t,r){if(!(e!=null&&e.length))return-1;const n=(l,d)=>d?l.width!==d.width||l.height!==d.height:!0;let i=e.length-1;const o=Math.max(t,r);for(let l=0;l<e.length;l+=1){const d=e[l];if((d.width>=o||d.height>=o)&&n(d,e[l+1])){i=l;break}}return i}}const tL={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},vs=tL,sL={HLS:"h"},rL=sL;class xr{constructor(e,t){Array.isArray(e)&&(e=e.map(r=>r instanceof xr?r:new xr(r))),this.value=e,this.params=t}}const nL="Dict";function iL(s){return Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":typeof s=="object"?JSON.stringify(s):String(s)}function aL(s,e,t,r){return new Error(`failed to ${s} "${iL(e)}" as ${t}`,{cause:r})}function yr(s,e,t){return aL("serialize",s,e,t)}class ev{constructor(e){this.description=e}}const Ym="Bare Item",oL="Boolean";function lL(s){if(typeof s!="boolean")throw yr(s,oL);return s?"?1":"?0"}function cL(s){return btoa(String.fromCharCode(...s))}const dL="Byte Sequence";function uL(s){if(ArrayBuffer.isView(s)===!1)throw yr(s,dL);return`:${cL(s)}:`}const hL="Integer";function fL(s){return s<-999999999999999||999999999999999<s}function tv(s){if(fL(s))throw yr(s,hL);return s.toString()}function mL(s){return`@${tv(s.getTime()/1e3)}`}function sv(s,e){if(s<0)return-sv(-s,e);const t=Math.pow(10,e);if(Math.abs(s*t%1-.5)<Number.EPSILON){const n=Math.floor(s*t);return(n%2===0?n:n+1)/t}else return Math.round(s*t)/t}const pL="Decimal";function gL(s){const e=sv(s,3);if(Math.floor(Math.abs(e)).toString().length>12)throw yr(s,pL);const t=e.toString();return t.includes(".")?t:`${t}.0`}const xL="String",yL=/[\x00-\x1f\x7f]+/;function vL(s){if(yL.test(s))throw yr(s,xL);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function bL(s){return s.description||s.toString().slice(7,-1)}const _L="Token";function Xm(s){const e=bL(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw yr(e,_L);return e}function Cd(s){switch(typeof s){case"number":if(!xe(s))throw yr(s,Ym);return Number.isInteger(s)?tv(s):gL(s);case"string":return vL(s);case"symbol":return Xm(s);case"boolean":return lL(s);case"object":if(s instanceof Date)return mL(s);if(s instanceof Uint8Array)return uL(s);if(s instanceof ev)return Xm(s);default:throw yr(s,Ym)}}const wL="Key";function Nd(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw yr(s,wL);return s}function th(s){return s==null?"":Object.entries(s).map(([e,t])=>t===!0?`;${Nd(e)}`:`;${Nd(e)}=${Cd(t)}`).join("")}function rv(s){return s instanceof xr?`${Cd(s.value)}${th(s.params)}`:Cd(s)}function EL(s){return`(${s.value.map(rv).join(" ")})${th(s.params)}`}function SL(s,e={whitespace:!0}){if(typeof s!="object"||s==null)throw yr(s,nL);const t=s instanceof Map?s.entries():Object.entries(s),r=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([n,i])=>{i instanceof xr||(i=new xr(i));let o=Nd(n);return i.value===!0?o+=th(i.params):(o+="=",Array.isArray(i.value)?o+=EL(i):o+=rv(i)),o}).join(`,${r}`)}function nv(s,e){return SL(s,e)}const or="CMCD-Object",Vt="CMCD-Request",fn="CMCD-Session",Gr="CMCD-Status",TL={br:or,ab:or,d:or,ot:or,tb:or,tpb:or,lb:or,tab:or,lab:or,url:or,pb:Vt,bl:Vt,tbl:Vt,dl:Vt,ltc:Vt,mtp:Vt,nor:Vt,nrr:Vt,rc:Vt,sn:Vt,sta:Vt,su:Vt,ttfb:Vt,ttfbb:Vt,ttlb:Vt,cmsdd:Vt,cmsds:Vt,smrt:Vt,df:Vt,cs:Vt,ts:Vt,cid:fn,pr:fn,sf:fn,sid:fn,st:fn,v:fn,msd:fn,bs:Gr,bsd:Gr,cdn:Gr,rtp:Gr,bg:Gr,pt:Gr,ec:Gr,e:Gr},AL={REQUEST:Vt};function kL(s){return Object.keys(s).reduce((e,t)=>{var r;return(r=s[t])===null||r===void 0||r.forEach(n=>e[n]=t),e},{})}function RL(s,e){const t={};if(!s)return t;const r=Object.keys(s),n=e?kL(e):{};return r.reduce((i,o)=>{var l;const d=TL[o]||n[o]||AL.REQUEST,c=(l=i[d])!==null&&l!==void 0?l:i[d]={};return c[o]=s[o],i},t)}function jL(s){return["ot","sf","st","e","sta"].includes(s)}function IL(s){return typeof s=="number"?xe(s):s!=null&&s!==""&&s!==!1}const iv="event";
687function CL(s,e){const t=new URL(s),r=new URL(e);if(t.origin!==r.origin)return s;const n=t.pathname.split("/").slice(1),i=r.pathname.split("/").slice(1,-1);for(;n[0]===i[0];)n.shift(),i.shift();for(;i.length;)i.shift(),n.unshift("..");return n.join("/")+t.search+t.hash}const Co=s=>Math.round(s),Ld=(s,e)=>Array.isArray(s)?s.map(t=>Ld(t,e)):s instanceof xr&&typeof s.value=="string"?new xr(Ld(s.value,e),s.params):(e.baseUrl&&(s=CL(s,e.baseUrl)),e.version===1?encodeURIComponent(s):s),ao=s=>Co(s/100)*100,NL=(s,e)=>{let t=s;return e.version>=2&&(s instanceof xr&&typeof s.value=="string"?t=new xr([s]):typeof s=="string"&&(t=[s])),Ld(t,e)},LL={br:Co,d:Co,bl:ao,dl:ao,mtp:ao,nor:NL,rtp:ao,tb:Co},av="request",ov="response",sh=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],PL=["e"],DL=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Ll(s){return DL.test(s)}function OL(s){return sh.includes(s)||PL.includes(s)||Ll(s)}const lv=["d","dl","nor","ot","rtp","su"];function ML(s){return sh.includes(s)||lv.includes(s)||Ll(s)}const FL=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function $L(s){return sh.includes(s)||lv.includes(s)||FL.includes(s)||Ll(s)}const UL=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function BL(s){return UL.includes(s)||Ll(s)}const VL={[ov]:$L,[iv]:OL,[av]:ML};function cv(s,e={}){const t={};if(s==null||typeof s!="object")return t;const r=e.version||s.v||1,n=e.reportingMode||av,i=r===1?BL:VL[n];let o=Object.keys(s).filter(i);const l=e.filter;typeof l=="function"&&(o=o.filter(l));const d=n===ov||n===iv;d&&!o.includes("ts")&&o.push("ts"),r>1&&!o.includes("v")&&o.push("v");const c=Tt({},LL,e.formatters),u={version:r,reportingMode:n,baseUrl:e.baseUrl};return o.sort().forEach(h=>{let f=s[h];const m=c[h];if(typeof m=="function"&&(f=m(f,u)),h==="v"){if(r===1)return;f=r}h=="pr"&&f===1||(d&&h==="ts"&&!xe(f)&&(f=Date.now()),IL(f)&&(jL(h)&&typeof f=="string"&&(f=new ev(f)),t[h]=f))}),t}function GL(s,e={}){const t={};if(!s)return t;const r=cv(s,e),n=RL(r,e==null?void 0:e.customHeaderMap);return Object.entries(n).reduce((i,[o,l])=>{const d=nv(l,{whitespace:!1});return d&&(i[o]=d),i},t)}function zL(s,e,t){return Tt(s,GL(e,t))}const qL="CMCD";function HL(s,e={}){return s?nv(cv(s,e),{whitespace:!1}):""}function KL(s,e={}){if(!s)return"";const t=HL(s,e);return encodeURIComponent(t)}function WL(s,e={}){if(!s)return"";const t=KL(s,e);return`${qL}=${t}`}const Qm=/CMCD=[^&#]+/;function YL(s,e,t){const r=WL(e,t);if(!r)return s;if(Qm.test(s))return s.replace(Qm,r);const n=s.includes("?")?"&":"?";return`${s}${n}${r}`}class XL{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=n=>{try{this.apply(n,{ot:vs.MANIFEST,su:!this.initialized})}catch(i){this.hls.logger.warn("Could not generate manifest CMCD data.",i)}},this.applyFragmentData=n=>{try{const{frag:i,part:o}=n,l=this.hls.levels[i.level],d=this.getObjectType(i),c={d:(o||i).duration*1e3,ot:d};(d===vs.VIDEO||d===vs.AUDIO||d==vs.MUXED)&&(c.br=l.bitrate/1e3,c.tb=this.getTopBandwidth(d)/1e3,c.bl=this.getBufferLength(d));const u=o?this.getNextPart(o):this.getNextFrag(i);u!=null&&u.url&&u.url!==i.url&&(c.nor=u.url),this.apply(n,c)}catch(i){this.hls.logger.warn("Could not generate segment CMCD data.",i)}},this.hls=e;const t=this.config=e.config,{cmcd:r}=t;r!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||e.sessionId,this.cid=r.contentId,this.useHeaders=r.useHeaders===!0,this.includeKeys=r.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHED,this.onMediaDetached,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;
687e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHED,this.onMediaDetached,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var r,n;this.audioBuffer=(r=t.tracks.audio)==null?void 0:r.buffer,this.videoBuffer=(n=t.tracks.video)==null?void 0:n.buffer}createData(){var e;return{v:1,sf:rL.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Tt(t,this.createData());const r=t.ot===vs.INIT||t.ot===vs.VIDEO||t.ot===vs.MUXED;this.starved&&r&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:n}=this;n&&(t=Object.keys(t).reduce((o,l)=>(n.includes(l)&&(o[l]=t[l]),o),{}));const i={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),zL(e.headers,t,i)):e.url=YL(e.url,t,i)}getNextFrag(e){var t;const r=(t=this.hls.levels[e.level])==null?void 0:t.details;if(r){const n=e.sn-r.startSN;return r.fragments[n+1]}}getNextPart(e){var t;const{index:r,fragment:n}=e,i=(t=this.hls.levels[n.level])==null||(t=t.details)==null?void 0:t.partList;if(i){const{sn:o}=n;for(let l=i.length-1;l>=0;l--){const d=i[l];if(d.index===r&&d.fragment.sn===o)return i[l+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return vs.TIMED_TEXT;if(e.sn==="initSegment")return vs.INIT;if(t==="audio")return vs.AUDIO;if(t==="main")return this.hls.audioTracks.length?vs.VIDEO:vs.MUXED}getTopBandwidth(e){let t=0,r;const n=this.hls;if(e===vs.AUDIO)r=n.audioTracks;else{const i=n.maxAutoLevel,o=i>-1?i+1:n.levels.length;r=n.levels.slice(0,o)}return r.forEach(i=>{i.bitrate>t&&(t=i.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,r=e===vs.AUDIO?this.audioBuffer:this.videoBuffer;return!r||!t?NaN:Ue.bufferInfo(r,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,r=e||this.config.loader;return class{constructor(i){this.loader=void 0,this.loader=new r(i)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(i,o,l){t(i),this.loader.load(i,o,l)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,r=e||this.config.loader;return class{constructor(i){this.loader=void 0,this.loader=new r(i)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(i,o,l){t(i),this.loader.load(i,o,l)}}}}const QL=3e5;class JL extends Hs{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(r=>r!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:r}=t;r!==null&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:r}=t;if((r==null?void 0:r.action)===os.SendAlternateToPenaltyBox&&r.flags===Is.MoveAllAlternatesMatchingHost){const n=this.levels;let i=this._pathwayPriority,o=this.pathwayId;if(t.context){const{groupId:l,pathwayId:d,type:c}=t.context;l&&n?o=this.getPathwayForGroupId(l,c,o):d&&(o=d)}o in this.penalizedPathways||(this.penalizedPathways[o]=performance.now()),!i&&n&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),r.resolved=this.pathwayId!==o),t.details===z.BUFFER_APPEND_ERROR&&!t.fatal?r.resolved=!0:r.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${o} levels: ${n&&n.length} priorities: ${Rt(i)} penalized: ${Rt(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const r=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${r}"`),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const r=this.penalizedPathways,n=performance.now();Object.keys(r).forEach(i=>
vendor: 4,364 bytes, line 687
687{n-r[i]>QL&&delete r[i]});for(let i=0;i<e.length;i++){const o=e[i];if(o in r)continue;if(o===this.pathwayId)return;const l=this.hls.nextLoadLevel,d=this.hls.levels[l];if(t=this.getLevelsForPathway(o),t.length>0){this.log(`Setting Pathway to "${o}"`),this.pathwayId=o,jy(t),this.hls.trigger(E.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[l];d&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==d.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==d.bitrate&&this.log(`Unstable Pathways change from bitrate ${d.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=l);break}}}getPathwayForGroupId(e,t,r){const n=this.getLevelsForPathway(r).concat(this.levels||[]);for(let i=0;i<n.length;i++)if(t===tt.AUDIO_TRACK&&n[i].hasAudioGroup(e)||t===tt.SUBTITLE_TRACK&&n[i].hasSubtitleGroup(e))return n[i].pathwayId;return r}clonePathways(e){const t=this.levels;if(!t)return;const r={},n={};e.forEach(i=>{const{ID:o,"BASE-ID":l,"URI-REPLACEMENT":d}=i;if(t.some(u=>u.pathwayId===o))return;const c=this.getLevelsForPathway(l).map(u=>{const h=new Dt(u.attrs);h["PATHWAY-ID"]=o;const f=h.AUDIO&&`${h.AUDIO}_clone_${o}`,m=h.SUBTITLES&&`${h.SUBTITLES}_clone_${o}`;f&&(r[h.AUDIO]=f,h.AUDIO=f),m&&(n[h.SUBTITLES]=m,h.SUBTITLES=m);const p=dv(u.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",d),x=new Aa({attrs:h,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:p,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let y=1;y<u.audioGroups.length;y++)x.addGroupId("audio",`${u.audioGroups[y]}_clone_${o}`);if(u.subtitleGroups)for(let y=1;y<u.subtitleGroups.length;y++)x.addGroupId("text",`${u.subtitleGroups[y]}_clone_${o}`);return x});t.push(...c),Jm(this.audioTracks,r,d,o),Jm(this.subtitleTracks,n,d,o)})}loadSteeringManifest(e){const t=this.hls.config,r=t.loader;this.loader&&this.loader.destroy(),this.loader=new r(t);let n;try{n=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(n.protocol!=="data:"){const u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+u)}const i={responseType:"json",url:n.href},o=t.steeringManifestLoadPolicy.default,l=o.errorRetry||o.timeoutRetry||{},d={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},c={onSuccess:(u,h,f,m)=>{this.log(`Loaded steering manifest: "${n}"`);const p=u.data;if((p==null?void 0:p.VERSION)!==1){this.log(`Steering VERSION ${p.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=p.TTL;const{"RELOAD-URI":x,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":v}=p;if(x)try{this.uri=new self.URL(x,n).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${x}`);return}this.scheduleRefresh(this.uri||f.url),y&&this.clonePathways(y);const _={steeringManifest:p,url:n.toString()};this.hls.trigger(E.STEERING_MANIFEST_LOADED,_),v&&this.updatePathwayPriority(v)},onError:(u,h,f,m)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${h.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let p=this.timeToLoad*1e3;if(u.code===429){const x=this.loader;if(typeof(x==null?void 0:x.getResponseHeader)=="function"){const y=x.getResponseHeader("Retry-After");y&&(p=parseFloat(y)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,p)},onTimeout:(u,h,f)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(i,d,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var r;const n=(r=this.hls)==null?void 0:r.media;if(n&&!n.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Jm(s,e,t,r){s&&Object.keys(e).forEach(n=>{const i=s.filter(o=>o.groupId===n).map(o=>{const l=Tt({},o);return l.details=void 0,l.attrs=new Dt(l.attrs),l.url=l.attrs.URI=dv(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),l.groupId=l.attrs["GROUP-ID"]=e[n],l.attrs["PATHWAY-ID"]=r,l});s.push(...i)})}function dv(s,e,t,r){const{HOST:n,PARAMS:i,[t]:o}=r;let l;e&&(l=o==null?void 0:o[e],l&&(s=l));const d=new self.URL(s);
687return n&&!l&&(d.host=n),i&&Object.keys(i).sort().forEach(c=>{c&&d.searchParams.set(c,i[c])}),d.href}class mi extends Hs{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=mi.CDMCleanupPromise?[mi.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:r,initData:n}=t,i=`"${t.type}" event: init data type: "${r}"`;if(this.debug(i),n!==null){if(!this.keyFormatPromise){let o=Object.keys(this.keySystemAccessPromises);o.length||(o=Qi(this.config));const l=o.map(gc).filter(d=>!!d);this.keyFormatPromise=this.getKeyFormatPromise(l)}this.keyFormatPromise.then(o=>{const l=Ro(o);if(r!=="sinf"||l!==Ft.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${r}" for selected key-system ${l}`);return}let d;try{const m=Zt(new Uint8Array(n)),p=zu(JSON.parse(m).sinf),x=ny(p);if(!x)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");d=new Uint8Array(x.subarray(8,24))}catch(m){this.warn(`${i} Failed to parse sinf: ${m}`);return}const c=ls(d),{keyIdToKeySessionPromise:u,mediaKeySessions:h}=this;let f=u[c];for(let m=0;m<h.length;m++){const p=h[m],x=p.decryptdata;if(!x.keyId)continue;const y=ls(x.keyId);if(ll(d,x.keyId)||x.uri.replace(/-/g,"").indexOf(c)!==-1){if(f=u[y],!f)continue;if(x.pssh)break;delete u[y],x.pssh=new Uint8Array(n),x.keyId=d,f=u[c]=f.then(()=>this.generateRequestWithPreferredKeySession(p,r,n,"encrypted-event-key-match")),f.catch(v=>this.handleError(v));break}}f||this.handleError(new Error(`Key ID ${c} not encountered in playlist. Key-system sessions ${h.length}.`))}).catch(o=>this.handleError(o))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(E.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(E.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:r}=this.config,n=t==null?void 0:t[e];if(n)return n.licenseUrl;if(e===Ft.WIDEVINE&&r)return r}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,r=t==null?void 0:t[e];if(r)return r.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,r=(o,l,d)=>!!o&&d.indexOf(o)===l,n=t.map(o=>o.audioCodec).filter(r),i=t.map(o=>o.videoCodec).filter(r);return n.length+i.length===0&&i.push("avc1.42e01e"),new Promise((o,l)=>{const d=c=>{const u=c.shift();this.getMediaKeysPromise(u,n,i).then(h=>o({keySystem:u,mediaKeys:h})).catch(h=>{c.length?d(c):h instanceof js?l(h):l(new js({type:Re.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};d(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:r}=this.config;if(typeof r!="function"){let n=`Configured requestMediaKeySystemAccess is not a function ${r}`;return _y===null&&self.location.protocol==="http:"&&(n=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(n))}return r(e,t)}getMediaKeysPromise(e,t,r){var n;const i=NC(e,t,r,this.config.drmSystemOptions||{});let o=this.keySystemAccessPromises[e],l=(n=o)==null?void 0:n.keySystemAccess;if(!l){this.log(`Requesting encrypted media "${e}" key-system access with config: ${Rt(i)}`),l=this.requestMediaKeySystemAccess(e,i);const d=o=this.keySystemAccessPromises[e]={keySystemAccess:l};return l.catch(c=>{this.log(`Failed to obtain access to key-system "${e}": ${c}`)}),l.then(c=>{this.log(`Access for key-system "${c.keySystem}" obtained`);const u=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const h=d.mediaKeys=c.createMediaKeys().then(f=>(this.log(`Media-keys created for "${e}"`),d.hasMediaKeys=!0,u.then(m=>m?this.setMediaKeysServerCertificate(f,e,m):f)));return h.catch(f=>{this.error(`Failed to create media-keys for "${e}"}: ${f}`)}),h})}return l.then(()=>o.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:r}){this.log(`Creating key-system session "${t}" keyId: ${ls(e.keyId||[])} keyUri: ${e.uri}`);const n=r.createSession(),i={decryptdata:e,keySystem:t,mediaKeys:r,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(i),i}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const r=this.createMediaKeySessionContext(e),n=oo(t),i="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(r,i,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyId ${ls(e.decryptdata.keyId||[])}
688      } (data length: ${t.byteLength})`),r.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>gc(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:r})=>this.attemptSetMediaKeys(t,r))}selectKeySystem(e){return new Promise((t,r)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:n})=>{const i=gc(n);i?t(i):r(new Error(`Unable to find format for key-system "${n}"`))}).catch(r)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=Qi(this.config),r=e.map(Ro).filter(n=>!!n&&t.indexOf(n)!==-1);return this.selectKeySystem(r)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let r=0;r<t.length;r++){const n=ZL(e,t[r]);if(n)return n}}loadKey(e){const t=e.keyInfo.decryptdata,r=oo(t),n=this.bannedKeyIds[r];if(n||this.getKeyStatus(t)==="internal-error"){const l=Zm(n||"internal-error",t);return this.handleError(l,e.frag),Promise.reject(l)}const i=`(keyId: ${r} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${i}`);const o=this.keyIdToKeySessionPromise[r];if(!o){const l=this.getKeySystemForKeyPromise(t).then(({keySystem:d,mediaKeys:c})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${i}`),this.attemptSetMediaKeys(d,c).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:d,mediaKeys:c,decryptdata:t}))))).then(d=>{const c="cenc",u=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(d,c,u,"playlist-key")});return l.catch(d=>this.handleError(d,e.frag)),this.keyIdToKeySessionPromise[r]=l,l}return o.catch(l=>{if(l instanceof js){const d=yt({},l.data);this.getKeyStatus(t)==="internal-error"&&(d.decryptdata=t);const c=new js(d,l.message);this.handleError(c,e.frag)}}),o}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof js){t&&(e.data.frag=t);const r=e.data.decryptdata;this.error(`${e.message}${r?` (${ls(r.keyId||[])})`:""}`),this.hls.trigger(E.ERROR,e.data)}else this.error(e.message),this.hls.trigger(E.ERROR,{type:Re.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}
vendor: 16,809 bytes, line 688
688getKeySystemForKeyPromise(e){const t=oo(e),r=this.keyIdToKeySessionPromise[t];if(!r){const n=Ro(e.keyFormat),i=n?[n]:Qi(this.config);return this.attemptKeySystemAccess(i)}return r}getKeySystemSelectionPromise(e){if(e.length||(e=Qi(this.config)),e.length===0)throw new js({type:Re.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Rt({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const r=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const n=Promise.all(r).then(()=>this.media?this.media.setMediaKeys(t):new Promise((i,o)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return o(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(i).catch(o)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(n),n.then(()=>{this.log(`Media-keys set for "${e}"`),r.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(i=>r.indexOf(i)===-1)})}generateRequestWithPreferredKeySession(e,t,r,n){var i;const o=(i=this.config.drmSystems)==null||(i=i[e.keySystem])==null?void 0:i.generateRequest;if(o)try{const p=o.call(this.hls,t,r,e);if(!p)throw new Error("Invalid response from configured generateRequest filter");t=p.initDataType,r=p.initData?p.initData:null,e.decryptdata.pssh=r?new Uint8Array(r):null}catch(p){if(this.warn(p.message),this.hls&&this.hls.config.debug)throw p}if(r===null)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e);const l=oo(e.decryptdata),d=e.decryptdata.uri;this.log(`Generating key-session request for "${n}" keyId: ${l} URI: ${d} (init data type: ${t} length: ${r.byteLength})`);const c=new Hu,u=e._onmessage=p=>{const x=e.mediaKeysSession;if(!x){c.emit("error",new Error("invalid state"));return}const{messageType:y,message:v}=p;this.log(`"${y}" message event for session "${x.sessionId}" message size: ${v.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,v).catch(_=>{c.eventNames().length?c.emit("error",_):this.handleError(_)}):y==="license-release"?e.keySystem===Ft.FAIRPLAY&&this.updateKeySession(e,Td("acknowledged")).then(()=>this.removeSession(e)).catch(_=>this.handleError(_)):this.warn(`unhandled media key message type "${y}"`)},h=(p,x)=>{x.keyStatus=p;let y;p.startsWith("usable")?c.emit("resolved"):p==="internal-error"||p==="output-restricted"||p==="output-downscaled"?y=Zm(p,x.decryptdata):p==="expired"?y=new Error(`key expired (keyId: ${l})`):p==="released"?y=new Error("key released"):p==="status-pending"||this.warn(`unhandled key status change "${p}" (keyId: ${l})`),y&&(c.eventNames().length?c.emit("error",y):this.handleError(y))},f=e._onkeystatuseschange=p=>{if(!e.mediaKeysSession){c.emit("error",new Error("invalid state"));return}const y=this.getKeyStatuses(e);if(!Object.keys(y).some(w=>y[w]!=="status-pending"))return;if(y[l]==="expired"){this.log(`Expired key ${Rt(y)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let _=y[l];if(_)h(_,e);else{var b;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(b=e.keyStatusTimeouts)[l]||(b[l]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const T=this.getKeyStatus(e.decryptdata);if(T&&T!=="status-pending")return this.log(`No status for keyId ${l} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${T} from other session.`),h(T,e);this.log(`key status for ${l} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),_="internal-error",h(_,e)},1e3)),this.log(`No status for keyId ${l} (${Rt(y)}).`)}};ys(e.mediaKeysSession,"message",u),ys(e.mediaKeysSession,"keystatuseschange",f);const m=new Promise((p,x)=>{c.on("error",x),c.on("resolved",p)});return e.mediaKeysSession.generateRequest(t,r).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${l} URI: ${d}`)}).catch(p=>{throw new js({type:Re.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_SESSION,error:p,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${p}`)}).then(()=>m).catch(p=>(c.removeAllListeners(),this.removeSession(e).then(()=>{throw p}))).then(()=>(c.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((r,n)=>{if(typeof n=="string"&&typeof r=="object"){const l=n;n=r,r=l}const i="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);if(e.keySystem===Ft.PLAYREADY&&i.length===16){const l=ls(i);t[l]=r,vy(i)}const o=ls(i);r==="internal-error"&&(this.bannedKeyIds[o]=r),this.log(`key status change "${r}" for keyStatuses keyId: ${o} key-session "${e.mediaKeysSession.sessionId}"`),t[o]=r}),t}fetchServerCertificate(e){const t=this.config,r=t.loader,n=new r(t),i=this.getServerCertificateUrl(e);return i?(this.log(`Fetching server certificate for "${e}"`),new Promise((o,l)=>{const d={responseType:"arraybuffer",url:i},c=t.certLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(f,m,p,x)=>{o(f.data)},onError:(f,m,p,x)=>{l(new js({type:Re.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:yt({url:d.url,data:void 0},f)},`"${e}" certificate request failed (${i}). Status: ${f.code} (${f.text})`))},onTimeout:(f,m,p)=>{l(new js({type:Re.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:{url:d.url,data:void 0}},`"${e}" certificate request timed out (${i})`))},onAbort:(f,m,p)=>{l(new Error("aborted"))}};n.load(d,u,h)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,r){return new Promise((n,i)=>{e.setServerCertificate(r).then(o=>{this.log(`setServerCertificate ${o?"success":"not supported by CDM"} (${r.byteLength}) on "${t}"`),n(e)}).catch(o=>{i(new js({type:Re.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:o,fatal:!0},o.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(r=>this.updateKeySession(e,new Uint8Array(r)).catch(n=>{throw new js({type:Re.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:n,fatal:!1},n.message)}))}unpackPlayReadyKeyMessage(e,t){const r=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!r.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const n=new DOMParser().parseFromString(r,"application/xml"),i=n.querySelectorAll("HttpHeader");if(i.length>0){let u;for(let h=0,f=i.length;h<f;h++){var o,l;u=i[h];const m=(o=u.querySelector("name"))==null?void 0:o.textContent,p=(l=u.querySelector("value"))==null?void 0:l.textContent;m&&p&&e.setRequestHeader(m,p)}}const d=n.querySelector("Challenge"),c=d==null?void 0:d.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return Td(atob(c))}setupLicenseXHR(e,t,r,n){const i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!r.decryptdata)throw new Error("Key removed");return i.call(this.hls,e,t,r,n)}).catch(o=>{if(!r.decryptdata)throw o;return e.open("POST",t,!0),i.call(this.hls,e,t,r,n)}).then(o=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:o||n})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t){const r=this.config.keyLoadPolicy.default;return new Promise((n,i)=>{const o=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${o}`);const l=new XMLHttpRequest;l.responseType="arraybuffer",l.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return i(new Error("invalid state"));if(l.readyState===4)if(l.status===200){this._requestLicenseFailureCount=0;let d=l.response;this.log(`License received ${d instanceof ArrayBuffer?d.byteLength:d}`);const c=this.config.licenseResponseCallback;if(c)try{d=c.call(this.hls,l,o,e)}catch(u){this.error(u)}n(d)}else{const d=r.errorRetry,c=d?d.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||l.status>=400&&l.status<500)i(new js({type:Re.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:l,response:{url:o,data:void 0,code:l.status,text:l.statusText}},`License Request XHR failed (${o}). Status: ${l.status} (${l.statusText})`));else{const u=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t).then(n,i)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=l,this.setupLicenseXHR(l,o,e,t).then(({xhr:d,licenseChallenge:c})=>{e.keySystem==Ft.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(d,c)),d.send(c)}).catch(i)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const r=t.media;this.media=r,ys(r,"encrypted",this.onMediaEncrypted),ys(r,"waitingforkey",this.onWaitingForKey);const n=this.mediaResolved;n?n():this.mediaKeys=r.mediaKeys}onMediaDetached(){const e=this.media;e&&(ws(e,"encrypted",this.onMediaEncrypted),ws(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const r=this.media,n=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Zr.clearKeyUriToKeyIdMap();const i=n.length;mi.CDMCleanupPromise=Promise.all(n.map(o=>this.removeSession(o)).concat((r==null||(e=r.setMediaKeys(null))==null?void 0:e.catch(o=>{this.log(`Could not clear media keys: ${o}`),this.hls&&this.hls.trigger(E.ERROR,{type:Re.OTHER_ERROR,details:z.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${o}`)})}))||Promise.resolve())).catch(o=>{this.log(`Could not close sessions and clear media keys: ${o}`),this.hls&&this.hls.trigger(E.ERROR,{type:Re.OTHER_ERROR,details:z.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${o}`)})}).then(()=>{i&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const r=t.reduce((n,i)=>(n.indexOf(i.keyFormat)===-1&&n.push(i.keyFormat),n),[]);this.log(`Selecting key-system from session-keys ${r.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(r)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:r,decryptdata:n}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${ls((n==null?void 0:n.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),r&&r.readyState!==XMLHttpRequest.DONE&&r.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(e);i>-1&&this.mediaKeySessions.splice(i,1);const{keyStatusTimeouts:o}=e;o&&Object.keys(o).forEach(c=>self.clearTimeout(o[c]));const{drmSystemOptions:l}=this.config;return(PC(l)?new Promise((c,u)=>{self.setTimeout(()=>u(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(c).catch(u)}):Promise.resolve()).catch(c=>{this.log(`Could not remove session: ${c}`),this.hls&&this.hls.trigger(E.ERROR,{type:Re.OTHER_ERROR,details:z.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${c}`)})}).then(()=>t.close()).catch(c=>{this.log(`Could not close session: ${c}`),this.hls&&this.hls.trigger(E.ERROR,{type:Re.OTHER_ERROR,details:z.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${c}`)})})}return Promise.resolve()}}mi.CDMCleanupPromise=void 0;function oo(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return ls(s.keyId)}function ZL(s,e){if(s.keyId&&e.mediaKeysSession.keyStatuses.has(s.keyId))return e.mediaKeysSession.keyStatuses.get(s.keyId);if(s.matches(e.decryptdata))return e.keyStatus}class js extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function Zm(s,e){const t=s==="output-restricted",r=t?z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:z.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new js({type:Re.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${s}"`)}class eP{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(E.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const r=this.hls.config;if(r.capLevelOnFPSDrop){const n=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=n,n&&typeof n.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,r){const n=performance.now();if(t){if(this.lastTime){const i=n-this.lastTime,o=r-this.lastDroppedFrames,l=t-this.lastDecodedFrames,d=1e3*o/i,c=this.hls;if(c.trigger(E.FPS_DROP,{currentDropped:o,currentDecoded:l,totalDroppedFrames:r}),d>0&&o>c.config.fpsDroppedMonitoringThreshold*l){let u=c.currentLevel;c.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=u)&&(u=u-1,c.trigger(E.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:c.currentLevel}),c.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=r,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function uv(s,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=s,e.dispatchEvent(t)}function hv(s,e){const t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues&&!s.cues.getCueById(e.id))try{if(s.addCue(e),!s.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(r){vt.debug(`[texttrack-utils]: ${r}`);try{const n=new self.TextTrackCue(e.startTime,e.endTime,e.text);n.id=e.id,s.addCue(n)}catch(n){vt.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${n}`)}}t==="disabled"&&(s.mode=t)}function oi(s,e){const t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues)for(let r=s.cues.length;r--;)e&&s.cues[r].removeEventListener("enter",e),s.removeCue(s.cues[r]);t==="disabled"&&(s.mode=t)}function Pd(s,e,t,r){const n=s.mode;if(n==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const i=sP(s.cues,e,t);for(let o=0;o<i.length;o++)(!r||r(i[o]))&&s.removeCue(i[o])}n==="disabled"&&(s.mode=n)}function tP(s,e){if(e<=s[0].startTime)return 0;const t=s.length-1;if(e>s[t].endTime)return-1;let r=0,n=t,i;for(;r<=n;)if(i=Math.floor((n+r)/2),e<s[i].startTime)n=i-1;else if(e>s[i].startTime&&r<t)r=i+1;else return i;return s[r].startTime-e<e-s[n].startTime?r:n}function sP(s,e,t){const r=[],n=tP(s,e);if(n>-1)for(let i=n,o=s.length;i<o;i++){const l=s[i];if(l.startTime>=e&&l.endTime<=t)r.push(l);else if(l.startTime>t)return r}return r}function No(s){const e=[];for(let t=0;t<s.length;t++){const r=s[t];(r.kind==="subtitles"||r.kind==="captions")&&r.label&&e.push(s[t])}return e}class rP extends Zu{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>
vendor: 7,612 bytes, line 688
688{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const r=No(this.media.textTracks);for(let i=0;i<r.length;i++)if(r[i].mode==="hidden")t=r[i];else if(r[i].mode==="showing"){t=r[i];break}const n=this.findTrackForTextTrack(t);this.subtitleTrack!==n&&this.setSubtitleTrack(n)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const r=this.media;if(!r)return;const n=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||r.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,n)return;No(r.textTracks).forEach(o=>{oi(o)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:r,groupId:n,details:i}=t,o=this.tracksInGroup[r];if(!o||o.groupId!==n){this.warn(`Subtitle track with id:${r} and group:${n} not found in active group ${o==null?void 0:o.groupId}`);return}const l=o.details;o.details=t.details,this.log(`Subtitle track ${r} "${o.name}" lang:${o.lang} group:${n} loaded [${i.startSN}-${i.endSN}]`),r===this.trackId&&this.playlistLoaded(r,t,l)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const r=t.subtitleGroups||null,n=this.groupIds;let i=this.currentTrack;if(!r||(n==null?void 0:n.length)!==(r==null?void 0:r.length)||r!=null&&r.some(o=>(n==null?void 0:n.indexOf(o))===-1)){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(u=>!r||r.indexOf(u.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(u=>u.default)&&(this.selectDefaultTrack=!1),o.forEach((u,h)=>{u.id=h});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.subtitlePreference;if(!i&&l){this.selectDefaultTrack=!1;const u=fr(l,o);if(u>-1)i=o[u];else{const h=fr(l,this.tracks);i=this.tracks[h]}}let d=this.findTrackId(i);d===-1&&i&&(d=this.findTrackId(null));const c={subtitleTracks:o};this.log(`Updating subtitle tracks, ${o.length} track(s) found in "${r==null?void 0:r.join(",")}" group-id`),this.hls.trigger(E.SUBTITLE_TRACKS_UPDATED,c),d!==-1&&this.trackId===-1&&this.setSubtitleTrack(d)}}findTrackId(e){const t=this.tracksInGroup,r=this.selectDefaultTrack;for(let n=0;n<t.length;n++){const i=t[n];if(!(r&&!i.default||!r&&!e)&&(!e||Sn(i,e)))return n}if(e){for(let n=0;n<t.length;n++){const i=t[n];if(Ia(e.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return n}for(let n=0;n<t.length;n++){const i=t[n];if(Ia(e.attrs,i.attrs,["LANGUAGE"]))return n}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let r=0;r<t.length;r++){const n=t[r];if(Id(n,e))return r}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===tt.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const r=this.currentTrack;if(r&&Sn(e,r))return r;const n=fr(e,this.tracksInGroup);if(n>-1){const i=this.tracksInGroup[n];return this.setSubtitleTrack(n),i}else{if(r)return null;{const i=fr(e,t);if(i>-1)return t[i]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const r=e.id,n=e.groupId,i=this.getUrlWithDirectives(e.url,t),o=e.details,l=o==null?void 0:o.age;this.log(`Loading subtitle ${r} "${e.name}" lang:${e.lang} group:${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${l&&o.live?" age "+l.toFixed(1)+(o.type&&" "+o.type||""):""} ${i}`),this.hls.trigger(E.SUBTITLE_TRACK_LOADING,{url:i,id:r,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=No(e.textTracks),r=this.currentTrack;let n;if(r&&(n=t.filter(i=>Id(r,i))[0],n||this.warn(`Unable to find subtitle TextTrack with name "${r.name}" and language "${r.lang}"`)),[].slice.call(t).forEach(i=>{i.mode!=="disabled"&&i!==n&&(i.mode="disabled")}),n){const i=this.subtitleDisplay?"showing":"hidden";n.mode!==i&&(n.mode=i)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!xe(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const r=this.currentTrack,n=t[e]||null;if(this.trackId=e,this.currentTrack=n,this.toggleTrackModes(),!n){this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:e});return}const i=!!n.details&&!n.details.live;if(e===this.trackId&&n===r&&i)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:o,groupId:l="",name:d,type:c,url:u}=n;this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:o,groupId:l,name:d,type:c,url:u});const h=this.switchParams(n.url,r==null?void 0:r.details,n.details);this.loadPlaylist(h)}}function nP(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const i=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(n=="x"?i:i&3|8).toString(16)})}}}function ca(s){let e=5381,t=s.length;for(;t;
vendor: 4,229 bytes, line 688
688)e=e*33^s.charCodeAt(--t);return(e>>>0).toString()}const pi=.025;let hl=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function iP(s,e,t){return`${s.identifier}-${t+1}-${ca(e)}`}class aP{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const r=this.playoutLimit;return e<=0||isNaN(r)?!1:r===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>r}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return Tc(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,r=Tc(t,e);return t-r<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=xe(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return Tc(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<pi))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?hl.Range:hl.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return oP(this)}}function Tc(s,e){return s-e.start<e.duration/2&&!(Math.abs(s-(e.start+e.duration))<pi)?e.start:e.start+e.duration}function fv(s,e,t){const r=new self.URL(s,t);return r.protocol!=="data:"&&r.searchParams.set("_HLS_primary_id",e),r}function Ac(s,e){for(;(t=s.assetList[++e])!=null&&t.error;)var t;return e}function oP(s){return`["${s.identifier}" ${s.cue.pre?"<pre>":s.cue.post?"<post>":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function ei(s){const e=s.timelineStart,t=s.duration||0;return`["${s.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class lP{constructor(e,t,r,n){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetail
vendor: 4,234 bytes, line 688
688s=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(E.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new e(t);this.interstitial=r,this.assetItem=n;const o=()=>{this.hasDetails=!0};i.once(E.LEVEL_LOADED,o),i.once(E.AUDIO_TRACK_LOADED,o),i.once(E.SUBTITLE_TRACK_LOADED,o),i.on(E.MEDIA_ATTACHING,(l,{media:d})=>{this.removeMediaListeners(),this.mediaAttached=d,this.interstitial.playoutLimit&&(d.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&i.on(E.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,i.trigger(E.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=fv(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const r=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset,i=Ue.bufferInfo(e,n,0);return this.getAssetTime(i.end)>=r-.02}reachedPlayout(e){const r=this.interstitial.playoutLimit;return this.startOffset+e>=r}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=Ue.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const r=t-this.startOffset;if(r>0&&r<e)return r}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const r=e-t;if(Math.abs(r)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,r=this.duration;return Math.min(Math.max(0,e-t),r)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=r=>delete r.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,r){var n;(n=this.hls)==null||n.on(e,t)}once(e,t,r){var n;(n=this.hls)==null||n.once(e,t)}off(e,t,r){var n;(n=this.hls)==null||n.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${ei(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const ep=.033;class cP extends Hs{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={}
vendor: 11,714 bytes, lines 688-689
688,this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((r,n)=>e<=n.startOffset&&t>n.startOffset?(delete n.error,r+1):r,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let r=-1;e.nextEvent?r=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(r=this.findEventIndex(e.previousEvent.identifier)+1);const n=this.items;if(n)for(n[r]||(t===void 0&&(t=e.start),r=this.findItemIndexAtTime(t));r>=0&&(i=n[r])!=null&&i.event;){var i;r--}return r}findItemIndexAtTime(e,t){const r=this.items;if(r)for(let n=0;n<r.length;n++){let i=r[n];if(t&&t!=="primary"&&(i=i[t]),e===i.start||e>i.start&&e<i.end)return n}return-1}findJumpRestrictedIndex(e,t){const r=this.items;if(r)for(let n=e;n<=t&&r[n];n++){const i=r[n].event;if(i!=null&&i.restrictions.jump&&!i.appendInPlace)return n}return-1}findEventIndex(e){const t=this.items;if(t)for(let n=t.length;n--;){var r;if(((r=t[n].event)==null?void 0:r.identifier)===e)return n}return-1}findAssetIndex(e,t){const r=e.assetList,n=r.length;if(n>1)for(let i=0;i<n;i++){const o=r[i];if(!o.error){const l=o.timelineStart;if(t===l||t>l&&(t<l+(o.duration||0)||i===n-1))return i}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const r=t.assetList,n=r[r.length-1];if(n)return n.identifier}return null}parseInterstitialDateRanges(e,t){const r=e.main.details,{dateRanges:n}=r,i=this.events,o=this.parseDateRanges(n,{url:r.url},t),l=Object.keys(n),d=i?i.filter(c=>!l.includes(c.identifier)):[];o.length&&o.sort((c,u)=>{const h=c.cue.pre,f=c.cue.post,m=u.cue.pre,p=u.cue.post;if(h&&!m)return-1;if(m&&!h||f&&!p)return 1;if(p&&!f)return-1;if(!h&&!m&&!f&&!p){const x=c.startTime,y=u.startTime;if(x!==y)return x-y}return c.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=o,d.forEach(c=>{this.removeEvent(c)}),this.updateSchedule(e,d)}updateSchedule(e,t=[],r=!1){const n=this.events||[];if(n.length||t.length||this.length<2){const i=this.items,o=this.parseSchedule(n,e);(r||t.length||(i==null?void 0:i.length)!==o.length||o.some((d,c)=>Math.abs(d.playout.start-i[c].playout.start)>.005||Math.abs(d.playout.end-i[c].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,i))}}parseDateRanges(e,t,r){const n=[],i=Object.keys(e);for(let o=0;o<i.length;o++){const l=i[o],d=e[l];if(d.isInterstitial){let c=this.eventMap[l];c?c.setDateRange(d):(c=new aP(d,t),this.eventMap[l]=c,r===!1&&(c.appendInPlace=r)),n.push(c)}}return n}parseSchedule(e,t){const r=[],n=t.main.details,i=n.live?1/0:n.edge;let o=0;if(e=e.filter(d=>!d.error&&!(d.cue.once&&d.hasPlayed)),e.length){this.resolveOffsets(e,t);let d=0,c=0;if(e.forEach((u,h)=>{const f=u.cue.pre,m=u.cue.post,p=e[h-1]||null,x=u.appendInPlace,y=m?i:u.startOffset,v=u.duration,_=u.timelineOccupancy===hl.Range?v:0,b=u.resumptionOffset,w=(p==null?void 0:p.startTime)===y,T=y+u.cumulativeDuration;let A=x?T+v:y+b;if(f||!m&&y<=0){const I=c;c+=_,u.timelineStart=T;const j=o;o+=v,r.push({event:u,start:T,end:A,playout:{start:j,end:o},integrated:{start:I,end:c}})}else if(y<=i){if(!w){const R=y-d;if(R>ep){const k=d,D=c;c+=R;const Y=o;o+=R;const q={previousEvent:e[h-1]||null,nextEvent:u,start:k,end:k+R,playout:{start:Y,end:o},integrated:{start:D,end:c}};r.push(q)}else R>0&&p&&(p.cumulativeDuration+=R,r[r.length-1].end=y)}m&&(A=T),u.timelineStart=T;const I=c;c+=_;const j=o;o+=v,r.push({event:u,start:T,end:A,playout:{start:j,end:o},integrated:{start:I,end:c}})}else return;const S=u.resumeTime;m||S>i?d=i:d=S}),d<i){var l;const u=d,h=c,f=i-d;c+=f;const m=o;o+=f,r.push({previousEvent:((l=r[r.length-1])==null?void 0:l.event)||null,nextEvent:null,start:d,end:u+f,playout:{start:m,end:o},integrated:{start:h,end:c}})}this.setDurations(i,o,c)}else r.push({previousEvent:null,nextEvent:null,start:0,end:i,playout:{start:0,end:i},integrated:{start:0,end:i}}),this.setDurations(i,i,i);return r}setDurations(e,t,r){this.durations={primary:e,playout:t,integrated:r}}resolveOffsets(e,t){const r=t.main.details,n=r.live?1/0:r.edge;let i=0,o=-1;e.forEach((l,d)=>{const c=l.cue.pre,u=l.cue.post,h=c?0:u?n:l.startTime;this.updateAssetDurations(l),o===h?l.cumulativeDuration=i:(i=0,o=h),!u&&l.snapOptions.in&&(l.resumeAnchor=kn(null,r.fragments,l.startOffset+l.resumptionOffset,0,0)||void 0),l.appendInPlace&&!l.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(l,t)||(l.appendInPlace=!1)),!l.appendInPlace&&d+1<e.length&&e[d+1].startTime-e[d].resumeTime<ep&&(e[d+1].appendInPlace=!1,e[d+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${l}`));const m=xe(l.resumeOffset)?l.resumeOffset:l.duration;i+=m})}primaryCanResumeInPlaceAt(e,t){const r=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(r-n)>pi?(this.log(`"${e.identifier}" resumption ${r} not aligned with estimated timeline end ${n}`),!1):!Object.keys(t).some(o=>{const l=t[o].details,d=l.edge;if(r>=d)return this.log(`"${e.identifier}" resumption ${r} past ${o} playlist end ${d}`),!1;const c=kn(null,l.fragments,r);if(!c)return this.log(`"${e.identifier}" resumption ${r} does not align with any fragments in ${o} playlist (${l.fragStart}-${l.fragmentEnd})`),!0;const u=o==="audio"?.175:0;return Math.abs(c.start-r)<pi+u||Math.abs(c.end-r)<pi+u?!1:(this.log(`"${e.identifier}" resumption ${r} not aligned with ${o} fragment bounds (${c.start}-${c.end} sn: ${c.sn} cc: ${c.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let r=0,n=!1,i=!1;for(let o=0;o<e.assetList.length;o++){const l=e.assetList[o],d=t+r;l.startOffset=r,l.timelineStart=d,n||(n=l.duration===null),i||(i=!!l.error);const c=l.error?0:l.duration||0;r+=c}n&&!i?e.duration=Math.max(r,e.duration):e.duration=r}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function Xs(s){return`[${s.event?'"'+s.event.identifier+'"':"primary"}: ${s.start.toFixed(2)}-${s.end.toFixed(2)}]`}class dP{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const r=e.assetListUrl;let n;try{n=fv(r,this.hls.sessionId,e.baseUrl)}catch(f){const m=this.assignAssetListError(e,z.ASSET_LIST_LOAD_ERROR,f,r);this.hls.trigger(E.ERROR,m);return}t&&n.protocol!=="data:"&&n.searchParams.set("_HLS_start_offset",""+t);const i=this.hls.config,o=i.loader,l=new o(i),d={responseType:"json",url:n.href},c=i.interstitialAssetListLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(f,m,p,x)=>{const y=f.data,v=y==null?void 0:y.ASSETS;if(!Array.isArray(v)){const _=this.assignAssetListError(e,z.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),p.url,m,x);this.hls.trigger(E.ERROR,_);return}e.assetListResponse=y,this.hls.trigger(E.ASSET_LIST_LOADED,{event:e,assetListResponse:y,networkDetails:x})},onError:(f,m,p,x)=>{const y=this.assignAssetListError(e,z.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${f.code} ${f.text} (${m.url})`),m.url,x,p);this.hls.trigger(E.ERROR,y)},onTimeout:(f,m,p)=>{const x=this.assignAssetListError(e,z.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${m.url})`),m.url,f,p);this.hls.trigger(E.ERROR,x)}};return l.load(d,u,h),this.hls.trigger(E.ASSET_LIST_LOADING,{event:e}),l}assignAssetListError(e,t,r,n,i,o){return e.error=r,{type:Re.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:r,networkDetails:o,stats:i}}}function tp(s){var e;s==null||(e=s.play())==null||e.catch(()=>{})}function lo(s,e){return`[${s}] Advancing timeline position to ${e}`}class uP extends Hs{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled||!this.schedule)return;const n=r-this.timelinePos;if(Math.abs(n)<1/7056e5)return;const o=n<=-.01;this.timelinePos=r,this.bufferedPos=r;const l=this.playingItem;if(!l){this.checkBuffer();return}if(o&&this.schedule.resetErrorsInRange(r,r-n)&&this.updateSchedule(!0),this.checkBuffer(),o&&r<l.start||r>=l.end){var d;const m=this.findItemIndex(l);let p=this.schedule.findItemIndexAtTime(r);if(p===-1&&(p=m+(o?-1:1),this.log(`seeked ${o?"back ":""}to position not covered by schedule ${r} (resolving from ${m} to ${p})`)),!this.isInterstitial(l)&&(d=this.media)!=null&&d.paused&&(this.shouldPlay=!1),!o&&p>m){const x=this.schedule.findJumpRestrictedIndex(m+1,p);if(x>m){this.setSchedulePosition(x);return}}this.setSchedulePosition(p);return}const c=this.playingAsset;if(!c){if(this.playingLastItem&&this.isInterstitial(l)){const m=l.event.assetList[0];m&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(r,m))}return}const u=c.timelineStart,h=c.duration||0;if(o&&r<u||r>=u+h){var f;(f=l.event)!=null&&f.appendInPlace&&(this.clearAssetPlayers(l.event,l),this.flushFrontBuffer(r)),this.setScheduleToAssetAtTime(r,c)}},this.onTimeupdate=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled)return;if(r>this.timelinePos)this.timelinePos=r,r>this.bufferedPos&&this.checkBuffer();else return;const n=this.playingItem;if(!n||this.playingLastItem)return;if(r>=n.end){this.timelinePos=n.end;const l=this.findItemIndex(n);this.setSchedulePosition(l+1)}const i=this.playingAsset;if(!i)return;const o=i.timelineStart+(i.duration||0);r>=o&&this.setScheduleToAssetAtTime(r,i)},this.onScheduleUpdate=(r,n)=>{const i=this.schedule;if(!i)return;const o=this.playingItem,l=i.events||[],d=i.items||[],c=i.durations,u=r.map(x=>x.identifier),h=!!(l.length||u.length);(h||n)&&this.log(`INTERSTITIALS_UPDATED (${l.length}): ${l}
689Schedule: ${d.map(x=>Xs(x))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let f=null,m=null;o&&(f=this.updateItem(o,this.timelinePos),this.itemsMatch(o,f)?this.playingItem=f:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const p=this.bufferingItem;if(p&&(m=this.updateItem(p,this.bufferedPos),this.itemsMatch(p,m)?this.bufferingItem=m:p.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(p.event,null))),r.forEach(x=>{x.assetList.forEach(y=>{this.clearAssetPlayer(y.identifier,null)})}),this.playerQueue.forEach(x=>{if(x.interstitial.appendInPlace){const y=x.assetItem.timelineStart,v=x.timelineOffset-y;if(v)try{x.timelineOffset=y}catch(_){Math.abs(v)>pi&&this.warn(`${_} ("${x.assetId}" ${x.timelineOffset}->${y})`)}}}),h||n){if(this.hls.trigger(E.INTERSTITIALS_UPDATED,{events:l.slice(0),schedule:d.slice(0),durations:c,removedIds:u}),this.isInterstitial(o)&&u.includes(o.event.identifier)){this.warn(`Interstitial "${o.event.identifier}" removed while playing`),this.primaryFallback(o.event);return}o&&this.trimInPlace(f,o),p&&m!==f&&this.trimInPlace(m,p),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new dP(e),this.schedule=new cP(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;
vendor: 4,901 bytes, line 689
689e&&(e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(E.MEDIA_ENDED,this.onMediaEnded,this),e.on(E.ERROR,this.onError,this),e.on(E.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(E.MEDIA_ENDED,this.onMediaEnded,this),e.off(E.ERROR,this.onError,this),e.off(E.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){ws(e,"play",this.onPlay),ws(e,"pause",this.onPause),ws(e,"seeking",this.onSeeking),ws(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const r=this.media=t.media;ys(r,"seeking",this.onSeeking),ys(r,"timeupdate",this.onTimeupdate),ys(r,"play",this.onPlay),ys(r,"pause",this.onPause)}onMediaAttached(e,t){const r=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,r===null)this.checkStart();else if(!n){this.clearScheduleState();const i=this.findItemIndex(r);this.setSchedulePosition(i)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const r=!!t.transferMedia,n=this.media;if(this.media=null,!r&&(n&&this.removeMediaListeners(n),this.detachedData)){const i=this.getBufferingPlayer();i&&(this.log(`Removing schedule state for detachedData and ${i}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,i.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,r=h=>h&&e.getAssetPlayer(h.identifier),n=(h,f,m,p,x)=>{if(h){let y=h[f].start;const v=h.event;if(v){if(f==="playout"||v.timelineOccupancy!==hl.Point){const _=r(m);(_==null?void 0:_.interstitial)===v&&(y+=_.assetItem.startOffset+_[x])}}else{const _=p==="bufferedPos"?o():e[p];y+=_-h.start}return y}return 0},i=(h,f)=>{var m;if(h!==0&&f!=="primary"&&(m=e.schedule)!=null&&m.length){var p;const x=e.schedule.findItemIndexAtTime(h),y=(p=e.schedule.items)==null?void 0:p[x];if(y){const v=y[f].start-y.start;return h+v}}return h},o=()=>{const h=e.bufferedPos;return h===Number.MAX_VALUE?l("primary"):Math.max(h,0)},l=h=>{var f,m;return(f=e.primaryDetails)!=null&&f.live?e.primaryDetails.edge:((m=e.schedule)==null?void 0:m.durations[h])||0},d=(h,f)=>{var m,p;const x=e.effectivePlayingItem;if(x!=null&&(m=x.event)!=null&&m.restrictions.skip||!e.schedule)return;e.log(`seek to ${h} "${f}"`);const y=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(h,f),_=(p=e.schedule.items)==null?void 0:p[v],b=e.getBuffer
vendor: 34,538 bytes, line 689
689ingPlayer(),w=b==null?void 0:b.interstitial,T=w==null?void 0:w.appendInPlace,A=y&&e.itemsMatch(y,_);if(y&&(T||A)){const S=r(e.playingAsset),I=(S==null?void 0:S.media)||e.primaryMedia;if(I){const j=f==="primary"?I.currentTime:n(y,f,e.playingAsset,"timelinePos","currentTime"),R=h-j,k=(T?j:I.currentTime)+R;if(k>=0&&(!S||T||k<=S.duration)){I.currentTime=k;return}}}if(_){let S=h;if(f!=="primary"){const j=_[f].start,R=h-j;S=_.start+R}const I=!e.isInterstitial(_);if((!e.isInterstitial(y)||y.event.appendInPlace)&&(I||_.event.appendInPlace)){const j=e.media||(T?b==null?void 0:b.media:null);j&&(j.currentTime=S)}else if(y){const j=e.findItemIndex(y);if(v>j){const k=e.schedule.findJumpRestrictedIndex(j+1,v);if(k>j){e.setSchedulePosition(k);return}}let R=0;if(I)e.timelinePos=S,e.checkBuffer();else{const k=_.event.assetList,D=h-(_[f]||_).start;for(let Y=k.length;Y--;){const q=k[Y];if(q.duration&&D>=q.startOffset&&D<q.startOffset+q.duration){R=Y;break}}}e.setSchedulePosition(v,R)}}},c=()=>{const h=e.effectivePlayingItem;if(e.isInterstitial(h))return h;const f=t();return e.isInterstitial(f)?f:null},u={get bufferedEnd(){const h=t(),f=e.bufferingItem;if(f&&f===h){var m;return n(f,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-f.playout.start||((m=e.bufferingAsset)==null?void 0:m.startOffset)||0}return 0},get currentTime(){const h=c(),f=e.effectivePlayingItem;return f&&f===h?n(f,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-f.playout.start:0},set currentTime(h){const f=c(),m=e.effectivePlayingItem;m&&m===f&&d(h+m.playout.start,"playout")},get duration(){const h=c();return h?h.playout.end-h.playout.start:0},get assetPlayers(){var h;const f=(h=c())==null?void 0:h.event.assetList;return f?f.map(m=>e.getAssetPlayer(m.identifier)):[]},get playingIndex(){var h;const f=(h=c())==null?void 0:h.event;return f&&e.effectivePlayingAsset?f.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return c()}};return this.manager={get events(){var h;return((h=e.schedule)==null||(h=h.events)==null?void 0:h.slice(0))||[]},get schedule(){var h;return((h=e.schedule)==null||(h=h.items)==null?void 0:h.slice(0))||[]},get interstitialPlayer(){return c()?u:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const h=t();return e.findItemIndex(h)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const h=e.effectivePlayingItem;return e.findItemIndex(h)},primary:{get bufferedEnd(){return o()},get currentTime(){const h=e.timelinePos;return h>0?h:0},set currentTime(h){d(h,"primary")},get duration(){return l("primary")},get seekableStart(){var h;return((h=e.primaryDetails)==null?void 0:h.fragmentStart)||0}},integrated:{get bufferedEnd(){return n(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return n(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(h){d(h,"integrated")},get duration(){return l("integrated")},get seekableStart(){var h;return i(((h=e.primaryDetails)==null?void 0:h.fragmentStart)||0,"integrated")}},skip:()=>{const h=e.effectivePlayingItem,f=h==null?void 0:h.event;if(f&&!f.restrictions.skip){const m=e.findItemIndex(h);if(f.appendInPlace){const p=h.playout.start+h.event.duration;d(p+.001,"playout")}else e.advanceAfterAssetEnded(f,m,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,r=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!r?!1:this.findItemIndex(t)===r.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const r=this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&!r.event.appendInPlace)return;let n=this.media;!n&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(n=this.primaryMedia);const i=(t=n)==null?void 0:t.currentTime;if(!(i===void 0||!xe(i)))return i}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const r=this.getAssetPlayer(e);r&&this.transferMediaFromPlayer(r,t)}transferMediaFromPlayer(e,t){const r=e.interstitial.appendInPlace,n=e.media;if(r&&n===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&n){this.detachedData={media:n};return}const i=e.transferMedia();this.log(`transfer MediaSource from ${e} ${Rt(i)}`),this.detachedData=i}else t&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}transferMediaTo(e,t){var r,n;if(e.media===t)return;let i=null;const o=this.hls,l=e!==o,d=l&&e.interstitial.appendInPlace,c=(r=this.detachedData)==null?void 0:r.mediaSource;let u;if(o.media)d&&(i=o.transferMedia(),this.detachedData=i),u="Primary";else if(c){const p=this.getBufferingPlayer();p?(i=p.transferMedia(),u=`${p}`):u="detached MediaSource"}else u="detached media";if(!i){if(c)i=this.detachedData,this.log(`using detachedData: MediaSource ${Rt(i)}`);else if(!this.detachedData||o.media===t){const p=this.playerQueue;p.length>1&&p.forEach(x=>{if(l&&x.interstitial.appendInPlace!==d){const y=x.interstitial;this.clearInterstitial(x.interstitial,null),y.appendInPlace=!1,y.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${y}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const h=i&&"mediaSource"in i&&((n=i.mediaSource)==null?void 0:n.readyState)!=="closed",f=h&&i?i:t;this.log(`${h?"transfering MediaSource":"attaching media"} to ${l?e:"Primary"} from ${u} (media.currentTime: ${t.currentTime})`);const m=this.schedule;if(f===i&&m){const p=l&&e.assetId===m.assetIdAtEnd;f.overrides={duration:m.duration,endOfStream:!l||p,cueRemoval:!l}}e.attachMedia(f)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e==null?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const r=this.timelinePos,n=this.effectivePlayingItem;if(r===-1){const i=this.hls.startPosition;if(this.log(lo("checkStart",i)),this.timelinePos=i,t.length&&t[0].cue.pre){const o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(i>=0||!this.primaryLive){const o=this.timelinePos=i>0?i:0,l=e.findItemIndexAtTime(o);this.setSchedulePosition(l)}}else if(n&&!this.playingItem){const i=e.findItemIndex(n);this.setSchedulePosition(i)}}advanceAssetBuffering(e,t){const r=e.event,n=r.findAssetIndex(t),i=Ac(r,n);if(!r.isAssetPastPlayoutLimit(i))this.bufferedToEvent(e,i);else if(this.schedule){var o;const l=(o=this.schedule.items)==null?void 0:o[this.findItemIndex(e)+1];l&&this.bufferedToItem(l)}}advanceAfterAssetEnded(e,t,r){const n=Ac(e,r);if(e.isAssetPastPlayoutLimit(n)){if(this.schedule){const i=this.schedule.items;if(i){const o=t+1,l=i.length;if(o>=l){this.setSchedulePosition(-1);return}const d=e.resumeTime;this.timelinePos<d&&(this.log(lo("advanceAfterAssetEnded",d)),this.timelinePos=d,e.appendInPlace&&this.advanceInPlace(d),this.checkBuffer(this.bufferedPos<d)),this.setSchedulePosition(o)}}}else{if(e.appendInPlace){const i=e.assetList[n];i&&this.advanceInPlace(i.timelineStart)}this.setSchedulePosition(t,n)}}setScheduleToAssetAtTime(e,t){const r=this.schedule;if(!r)return;const n=t.parentIdentifier,i=r.getEvent(n);if(i){const o=r.findEventIndex(n),l=r.findAssetIndex(i,e);this.advanceAfterAssetEnded(i,o,l-1)}}setSchedulePosition(e,t){var r;const n=(r=this.schedule)==null?void 0:r.items;if(!n||this.playbackDisabled)return;const i=e>=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${i&&Xs(i)}) pos: ${this.timelinePos}`);const o=this.waitingItem||this.playingItem,l=this.playingLastItem;if(this.isInterstitial(o)){const u=o.event,h=this.playingAsset,f=h==null?void 0:h.identifier,m=f?this.getAssetPlayer(f):null;if(m&&f&&(!this.eventItemsMatch(o,i)||t!==void 0&&f!==u.assetList[t].identifier)){var d;const p=u.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${p+1}/${u.assetList.length} ${ei(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(E.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:p,event:u,schedule:n.slice(0),scheduleIndex:e,player:m}),o!==this.playingItem){this.itemsMatch(o,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),p);return}this.retreiveMediaSource(f,i),m.media&&!((d=this.detachedData)!=null&&d.mediaSource)&&m.detachMedia()}if(!this.eventItemsMatch(o,i)&&(this.endedItem=o,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${Xs(o)}`),u.hasPlayed=!0,this.hls.trigger(E.INTERSTITIAL_ENDED,{event:u,schedule:n.slice(0),scheduleIndex:e}),u.cue.once)){var c;this.updateSchedule();const p=(c=this.schedule)==null?void 0:c.items;if(i&&p){const x=this.findItemIndex(i);this.advanceSchedule(x,p,t,o,l)}return}}this.advanceSchedule(e,n,t,o,l)}advanceSchedule(e,t,r,n,i){const o=this.schedule;if(!o)return;const l=t[e]||null,d=this.primaryMedia,c=this.playerQueue;if(c.length&&c.forEach(u=>{const h=u.interstitial,f=o.findEventIndex(h.identifier);(f<e||f>e+1)&&this.clearInterstitial(h,l)}),this.isInterstitial(l)){this.timelinePos=Math.min(Math.max(this.timelinePos,l.start),l.end);const u=l.event;if(r===void 0){r=o.findAssetIndex(u,this.timelinePos);const p=Ac(u,r-1);if(u.isAssetPastPlayoutLimit(p)||u.appendInPlace&&this.timelinePos===l.end){this.advanceAfterAssetEnded(u,e,r);return}r=p}const h=this.waitingItem;this.assetsBuffered(l,d)||this.setBufferingItem(l);let f=this.preloadAssets(u,r);if(this.eventItemsMatch(l,h||n)||(this.waitingItem=l,this.log(`INTERSTITIAL_STARTED ${Xs(l)} ${u.appendInPlace?"append in place":""}`),this.hls.trigger(E.INTERSTITIAL_STARTED,{event:u,schedule:t.slice(0),scheduleIndex:e})),!u.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${u}`);return}if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!d){this.log(`Waiting for attachMedia to start Interstitial ${u}`);return}this.waitingItem=this.endedItem=null,this.playingItem=l;const m=u.assetList[r];if(!m){this.advanceAfterAssetEnded(u,e,r||0);return}if(f||(f=this.getAssetPlayer(m.identifier)),f===null||f.destroyed){const p=u.assetList.length;this.warn(`asset ${r+1}/${p} player destroyed ${u}`),f=this.createAssetPlayer(u,m,r),f.loadSource()}if(!this.eventItemsMatch(l,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(m))return;this.startAssetPlayer(f,r,t,e,d),this.shouldPlay&&tp(f.media)}else l?(this.resumePrimary(l,e,n),this.shouldPlay&&tp(this.hls.media)):i&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(o.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,r){var n,i;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Xs(e)}`),!((n=this.detachedData)!=null&&n.mediaSource)){let l=this.timelinePos;(l<e.start||l>=e.end)&&(l=this.getPrimaryResumption(e,t),this.log(lo("resumePrimary",l)),this.timelinePos=l),this.attachPrimary(l,e)}if(!r)return;const o=(i=this.schedule)==null?void 0:i.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Xs(e)}`),this.hls.trigger(E.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const r=e.start;if(this.primaryLive){const n=this.primaryDetails;if(t===0)return this.hls.startPosition;if(n&&(r<n.fragmentStart||r>n.edge))return this.hls.liveSyncPosition||-1}return r}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:Ue.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,r){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const n=this.primaryMedia;if(!n)return;const i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,n),r&&this.startLoadingPrimaryAt(e,r)),r||(this.log(lo("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}startLoadingPrimaryAt(e,t){var r;const n=this.hls;!n.loadingEnabled||!n.media||Math.abs((((r=n.mainForwardBufferInfo)==null?void 0:r.start)||n.media.currentTime)-e)>.5?n.startLoad(e,t):n.bufferingEnabled||n.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(E.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(E.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const r=this.hls.levels[t.level];if(!r.details)return;const n=yt(yt({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=n,this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const r=this.hls.audioTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=yt(yt({},this.altSelection),{},{audio:r});return}const i=yt(yt({},n),{},{audio:r});this.mediaSelection=i}onSubtitleTrackUpdated(e,t){const r=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=yt(yt({},this.altSelection),{},{subtitles:r});return}const i=yt(yt({},n),{},{subtitles:r});this.mediaSelection=i}onAudioTrackSwitching(e,t){const r=dm(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setAudioOption(t)||n.setAudioOption(r)))}onSubtitleTrackSwitch(e,t){const r=dm(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setSubtitleOption(t)||t.id!==-1&&n.setSubtitleOption(r)))}onBufferCodecs(e,t){const r=t.tracks;r&&(this.requiredTracks=r)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const r=this.playingItem;if(r&&!this.itemsMatch(r,this.bufferingItem)&&!this.isInterstitial(r)){const n=this.timelinePos;this.bufferedPos=n,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let n=0;n<t.length;n++){const i=t[n];if(i.cue.post){var r;const o=this.schedule.findEventIndex(i.identifier),l=(r=this.schedule.items)==null?void 0:r[o];this.isInterstitial(l)&&this.eventItemsMatch(l,this.bufferingItem)&&this.bufferedToItem(l,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const r=this.findItemIndex(t);this.setSchedulePosition(r+1)}else this.shouldPlay=!1}updateItem(e,t){var r;const n=(r=this.schedule)==null?void 0:r.items;if(e&&n){const i=this.findItemIndex(e,t);return n[i]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((i,o)=>{e.event.isAssetPastPlayoutLimit(o)&&this.clearAssetPlayer(i.identifier,null)});const r=e.end+.25,n=Ue.bufferInfo(this.primaryMedia,r,0);(n.end>r||(n.nextStart||0)>r)&&(this.log(`trim buffered interstitial ${Xs(e)} (was ${Xs(t)})`),this.attachPrimary(r,null,!0),this.flushFrontBuffer(r))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var r;return!!t&&(e===t||e.event.identifier===((r=t.event)==null?void 0:r.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const r=this.mediaSelection;r&&((t=this.schedule)==null||t.updateSchedule(r,[],e))}checkBuffer(e){var t;const r=(t=this.schedule)==null?void 0:t.items;if(!r)return;const n=Ue.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=n.len<1),this.updateBufferedPos(n.end,r,e)}updateBufferedPos(e,t,r){const n=this.schedule,i=this.bufferingItem;if(this.bufferedPos>e||!n)return;if(t.length===1&&this.itemsMatch(t[0],i)){this.bufferedPos=e;return}const o=this.playingItem,l=this.findItemIndex(o);let d=n.findItemIndexAtTime(e);if(this.bufferedPos<e){var c;const u=this.findItemIndex(i),h=Math.min(u+1,t.length-1),f=t[h];if((d===-1&&i&&e>=i.end||(c=f.event)!=null&&c.appendInPlace&&e+.01>=f.start)&&(d=h),this.isInterstitial(i)){const m=i.event;if(h-l>1&&m.appendInPlace===!1||m.assetList.length===0&&m.assetListLoader)return}if(this.bufferedPos=e,d>u&&d>l)this.bufferedToItem(f);else{const m=this.primaryDetails;this.primaryLive&&m&&e>m.edge-m.targetduration&&f.start<m.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(f)&&this.preloadAssets(f.event,0)}}else r&&o&&!this.itemsMatch(o,i)&&(d===l?this.bufferedToItem(o):d===l+1&&this.bufferedToItem(t[d]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(n=>{const i=this.getAssetPlayer(n.identifier);return!(i!=null&&i.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,r=this.schedule;if(!this.itemsMatch(e,t)&&r){const{items:n,events:i}=r;if(!n||!i)return t;const o=this.isInterstitial(e),l=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const d=l?l.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Xs(e)}`+(t?` (${d.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(o){const c=r.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((u,h)=>{const f=this.getAssetPlayer(u.identifier);f&&(h===c&&f.loadSource(),f.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(c=>c.pauseBuffering());this.hls.trigger(E.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const r=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(r!==null){this.bufferingAsset=null;const n=this.detachedData;n?n.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),r=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(r)}bufferedToEvent(e,t){const r=e.event,n=r.assetList.length===0&&!r.assetListLoader,i=r.cue.once;if(n||!i){const o=this.preloadAssets(r,t);if(o!=null&&o.interstitial.appendInPlace){const l=this.primaryMedia;l&&this.bufferAssetPlayer(o,l)}}}preloadAssets(e,t){const r=e.assetUrl,n=e.assetList.length,i=n===0&&!e.assetListLoader,o=e.cue.once;if(i){const d=e.timelineStart;if(e.appendInPlace){var l;const f=this.playingItem;!this.isInterstitial(f)&&(f==null||(l=f.nextEvent)==null?void 0:l.identifier)===e.identifier&&this.flushFrontBuffer(d+.25)}let c,u=0;if(!this.playingItem&&this.primaryLive&&(u=this.hls.startPosition,u===-1&&(u=this.hls.liveSyncPosition||0)),u&&!(e.cue.pre||e.cue.post)){const f=u-d;f>0&&(c=Math.round(f*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${r?1:n} ${e}${c?` live-start: ${u} start-offset: ${c}`:""}`),r)return this.createAsset(e,0,0,d,e.duration,r);const h=this.assetListLoader.loadAssetList(e,c);h&&(e.assetListLoader=h)}else if(!o&&n){for(let c=t;c<n;c++){const u=e.assetList[c],h=this.getAssetPlayerQueueIndex(u.identifier);(h===-1||this.playerQueue[h].destroyed)&&!u.error&&this.createAssetPlayer(e,u,c)}const d=e.assetList[t];if(d){const c=this.getAssetPlayer(d.identifier);return c&&c.loadSource(),c}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(n=>{this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let r=0;r<t.length;r++)if(e===t[r].assetId)return r;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let r=0;r<e.length;r++)if(e[r].media===t)return e[r]}return null}createAsset(e,t,r,n,i,o){const l={parentIdentifier:e.identifier,identifier:iP(e,o,t),duration:i,startOffset:r,timelineStart:n,uri:o};return this.createAssetPlayer(e,l,t)}createAssetPlayer(e,t,r){const n=this.hls,i=n.userConfig;let o=i.videoPreference;const l=n.loadLevelObj||n.levels[n.currentLevel];(o||l)&&(o=Tt({},o),l.videoCodec&&(o.videoCodec=l.videoCodec),l.videoRange&&(o.allowedVideoRanges=[l.videoRange]));const d=n.audioTracks[n.audioTrack],c=n.subtitleTracks[n.subtitleTrack];let u=0;if(this.primaryLive||e.appendInPlace){const w=this.timelinePos-t.timelineStart;if(w>1){const T=t.duration;T&&w<T&&(u=w)}}const h=t.identifier,f=yt(yt({},i),{},{maxMaxBufferLength:Math.min(180,n.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:d||i.audioPreference,subtitlePreference:c||i.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(f.timelineOffset=t.timelineStart));const m=f.cmcd;m!=null&&m.sessionId&&m.contentId&&(f.cmcd=Tt({},m,{contentId:ca(t.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${e} and asset ${h}`);const p=new lP(this.HlsPlayerClass,f,e,t);this.playerQueue.push(p),e.assetList[r]=t;let x=!0;const y=w=>{if(w.live){var T;const I=new Error(`Interstitials MUST be VOD assets ${e}`),j={fatal:!0,type:Re.OTHER_ERROR,details:z.INTERSTITIAL_ASSET_ITEM_ERROR,error:I},R=((T=this.schedule)==null?void 0:T.findEventIndex(e.identifier))||-1;this.handleAssetItemError(j,e,R,r,I.message);return}const A=w.edge-w.fragmentStart,S=t.duration;(x||S===null||A>S)&&(x=!1,this.log(`Interstitial asset "${h}" duration change ${S} > ${A}`),t.duration=A,this.updateSchedule())};p.on(E.LEVEL_UPDATED,(w,{details:T})=>y(T)),p.on(E.LEVEL_PTS_UPDATED,(w,{details:T})=>y(T)),p.on(E.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const v=(w,T)=>{const A=this.getAssetPlayer(h);if(A&&T.tracks){A.off(E.BUFFER_CODECS,v),A.tracks=T.tracks;const S=this.primaryMedia;this.bufferingAsset===A.assetItem&&S&&!A.media&&this.bufferAssetPlayer(A,S)}};p.on(E.BUFFER_CODECS,v);const _=()=>{var w;const T=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${T}`),!T||!this.schedule)return;const A=this.schedule.findEventIndex(e.identifier),S=(w=this.schedule.items)==null?void 0:w[A];this.isInterstitial(S)&&this.advanceAssetBuffering(S,t)};p.on(E.BUFFERED_TO_END,_);const b=w=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const A=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,A,w)};return p.once(E.MEDIA_ENDED,b(r)),p.once(E.PLAYOUT_LIMIT_REACHED,b(1/0)),p.on(E.ERROR,(w,T)=>{if(!this.schedule)return;const A=this.getAssetPlayer(h);if(T.details===z.BUFFER_STALLED_ERROR){if(A!=null&&A.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(T,e,this.schedule.findEventIndex(e.identifier),r,`Asset player error ${T.error} ${e}`)}),p.on(E.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const T=new Error(`Asset player destroyed unexpectedly ${h}`),A={fatal:!0,type:Re.OTHER_ERROR,details:z.INTERSTITIAL_ASSET_ITEM_ERROR,error:T};this.handleAssetItemError(A,e,this.schedule.findEventIndex(e.identifier),r,T.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${ei(t)}`),this.hls.trigger(E.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:r,event:e,player:p}),p}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(r=>{this.clearAssetPlayer(r.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const r=this.playerQueue[t];this.transferMediaFromPlayer(r,null),r.resetDetails()}}clearAssetPlayer(e,t){const r=this.getAssetPlayerQueueIndex(e);if(r!==-1){const n=this.playerQueue[r];this.log(`clear ${n} toSegment: ${t&&Xs(t)}`),this.transferMediaFromPlayer(n,t),this.playerQueue.splice(r,1),n.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,r,n,i){const{interstitial:o,assetItem:l,assetId:d}=e,c=o.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=l,(!u||u.identifier!==d)&&(u&&(this.clearAssetPlayer(u.identifier,r[n]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${c} ${ei(l)}`),this.hls.trigger(E.INTERSTITIAL_ASSET_STARTED,{asset:l,assetListIndex:t,event:o,schedule:r.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,i)}bufferAssetPlayer(e,t){var r,n;if(!this.schedule)return;const{interstitial:i,assetItem:o}=e,l=this.schedule.findEventIndex(i.identifier),d=(r=this.schedule.items)==null?void 0:r[l];if(!d)return;e.loadSource(),this.setBufferingItem(d),this.bufferingAsset=o;const c=this.getBufferingPlayer();if(c===e)return;const u=i.appendInPlace;if(u&&(c==null?void 0:c.interstitial.appendInPlace)===!1)return;const h=(c==null?void 0:c.tracks)||((n=this.detachedData)==null?void 0:n.tracks)||this.requiredTracks;if(u&&o!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(h&&!Yx(h,e.tracks)){const f=new Error(`Asset ${ei(o)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),m={fatal:!0,type:Re.OTHER_ERROR,details:z.INTERSTITIAL_ASSET_ITEM_ERROR,error:f},p=i.findAssetIndex(o);this.handleAssetItemError(m,i,l,p,f.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,r=this.primaryMedia;if(!t||!r)return;const n=r.currentTime,i=t.findAssetIndex(e,n),o=e.assetList[i];if(o){const l=this.getAssetPlayer(o.identifier);if(l){const d=l.currentTime||n-o.timelineStart,c=l.duration-d;if(this.warn(`Stalled at ${d} of ${d+c} in ${l} ${e} (media.currentTime: ${n})`),d&&(c/r.playbackRate<.5||l.bufferedInPlaceToEnd(r))&&l.hls){const u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,i)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,r,n,i){if(e.details===z.BUFFER_STALLED_ERROR)return;const o=t.assetList[n]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${o&&ei(o)} ${e.error}`),!this.schedule)return;const l=(o==null?void 0:o.identifier)||"",d=this.getAssetPlayerQueueIndex(l),c=this.playerQueue[d]||null,u=this.schedule.items,h=Tt({},e,{fatal:!1,errorAction:hi(!0),asset:o,assetListIndex:n,event:t,schedule:u,scheduleIndex:r,player:c});if(this.hls.trigger(E.INTERSTITIAL_ASSET_ERROR,h),!e.fatal)return;const f=this.playingAsset,m=this.bufferingAsset,p=new Error(i);if(o&&(this.clearAssetPlayer(l,null),o.error=p),!t.assetList.some(x=>!x.error))t.error=p;else for(let x=n;x<t.assetList.length;x++)this.resetAssetPlayer(t.assetList[x].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):f&&f.identifier===l?this.advanceAfterAssetEnded(t,r,n):m&&m.identifier===l&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,m)}primaryFallback(e){const t=e.timelineStart,r=this.effectivePlayingItem;let n=this.timelinePos;if(r){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${n} playing: ${Xs(r)} error: ${e.error}`),n===-1&&(n=this.hls.startPosition);const o=this.updateItem(r,n);this.itemsMatch(r,o)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(n===-1){this.checkStart();return}if(!this.schedule)return;const i=this.schedule.findItemIndexAtTime(n);this.setSchedulePosition(i)}onAssetListLoaded(e,t){var r,n;const i=t.event,o=i.identifier,l=t.assetListResponse.ASSETS;if(!((r=this.schedule)!=null&&r.hasEvent(o)))return;const d=i.timelineStart,c=i.duration;let u=0;l.forEach((x,y)=>{const v=parseFloat(x.DURATION);this.createAsset(i,y,u,d+u,v,x.URI),u+=v}),i.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${c}) ${i}`);const h=this.waitingItem,f=(h==null?void 0:h.event.identifier)===o;this.updateSchedule();const m=(n=this.bufferingItem)==null?void 0:n.event;if(f){var p;const x=this.schedule.findEventIndex(o),y=(p=this.schedule.items)==null?void 0:p[x];if(y){if(!this.playingItem&&this.timelinePos>y.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==x){i.error=new Error(`Interstitial ${l.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${i}`),this.log(i.error.message),this.updateSchedule(!0),this.primaryFallback(i);return}this.setBufferingItem(y)}this.setSchedulePosition(x)}else if((m==null?void 0:m.identifier)===o){const x=i.assetList[0];if(x){const y=this.getAssetPlayer(x.identifier);if(m.appendInPlace){const v=this.primaryMedia;y&&v&&this.bufferAssetPlayer(y,v)}else y&&y.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case z.ASSET_LIST_PARSING_ERROR:case z.ASSET_LIST_LOAD_ERROR:case z.ASSET_LIST_LOAD_TIMEOUT:{const r=t.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break}case z.BUFFER_STALLED_ERROR:{const r=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&r.event.appendInPlace){this.handleInPlaceStall(r.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const sp=500;class hP extends qu{constructor(e,t,r){super(e,t,r,"subtitle-stream-controller",we.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=te.IDLE,this.setInterval(sp),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:r,success:n}=t;if(this.fragContextChanged(r)||(zt(r)&&(this.fragPrevious=r),this.state=te.IDLE),!n)return;const i=this.tracksBuffered[this.currentTrackId];if(!i)return;let o;const l=r.start;for(let c=0;c<i.length;c++)if(l>=i[c].start&&l<=i[c].end){o=i[c];break}const d=r.start+r.duration;o?o.end=d:(o={start:l,end:d},i.push(o)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:r,endOffset:n}=t;if(r===0&&n!==Number.POSITIVE_INFINITY){const i=n-1;if(i<=0)return;t.endOffsetSubtitles=Math.max(0,i),this.tracksBuffered.forEach(o=>{for(let l=0;l<o.length;){if(o[l].end<=i){o.shift();continue}else if(o[l].start<i)o[l].start=i;else break;l++}}),this.fragmentTracker.removeFragmentsInRange(r,i,we.SUBTITLE)}}onError(e,t){const r=t.frag;(r==null?void 0:r.type)===we.SUBTITLE&&(t.details===z.FRAG_GAP&&this.fragmentTracker.fragBuffered(r,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==te.STOPPED&&(this.state=te.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Jy(this.levels,t)){this.levels=t.map(r=>new Aa(r));return}this.tracksBuffered=[],this.levels=t.map(r=>{const n=new Aa(r);return this.tracksBuffered[n.id]=[],n}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,we.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var r;if(this.currentTrackId=t.id,!((r=this.levels)!=null&&r.length)||this.currentTrackId===-1){this.clearInterval();return}const n=this.levels[this.currentTrackId];n!=null&&n.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,n&&this.state!==te.STOPPED&&this.setInterval(sp)}onSubtitleTrackLoaded(e,t){var r;const{currentTrackId:n,levels:i}=this,{details:o,id:l}=t;if(!i){this.warn(`Subtitle tracks were reset while loading level ${l}`);return}const d=i[l];if(l>=i.length||!d)return;this.log(`Subtitle track ${l} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""},duration:${o.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(o.live||(r=d.details)!=null&&r.live){if(o.deltaUpdateFailed)return;const h=this.mainDetails;if(!h){this.startFragRequested=!1;return}const f=h.fragments[0];if(!d.details)o.hasProgramDateTime&&h.hasProgramDateTime?(dl(o,h),c=o.fragmentStart):f&&(c=f.start,kd(o,c));else{var u;c=this.alignPlaylists(o,d.details,(u=this.levelLastLoaded)==null?void 0:u.details),c===0&&f&&(c=f.start,kd(o,c))}h&&!this.startFragRequested&&this.setStartPosition(h,c)}d.details=o,this.levelLastLoaded=d,l===n&&(this.hls.trigger(E.SUBTITLE_TRACK_UPDATED,{details:o,id:l,groupId:t.groupId}),this.tick(),o.live&&!this.fragCurrent&&this.media&&this.state===te.IDLE&&(kn(null,o.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),d.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:r}=e,n=t.decryptdata,i=this.hls;if(!this.fragContextChanged(t)&&r&&r.byteLength>0&&n!=null&&n.key&&n.iv&&fi(n.method)){const o=performance.now();
vendor: 29,004 bytes, lines 689-700
689this.decrypter.decrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer,Gu(n.method)).catch(l=>{throw i.trigger(E.ERROR,{type:Re.MEDIA_ERROR,details:z.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:t}),l}).then(l=>{const d=performance.now();i.trigger(E.FRAG_DECRYPTED,{frag:t,payload:l,stats:{tstart:o,tdecrypt:d}})}).catch(l=>{this.warn(`${l.name}: ${l.message}`),this.state=te.IDLE})}}doTick(){if(!this.media){this.state=te.IDLE;return}if(this.state===te.IDLE){const{currentTrackId:e,levels:t}=this,r=t==null?void 0:t[e];if(!r||!t.length||!r.details||this.waitForLive(r))return;const{config:n}=this,i=this.getLoadPosition(),o=Ue.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,n.maxBufferHole),{end:l,len:d}=o,c=r.details,u=this.hls.maxBufferLength+c.levelTargetDuration;if(d>u)return;const h=c.fragments,f=h.length,m=c.edge;let p=null;const x=this.fragPrevious;if(l<m){const _=n.maxFragLookUpTolerance,b=l>m-_?0:_;p=kn(x,h,Math.max(h[0].start,l),b),!p&&x&&x.start<h[0].start&&(p=h[0])}else p=h[f-1];if(p=this.filterReplacedPrimary(p,r.details),!p)return;const y=p.sn-c.startSN,v=h[y-1];if(v&&v.cc===p.cc&&this.fragmentTracker.getState(v)===ss.NOT_LOADED&&(p=v),this.fragmentTracker.getState(p)===ss.NOT_LOADED){const _=this.mapToInitFragWhenRequired(p);_&&this.loadFragment(_,r,l)}}}loadFragment(e,t,r){zt(e)?super.loadFragment(e,t,r):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new fP(this.tracksBuffered[this.currentTrackId]||[])}}class fP{constructor(e){this.buffered=void 0;const t=(r,n,i)=>{if(n=n>>>0,n>i-1)throw new DOMException(`Failed to execute '${r}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${i})`);return e[n][r]};this.buffered={get length(){return e.length},end(r){return t("end",r,e.length)},start(r){return t("start",r,e.length)}}}}const mP={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},mv=s=>String.fromCharCode(mP[s]||s),Js=15,Ar=100,pP={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},gP={17:2,18:4,21:6,22:8,23:10,19:13,20:15},xP={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},yP={25:2,26:4,29:6,30:8,31:10,27:13,28:15},vP=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class bP{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const r=typeof t=="function"?t():t;vt.log(`${this.time} [${e}] ${r}`)}}}const mn=function(e){const t=[];for(let r=0;r<e.length;r++)t.push(e[r].toString(16));return t};class pv{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let r=0;r<t.length;r++){const n=t[r];e.hasOwnProperty(n)&&(this[n]=e[n])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class _P{constructor(){this.uchar=" ",this.penState=new pv}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class wP{constructor(e){this.chars=[],this.pos=0,this.currPenState=new pv,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Ar;t++)this.chars.push(new _P);this.logger=e}equals(e){for(let t=0;t<Ar;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Ar;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Ar;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Ar&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ar)}moveCursor(e){const t=this.pos+e;if(e>1)for(let r=this.pos+1;r<t+1;r++)this.chars[r].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=mv(e);if(this.pos>=Ar){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<Ar;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let r=0;r<Ar;r++){const n=this.chars[r].uchar;n!==" "&&(t=!1),e.push(n)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class kc{constructor(e){this.rows=[],this.currRow=Js-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Js;t++)this.rows.push(new wP(e));this.logger=e}reset(){for(let e=0;e<Js;e++)this.rows[e].clear();this.currRow=Js-1}equals(e){let t=!0;for(let r=0;r<Js;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}copy(e){for(let t=0;t<Js;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Js;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+Rt(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let l=0;l<Js;l++)this.rows[l].clear();const i=this.currRow+1-this.nrRollUpRows,o=this.lastOutputScreen;if(o){const l=o.rows[i].cueStartTime,d=this.logger.time;if(l!==null&&d!==null&&l<d)for(let c=0;c<this.nrRollUpRows;c++)this.rows[t-this.nrRollUpRows+c+1].copy(o.rows[i+c])}}this.currRow=t;const r=this.rows[this.currRow];if(e.indent!==null){const i=e.indent,o=Math.max(i-1,0);r.setCursor(e.indent),e.color=r.chars[o].penState.foreground}const n={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(n)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+Rt(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let r="",n=-1;for(let i=0;i<Js;i++){const o=this.rows[i].getTextString();o&&(n=i+1,e?t.push("Row "+n+": '"+o+"'"):t.push(o.trim()))}return t.length>0&&(e?r="["+t.join(" | ")+"]":r=t.join(`
690`)),r}getTextAndFormat(){return this.rows}}class rp{constructor(e,t,r){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new kc(r),this.nonDisplayedMemory=new kc(r),this.lastOutputScreen=new kc(r),this.currRollUpRow=this.displayedMemory.rows[Js-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Js-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let r=0;r<e.length;r++)this.writeScreen.insertChar(e[r]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const r=Math.floor(e/2)-16,n=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=n[r]}this.logger.log(2,"MIDROW: "+Rt(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class np{constructor(e,t,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=SP(),this.logger=void 0;const n=this.logger=new bP;this.channels=[null,new rp(e,t,n),new rp(e+1,r,n)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let r=0;r<t.length;r+=2){const n=t[r]&127,i=t[r+1]&127;let o=!1,l=null;if(n===0&&i===0)continue;this.logger.log(3,()=>"["+mn([t[r],t[r+1]])+"] -> ("+mn([n,i])+")");const d=this.cmdHistory;if(n>=16&&n<=31){if(EP(n,i,d)){co(null,null,d),this.logger.log(3,()=>"Repeated command ("+mn([n,i])+") is dropped");continue}co(n,i,this.cmdHistory),o=this.parseCmd(n,i),o||(o=this.parseMidrow(n,i)),o||(o=this.parsePAC(n,i)),o||(o=this.parseBackgroundAttributes(n,i))}else co(null,null,d);if(!o&&(l=this.parseChars(n,i),l)){const u=this.currentChannel;u&&u>0?this.channels[u].insertChars(l):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!o&&!l&&this.logger.log(2,()=>"Couldn't parse cleaned data "+mn([n,i])+" orig: "+mn([t[r],t[r+1]]))}}parseCmd(e,t){const r=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=33&&t<=35;if(!(r||n))return!1;const i=e===20||e===21||e===23?1:2,o=this.channels[i];return e===20||e===21||e===28||e===29?t===32?o.ccRCL():t===33?o.ccBS():t===34?o.ccAOF():t===35?o.ccAON():t===36?o.ccDER():t===37?o.ccRU(2):t===38?o.ccRU(3):t===39?o.ccRU(4):t===40?o.ccFON():t===41?o.ccRDC():t===42?o.ccTR():t===43?o.ccRTD():t===44?o.ccEDM():t===45?o.ccCR():t===46?o.ccENM():t===47&&o.ccEOC():o.ccTO(t-32),this.currentChannel=i,!0}parseMidrow(e,t){let r=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?r=1:r=2,r!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const n=this.channels[r];return n?(n.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+mn([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let r;const n=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,i=(e===16||e===24)&&t>=64&&t<=95;if(!(n||i))return!1;const o=e<=23?1:2;t>=64&&t<=95?r=o===1?pP[e]:xP[e]:r=o===1?gP[e]:yP[e];const l=this.channels[o];return l?(l.setPAC(this.interpretPAC(r,t)),this.currentChannel=o,!0):!1}interpretPAC(e,t){let r;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?r=t-96:r=t-64,n.underline=(r&1)===1,r<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(n.italics=!0,n.color="white"):n.indent=Math.floor((r-16)/2)*4,n}parseChars(e,t){let r,n=null,i=null;if(e>=25?(r=2,i=e-8):(r=1,i=e),i>=17&&i<=19){let o;i===17?o=t+80:i===18?o=t+112:o=t+144,this.logger.log(2,()=>"Special char '"+mv(o)+"' in channel "+r),n=[o]}else e>=32&&e<=127&&(n=t===0?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes =  "+mn(n).join(",")),n}parseBackgroundAttributes(e,t){const r=(e===16||e===24)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=45&&t<=47;if(!(r||n))return!1;let i;const o={};e===16||e===24?(i=Math.floor((t-32)/2),o.background=vP[i],t%2===1&&(o.background=o.background+"_semi")):t===45?o.background="transparent":(o.foreground="black",t===47&&(o.underline=!0));const l=e<=23?1:2;return this.channels[l].setBkgData(o),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}co(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const r=this.channels[t];r&&r.cueSplitAtTime(e)}}}function co(s,e,t){t.a=s,t.b=e}function EP(s,e,t){return t.a===s&&t.b===e}function SP(){return{a:null,b:null}}var rh=function(){if(cl!=null&&cl.VTTCue)return self.VTTCue;const s=["","lr","rl"],e=["start","middle","end","left","right"];function t(l,d){if(typeof d!="string"||!Array.isArray(l))return!1;const c=d.toLowerCase();return~l.indexOf(c)?c:!1}function r(l){return t(s,l)}function n(l){return t(e,l)}function i(l,...d){let c=1;for(;c<arguments.length;c++){const u=arguments[c];for(const h in u)l[h]=u[h]}return l}function o(l,d,c){const u=this,h={enumerable:!0};u.hasBeenReset=!1;let f="",m=!1,p=l,x=d,y=c,v=null,_="",b=!0,w="auto",T="start",A=50,S="middle",I=50,j="middle";Object.defineProperty(u,"id",i({},h,{get:function(){return f},set:function(R){f=""+R}})),Object.defineProperty(u,"pauseOnExit",i({},h,{get:function(){return m},set:function(R){m=!!R}})),Object.defineProperty(u,"startTime",i({},h,{get:function(){return p},set:function(R){if(typeof R!="number")throw new TypeError("Start time must be set to a number.");p=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"endTime",i({},h,{get:function(){return x},set:function(R){if(typeof R!="number")throw new TypeError("End time must be set to a number.");x=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"text",i({},h,{get:function(){return y},set:function(R){y=""+R,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",i({},h,{get:function(){return v},set:function(R){v=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",i({},h,{get:function(){return _},set:function(R){const k=r(R);if(k===!1)throw new SyntaxError("An invalid or illegal string was specified.");_=k,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",i({},h,{get:function(){return b},set:function(R){b=!!R,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",i({},h,{get:function(){return w},set:function(R){if(typeof R!="number"&&R!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");w=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"lineAlign",i({},h,{get:function(){return T},set:function(R){const k=n(R);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");T=k,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",i({},h,{get:function(){return A},set:function(R){if(R<0||R>100)throw new Error("Position must be between 0 and 100.");A=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",i({},h,{get:function(){return S},set:function(R){const k=n(R);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");S=k,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",i({},h,{get:function(){return I},set:function(R){if(R<0||R>100)throw new Error("Size must be between 0 and 100.");I=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",i({},h,{get:function(){return j},set:function(R){const k=n(R);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");j=k,this.hasBeenReset=!0}})),u.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o}();class TP{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function gv(s){function e(r,n,i,o){return(r|0)*3600+(n|0)*60+(i|0)+parseFloat(o||0)}const t=s.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class AP{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,r){for(let n=0;n<r.length;++n)if(t===r[n]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const r=parseFloat(t);if(r>=0&&r<=100)return this.set(e,r),!0}return!1}}function xv(s,e,t,r){const n=r?s.split(r):[s];for(const i in n){if(typeof n[i]!="string")continue;const o=n[i].split(t);if(o.length!==2)continue;const l=o[0],d=o[1];e(l,d)}}const Dd=new rh(0,0,""),uo=Dd.align==="middle"?"middle":"center";function kP(s,e,t){const r=s;function n(){const l=gv(s);if(l===null)throw new Error("Malformed timestamp: "+r);return s=s.replace(/^[^\sa-zA-Z-]+/,""),l}function i(l,d){const c=new AP;xv(l,function(f,m){let p;switch(f){case"region":for(let x=t.length-1;x>=0;x--)if(t[x].id===m){c.set(f,t[x].region);break}break;case"vertical":c.alt(f,m,["rl","lr"]);break;case"line":p=m.split(","),c.integer(f,p[0]),c.percent(f,p[0])&&c.set("snapToLines",!1),c.alt(f,p[0],["auto"]),p.length===2&&c.alt("lineAlign",p[1],["start",uo,"end"]);break;case"position":p=m.split(","),c.percent(f,p[0]),p.length===2&&c.alt("positionAlign",p[1],["start",uo,"end","line-left","line-right","auto"]);break;case"size":c.percent(f,m);break;case"align":c.alt(f,m,["start",uo,"end","left","right"]);break}},/:/,/\s/),d.region=c.get("region",null),d.vertical=c.get("vertical","");let u=c.get("line","auto");u==="auto"&&Dd.line===-1&&(u=-1),d.line=u,d.lineAlign=c.get("lineAlign","start"),d.snapToLines=c.get("snapToLines",!0),d.size=c.get("size",100),d.align=c.get("align",uo);let h=c.get("position","auto");h==="auto"&&Dd.position===50&&(h=d.align==="start"||d.align==="left"?0:d.align==="end"||d.align==="right"?100:50),d.position=h}function o(){s=s.replace(/^\s+/,"")}if(o(),e.startTime=n(),o(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+r);s=s.slice(3),o(),e.endTime=n(),o(),i(s,e)}function yv(s){return s.replace(/<br(?: \/)?>/gi,`
691`)}class RP{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new TP,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function r(){let i=t.buffer,o=0;for(i=yv(i);o<i.length&&i[o]!=="\r"&&i[o]!==`
692`;)++o;const l=i.slice(0,o);return i[o]==="\r"&&++o,i[o]===`
693`&&++o,t.buffer=i.slice(o),l}function n(i){xv(i,function(o,l){},/:/)}try{let i="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;i=r();const l=i.match(/^()?WEBVTT([ \t].*)?$/);if(!(l!=null&&l[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let o=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(o?o=!1:i=r(),t.state){case"HEADER":/:/.test(i)?n(i):i||(t.state="ID");continue;case"NOTE":i||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(i)){t.state="NOTE";break}if(!i)continue;if(t.cue=new rh(0,0,""),t.state="CUE",i.indexOf("-->")===-1){t.cue.id=i;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{kP(i,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const l=i.indexOf("-->")!==-1;if(!i||l&&(o=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
694`),t.cue.text+=i}continue;case"BADCUE":i||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
695
696`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const jP=/\r\n|\n\r|\n|\r/g,Rc=function(e,t,r=0){return e.slice(r,r+t.length)===t},IP=function(e){let t=parseInt(e.slice(-3));const r=parseInt(e.slice(-6,-4)),n=parseInt(e.slice(-9,-7)),i=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!xe(t)||!xe(r)||!xe(n)||!xe(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*r,t+=60*1e3*n,t+=60*60*1e3*i,t};function nh(s,e,t){return ca(s.toString())+ca(e.toString())+ca(t)}const CP=function(e,t,r){let n=e[t],i=e[n.prevCC];if(!i||!i.new&&n.new){e.ccOffset=e.presentationOffset=n.start,n.new=!1;return}for(;(o=i)!=null&&o.new;){var o;e.ccOffset+=n.start-i.start,n.new=!1,n=i,i=e[n.prevCC]}e.presentationOffset=r};function NP(s,e,t,r,n,i,o){const l=new RP,d=Os(new Uint8Array(s)).trim().replace(jP,`
697`).split(`
698`),c=[],u=e?FN(e.baseTime,e.timescale):0;let h="00:00.000",f=0,m=0,p,x=!0;l.oncue=function(y){const v=t[r];let _=t.ccOffset;const b=(f-u)/9e4;if(v!=null&&v.new&&(m!==void 0?_=t.ccOffset=v.start:CP(t,r,b)),b){if(!e){p=new Error("Missing initPTS for VTT MPEGTS");return}_=b-t.presentationOffset}const w=y.endTime-y.startTime,T=Cs((y.startTime+_-m)*9e4,n*9e4)/9e4;y.startTime=Math.max(T,0),y.endTime=Math.max(T+w,0);const A=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(A)),y.id||(y.id=nh(y.startTime,y.endTime,A)),y.endTime>0&&c.push(y)},l.onparsingerror=function(y){p=y},l.onflush=function(){if(p){o(p);return}i(c)},d.forEach(y=>{if(x)if(Rc(y,"X-TIMESTAMP-MAP=")){x=!1,y.slice(16).split(",").forEach(v=>{Rc(v,"LOCAL:")?h=v.slice(6):Rc(v,"MPEGTS:")&&(f=parseInt(v.slice(7)))});try{m=IP(h)/1e3}catch(v){p=v}return}else y===""&&(x=!1);l.parse(y+`
699`)}),l.flush()}const jc="stpp.ttml.im1t",vv=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,bv=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,LP={left:"start",center:"center",right:"end",start:"start",end:"end"};function ip(s,e,t,r){const n=Ze(new Uint8Array(s),["mdat"]);if(n.length===0){r(new Error("Could not parse IMSC1 mdat"));return}const i=n.map(l=>Os(l)),o=MN(e.baseTime,1,e.timescale);try{i.forEach(l=>t(PP(l,o)))}catch(l){r(l)}}function PP(s,e){const n=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!n)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},o=Object.keys(i).reduce((h,f)=>(h[f]=n.getAttribute(`ttp:${f}`)||i[f],h),{}),l=n.getAttribute("xml:space")!=="preserve",d=ap(Ic(n,"styling","style")),c=ap(Ic(n,"layout","region")),u=Ic(n,"body","[begin]");return[].map.call(u,h=>{const f=_v(h,l);if(!f||!h.hasAttribute("begin"))return null;const m=Nc(h.getAttribute("begin"),o),p=Nc(h.getAttribute("dur"),o);let x=Nc(h.getAttribute("end"),o);if(m===null)throw op(h);if(x===null){if(p===null)throw op(h);x=m+p}const y=new rh(m-e,x-e,f);y.id=nh(y.startTime,y.endTime,y.text);const v=c[h.getAttribute("region")],_=d[h.getAttribute("style")],b=DP(v,_,d),{textAlign:w}=b;if(w){const T=LP[w];T&&(y.lineAlign=T),y.align=w}return Tt(y,b),y}).filter(h=>h!==null)}function Ic(s,e,t){const r=s.getElementsByTagName(e)[0];return r?[].slice.call(r.querySelectorAll(t)):[]}function ap(s){return s.reduce((e,t)=>{const r=t.getAttribute("xml:id");return r&&(e[r]=t),e},{})}function _v(s,e){return[].slice.call(s.childNodes).reduce((t,r,n)=>{var i;return r.nodeName==="br"&&n?t+`
700`:(i=r.childNodes)!=null&&i.length?_v(r,e):e?t+r.textContent.trim().replace(/\s+/g," "):t+r.textContent},"")}function DP(s,e,t){const r="http://www.w3.org/ns/ttml#styling";let n=null;const i=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],o=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return o&&t.hasOwnProperty(o)&&(n=t[o]),i.reduce((l,d)=>{const c=Cc(e,r,d)||Cc(s,r,d)||Cc(n,r,d);return c&&(l[d]=c),l},{})}function Cc(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function op(s){return new Error(`Could not parse ttml timestamp ${s}`)}function Nc(s,e){if(!s)return null;let t=gv(s);return t===null&&(vv.test(s)?t=OP(s,e):bv.test(s)&&(t=MP(s,e))),t}function OP(s,e){const t=vv.exec(s),r=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+r/e.frameRate}function MP(s,e){const t=bv.exec(s),r=Number(t[1]);switch(t[2]){case"h":return r*3600;case"m":return r*60;case"ms":return r*1e3;case"f":return r/e.frameRate;case"t":return r/e.tickRate}return r}class ho{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,r){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class FP{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=cp(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}}
vendor: 4,134 bytes, line 700
700,e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new ho(this,"textTrack1"),t=new ho(this,"textTrack2"),r=new ho(this,"textTrack3"),n=new ho(this,"textTrack4");this.cea608Parser1=new np(1,e,t),this.cea608Parser2=new np(3,r,n)}addCues(e,t,r,n,i){let o=!1;for(let l=i.length;l--;){const d=i[l],c=$P(d[0],d[1],t,r);if(c>=0&&(d[0]=Math.min(d[0],t),d[1]=Math.max(d[1],r),o=!0,c/(r-t)>.5))return}if(o||i.push([t,r]),this.config.renderTextTracksNatively){const l=this.captionsTracks[e];this.Cues.newCue(l,t,r,n)}else{const l=this.Cues.newCue(null,t,r,n);this.hls.trigger(E.CUES_PARSED,{type:"captions",cues:l,track:e})}}onInitPtsFound(e,{frag:t,id:r,initPTS:n,timescale:i,trackId:o}){const{unparsedVttFrags:l}=this;r===we.MAIN&&(this.initPTS[t.cc]={baseTime:n,timescale:i,trackId:o}),l.length&&(this.unparsedVttFrags=[],l.forEach(d=>{this.initPTS[d.frag.cc]?this.onFragLoaded(E.FRAG_LOADED,d):this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:d.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:r}=this;if(r)for(let n=0;n<r.textTracks.length;n++){const i=r.textTracks[n];if(lp(i,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return i}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:r,media:n}=this,{label:i,languageCode:o}=t[e],l=this.getExistingTrack(i,o);if(l)r[e]=l,oi(r[e]),uv(r[e],n);else{const d=this.createTextTrack("captions",i,o);d&&(d[e]=!0,r[e]=d)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const r=t.label,n={_id:e,label:r,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=n,this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[n]})}createTextTrack(e,t,r){const n=this.media;if(n)return n.addTextTrack(e,t,r)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const r=!!t.transferMedia;if(this.media=null,r)return;const{captionsTracks:n}=this;Object.keys(n).forEach(i=>{oi(n[i]),delete n[i]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=cp(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let r=0;r<t.length;r++)oi(t[r])}
vendor: 23,084 bytes, line 700
700onSubtitleTracksUpdated(e,t){const r=t.subtitleTracks||[],n=r.some(i=>i.textCodec===jc);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(Jy(this.tracks,r)){this.tracks=r;return}if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const o=this.media,l=o?No(o.textTracks):null;if(this.tracks.forEach((d,c)=>{let u;if(l){let h=null;for(let f=0;f<l.length;f++)if(l[f]&&lp(l[f],d)){h=l[f],l[f]=null;break}h&&(u=h)}if(u)oi(u);else{const h=wv(d);u=this.createTextTrack(h,d.name,d.lang),u&&(u.mode="disabled")}u&&this.textTracks.push(u)}),l!=null&&l.length){const d=l.filter(c=>c!==null).map(c=>c.label);d.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${d.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const o=this.tracks.map(l=>({label:l.name,kind:l.type.toLowerCase(),default:l.default,subtitleTrack:l}));this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:o})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(r=>{const n=/(?:CC|SERVICE)([1-4])/.exec(r.instreamId);if(!n)return;const i=`textTrack${n[1]}`,o=this.captionsProperties[i];o&&(o.label=r.name,r.lang&&(o.languageCode=r.lang),o.media=r)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===we.MAIN){var r,n;const{cea608Parser1:i,cea608Parser2:o,lastSn:l}=this,{cc:d,sn:c}=t.frag,u=(r=(n=t.part)==null?void 0:n.index)!=null?r:-1;i&&o&&(c!==l+1||c===l&&u!==this.lastPartIndex+1||d!==this.lastCc)&&(i.reset(),o.reset()),this.lastCc=d,this.lastSn=c,this.lastPartIndex=u}}onFragLoaded(e,t){const{frag:r,payload:n}=t;if(r.type===we.SUBTITLE)if(n.byteLength){const i=r.decryptdata,o="stats"in t;if(i==null||!i.encrypted||o){const l=this.tracks[r.level],d=this.vttCCs;d[r.cc]||(d[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),l&&l.textCodec===jc?this._parseIMSC1(r,n):this._parseVTTs(t)}}else this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const r=this.hls;ip(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),r.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{r.logger.log(`Failed to parse IMSC1: ${n}`),r.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:n})})}_parseVTTs(e){var t;const{frag:r,payload:n}=e,{initPTS:i,unparsedVttFrags:o}=this,l=i.length-1;if(!i[r.cc]&&l===-1){o.push(e);return}const d=this.hls,c=(t=r.initSegment)!=null&&t.data?zs(r.initSegment.data,new Uint8Array(n)).buffer:n;NP(c,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,u=>{this._appendCues(u,r.level),d.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})},u=>{const h=u.message==="Missing initPTS for VTT MPEGTS";h?o.push(e):this._fallbackToIMSC1(r,n),d.logger.log(`Failed to parse VTT cue: ${u}`),!(h&&l>r.cc)&&d.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:u})})}_fallbackToIMSC1(e,t){const r=this.tracks[e.level];r.textCodec||ip(t,this.initPTS[e.cc],()=>{r.textCodec=jc,this._parseIMSC1(e,t)},()=>{r.textCodec="wvtt"})}_appendCues(e,t){const r=this.hls;if(this.config.renderTextTracksNatively){const n=this.textTracks[t];if(!n||n.mode==="disabled")return;e.forEach(i=>hv(n,i))}else{const n=this.tracks[t];if(!n)return;const i=n.default?"default":"subtitles"+t;r.trigger(E.CUES_PARSED,{type:"subtitles",cues:e,track:i})}}onFragDecrypted(e,t){const{frag:r}=t;r.type===we.SUBTITLE&&this.onFragLoaded(E.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:r,samples:n}=t;if(!(r.type===we.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let i=0;i<n.length;i++){const o=n[i].bytes;if(o){this.cea608Parser1||this.initCea608Parsers();const l=this.extractCea608Data(o);this.cea608Parser1.addData(n[i].pts,l[0]),this.cea608Parser2.addData(n[i].pts,l[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:r,endOffsetSubtitles:n,type:i}){const{media:o}=this;if(!(!o||o.currentTime<r)){if(!i||i==="video"){const{captionsTracks:l}=this;Object.keys(l).forEach(d=>Pd(l[d],t,r))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:l}=this;Object.keys(l).forEach(d=>Pd(l[d],t,n))}}}extractCea608Data(e){const t=[[],[]],r=e[0]&31;let n=2;for(let i=0;i<r;i++){const o=e[n++],l=127&e[n++],d=127&e[n++];if(l===0&&d===0)continue;if((4&o)!==0){const u=3&o;(u===0||u===1)&&(t[u].push(l),t[u].push(d))}}return t}}function wv(s){return s.characteristics&&/transcribes-spoken-dialog/gi.test(s.characteristics)&&/describes-music-and-sound/gi.test(s.characteristics)?"captions":"subtitles"}function lp(s,e){return!!s&&s.kind===wv(e)&&Id(e,s)}function $P(s,e,t,r){return Math.min(e,r)-Math.max(s,t)}function cp(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const UP=/\s/,BP={newCue(s,e,t,r){const n=[];let i,o,l,d,c;const u=self.VTTCue||self.TextTrackCue;for(let f=0;f<r.rows.length;f++)if(i=r.rows[f],l=!0,d=0,c="",!i.isEmpty()){var h;for(let x=0;x<i.chars.length;x++)UP.test(i.chars[x].uchar)&&l?d++:(c+=i.chars[x].uchar,l=!1);i.cueStartTime=e,e===t&&(t+=1e-4),d>=16?d--:d++;const m=yv(c.trim()),p=nh(e,t,m);s!=null&&(h=s.cues)!=null&&h.getCueById(p)||(o=new u(e,t,m),o.id=p,o.line=f+1,o.align="left",o.position=10+Math.min(80,Math.floor(d*8/32)*10),n.push(o))}return s&&n.length&&(n.sort((f,m)=>f.line==="auto"||m.line==="auto"?0:f.line>8&&m.line>8?m.line-f.line:f.line-m.line),n.forEach(f=>hv(s,f))),n}};function VP(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const GP=/(\d+)-(\d+)\/(\d+)/;class dp{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||KP,this.controller=new self.AbortController,this.stats=new Ou}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,r){const n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();const i=zP(e,this.controller.signal),o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:d,maxLoadTimeMs:c}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,i),self.clearTimeout(this.requestTimeout),t.timeout=d&&xe(d)?d:c,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout),(ja(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var f;this.response=this.loader=h;const m=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},c-(m-n.loading.start)),!h.ok){const{status:x,statusText:y}=h;throw new WP(y||"fetch, bad network response",x,h)}n.loading.first=m,n.total=HP(h.headers)||n.total;const p=(f=this.callbacks)==null?void 0:f.onProgress;return p&&xe(t.highWaterMark)?this.loadProgressively(h,n,e,t.highWaterMark,p):o?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{var f,m;const p=this.response;if(!p)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const x=h[l];x&&(n.loaded=n.total=x);const y={url:p.url,data:h,code:p.status},v=(f=this.callbacks)==null?void 0:f.onProgress;v&&!xe(t.highWaterMark)&&v(n,e,h,p),(m=this.callbacks)==null||m.onSuccess(y,n,e,p)}).catch(h=>{var f;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const m=h&&h.code||0,p=h?h.message:null;(f=this.callbacks)==null||f.onError({code:m,text:p},e,h?h.details:null,n)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,r,n=0,i){const o=new Ny,l=e.body.getReader(),d=()=>l.read().then(c=>{if(c.done)return o.dataLength&&i(t,r,o.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const u=c.value,h=u.length;return t.loaded+=h,h<n||o.dataLength?(o.push(u),o.dataLength>=n&&i(t,r,o.flush().buffer,e)):i(t,r,u.buffer,e),d()}).catch(()=>Promise.reject());return d()}}function zP(s,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Tt({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function qP(s){const e=GP.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function HP(s){const e=s.get("Content-Range");if(e){const r=qP(e);if(xe(r))return r}const t=s.get("Content-Length");if(t)return parseInt(t)}function KP(s,e){return new self.Request(s.url,e)}class WP extends Error{constructor(e,t,r){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=r}}const YP=/^age:\s*[\d.]+\s*$/im;class Ev{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Ou,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const r=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!(this.loader!==r||this.stats.aborted))return i(r,t.url)}).catch(o=>{if(!(this.loader!==r||this.stats.aborted))return r.open("GET",t.url,!0),i(r,t.url)}).then(()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,t,e)}).catch(o=>{var l;(l=this.callbacks)==null||l.onError({code:r.status,text:o.message},t,r,n)}):this.openAndSendXhr(r,t,e)}openAndSendXhr(e,t,r){e.readyState||e.open("GET",t.url,!0);const n=t.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:o}=r.loadPolicy;if(n)for(const l in n)e.setRequestHeader(l,n[l]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),r.timeout=i&&xe(i)?i:o,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:r}=this;if(!e||!t)return;const n=t.readyState,i=this.config;if(!r.aborted&&n>=2&&(r.loading.first===0&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),n===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const c=t.status,u=t.responseType==="text"?t.responseText:null;if(c>=200&&c<300){const p=u??t.response;if(p!=null){var o,l;r.loading.end=Math.max(self.performance.now(),r.loading.first);const x=t.responseType==="arraybuffer"?p.byteLength:p.length;r.loaded=r.total=x,r.bwEstimate=r.total*8e3/(r.loading.end-r.loading.first);const y=(o=this.callbacks)==null?void 0:o.onProgress;y&&y(r,e,p,t);const v={url:t.responseURL,data:p,code:c};(l=this.callbacks)==null||l.onSuccess(v,r,e,t);return}}const h=i.loadPolicy.errorRetry,f=r.retry,m={url:e.url,data:void 0,code:c};if(ol(h,f,!1,m))this.retry(h);else{var d;vt.error(`${c} while loading ${e.url}`),(d=this.callbacks)==null||d.onError({code:c,text:t.statusText},e,t,r)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(ol(e,t,!0))this.retry(e);else{var r;vt.warn(`timeout while loading ${(r=this.context)==null?void 0:r.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:r}=this;this.retryDelay=Uu(e,r.retry),r.retry++,vt.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${r.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&YP.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const XP={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},QP=yt(yt({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Ev,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:cC,bufferController:ZN,capLevelController:eh,errorController:mC,fpsController:eP,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:_y,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:XP},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},JP()),{},{subtitleStreamController:hP,subtitleTrackController:rP,timelineController:FP,audioStreamController:YN,audioTrackController:XN,emeController:mi,cmcdController:XL,contentSteeringController:JL,interstitialsController:uP});function JP(){return{cueHandler:BP,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function ZP(s,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=Od(s),n=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(o=>{const l=`${o==="level"?"playlist":o}LoadPolicy`,d=e[l]===void 0,c=[];i.forEach(u=>{const h=`${o}Loading${u}`,f=e[h];if(f!==void 0&&d){c.push(h);const m=r[l].default;switch(e[l]={default:m},u){case"TimeOut":m.maxLoadTimeMs=f,m.maxTimeToFirstByteMs=f;break;case"MaxRetry":m.errorRetry.maxNumRetry=f,m.timeoutRetry.maxNumRetry=f;break;case"RetryDelay":m.errorRetry.retryDelayMs=f,m.timeoutRetry.retryDelayMs=f;break;case"MaxRetryTimeout":m.errorRetry.maxRetryDelayMs=f,m.timeoutRetry.maxRetryDelayMs=f;break}}}),c.length&&t.warn(`hls.js config: "${c.join('", "')}" setting(s) are deprecated, use "${l}": ${Rt(e[l])}`)}),yt(yt({},r),e)}function Od(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(Od):Object.keys(s).reduce((e,t)=>(e[t]=Od(s[t]),e),{}):s}function eD(s,e){const t=s.loader;t!==dp&&t!==Ev?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):VP()&&(s.loader=dp,s.progressive=!0,s.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Lo=2,tD=.1,sD=.05,rD=100;class nD extends gy{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var r;(r=this.media)!=null&&r.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var r;this.ended=((r=this.media)==null?void 0:r.currentTime)||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(rD),this.mediaSource=t.mediaSource;const r=this.media=t.media;ys(r,"playing",this.onMediaPlaying),ys(r,"waiting",this.onMediaWaiting),ys(r,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:r}=this;r&&(ws(r,"playing",this.onMediaPlaying),ws(r,"waiting",this.onMediaWaiting),ws(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var r,n;const i=(r=this.hls)==null?void 0:r.config;if(!i)return;const o=this.media;if(!o)return;const{seeking:l}=o,d=this.seeking&&!l,c=!this.seeking&&l,u=o.paused&&!l||o.ended||o.playbackRate===0;if(this.seeking=l,e!==t){t&&(this.ended=0),this.moved=!0,l||(this.nudgeRetry=0,i.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(c||d){d&&this.stallResolved(e);return}if(u){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&o.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1}));return}if(!Ue.getBuffered(o).length){this.nudgeRetry=0;return}const h=Ue.bufferInfo(o,e,0),f=h.nextStart||0,m=this.fragmentTracker;if(l&&m&&this.hls){const A=up(this.hls.inFlightFragments,e),S=h.len>Lo,I=!f||A||f-e>Lo&&!m.getPartialFragment(e);if(S||I)return;this.moved=!1}const p=(n=this.hls)==null?void 0:n.latestLevelDetails;if(!this.moved&&this.stalled!==null&&m){if(!(h.len>0)&&!f)return;
vendor: 20,459 bytes, line 700
700const S=Math.max(f,h.start||0)-e,j=!!(p!=null&&p.live)?p.targetduration*2:Lo,R=fo(e,m);if(S>0&&(S<=j||R)){o.paused||this._trySkipBufferHole(R);return}}const x=i.detectStallWithCurrentTimeMs,y=self.performance.now(),v=this.waiting;let _=this.stalled;if(_===null)if(v>0&&y-v<x)_=this.stalled=v;else{this.stalled=y;return}const b=y-_;if(!l&&(b>=x||v)&&this.hls){var w;if(((w=this.mediaSource)==null?void 0:w.readyState)==="ended"&&!(p!=null&&p.live)&&Math.abs(e-((p==null?void 0:p.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return}const T=Ue.bufferInfo(o,e,i.maxBufferHole);this._tryFixBufferStall(T,b,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const r=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(r)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(E.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var r;const n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(r=this.buffered.audio)!=null&&r.length&&n&&n.length>1&&e>n.end(0)){const i=Ue.bufferedInfo(Ue.timeRangesToArray(this.buffered.audio),e,0);if(i.len>1&&t>=i.start){const o=Ue.timeRangesToArray(n),l=Ue.bufferedInfo(o,t,0).bufferedIndex;if(l>-1&&l<o.length-1){const d=Ue.bufferedInfo(o,e,0).bufferedIndex,c=o[l].end,u=o[l+1].start;if((d===-1||d>l)&&u-c<1&&e-c<2){const h=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${c} -> ${u} buffered index: ${d}`);this.warn(h.message),this.media.currentTime+=1e-6;let f=fo(e,this.fragmentTracker);f&&"fragment"in f?f=f.fragment:f||(f=void 0);const m=Ue.bufferInfo(this.media,e,0);this.hls.trigger(E.ERROR,{type:Re.MEDIA_ERROR,details:z.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:f,buffer:m.len,bufferInfo:m})}}}}}_tryFixBufferStall(e,t,r){var n,i;const{fragmentTracker:o,media:l}=this,d=(n=this.hls)==null?void 0:n.config;if(!l||!o||!d)return;const c=(i=this.hls)==null?void 0:i.latestLevelDetails,u=fo(r,o);if((u||c!=null&&c.live&&r<c.fragmentStart)&&(this._trySkipBufferHole(u)||!this.media))return;const h=e.buffered,f=this.adjacentTraversal(e,r);(h&&h.length>1&&e.len>d.maxBufferHole||e.nextStart&&(e.nextStart-r<d.maxBufferHole||f))&&(t>d.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const r=this.fragmentTracker,n=e.nextStart;if(r&&n){const i=r.getFragAtPos(t,we.MAIN),o=r.getFragAtPos(n,we.MAIN);if(i&&o)return o.sn-i.sn<2}return!1}_reportStall(e){const{hls:t,media:r,stallReported:n,stalled:i}=this;if(!n&&i!==null&&r&&t){this.stallReported=!0;const o=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${Rt(e)})`);this.warn(o.message),t.trigger(E.ERROR,{type:Re.MEDIA_ERROR,details:z.BUFFER_STALLED_ERROR,fatal:!1,error:o,buffer:e.len,bufferInfo:e,stalled:{start:i}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:r,media:n}=this,i=(t=this.hls)==null?void 0:t.config;if(!n||!r||!i)return 0;const o=n.currentTime,l=Ue.bufferInfo(n,o,0),d=o<l.start?l.start:l.nextStart;if(d&&this.hls){const u=l.len<=i.maxBufferHole,h=l.len>0&&l.len<1&&n.readyState<3,f=d-o;if(f>0&&(u||h)){if(f>i.maxBufferHole){let p=!1;if(o===0){const x=r.getAppendedFrag(0,we.MAIN);x&&d<x.end&&(p=!0)}if(!p&&e){var c;if(!((c=this.hls.loadLevelObj)!=null&&c.details)||up(this.hls.inFlightFragments,d))return 0;let y=!1,v=e.end;for(;v<d;){const _=fo(v,r);if(_)v+=_.duration;else{y=!0;break}}if(y)return 0}}const m=Math.max(d+sD,o+tD);if(this.warn(`skipping hole, adjusting currentTime from ${o} to ${m}`),this.moved=!0,n.currentTime=m,!(e!=null&&e.gap)){const p=new Error(`fragment loaded with buffer holes, seeking from ${o} to ${m}`),x={type:Re.MEDIA_ERROR,details:z.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:p,reason:p.message,buffer:l.len,bufferInfo:l};e&&("fragment"in e?x.part=e:x.frag=e),this.hls.trigger(E.ERROR,x)}return m}}return 0}_tryNudgeBuffer(e){const{hls:t,media:r,nudgeRetry:n}=this,i=t==null?void 0:t.config;if(!r||!i)return 0;const o=r.currentTime;if(this.nudgeRetry++,n<i.nudgeMaxRetry){const l=o+(n+1)*i.nudgeOffset,d=new Error(`Nudging 'currentTime' from ${o} to ${l}`);this.warn(d.message),r.currentTime=l,t.trigger(E.ERROR,{type:Re.MEDIA_ERROR,details:z.BUFFER_NUDGE_ON_STALL,error:d,fatal:!1,buffer:e.len,bufferInfo:e})}else{const l=new Error(`Playhead still not moving while enough data buffered @${o} after ${i.nudgeMaxRetry} nudges`);this.error(l.message),t.trigger(E.ERROR,{type:Re.MEDIA_ERROR,details:z.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:e.len,bufferInfo:e})}}}function up(s,e){const t=hp(s.main);if(t&&t.start<=e)return t;const r=hp(s.audio);return r&&r.start<=e?r:null}function hp(s){if(!s)return null;switch(s.state){case te.IDLE:case te.STOPPED:case te.ENDED:case te.ERROR:return null}return s.frag}function fo(s,e){return e.getAppendedFrag(s,we.MAIN)||e.getPartialFragment(s)}const iD=.25;function Md(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Lc(s,e,t,r,n){let i=new s(e,t,"");try{i.value=r,n&&(i.type=n)}catch{i=new s(e,t,Rt(n?yt({type:n},r):r))}return i}const mo=(()=>{const s=Md();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class aD{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(E.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var r;this.media=t.media,((r=t.overrides)==null?void 0:r.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&oi(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const r=e[t];if(r.kind==="metadata"&&r.label==="id3")return uv(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:r,enableID3MetadataCues:n}=this.hls.config;if(!r&&!n)return;const{samples:i}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=Md();if(o)for(let l=0;l<i.length;l++){const d=i[l].type;if(d===Ns.emsg&&!r||!n)continue;const c=$y(i[l].data),u=i[l].pts;let h=u+i[l].duration;h>mo&&(h=mo),h-u<=0&&(h=u+iD);for(let m=0;m<c.length;m++){const p=c[m];if(!Uy(p)){this.updateId3CueEnds(u,d);const x=Lc(o,u,h,p,d);x&&this.id3Track.addCue(x)}}}}updateId3CueEnds(e,t){var r;const n=(r=this.id3Track)==null?void 0:r.cues;if(n)for(let i=n.length;i--;){const o=n[i];o.type===t&&o.startTime<e&&o.endTime===mo&&(o.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:r,type:n}){const{id3Track:i,hls:o}=this;if(!o)return;const{config:{enableEmsgMetadataCues:l,enableID3MetadataCues:d}}=o;if(i&&(l||d)){let c;n==="audio"?c=u=>u.type===Ns.audioId3&&d:n==="video"?c=u=>u.type===Ns.emsg&&l:c=u=>u.type===Ns.audioId3&&d||u.type===Ns.emsg&&l,Pd(i,t,r,c)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:r,timelineOffset:n,enableDateRangeMetadataCues:i,interstitialsController:o}=this.hls.config;if(!i)return;const l=Md();if(r&&n&&!o){const{fragmentStart:x,fragmentEnd:y}=e;let v=this.assetCue;v?(v.startTime=x,v.endTime=y):l&&(v=this.assetCue=Lc(l,x,y,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=r,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:d}=this,{dateRanges:c}=e,u=Object.keys(c);let h=this.dateRangeCuesAppended;if(d&&t){var f;if((f=d.cues)!=null&&f.length){const x=Object.keys(h).filter(y=>!u.includes(y));for(let y=x.length;y--;){var m;const v=x[y],_=(m=h[v])==null?void 0:m.cues;delete h[v],_&&Object.keys(_).forEach(b=>{const w=_[b];if(w){w.removeEventListener("enter",this.onEventCueEnter);try{d.removeCue(w)}catch{}}})}}else h=this.dateRangeCuesAppended={}}const p=e.fragments[e.fragments.length-1];if(!(u.length===0||!xe(p==null?void 0:p.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let x=0;x<u.length;x++){const y=u[x],v=c[y],_=v.startTime,b=h[y],w=(b==null?void 0:b.cues)||{};let T=(b==null?void 0:b.durationKnown)||!1,A=mo;const{duration:S,endDate:I}=v;if(I&&S!==null)A=_+S,T=!0;else if(v.endOnNext&&!T){const R=u.reduce((k,D)=>{if(D!==v.id){const Y=c[D];if(Y.class===v.class&&Y.startDate>v.startDate&&(!k||v.startDate<k.startDate))return Y}return k},null);R&&(A=R.startTime,T=!0)}const j=Object.keys(v.attr);for(let R=0;R<j.length;R++){const k=j[R];if(!kC(k))continue;const D=w[k];if(D)T&&!(b!=null&&b.durationKnown)?D.endTime=A:Math.abs(D.startTime-_)>.01&&(D.startTime=_,D.endTime=A);else if(l){let Y=v.attr[k];RC(k)&&(Y=Xx(Y));const X=Lc(l,_,A,{key:k,data:Y},Ns.dateRange);X&&(X.id=y,this.id3Track.addCue(X),w[k]=X,o&&(k==="X-ASSET-LIST"||k==="X-ASSET-URL")&&X.addEventListener("enter",this.onEventCueEnter))}}h[y]={cues:w,dateRange:v,durationKnown:T}}}}}class oD{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,r=this.levelDetails;if(!t||!r)return;this.currentTime=t.currentTime;const n=this.computeLatency();if(n===null)return;this._latency=n;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:o}=this.config;if(!i||o===1||!r.live)return;const l=this.targetLatency;if(l===null)return;const d=n-l,c=Math.min(this.maxLatency,l+r.targetduration);if(d<c&&d>.05&&this.forwardBufferLength>1){const h=Math.min(2,Math.max(1,o)),f=Math.round(2/(1+Math.exp(-.75*d-this.edgeStalled))*20)/20,m=Math.min(h,Math.max(1,f));this.changeMediaPlaybackRate(t,m)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:r,targetduration:n}=e,{liveSyncDuration:i,liveSyncDurationCount:o,lowLatencyMode:l}=this.config,d=this.hls.userConfig;let c=l&&r||t;(this._targetLatencyUpdated||d.liveSyncDuration||d.liveSyncDurationCount||c===0)&&(c=i!==void 0?i:o*n);const u=n;return c+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const r=this.levelDetails;if(r===null)return null;const n=r.edge,i=e-t-this.edgeStalled,o=n-r.totalduration,l=n-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(o,i),l)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var r;t.details===z.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(r=this.levelDetails)!=null&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var r,n;e.playbackRate!==t&&((r=this.hls)==null||r.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(n=this.targetLatency)==null?void 0:n.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class lD extends Zu{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const r=this.hls.config.preferManagedMediaSource,n=[],i={},o={};let l=!1,d=!1,c=!1;t.levels.forEach(u=>{const h=u.attrs;let{audioCodec:f,videoCodec:m}=u;f&&(u.audioCodec=f=rl(f,r)||void 0),m&&(m=u.videoCodec=zI(m));const{width:p,height:x,unknownCodecs:y}=u,v=(y==null?void 0:y.length)||0;if(l||(l=!!(p&&x)),d||(d=!!m),c||(c=!!f),v||f&&!this.isAudioSupported(f)||m&&!this.isVideoSupported(m)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}const{CODECS:_,"FRAME-RATE":b,"HDCP-LEVEL":w,"PATHWAY-ID":T,RESOLUTION:A,"VIDEO-RANGE":S}=h,j=`${`${T||"."}-`}${u.bitrate}-${A}-${b}-${_}-${S}-${w}`;if(i[j])if(i[j].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const R=o[j]+=1;u.attrs["PATHWAY-ID"]=new Array(R+1).join(".");const k=this.createLevel(u);i[j]=k,n.push(k)}else i[j].addGroupId("audio",h.AUDIO),i[j].addGroupId("text",h.SUBTITLES);else{const R=this.createLevel(u);i[j]=R,o[j]=1,n.push(R)}}),this.filterAndSortMediaOptions(n,t,l,d,c)}createLevel(e){const t=new Aa(e),r=e.supplemental;if(r!=null&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){const n=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(n.message),t.supportedResult=ly(n,[])}return t}isAudioSupported(e){return Sa(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Sa(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,r,n,i){var o;let l=[],d=[],c=e;const u=((o=t.stats)==null?void 0:o.parsing)||{};if((r||n)&&i&&(c=c.filter(({videoCodec:_,videoRange:b,width:w,height:T})=>(!!_||!!(w&&T))&&eC(b))),c.length===0){Promise.resolve().then(()=>{if(this.hls){let _="no level with compatible codecs found in manifest",b=_;t.levels.length&&(b=`one or more CODECS in variant not supported: ${Rt(t.levels.map(T=>T.attrs.CODECS).filter((T,A,S)=>S.indexOf(T)===A))}`,this.warn(b),_+=` (${b})`);const w=new Error(_);this.hls.trigger(E.ERROR,{type:Re.MEDIA_ERROR,details:z.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:w,reason:b})}}),u.end=performance.now();return}t.audioTracks&&(l=t.audioTracks.filter(_=>!_.audioCodec||this.isAudioSupported(_.audioCodec)),fp(l)),t.subtitles&&(d=t.subtitles,fp(d));const h=c.slice(0);c.sort((_,b)=>{if(_.attrs["HDCP-LEVEL"]!==b.attrs["HDCP-LEVEL"])return(_.attrs["HDCP-LEVEL"]||"")>(b.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&_.height!==b.height)return _.height-b.height;if(_.frameRate!==b.frameRate)return _.frameRate-b.frameRate;if(_.videoRange!==b.videoRange)return nl.indexOf(_.videoRange)-nl.indexOf(b.videoRange);if(_.videoCodec!==b.videoCodec){const w=nm(_.videoCodec),T=nm(b.videoCodec);if(w!==T)return T-w}if(_.uri===b.uri&&_.codecSet!==b.codecSet){const w=sl(_.codecSet),T=sl(b.codecSet);if(w!==T)return T-w}return _.averageBitrate!==b.averageBitrate?_.averageBitrate-b.averageBitrate:0});let f=h[0];if(this.steering&&(c=this.steering.filterParsedLevels(c),c.length!==h.length)){for(let _=0;_<h.length;_++)if(h[_].pathwayId===c[0].pathwayId){f=h[_];break}}this._levels=c;for(let _=0;_<c.length;_++)if(c[_]===f){var m;this._firstLevel=_;const b=f.bitrate,w=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${c.length} level(s) found, first bitrate: ${b}`),((m=this.hls.userConfig)==null?void 0:m.abrEwmaDefaultEstimate)===void 0){const T=Math.min(b,this.hls.config.abrEwmaDefaultEstimateMax);T>w&&w===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=T)}break}const p=i&&!n,x=this.hls.config,y=!!(x.audioStreamController&&x.audioTrackController),v={levels:c,audioTracks:l,subtitleTracks:d,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:i,video:n,altAudio:y&&!p&&l.some(_=>!!_.url)};u.end=performance.now(),this.hls.trigger(E.MANIFEST_PARSED,v)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const u=new Error("invalid level idx"),h=e<0;if(this.hls.trigger(E.ERROR,{type:Re.OTHER_ERROR,details:z.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:u,reason:u.message}),h)return;e=Math.min(e,t.length-1)}const r=this.currentLevelIndex,n=this.currentLevel,i=n?n.attrs["PATHWAY-ID"]:void 0,o=t[e],l=o.attrs["PATHWAY-ID"];
vendor: 4,387 bytes, line 700
700if(this.currentLevelIndex=e,this.currentLevel=o,r===e&&n&&i===l)return;this.log(`Switching to level ${e} (${o.height?o.height+"p ":""}${o.videoRange?o.videoRange+" ":""}${o.codecSet?o.codecSet+" ":""}@${o.bitrate})${l?" with Pathway "+l:""} from level ${r}${i?" with Pathway "+i:""}`);const d={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(E.LEVEL_SWITCHING,d);const c=o.details;if(!c||c.live){const u=this.switchParams(o.uri,n==null?void 0:n.details,c);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),r=e.filter(n=>t.indexOf(n)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=r}}onError(e,t){t.fatal||!t.context||t.context.type===tt.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===we.MAIN){const r=t.elementaryStreams;if(!Object.keys(r).some(i=>!!r[i]))return;const n=this._levels[t.level];n!=null&&n.loadError&&(this.log(`Resetting level error count of ${n.loadError} on frag buffered`),n.loadError=0)}}onLevelLoaded(e,t){var r;const{level:n,details:i}=t,o=t.levelInfo;if(!o){var l;this.warn(`Invalid level index ${n}`),(l=t.deliveryDirectives)!=null&&l.skip&&(i.deltaUpdateFailed=!0);return}if(o===this.currentLevel||t.withoutMultiVariant){o.fragmentError===0&&(o.loadError=0);let d=o.details;d===t.details&&d.advanced&&(d=void 0),this.playlistLoaded(n,t,d)}else(r=t.deliveryDirectives)!=null&&r.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const r=this.getUrlWithDirectives(e.uri,t),n=this.currentLevelIndex,i=e.attrs["PATHWAY-ID"],o=e.details,l=o==null?void 0:o.age;this.log(`Loading level index ${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${i?" Pathway "+i:""}${l&&o.live?" age "+l.toFixed(1)+(o.type&&" "+o.type||""):""} ${r}`),this.hls.trigger(E.LEVEL_LOADING,{url:r,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const r=this._levels.filter((i,o)=>o!==e?!0:(this.steering&&this.steering.removeLevel(i),i===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,i.details&&i.details.fragments.forEach(l=>l.level=-1)),!1));jy(r),this._levels=r,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const n=r.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(E.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:r}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(E.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function fp(s){const e={};
vendor: 39,241 bytes, line 700
700s.forEach(t=>{const r=t.groupId||"";t.id=e[r]=e[r]||0,e[r]++})}function Sv(){return self.SourceBuffer||self.WebKitSourceBuffer}function Tv(){if(!rn())return!1;const e=Sv();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function cD(){if(!Tv())return!1;const s=rn();return typeof(s==null?void 0:s.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(Ta(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(Ta(e,"audio"))))}function dD(){var s;const e=Sv();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}const uD=100;class hD extends qu{constructor(e,t,r){super(e,t,r,"stream-controller",we.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const n=this.media,i=n?n.currentTime:null;if(i===null||!xe(i)||(this.log(`Media seeked to ${i.toFixed(3)}`),!this.getBufferedFrag(i)))return;const o=this.getFwdBufferInfoAtPos(n,i,we.MAIN,0);if(o===null||o.len===0){this.warn(`Main forward buffer length at ${i} on "seeked" event ${o?o.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:r,hls:n}=this;if(this.stopLoad(),this.setInterval(uD),this.level=-1,!this.startFragRequested){let i=n.startLevel;i===-1&&(n.config.testBandwidth&&this.levels.length>1?(i=0,this.bitrateTest=!0):i=n.firstAutoLevel),n.nextLoadLevel=i,this.level=n.loadLevel,this._hasEnoughToStart=!!t}r>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r),this.state=te.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=te.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case te.WAITING_LEVEL:{const{levels:e,level:t}=this,r=e==null?void 0:e[t],n=r==null?void 0:r.details;if(n&&(!n.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(n))break;this.state=te.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=te.IDLE;break}break}case te.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===te.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:r,media:n}=this;if(t===null||!n&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const i=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(r!=null&&r[i]))return;const o=r[i],l=this.getMainFwdBufferInfo();if(l===null)return;const d=this.getLevelDetails();if(d&&this._streamEnded(l,d)){const x={};this.altAudio===2&&(x.type="video"),this.hls.trigger(E.BUFFER_EOS,x),this.state=te.ENDED;return}if(!this.buffering)return;e.loadLevel!==i&&e.manualLevel===-1&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;const c=o.details;if(!c||this.state===te.WAITING_LEVEL||this.waitForLive(o)){this.level=i,this.state=te.WAITING_LEVEL,this.startFragRequested=!1;return}const u=l.len,h=this.getMaxBufferLength(o.maxBitrate);if(u>=h)return;this.backtrackFragment&&this.backtrackFragment.start>l.end&&(this.backtrackFragment=null);const f=this.backtrackFragment?this.backtrackFragment.start:l.end;let m=this.getNextFragment(f,c);if(this.couldBacktrack&&!this.fragPrevious&&m&&zt(m)&&this.fragmentTracker.getState(m)!==ss.OK){var p;const y=((p=this.backtrackFragment)!=null?p:m).sn-c.startSN,v=c.fragments[y-1];v&&m.cc===v.cc&&(m=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&l.len&&(this.backtrackFragment=null);if(m&&this.isLoopLoading(m,f)){if(!m.gap){const y=this.audioOnly&&!this.altAudio?kt.AUDIO:kt.VIDEO,v=(y===kt.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,y,we.MAIN)}m=this.getNextFragmentLoopLoading(m,c,l,we.MAIN,h)}m&&(m.initSegment&&!m.initSegment.data&&!this.bitrateTest&&(m=m.initSegment),this.loadFragment(m,o,f))}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);n===ss.NOT_LOADED||n===ss.PARTIAL?zt(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,r):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,we.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let r;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const i=this.getLevelDetails();if(i!=null&&i.live){const l=this.getMainFwdBufferInfo();if(!l||l.len<i.targetduration*2)return}if(!t.paused&&e){const l=this.hls.nextLoadLevel,d=e[l],c=this.fragLastKbps;c&&this.fragCurrent?r=this.fragCurrent.duration*d.maxBitrate/(1e3*c)+1:r=0}else r=0;const o=this.getBufferedFrag(t.currentTime+r);if(o){const l=this.followingBufferedFrag(o);if(l){this.abortCurrentFrag();const d=l.maxStartPTS?l.maxStartPTS:l.start,c=l.duration,u=Math.max(o.end,d+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*(this.couldBacktrack?.5:.125)),c*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(u,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case te.KEY_LOADING:case te.FRAG_LOADING:case te.FRAG_LOADING_WAITING_RETRY:case te.PARSING:case te.PARSED:this.state=te.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const r=t.media;ys(r,"playing",this.onMediaPlaying),ys(r,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:r}=this;r&&(ws(r,"playing",this.onMediaPlaying),ws(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(E.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let r=!1,n=!1;for(let i=0;i<t.levels.length;i++){const o=t.levels[i].audioCodec;o&&(r=r||o.indexOf("mp4a.40.2")!==-1,n=n||o.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=r&&n&&!dD(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:r}=this;if(!r||this.state!==te.IDLE)return;const n=t.levelInfo;(!n.details||n.details.live&&(this.levelLastLoaded!==n||n.details.expired)||this.waitForCdnTuneIn(n.details))&&(this.state=te.WAITING_LEVEL)}onLevelLoaded(e,t){var r;const{levels:n,startFragRequested:i}=this,o=t.level,l=t.details,d=l.totalduration;if(!n){this.warn(`Levels were reset while loading level ${o}`);return}this.log(`Level ${o} loaded [${l.startSN},${l.endSN}]${l.lastPartSn?`[part-${l.lastPartSn}-${l.lastPartIndex}]`:""}, cc [${l.startCC}, ${l.endCC}] duration:${d}`);const c=t.levelInfo,u=this.fragCurrent;u&&(this.state===te.FRAG_LOADING||this.state===te.FRAG_LOADING_WAITING_RETRY)&&u.level!==t.level&&u.loader&&this.abortCurrentFrag();let h=0;if(l.live||(r=c.details)!=null&&r.live){var f;if(this.checkLiveUpdate(l),l.deltaUpdateFailed)return;h=this.alignPlaylists(l,c.details,(f=this.levelLastLoaded)==null?void 0:f.details)}if(c.details=l,this.levelLastLoaded=c,i||this.setStartPosition(l,h),this.hls.trigger(E.LEVEL_UPDATED,{details:l,level:o}),this.state===te.WAITING_LEVEL){if(this.waitForCdnTuneIn(l))return;this.state=te.IDLE}i&&l.live&&this.synchronizeToLiveEdge(l),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:r}=this;if(!r)return;const n=this.hls.liveSyncPosition,i=this.getLoadPosition(),o=e.fragmentStart,l=e.edge,d=i>=o-t.maxFragLookUpTolerance&&i<=l;if(n!==null&&r.duration>n&&(i<n||!d)){const u=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!d&&r.readyState<4||i<l-u)&&(this._hasEnoughToStart||(this.nextLoadPosition=n),r.readyState))if(this.warn(`Playback: ${i.toFixed(3)} is located too far from the end of live sliding playlist: ${l}, reset currentTime to : ${n.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var c;const h=Ue.bufferInfo(r,n,0);if(!((c=h.buffered)!=null&&c.length)){r.currentTime=n;return}if(h.start<=i){r.currentTime=n;return}const{nextStart:m}=Ue.bufferedInfo(h.buffered,i,0);m&&(r.currentTime=m)}else r.currentTime=n}}_handleFragmentLoadProgress(e){var t;const r=e.frag,{part:n,payload:i}=e,{levels:o}=this;if(!o){this.warn(`Levels were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);return}const l=o[r.level];if(!l){this.warn(`Level ${r.level} not found on progress`);return}const d=l.details;if(!d){this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),this.fragmentTracker.removeFragment(r);return}const c=l.videoCodec,u=d.PTSKnown||!d.live,h=(t=r.initSegment)==null?void 0:t.data,f=this._getAudioCodec(l),m=this.transmuxer=this.transmuxer||new Qy(this.hls,we.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),p=n?n.index:-1,x=p!==-1,y=new Vu(r.level,r.sn,r.stats.chunkCount,i.byteLength,p,x),v=this.initPTS[r.cc];m.push(i,h,f,c,r,n,d.totalduration,u,y,v)}onAudioTrackSwitching(e,t){const r=this.hls,n=this.altAudio!==0;if(il(t.url,r))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const o=this.fragCurrent;o&&(this.log("Switching to main audio track, cancel main fragment load"),o.abortRequests(),this.fragmentTracker.removeFragment(o)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(n){this.altAudio=0,this.fragmentTracker.removeAllFragments(),r.once(E.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(E.AUDIO_TRACK_SWITCHED,t)}),r.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}r.trigger(E.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const r=il(t.url,this.hls);if(r){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=r?2:0,this.tick()}onBufferCreated(e,t){const r=t.tracks;let n,i,o=!1;for(const l in r){const d=r[l];if(d.id==="main"){if(i=l,n=d,l==="video"){const c=r[l];c&&(this.videoBuffer=c.buffer)}}else o=!0}o&&n?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:r,part:n}=t,i=r.type===we.MAIN;if(i){if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${n?" p: "+n.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),this.state===te.PARSED&&(this.state=te.IDLE);return}const l=n?n.stats:r.stats;this.fragLastKbps=Math.round(8*l.total/(l.buffering.end-l.loading.first)),zt(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,n)}const o=this.media;o&&(!this._hasEnoughToStart&&Ue.getBuffered(o).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var r;if(t.fatal){this.state=te.ERROR;return}switch(t.details){case z.FRAG_GAP:case z.FRAG_PARSING_ERROR:case z.FRAG_DECRYPT_ERROR:case z.FRAG_LOAD_ERROR:case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_ERROR:case z.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(we.MAIN,t);break;case z.LEVEL_LOAD_ERROR:case z.LEVEL_LOAD_TIMEOUT:case z.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===te.WAITING_LEVEL&&((r=t.context)==null?void 0:r.type)===tt.LEVEL&&(this.state=te.IDLE);break;case z.BUFFER_ADD_CODEC_ERROR:case z.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case z.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case z.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=te.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==kt.AUDIO||!this.altAudio){const r=(t===kt.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,t,we.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let r=this.startPosition;if(r>=0&&t<r){if(e.seeking){this.log(`could not seek to ${r}, already seeking at ${t}`);return}const n=this.timelineOffset;n&&r&&(r+=n);const i=this.getLevelDetails(),o=Ue.getBuffered(e),l=o.length?o.start(0):0,d=l-r,c=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||d>0&&(d<c||this.loadingParts&&d<2*((i==null?void 0:i.partTarget)||0)))&&(this.log(`adjusting start position by ${d} to match buffer start`),r+=d,this.startPosition=r),t<r&&(this.log(`seek to target start position ${r} from current time ${t} buffer start ${l}`),e.currentTime=r)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(r=>{const{hls:n}=this,i=r==null?void 0:r.frag;if(!i||this.fragContextChanged(i))return;t.fragmentError=0,this.state=te.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const o=i.stats;o.parsing.start=o.parsing.end=o.buffering.start=o.buffering.end=self.performance.now(),n.trigger(E.FRAG_LOADED,r),i.bitrateTest=!1}).catch(r=>{this.state===te.STOPPED||this.state===te.ERROR||(this.warn(r),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:r}=this,{remuxResult:n,chunkMeta:i}=e,o=this.getCurrentContext(i);if(!o){this.resetWhenMissingContext(i);return}const{frag:l,part:d,level:c}=o,{video:u,text:h,id3:f,initSegment:m}=n,{details:p}=c,x=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=te.PARSING,m){const y=m.tracks;if(y){const w=l.initSegment||l;if(this.unhandledEncryptionError(m,l))return;this._bufferInitSegment(c,y,w,i),r.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:w,id:t,tracks:y})}const v=m.initPTS,_=m.timescale,b=this.initPTS[l.cc];if(xe(v)&&(!b||b.baseTime!==v||b.timescale!==_)){const w=m.trackId;this.initPTS[l.cc]={baseTime:v,timescale:_,trackId:w},r.trigger(E.INIT_PTS_FOUND,{frag:l,id:t,initPTS:v,timescale:_,trackId:w})}}if(u&&p){x&&u.type==="audiovideo"&&this.logMuxedErr(l);const y=p.fragments[l.sn-1-p.startSN],v=l.sn===p.startSN,_=!y||l.cc>y.cc;if(n.independent!==!1){const{startPTS:b,endPTS:w,startDTS:T,endDTS:A}=u;if(d)d.elementaryStreams[u.type]={startPTS:b,endPTS:w,startDTS:T,endDTS:A};else if(u.firstKeyFrame&&u.independent&&i.id===1&&!_&&(this.couldBacktrack=!0),u.dropped&&u.independent){const S=this.getMainFwdBufferInfo(),I=(S?S.end:this.getLoadPosition())+this.config.maxBufferHole,j=u.firstKeyFramePTS?u.firstKeyFramePTS:b;if(!v&&I<j-this.config.maxBufferHole&&!_){this.backtrack(l);return}else _&&(l.gap=!0);l.setElementaryStreamInfo(u.type,l.start,w,l.start,A,!0)}else v&&b-(p.appliedTimelineOffset||0)>Lo&&(l.gap=!0);l.setElementaryStreamInfo(u.type,b,w,T,A),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(u,l,d,i,v||_)}else if(v||_)l.gap=!0;else{this.backtrack(l);return}}if(x){const{startPTS:y,endPTS:v,startDTS:_,endDTS:b}=x;d&&(d.elementaryStreams[kt.AUDIO]={startPTS:y,endPTS:v,startDTS:_,endDTS:b}),l.setElementaryStreamInfo(kt.AUDIO,y,v,_,b),this.bufferFragmentData(x,l,d,i)}if(p&&f!=null&&f.samples.length){const y={id:t,frag:l,details:p,samples:f.samples};r.trigger(E.FRAG_PARSING_METADATA,y)}if(p&&h){const y={id:t,frag:l,details:p,samples:h.samples};r.trigger(E.FRAG_PARSING_USERDATA,y)}}logMuxedErr(e){this.warn(`${zt(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,r,n){if(this.state!==te.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));const{audio:i,video:o,audiovideo:l}=t;if(i){const c=e.audioCodec;let u=Ao(i.codec,c);u==="mp4a"&&(u="mp4a.40.5");const h=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){u&&(u.indexOf("mp4a.40.5")!==-1?u="mp4a.40.2":u="mp4a.40.5");const f=i.metadata;f&&"channelCount"in f&&(f.channelCount||1)!==1&&h.indexOf("firefox")===-1&&(u="mp4a.40.5")}u&&u.indexOf("mp4a.40.5")!==-1&&h.indexOf("android")!==-1&&i.container!=="audio/mpeg"&&(u="mp4a.40.2",this.log(`Android: force audio codec to ${u}`)),c&&c!==u&&this.log(`Swapping manifest audio codec "${c}" for "${u}"`),i.levelCodec=u,i.id=we.MAIN,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${u||""}/${c||""}/${i.codec}]`),delete t.audiovideo}if(o){o.levelCodec=e.videoCodec,o.id=we.MAIN;const c=o.codec;if((c==null?void 0:c.length)===4)switch(c){case"hvc1":case"hev1":o.codec="hvc1.1.6.L120.90";break;case"av01":o.codec="av01.0.04M.08";break;case"avc1":o.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${o.container}, codecs[level/parsed]=[${e.videoCodec||""}/${c}]${o.codec!==c?" parsed-corrected="+o.codec:""}${o.supplemental?" supplemental="+o.supplemental:""}`),delete t.audiovideo}l&&(this.log(`Init audiovideo buffer, container:${l.container}, codecs[level/parsed]=[${e.codecs}/${l.codec}]`),delete t.video,delete t.audio);const d=Object.keys(t);if(d.length){if(this.hls.trigger(E.BUFFER_CODECS,t),!this.hls)return;d.forEach(c=>{const h=t[c].initSegment;h!=null&&h.byteLength&&this.hls.trigger(E.BUFFER_APPENDING,{type:c,data:h,frag:r,part:null,chunkMeta:n,parent:r.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,we.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,r=e==null?void 0:e[t];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=te.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const r=e.currentTime;if(Ue.isBuffered(e,r)?t=this.getAppendedFrag(r):Ue.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;const n=this.fragPlaying,i=t.level;(!n||t.sn!==n.sn||n.level!==i)&&(this.fragPlaying=t,this.hls.trigger(E.FRAG_CHANGED,{frag:t}),(!n||n.level!==i)&&this.hls.trigger(E.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return xe(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(xe(t)){const r=this.getLevelDetails(),n=this.currentFrag||(r?kn(null,r.fragments,t):null);if(n){const i=n.programDateTime;if(i!==null){const o=i+(t-n.start)*1e3;return new Date(o)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class fD extends Hs{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const r in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[r].loader;if(n){var t;if(e&&e!==((t=n.context)==null?void 0:t.frag.type))return;n.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=z.KEY_LOAD_ERROR,r,n,i){return new jr({type:Re.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:i,error:r,networkDetails:n})}loadClear(e,t,r){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let n=0,i=t.length;n<i;n++){const o=t[n];if(e.cc<=o.cc&&(!zt(e)||!zt(o)||e.sn<o.sn)||!r&&n==i-1)return this.emeController.selectKeySystemFormat(o).then(l=>{if(!this.emeController)return;o.setKeyFormat(l);const d=Ro(l);if(d)return this.emeController.getKeySystemAccess([d])})}if(this.config.requireKeySystemAccessOnStart){const n=Qi(this.config);if(n.length)return this.emeController.getKeySystemAccess(n)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var r,n;t&&e.setKeyFormat(t);const i=e.decryptdata;if(!i){const c=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,z.KEY_LOAD_ERROR,c))}const o=i.uri;if(!o)return Promise.reject(this.createKeyLoadError(e,z.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${o}"`)));const l=Pc(i);let d=this.keyIdToKeyInfo[l];if((r=d)!=null&&r.decryptdata.key)return i.key=d.decryptdata.key,Promise.resolve({frag:e,keyInfo:d});if(this.emeController&&(n=d)!=null&&n.keyLoadPromise)switch(this.emeController.getKeyStatus(d.decryptdata)){case"usable":case"usable-in-future":return d.keyLoadPromise.then(u=>{const{keyInfo:h}=u;return i.key=h.decryptdata.key,{frag:e,keyInfo:h}})}switch(this.log(`${this.keyIdToKeyInfo[l]?"Rel":"L"}oading${i.keyId?" keyId: "+ls(i.keyId):""} URI: ${i.uri} from ${e.type} ${e.level}`),d=this.keyIdToKeyInfo[l]={decryptdata:i,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return i.keyFormat==="identity"?this.loadKeyHTTP(d,e):this.loadKeyEME(d,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(d,e);default:return Promise.reject(this.createKeyLoadError(e,z.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(e,t){const r={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var n;if(!e.decryptdata.keyId&&(n=t.initSegment)!=null&&n.data){const o=NI(t.initSegment.data);if(o.length){let l=o[0];l.some(d=>d!==0)?(this.log(`Using keyId found in init segment ${ls(l)}`),Zr.setKeyIdForUri(e.decryptdata.uri,l)):(l=Zr.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${ls(l)}`)),e.decryptdata.keyId=l}}if(!e.decryptdata.keyId&&!zt(t))return Promise.resolve(r);const i=this.emeController.loadKey(r);return(e.keyLoadPromise=i.then(o=>(e.mediaKeySessionContext=o,r))).catch(o=>{throw e.keyLoadPromise=null,"data"in o&&(o.data.frag=t),o})}return Promise.resolve(r)}loadKeyHTTP(e,t){const r=this.config,n=r.loader,i=new n(r);return t.keyLoader=e.loader=i,e.keyLoadPromise=new Promise((o,l)=>{const d={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},c=r.keyLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(f,m,p,x)=>{const{frag:y,keyInfo:v}=p,_=Pc(v.decryptdata);if(!y.decryptdata||v!==this.keyIdToKeyInfo[_])return l(this.createKeyLoadError(y,z.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),x));v.decryptdata.key=y.decryptdata.key=new Uint8Array(f.data),y.keyLoader=null,v.loader=null,o({frag:y,keyInfo:v})},onError:(f,m,p,x)=>{this.resetLoader(m),l(this.createKeyLoadError(t,z.KEY_LOAD_ERROR,new Error(`HTTP Error ${f.code} loading key ${f.text}`),p,yt({url:d.url,data:void 0},f)))},onTimeout:(f,m,p)=>{this.resetLoader(m),l(this.createKeyLoadError(t,z.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),p))},onAbort:(f,m,p)=>{this.resetLoader(m),l(this.createKeyLoadError(t,z.INTERNAL_ABORTED,new Error("key loading aborted"),p))}};i.load(d,u,h)})}resetLoader(e){const{frag:t,keyInfo:r,url:n}=e,i=r.loader;t.keyLoader===i&&(t.keyLoader=null,r.loader=null);const o=Pc(r.decryptdata)||n;delete this.keyIdToKeyInfo[o],i&&i.destroy()}}function Pc(s){if(s.keyFormat!==cs.FAIRPLAY){const e=s.keyId;if(e)return ls(e)}return s.uri}function mp(s){const{type:e}=s;switch(e){case tt.AUDIO_TRACK:return we.AUDIO;case tt.SUBTITLE_TRACK:return we.SUBTITLE;default:return we.MAIN}}function Dc(s,e){let t=s.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class mD{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,r=t.pLoader,n=t.loader,i=r||n,o=new i(t);return this.loaders[e.type]=o,o}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:r}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:tt.MANIFEST,url:r,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:r,level:n,pathwayId:i,url:o,deliveryDirectives:l,levelInfo:d}=t;this.load({id:r,level:n,pathwayId:i,responseType:"text",type:tt.LEVEL,url:o,deliveryDirectives:l,levelOrTrack:d})}onAudioTrackLoading(e,t){const{id:r,groupId:n,url:i,deliveryDirectives:o,track:l}=t;this.load({id:r,groupId:n,level:null,responseType:"text",type:tt.AUDIO_TRACK,url:i,deliveryDirectives:o,levelOrTrack:l})}onSubtitleTrackLoading(e,t){const{id:r,groupId:n,url:i,deliveryDirectives:o,track:l}=t;this.load({id:r,groupId:n,level:null,responseType:"text",type:tt.SUBTITLE_TRACK,url:i,deliveryDirectives:o,levelOrTrack:l})}onLevelsUpdated(e,t){const r=this.loaders[tt.LEVEL];if(r){const n=r.context;n&&!t.levels.some(i=>i===n.levelOrTrack)&&(r.abort(),delete this.loaders[tt.LEVEL])}}load(e){var t;const r=this.hls.config;let n=this.getInternalLoader(e);if(n){const c=this.hls.logger,u=n.context;if(u&&u.levelOrTrack===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives)){u.url===e.url?c.log(`[playlist-loader]: ignore ${e.url} ongoing request`):c.log(`[playlist-loader]: ignore ${e.url} in favor of ${u.url}`);return}c.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let i;if(e.type===tt.MANIFEST?i=r.manifestLoadPolicy.default:i=Tt({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),xe((t=e.deliveryDirectives)==null?void 0:t.part)){let c;if(e.type===tt.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===tt.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===tt.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){const u=c.partTarget,h=c.targetduration;if(u&&h){const f=Math.max(u*3,h*.8)*1e3;i=Tt({},i,{maxTimeToFirstByteMs:Math.min(f,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(f,i.maxTimeToFirstByteMs)})}}}const o=i.errorRetry||i.timeoutRetry||{},l={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},d={onSuccess:(c,u,h,f)=>{const m=this.getInternalLoader(h);this.resetInternalLoader(h.type);const p=c.data;u.parsing.start=performance.now(),mr.isMediaPlaylist(p)||h.type!==tt.MANIFEST?this.handleTrackOrLevelPlaylist(c,u,h,f||null,m):this.handleMasterPlaylist(c,u,h,f)},onError:(c,u,h,f)=>{this.handleNetworkError(u,h,!1,c,f)},onTimeout:(c,u,h)=>{this.handleNetworkError(u,h,!0,void 0,c)}};n.load(e,l,d)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:r}=this.hls;(e||r)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,r,n){const i=this.hls,o=e.data,l=Dc(e,r),d=mr.parseMasterPlaylist(o,l);if(d.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,r,d.playlistParsingError,n,t);return}const{contentSteering:c,levels:u,sessionData:h,sessionKeys:f,startTimeOffset:m,variableList:p}=d;this.variableList=p,u.forEach(_=>{const{unknownCodecs:b}=_;if(b){const{preferManagedMediaSource:w}=this.hls.config;let{audioCodec:T,videoCodec:A}=_;for(let S=b.length;S--;){const I=b[S];Sa(I,"audio",w)?(_.audioCodec=T=T?`${T},${I}`:I,Si.audio[T.substring(0,4)]=2,b.splice(S,1)):Sa(I,"video",w)&&(_.videoCodec=A=A?`${A},${I}`:I,Si.video[A.substring(0,4)]=2,b.splice(S,1))}}});const{AUDIO:x=[],SUBTITLES:y,"CLOSED-CAPTIONS":v}=mr.parseMasterPlaylistMedia(o,l,d);x.length&&!x.some(b=>!b.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),x.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Dt({}),bitrate:0,url:""})),i.trigger(E.MANIFEST_LOADED,{levels:u,audioTracks:x,subtitles:y,captions:v,contentSteering:c,url:l,stats:t,networkDetails:n,sessionData:h,sessionKeys:f,startTimeOffset:m,variableList:p})}handleTrackOrLevelPlaylist(e,t,r,n,i){const o=this.hls,{id:l,level:d,type:c}=r,u=Dc(e,r),h=xe(d)?d:xe(l)?l:0,f=mp(r),m=mr.parseLevelPlaylist(e.data,u,h,f,0,this.variableList);if(c===tt.MANIFEST){const p={attrs:new Dt({}),bitrate:0,details:m,name:"",url:u};m.requestScheduled=t.loading.start+Ay(m,0),o.trigger(E.MANIFEST_LOADED,{levels:[p],audioTracks:[],url:u,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=m,this.handlePlaylistLoaded(m,e,t,r,n,i)}handleManifestParsingError(e,t,r,n,i){this.hls.trigger(E.ERROR,{type:Re.NETWORK_ERROR,details:z.MANIFEST_PARSING_ERROR,fatal:t.type===tt.MANIFEST,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:n,stats:i})}handleNetworkError(e,t,r=!1,n,i){let o=`A network ${r?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===tt.LEVEL?o+=`: ${e.level} id: ${e.id}`:(e.type===tt.AUDIO_TRACK||e.type===tt.SUBTITLE_TRACK)&&(o+=` id: ${e.id} group-id: "${e.groupId}"`);const l=new Error(o);this.hls.logger.warn(`[playlist-loader]: ${o}`);let d=z.UNKNOWN,c=!1;const u=this.getInternalLoader(e);switch(e.type){case tt.MANIFEST:d=r?z.MANIFEST_LOAD_TIMEOUT:z.MANIFEST_LOAD_ERROR,c=!0;break;case tt.LEVEL:d=r?z.LEVEL_LOAD_TIMEOUT:z.LEVEL_LOAD_ERROR,c=!1;break;case tt.AUDIO_TRACK:d=r?z.AUDIO_TRACK_LOAD_TIMEOUT:z.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case tt.SUBTITLE_TRACK:d=r?z.SUBTITLE_TRACK_LOAD_TIMEOUT:z.SUBTITLE_LOAD_ERROR,c=!1;break}u&&this.resetInternalLoader(e.type);const h={type:Re.NETWORK_ERROR,details:d,fatal:c,url:e.url,loader:u,context:e,error:l,networkDetails:t,stats:i};if(n){const f=(t==null?void 0:t.url)||e.url;h.response=yt({url:f,data:void 0},n)}this.hls.trigger(E.ERROR,h)}handlePlaylistLoaded(e,t,r,n,i,o){const l=this.hls,{type:d,level:c,levelOrTrack:u,id:h,groupId:f,deliveryDirectives:m}=n,p=Dc(t,n),x=mp(n);let y=typeof n.level=="number"&&x===we.MAIN?c:void 0;const v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!l.config.ignorePlaylistParsingErrors){l.trigger(E.ERROR,{type:Re.NETWORK_ERROR,details:z.LEVEL_PARSING_ERROR,fatal:!1,url:p,error:v,reason:v.message,response:t,context:n,level:y,parent:x,networkDetails:i,stats:r});return}e.playlistParsingError=null}if(!e.fragments.length){const _=e.playlistParsingError=new Error("No Segments found in Playlist");l.trigger(E.ERROR,{type:Re.NETWORK_ERROR,details:z.LEVEL_EMPTY_ERROR,fatal:!1,url:p,error:_,reason:_.message,response:t,context:n,level:y,parent:x,networkDetails:i,stats:r});return}switch(e.live&&o&&(o.getCacheAge&&(e.ageHeader=o.getCacheAge()||0),(!o.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),d){case tt.MANIFEST:case tt.LEVEL:if(y){if(!u)y=0;else if(u!==l.levels[y]){const _=l.levels.indexOf(u);_>-1&&(y=_)}}l.trigger(E.LEVEL_LOADED,{details:e,levelInfo:u||l.levels[0],level:y||0,id:h||0,stats:r,networkDetails:i,deliveryDirectives:m,withoutMultiVariant:d===tt.MANIFEST});break;case tt.AUDIO_TRACK:l.trigger(E.AUDIO_TRACK_LOADED,{details:e,track:u,id:h||0,groupId:f||"",stats:r,networkDetails:i,deliveryDirectives:m});break;case tt.SUBTITLE_TRACK:l.trigger(E.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:h||0,groupId:f||"",stats:r,networkDetails:i,deliveryDirectives:m});break}}}class _s{static get version(){return ka}static isMSESupported(){return Tv()}static isSupported(){return cD()}static getMediaSource(){return rn()}static get Events(){return E}static get MetadataSchema(){return Ns}static get ErrorTypes(){return Re}static get ErrorDetails(){return z}static get DefaultConfig(){return _s.defaultConfig?_s.defaultConfig:QP}static set DefaultConfig(e){_s.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Hu,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=bI(e.debug||!1,"Hls instance",e.assetPlayerId),r=this.config=ZP(_s.DefaultConfig,e,t);this.userConfig=e,r.progressive&&eD(r,t);const{abrController:n,bufferController:i,capLevelController:o,errorController:l,fpsController:d}=r,c=new l(this),u=this.abrController=new n(this),h=new pC(this),f=r.interstitialsController,m=f?this.interstitialsController=new f(this,_s):null,p=this.bufferController=new i(this,h),x=this.capLevelController=new o(this),y=new d(this),v=new mD(this),_=r.contentSteeringController,b=_?new _(this):null,w=this.levelController=new lD(this,b),T=new aD(this),A=new fD(this.config,this.logger),S=this.streamController=new hD(this,h,A),I=this.gapController=new nD(this,h);x.setStreamController(S),y.setStreamController(S);const j=[v,w,S];m&&j.splice(1,0,m),b&&j.splice(1,0,b),this.networkControllers=j;const R=[u,p,I,x,y,T,h];this.audioTrackController=this.createController(r.audioTrackController,j);const k=r.audioStreamController;k&&j.push(this.audioStreamController=new k(this,h,A)),this.subtitleTrackController=this.createController(r.subtitleTrackController,j);const D=r.subtitleStreamController;D&&j.push(this.subtititleStreamController=new D(this,h,A)),this.createController(r.timelineController,R),A.emeController=this.emeController=this.createController(r.emeController,R),this.cmcdController=this.createController(r.cmcdController,R),this.latencyController=this.createController(oD,R),this.coreComponents=R,j.push(c);const Y=c.onErrorOut;typeof Y=="function"&&this.on(E.ERROR,Y,c),this.on(E.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){const r=new e(this);return t&&t.push(r),r}return null}on(e,t,r=this){this._emitter.on(e,t,r)}once(e,t,r=this){this._emitter.once(e,t,r)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,r=this,n){this._emitter.off(e,t,r,n)}listeners(e){return this._emitter.listeners(e)}emit(e,t,r){return this._emitter.emit(e,t,r)}
vendor: 6,936 bytes, line 700
700trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(r){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+r.message+'". Here is a stacktrace:',r),!this.triggeringException){this.triggeringException=!0;const n=e===E.ERROR;this.trigger(E.ERROR,{type:Re.OTHER_ERROR,details:z.INTERNAL_EXCEPTION,fatal:n,event:e,error:r}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(E.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const i=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(E.ERROR,{type:Re.OTHER_ERROR,details:z.ATTACH_MEDIA_ERROR,fatal:!0,error:i});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,r=t?e.media:e,n=t?e:{media:r};this._media=r,this.trigger(E.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia"),this.trigger(E.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(E.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,r=this._url,n=this._url=Du.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),t&&r&&(r!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(E.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(e,t),!(!this.started||!this.networkControllers));r++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[we.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[we.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[we.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=nP()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){ZI(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const r=e.length;for(let n=0;n<r;n++)if(e[n].maxBitrate>=t)return n;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:r}=this;let n;if(t===-1&&e!=null&&e.length?n=e.length-1:n=t,r)for(let i=n;i--;){const o=e[i].attrs["HDCP-LEVEL"];if(o&&o<=r)return i}return n}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}
700setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const r=uy(t);return cy(e,r,navigator.mediaCapabilities)}}_s.defaultConfig=void 0;function pD(s,e="output",t={},r){return{maxBufferLength:30,maxMaxBufferLength:60,startLevel:-1,xhrSetup:(n,i)=>{if(r&&i.includes("media.gradzen.com")&&!i.includes("token=")){const o=i.includes("?")?"&":"?",l=`${i}${o}token=${r}`;n.open("GET",l,!0)}},...t}}function Ca(s,e){if(e==="BDT")return`৳${s.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:2})}`;const t={USD:"en-US",INR:"en-IN"};return new Intl.NumberFormat(t[e]||"en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:2}).format(s)}function r3(s){return{BDT:"৳",USD:"$",INR:"₹"}[s]||s}var Av=["PageUp","PageDown"],kv=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Rv={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Ui="Slider",[Fd,gD,xD]=mg(Ui),[jv]=cn(Ui,[xD]),[yD,Pl]=jv(Ui),Iv=g.forwardRef((s,e)=>{const{name:t,min:r=0,max:n=100,step:i=1,orientation:o="horizontal",disabled:l=!1,minStepsBetweenThumbs:d=0,defaultValue:c=[r],value:u,onValueChange:h=()=>{},onValueCommit:f=()=>{},inverted:m=!1,form:p,...x}=s,y=g.useRef(new Set),v=g.useRef(0),b=o==="horizontal"?vD:bD,[w=[],T]=Oa({prop:u,defaultProp:c,onChange:k=>{var Y;(Y=[...y.current][v.current])==null||Y.focus(),h(k)}}),A=g.useRef(w);function S(k){const D=TD(w,k);R(k,D)}function I(k){R(k,v.current)}function j(){const k=A.current[v.current];w[v.current]!==k&&f(w)}function R(k,D,{commit:Y}={commit:!1}){const q=jD(i),X=ID(Math.round((k-r)/i)*i+r,q),F=nu(X,[r,n]);T((P=[])=>{const N=ED(P,F,D);if(RD(N,d*i)){v.current=N.indexOf(F);const O=String(N)!==String(P);return O&&Y&&f(N),O?N:P}else return P})}return a.jsx(yD,{scope:s.__scopeSlider,name:t,disabled:l,min:r,max:n,valueIndexToChangeRef:v,thumbs:y.current,values:w,orientation:o,form:p,children:a.jsx(Fd.Provider,{scope:s.__scopeSlider,children:a.jsx(Fd.Slot,{scope:s.__scopeSlider,children:a.jsx(b,{"aria-disabled":l,"data-disabled":l?"":void 0,...x,ref:e,onPointerDown:Et(x.onPointerDown,()=>{l||(A.current=w)}),min:r,max:n,inverted:m,onSlideStart:l?void 0:S,onSlideMove:l?void 0:I,onSlideEnd:l?void 0:j,onHomeKeyDown:()=>!l&&R(r,0,{commit:!0}),onEndKeyDown:()=>!l&&R(n,w.length-1,{commit:!0}),onStepKeyDown:({event:k,direction:D})=>
700{if(!l){const X=Av.includes(k.key)||k.shiftKey&&kv.includes(k.key)?10:1,F=v.current,P=w[F],N=i*X*D;R(P+N,F,{commit:!0})}}})})})})});Iv.displayName=Ui;var[Cv,Nv]=jv(Ui,{startEdge:"left",endEdge:"right",size:"width",direction:1}),vD=g.forwardRef((s,e)=>{const{min:t,max:r,dir:n,inverted:i,onSlideStart:o,onSlideMove:l,onSlideEnd:d,onStepKeyDown:c,...u}=s,[h,f]=g.useState(null),m=qt(e,b=>f(b)),p=g.useRef(void 0),x=yg(n),y=x==="ltr",v=y&&!i||!y&&i;function _(b){const w=p.current||h.getBoundingClientRect(),T=[0,w.width],S=ih(T,v?[t,r]:[r,t]);return p.current=w,S(b-w.left)}return a.jsx(Cv,{scope:s.__scopeSlider,startEdge:v?"left":"right",endEdge:v?"right":"left",direction:v?1:-1,size:"width",children:a.jsx(Lv,{dir:x,"data-orientation":"horizontal",...u,ref:m,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:b=>{const w=_(b.clientX);o==null||o(w)},onSlideMove:b=>{const w=_(b.clientX);l==null||l(w)},onSlideEnd:()=>{p.current=void 0,d==null||d()},onStepKeyDown:b=>{const T=Rv[v?"from-left":"from-right"].includes(b.key);c==null||c({event:b,direction:T?-1:1})}})})}),bD=g.forwardRef((s,e)=>{const{min:t,max:r,inverted:n,onSlideStart:i,onSlideMove:o,onSlideEnd:l,onStepKeyDown:d,...c}=s,u=g.useRef(null),h=qt(e,u),f=g.useRef(void 0),m=!n;function p(x){const y=f.current||u.current.getBoundingClientRect(),v=[0,y.height],b=ih(v,m?[r,t]:[t,r]);return f.current=y,b(x-y.top)}return a.jsx(Cv,{scope:s.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:a.jsx(Lv,{"data-orientation":"vertical",...c,ref:h,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:x=>{const y=p(x.clientY);i==null||i(y)},onSlideMove:x=>{const y=p(x.clientY);o==null||o(y)},onSlideEnd:()=>{f.current=void 0,l==null||l()},onStepKeyDown:x=>{const v=Rv[m?"from-bottom":"from-top"].includes(x.key);d==null||d({event:x,direction:v?-1:1})}})})}),Lv=g.forwardRef((s,e)=>{const{__scopeSlider:t,onSlideStart:r,onSlideMove:n,onSlideEnd:i,onHomeKeyDown:o,onEndKeyDown:l,onStepKeyDown:d,...c}=s,u=Pl(Ui,t);return a.jsx(bt.span,{...c,ref:e,onKeyDown:Et(s.onKeyDown,h=>{h.key==="Home"?(o(h),h.preventDefault()):h.key==="End"?(l(h),h.preventDefault()):Av.concat(kv).includes(h.key)&&(d(h),h.preventDefault())}),onPointerDown:Et(s.onPointerDown,h=>{const f=h.target;f.setPointerCapture(h.pointerId),h.preventDefault(),u.thumbs.has(f)?f.focus():r(h)}),onPointerMove:Et(s.onPointerMove,h=>{h.target.hasPointerCapture(h.pointerId)&&n(h)}),onPointerUp:Et(s.onPointerUp,h=>{const f=h.target;f.hasPointerCapture(h.pointerId)&&(f.releasePointerCapture(h.pointerId),i(h))})})}),Pv="SliderTrack",Dv=g.forwardRef((s,e)=>{const{__scopeSlider:t,...r}=s,n=Pl(Pv,t);return a.jsx(bt.span,{"data-disabled":n.disabled?"":void 0,"data-orientation":n.orientation,...r,ref:e})});Dv.displayName=Pv;var $d="SliderRange",Ov=g.forwardRef((s,e)=>{const{__scopeSlider:t,...r}=s,n=Pl($d,t),i=Nv($d,t),o=g.useRef(null),l=qt(e,o),d=n.values.length,c=n.values.map(f=>$v(f,n.min,n.max)),u=d>1?Math.min(...c):0,h=100-Math.max(...c);return a.jsx(bt.span,{"data-orientation":n.orientation,"data-disabled":n.disabled?"":void 0,...r,ref:l,style:{...s.style,[i.startEdge]:u+"%",[i.endEdge]:h+"%"}})});Ov.displayName=$d;var Ud="SliderThumb",Mv=g.forwardRef((s,e)=>{const t=gD(s.__scopeSlider),[r,n]=g.useState(null),i=qt(e,l=>n(l)),o=g.useMemo(()=>r?t().findIndex(l=>l.ref.current===r):-1,[t,r]);return a.jsx(_D,{...s,ref:i,index:o})}),_D=g.forwardRef((s,e)=>{const{__scopeSlider:t,index:r,name:n,...i}=s,o=Pl(Ud,t),l=Nv(Ud,t),[d,c]=g.useState(null),u=qt(e,_=>c(_)),h=d?o.form||!!d.closest("form"):!0,f=ru(d),m=o.values[r],p=m===void 0?0:$v(m,o.min,o.max),x=SD(r,o.values.length),y=f==null?void 0:f[l.size],v=y?AD(y,p,l.direction):0;return g.useEffect(()=>{if(d)return o.thumbs.add(d),()=>{o.thumbs.delete(d)}},[d,o.thumbs]),a.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[l.startEdge]:`calc(${p}% + ${v}px)`},children:[a.jsx(Fd.ItemSlot,{scope:s.__scopeSlider,children:a.jsx(bt.span,{role:"slider","aria-label":s["aria-label"]||x,"aria-valuemin":o.min,"aria-valuenow":m,"aria-valuemax":o.max,"aria-orientation":o.orientation,"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0,tabIndex:o.disabled?void 0:0,...i,ref:u,style:m===void 0?{display:"none"}:s.style,onFocus:Et(s.onFocus,()=>{o.valueIndexToChangeRef.current=r})})}),h&&a.jsx(Fv,{name:n??(o.name?o.name+(o.values.length>1?"[]":""):void 0),form:o.form,value:m},r)]})});Mv.displayName=Ud;var wD="RadioBubbleInput",Fv=g.forwardRef(({__scopeSlider:s,value:e,...t},r)=>{const n=g.useRef(null),i=qt(n,r),o=su(e);return g.useEffect(()=>{const l=n.current;if(!l)return;const d=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(d,"value").set;if(o!==e&&u){const h=new Event("input",{bubbles:!0});u.call(l,e),l.dispatchEvent(h)}},[o,e]),a.jsx(bt.input,{style:{display:"none"},...t,ref:i,defaultValue:e})});Fv.displayName=wD;function ED(s=[],e,t){const r=[...s];return r[t]=e,r.sort((n,i)=>n-i)}function $v(s,e,t){const i=100/(t-e)*(s-e);return nu(i,[0,100])}function SD(s,e){return e>2?`Value ${s+1} of ${e}`:e===2?["Minimum","Maximum"][s]:void 0}function TD(s,e){if(s.length===1)return 0;const t=s.map(n=>Math.abs(n-e)),r=Math.min(...t);return t.indexOf(r)}function AD(s,e,t){const r=s/2,i=ih([0,50],[0,r]);return(r-i(e)*t)*t}function kD(s){return s.slice(0,-1).map((e,t)=>s[t+1]-e)}function RD(s,e){if(e>0){const t=kD(s);return Math.min(...t)>=e}return!0}function ih(s,e){return t=>{if(s[0]===s[1]||e[0]===e[1])return e[0];const r=(e[1]-e[0])/(s[1]-s[0]);return e[0]+r*(t-s[0])}}function jD(s){return(String(s).split(".")[1]||"").length}function ID(s,e){const t=Math.pow(10,e);return Math.round(s*t)/t}var Uv=Iv,CD=Dv,ND=Ov,LD=Mv;const Bd=g.forwardRef(({className:s,...e},t)=>a.jsxs(Uv,{ref:t,className:C("relative flex w-full touch-none select-none items-center",s
700),...e,children:[a.jsx(CD,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:a.jsx(ND,{className:"absolute h-full bg-primary"})}),a.jsx(LD,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));Bd.displayName=Uv.displayName;function pp(s){const e=Math.floor(s/3600),t=Math.floor(s%3600/60),r=Math.floor(s%60);return e>0?`${e}:${t.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`:`${t}:${r.toString().padStart(2,"0")}`}function gp(s){return s.includes(".m3u8")}function PD({volume:s,muted:e}){return e||s===0?a.jsx(uE,{className:"w-4 h-4"}):s<.5?a.jsx(cE,{className:"w-4 h-4"}):a.jsx(dE,{className:"w-4 h-4"})}function DD({videoUrl:s,fallbackUrl:e,expectedDuration:t,mediaToken:r,onPlay:n,onPause:i,onEnded:o,onProgress:l,onTimeUpdate:d,initialPosition:c=0,totalCharged:u=0,hasFullAccess:h=!1,isCharging:f=!1,shouldCharge:m=!1,autoPlay:p=!1,isInView:x,globalMuted:y,onMuteChange:v,extraControls:_}){var be;const b=g.useRef(null),w=g.useRef(null),T=g.useRef(null),A=g.useRef(!1),S=g.useRef(!1),[I,j]=g.useState(!1),[R,k]=g.useState(y??!1),[D,Y]=g.useState(1),[q,X]=g.useState(!1),[F,P]=g.useState(0),[N,O]=g.useState(t||0),[$,B]=g.useState(!1),[U,K]=g.useState(!1),[ee,ce]=g.useState(!0),[Q,re]=g.useState(null),[ve,Ce]=g.useState([]),[Pe,Me]=g.useState(-1),[le,oe]=g.useState(!1),He=g.useRef(1),ct=g.useRef(null),se=g.useRef(null);g.useEffect(()=>{const ie=b.current;if(!(!ie||!s)){if(K(!1),T.current&&(T.current.destroy(),T.current=null),gp(s))if(_s.isSupported()){console.log("[Player] HLS mode: initializing with signed loader, url:",s);const Qe=pD(s,"output",{},r),Ve=new _s(Qe);Ve.loadSource(s),Ve.attachMedia(ie),Ve.on(_s.Events.MANIFEST_PARSED,(It,At)=>{const Yt=Ve.levels.map((W,Se)=>({height:W.height,index:Se}));console.log("[Player] HLS manifest parsed:",Yt.length,"quality levels:",Yt.map(W=>`${W.height}p`).join(", ")),Ce(Yt),re("hls"),c>0&&(ie.currentTime=c)}),Ve.on(_s.Events.LEVEL_SWITCHED,(It,At)=>{const Yt=Ve.levels[At.level];console.log("[Player] HLS quality switched to:",Yt?`${Yt.height}p`:`level ${At.level}`),Me(At.level)}),Ve.on(_s.Events.ERROR,(It,At)=>{if(At.fatal)switch(At.type){case _s.ErrorTypes.NETWORK_ERROR:e?(console.warn("[Player] HLS fallback: network error, switching to MP4:",e),A.current=!0,Ve.destroy(),T.current=null,re("mp4"),Ce([]),ie.src=e,ie.load()):(console.error("[Player] HLS network error, attempting recovery..."),Ve.startLoad());break;case _s.ErrorTypes.MEDIA_ERROR:console.error("[Player] HLS media error, attempting recovery..."),Ve.recoverMediaError();break;default:console.error("[Player] Fatal HLS error:",At),Ve.destroy(),K(!0);break}}),T.current=Ve}else ie.canPlayType("application/vnd.apple.mpegurl")&&(console.log("[Player] HLS mode: native Safari playback"),re("hls"),ie.src=s);else console.log("[Player] MP4 mode: direct playback"),re("mp4"),Ce([]),ie.src=s;return()=>{T.current&&(T.current.destroy(),T.current=null)}}},[s,c]);const Be=g.useCallback(()=>{b.current&&(I?b.current.pause():b.current.play())},[I]);g.useEffect(()=>{const ie=b.current;if(!ie)return;const Qe=()=>{j(!0),n==null||n()},Ve=()=>{j(!1),i==null||i()},It=()=>{P(ie.currentTime),d==null||d(ie.currentTime),ie.duration&&isFinite(ie.duration)&&(l==null||l(Math.min(1,ie.currentTime/ie.duration)))},At=()=>{ie.duration&&isFinite(ie.duration)&&O(ie.duration),c>0&&!gp(s)&&(ie.currentTime=c),t&&t>0&&ie.duration<t*.5&&e&&T.current&&Q==="hls"&&(console.warn(`[Player] HLS duration (${Math.round(ie.duration)}s) much shorter than expected (${t}s), falling back to MP4`),A.current=!0,T.current.destroy(),T.current=null,re("mp4"),Ce([]),ie.src=e,ie.load())},Yt=()=>{j(!1),o==null||o()},W=()=>{ie.duration&&isFinite(ie.duration)&&O(ie.duration)},Se=()=>B(!0),it=()=>{B(!1),A.current&&(A.current=!1,K(!1))},Ct=()=>{if(A.current){A.current=!1;return}K(!0)};return ie.addEventListener("play",Qe),ie.addEventListener("pause",Ve),ie.addEventListener("timeupdate",It),ie.addEventListener("loadedmetadata",At),ie.addEventListener("durationchange",W),ie.addEventListener("ended",Yt),ie.addEventListener("waiting",Se),ie.addEventListener("canplay",it),ie.addEventListener("error",Ct),()=>{ie.removeEventListener("play",Qe),ie.removeEventListener("pause",Ve),ie.removeEventListener("timeupdate",It),ie.removeEventListener("loadedmetadata",At),ie.removeEventListener("durationchange",W),ie.removeEventListener("ended",Yt),ie.removeEventListener("waiting",Se),ie.removeEventListener("canplay",it),ie.removeEventListener("error",Ct)}},[n,i,o,l,d,c,s]);const Ke=g.useCallback(()=>{ce(!0),ct.current&&clearTimeout(ct.current),I&&(ct.current=setTimeout(()=>ce(!1),3e3))},[I]),Ee=ie=>{b.current&&(b.current.currentTime=ie[0])};g.useEffect(()=>{y===void 0||!b.current||(b.current.muted=y,k(y))},[y]),g.useEffect(()=>{const ie=b.current;if(!(!ie||x===void 0)){if(!x)ie.paused||ie.pause();else if(p){const Qe=y??!0;ie.muted=Qe,k(Qe),ie.play().then(()=>{S.current=!0}
700).catch(()=>{Qe||(ie.muted=!0,k(!0),ie.play().catch(()=>{}))})}}},[x,p,Q,y]);const fe=()=>{if(!b.current)return;const ie=!R;if(b.current.muted=ie,k(ie),v==null||v(ie),ie)He.current=D;else if(D===0){const Qe=He.current>0?He.current:1;Y(Qe),b.current.volume=Qe}},et=ie=>{if(!b.current)return;const Qe=ie[0];Y(Qe),b.current.volume=Qe,Qe===0&&!R?(b.current.muted=!0,k(!0),v==null||v(!0)):Qe>0&&R&&(b.current.muted=!1,k(!1),v==null||v(!1))},rt=ie=>{T.current&&(T.current.currentLevel=ie,Me(ie),oe(!1))},We=()=>{w.current&&(document.fullscreenElement?document.exitFullscreen():w.current.requestFullscreen())},dt=()=>{b.current&&(b.current.currentTime=0,b.current.play())},pe=Pe===-1?"Auto":`${((be=ve.find(ie=>ie.index===Pe))==null?void 0:be.height)||"?"}p`,ge=Q==="hls"&&ve.length>1;return a.jsxs("div",{ref:w,className:"relative bg-black aspect-video overflow-hidden group",onMouseMove:Ke,onMouseLeave:()=>{I&&ce(!1),X(!1),oe(!1)},onTouchStart:Ke,children:[a.jsx("video",{ref:b,className:"w-full h-full",playsInline:!0,onClick:Be}),U&&a.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center bg-black/80 gap-3",children:[a.jsx(Lr,{className:"w-10 h-10 text-destructive"}),a.jsx("p",{className:"text-white font-medium",children:"Video unavailable"}),a.jsx("p",{className:"text-white/60 text-sm text-center px-8",children:"This video file could not be loaded. It may need to be re-uploaded."}),a.jsxs(ye,{variant:"secondary",size:"sm",className:"mt-2",onClick:()=>{K(!1),b.current&&b.current.load()},children:[a.jsx(Kh,{className:"w-4 h-4 mr-2"}),"Retry"]})]}),$&&!U&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30",children:a.jsx(ts,{className:"w-12 h-12 text-white animate-spin"})}),!I&&!$&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center cursor-pointer",onClick:Be,children:a.jsx("div",{className:"w-16 h-16 rounded-full bg-white/90 flex items-center justify-center shadow-lg",children:a.jsx(qh,{className:"w-7 h-7 text-primary ml-1",fill:"currentColor"})})}),a.jsxs("div",{className:C("absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-4 transition-opacity",ee||!I?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"),children:[a.jsx(Bd,{value:[F],min:0,max:N||100,step:.1,onValueChange:Ee,className:"mb-3"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ye,{variant:"ghost",size:"icon",className:"text-white hover:bg-white/20 h-8 w-8",onClick:Be,children:I?a.jsx(Qw,{className:"w-4 h-4"}):a.jsx(qh,{className:"w-4 h-4 ml-0.5",fill:"currentColor"})}),a.jsx(ye,{variant:"ghost",size:"icon",className:"text-white hover:bg-white/20 h-8 w-8",onClick:dt,children:a.jsx(Kh,{className:"w-4 h-4"})}),a.jsxs("div",{className:"relative flex items-center",onMouseEnter:()=>{se.current&&clearTimeout(se.current),X(!0)},onMouseLeave:()=>{se.current=setTimeout(()=>X(!1),300)},children:[a.jsx(ye,{variant:"ghost",size:"icon",className:"text-white hover:bg-white/20 h-8 w-8",onClick:fe,children:a.jsx(PD,{volume:D,muted:R})}),a.jsx("div",{className:C("flex items-center transition-all overflow-hidden",q?"w-20 opacity-100 ml-1":"w-0 opacity-0"),children:a.jsx(Bd,{value:[R?0:D],min:0,max:1,step:.01,onValueChange:et,className:"w-20"})})]}),a.jsxs("span",{className:"text-white text-sm ml-2",children:[pp(F)," / ",pp(N)]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[m&&!h&&u>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-white/80 text-sm",children:[f&&a.jsx(ts,{className:"w-3 h-3 animate-spin"}),a.jsxs("span",{children:["Charged: ",Ca(u,"BDT")]})]}),h&&a.jsx("span",{className:"text-green-400 text-sm",children:"Unlimited Access"}),ge&&a.jsxs("div",{className:"relative",children:[a.jsxs(ye,{variant:"ghost",size:"sm",className:"text-white hover:bg-white/20 h-8 px-2 text-xs gap-1",onClick:()=>oe(ie=>!ie),children:[a.jsx(bn,{className:"w-3.5 h-3.5"}),pe]}),le&&a.jsxs("div",{className:"absolute bottom-full right-0 mb-1 bg-black/90 rounded-md border border-white/20 py-1 min-w-[100px] z-50",children:[a.jsx("button",{className:C("w-full text-left px-3 py-1.5 text-xs text-white hover:bg-white/20 transition-colors",Pe===-1&&"text-primary font-semibold"),onClick:()=>rt(-1),children:"Auto"}),ve.sort((ie,Qe)=>Qe.height-ie.height).map(ie=>a.jsxs("button",{className:C("w-full text-left px-3 py-1.5 text-xs text-white hover:bg-white/20 transition-colors",Pe===ie.index&&"text-primary font-semibold"),onClick:()=>rt(ie.index),children:[ie.height,"p"]},ie.index))]})]}),_,a.jsx(ye,{variant:"ghost",size:"icon",className:"text-white hover:bg-white/20 h-8 w-8",onClick:We,children:a.jsx(t0,{className:"w-4 h-4"})})]})]})]})]})}const OD=["/","/profile"],MD=["/u/","/page/","/profile/"];function xp(s){return OD.includes(s)||MD.some(e=>s.startsWith(e))}function FD(){const s=dn(),e=br(),[t,r]=g.useState(null),n=g.useRef(null);g.useEffect(()=>{const d=()=>r(uc()?{...uc()}:null);return d(),window.addEventListener("pipStateChanged",d),()=>window.removeEventListener("pipStateChanged",d)},[]),g.useEffect(()=>{!xp(e.pathname)&&uc()&&Qf()},[e.pathname]);const i=g.useCallback(()=>{Qf()},[]),o=g.useCallback(()=>{var c;const d=n.current;d&&(document.fullscreenElement?document.exitFullscreen():(c=d.requestFullscreen)==null||c.call(d))},[]),l=g.useCallback(d=>{uI(d),r(c=>c?{...c,muted:d}:null)},[]);return s||!t||!xp(e.pathname)?null:a.jsxs("div",{ref:n,className:"fixed bottom-4 right-4 z-50 w-80 aspect-video rounded-lg overflow-hidden shadow-2xl border border-border bg-black group",children:[a.jsx(DD,{videoUrl:t.hlsUrl,fallbackUrl:t.fallbackUrl,mediaToken:t.mediaToken,initialPosition:t.currentTime,autoPlay:!0,isInView:!0,globalMuted:t.muted,onMuteChange:l}),a.jsxs("div",{className:"absolute top-1 right-1 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:[a.jsx("button",{onClick:o,className:"p-1.5 rounded-full bg-black/60 hover:bg-black/80 text-white transition-colors",children:a.jsx(t0,{className:"w-3.5 h-3.5"})}),a.jsx("button",{onClick:i,className:"p-1.5 rounded-full bg-black/60 hover:bg-black/80 text-white transition-colors",children:a.jsx(Fs,{className:"w-3.5 h-3.5"})})]})]})}const $D=g.lazy(()=>M(()=>import("./SocialFeed-ZU-nwGdt.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59]))),UD=g.lazy(()=>M(()=>import("./Reels-DAyEXCdz.js"),__vite__mapDeps([60,1,61,16,3,17,25,27,26,62,2,63,32,21,64,45,22,58,65,66,20,23,59]))),BD=g.lazy(()=>M(()=>import("./Dashboard-BNaOI6f7.js"),__vite__mapDeps([67,1,2,3,68,48,69,18,16,17,20,21,22,23,24,25,26,27,11,12,28,70,29,71,72,73,39,74,40,13,43,31,32,45,42,46,57,75,76,77,78,5,6,7,8,50,58,47,51,52,53,79,41,35,80,59]))),VD=g.lazy(()=>M(()=>import("./MyNetwork-BteNVmKD.js"),__vite__mapDeps([81,1,2,3,23,82,33,29,56,83,55,48,79,84,85,59]))),GD=g.lazy(()=>M(()=>import("./Courses-G4zYTDmd.js"),__vite__mapDeps([86,1,23,3,87,58,88,89,90,47,91,92,26,93,94,46,95,52,10,96,97,2,98,99,100,12,101,102,8,103,104,105,17,106,107,108,62,14,109,28,110,21,111,112,113,27,114,65,115,116,32,117,118,119,63,120,13,121,122,123,124,125,126,29,64,127,128,75,129,130,11,131,132,133,134,135,136,137,138,139,45,140,77,30,141,72,42,142,143,37,144,145,43,31,146,22,53,66,85,55,147,148,149,150,151,152,153,154,25,59]))),zD=g.lazy(()=>M(()=>import("./MobileMenu-BXWOBUOQ.js"),__vite__mapDeps([155,1,2,3,79,14,42,46,59])));g.lazy(()=>M(()=>import("./JobAnalytics-C-VyCni3.js"),__vite__mapDeps([156,1,157,2,3,43,59,90])));g.lazy(()=>M(()=>import("./AptitudeTests-BE2ljUNm.js"),__vite__mapDeps([158,1,16,3,17,2,12,22,59])));g.lazy(()=>M(()=>import("./LearningCenter-Cg9e6b86.js"),__vite__mapDeps([159,1,147,43,126,3,59,2])));const qD=[$D,UD,BD,VD,GD,zD];function HD({Component:s}){return a.jsx(g.Suspense,{fallback:a.jsx(vu,{}),children:a.jsx(Pu.Provider,{value:!0,children:a.jsx(s,{})})})}function KD(){const s=hs(),e=br(),t=dn(),{activeTabIndex:r,setActiveTabIndex:n}=Lu(),i=v=>{s(`/search?q=${encodeURIComponent(v)}`)},o=Hx,l=qD,d=o.indexOf(e.pathname),c=d>=0;g.useEffect(()=>{d>=0&&d!==r&&n(d)},[d,r,n]);const u=g.useCallback(v=>{n(v)},[n]),h=t&&c,f=e.pathname==="/reels",m=/^\/courses\/[^/]+\/watch\/[^/]+/.test(e.pathname),p=/^\/(profile|u\/[^/]+)/.test(e.pathname),x=/^\/page\/[^/]+/.test(e.pathname),y=f||m||p||x;return a.jsxs(oI,{onSearchSubmit:i,hideSidebar:y,contentClassName:h?"p-0 overflow-hidden":f?"p-0 overflow-hidden bg-black min-h-0 h-full":m?"p-0 overflow-hidden":void 0,children:[h?a.jsx(dI,{activeIndex:r,onTabChange:u,tabPaths:o,children:l.map((v,_)=>a.jsx(HD,{Component:v},o[_]))}):a.jsx(Pu.Provider,{value:!0,children:a.jsx(uk,{children:a.jsx(g.Suspense,{fallback:a.jsx(vu,{}),children:a.jsx(P_,{})})})}),a.jsx(FD,{})]})}const Oc="last_visit_ping";function WD(){const s=new Date,e=s.getFullYear(),t=String(s.getMonth()+1).padStart(2,"0"),r=String(s.getDate()).padStart(2,"0");return`${e}-${t}-${r}`}function YD(){const{user:s}=$t();g.useEffect(()=>{if(!(s!=null&&s.id))return;const e=WD();if((()=>{try{return localStorage.getItem(Oc)}catch{return null}})()!==e){try{localStorage.setItem(Oc,e)}catch{}L.from("user_activity_log").insert({user_id:s.id,activity_type:"session_open",activity_category:"session",is_visible_to_user:!1,can_user_delete:!1}).then(({error:r})=>{if(r)try{localStorage.removeItem(Oc)}catch{}})}},[s==null?void 0:s.id])}const Vd="returnUrl",XD=30*60*1e3;function Bv(s){return typeof s=="string"&&s.startsWith("/")&&!s.startsWith("//")}function QD(s){if(Bv(s))try{localStorage.setItem(Vd,JSON.stringify({url:s,ts:Date.now()}))}catch{}}function Ji(){try{const s=localStorage.getItem(Vd);if(!s)return null;localStorage.removeItem(Vd);const e=JSON.parse(s);return!Bv(e.url)||typeof e.ts!="number"||Date.now()-e.ts>XD?null:e.url}catch{return null}}function JD({children:s}){const{user:e,loading:t}=$t(),r=br();return YD(),t?a.jsx("div",{className:"flex items-center justify-center h-screen bg-background",children:a.jsx(ts,{className:"h-8 w-8 animate-spin text-primary"})}):e?a.jsx(a.Fragment,{children:s}):(QD(r.pathname+r.search),a.jsx(da,{to:"/",replace:!0}))}function ZD({isOnline:s,wasOffline:e}){return s&&!e?null:a.jsx("div",{className:C("fixed top-0 left-0 right-0 z-[100] flex items-center justify-center gap-2 py-2 px-4 text-sm font-medium transition-all duration-300",s?"bg-primary text-primary-foreground animate-in slide-in-from-top":"bg-muted/95 text-muted-foreground backdrop-blur-sm border-b"),children:s?a.jsxs(a.Fragment,{children:[a.jsx(bi,{className:"h-4 w-4"}),a.jsx("span",{children:"You're back online"})]}):a.jsxs(a.Fragment,{children:[a.jsx(n0,{className:"h-4 w-4"}),a.jsx("span",{children:"You're offline — showing cached content"})]})})}function e2(){const{user:s}=$t(),[e,t]=g.useState(0),r=g.useCallback(async()=>
700{if(!s){t(0);return}try{const{data:n,error:i}=await L.from("conversation_participants").select("conversation_id, last_read_at").eq("user_id",s.id);if(i||!(n!=null&&n.length)){t(0);return}let o=0;for(const l of n){const d=L.from("messages").select("id",{count:"exact",head:!0}).eq("conversation_id",l.conversation_id).neq("sender_id",s.id).eq("is_deleted",!1);l.last_read_at&&d.gt("created_at",l.last_read_at);const{count:c}=await d;o+=c??0}t(o)}catch{}},[s]);return g.useEffect(()=>{r()},[r]),g.useEffect(()=>{if(!s)return;const n=L.channel("chat-bubble-unread").on("postgres_changes",{event:"INSERT",schema:"public",table:"messages"},i=>{i.new.sender_id!==s.id&&t(l=>l+1)}).on("postgres_changes",{event:"UPDATE",schema:"public",table:"conversation_participants",filter:`user_id=eq.${s.id}`},()=>{r()}).subscribe();return()=>{L.removeChannel(n)}},[s,r]),{totalUnread:e}}const Na={async createProject(s){const{data:e,error:t}=await L.rpc("create_marketplace_project_with_escrow",{p_title:s.title,p_description:s.description,p_deadline:s.deadline,p_budget_amount:s.budget_amount,p_budget_currency:s.budget_currency,p_required_skills:s.required_skills,p_project_type:s.project_type,p_difficulty_level:s.difficulty_level,p_deliverables:s.deliverables,p_poster_type:s.poster_type,p_company_name:s.company_name,p_initial_payment_pct:Math.round(s.initial_payment_pct),p_work_location:s.work_location,p_location_address:s.location_address,p_duration:s.duration,p_wallet_charge_amount:s.wallet_charge_amount??null,p_requires_manual_payment:s.requires_manual_payment??!1});return t?{success:!1,error:t.message}:e},async getActiveProjects(s=20,e=0){const{data:t,error:r}=await L.from("marketplace_projects").select("*").eq("status","active").eq("admin_approval_status","approved").eq("is_hidden",!1).order("created_at",{ascending:!1}).range(e,e+s-1);if(r)throw r;const n=(t==null?void 0:t.map(h=>h.id))||[],i=[...new Set((t||[]).map(h=>h.poster_id).filter(Boolean))];let o=new Map;if(i.length>0){const{data:h}=await L.from("profiles").select("user_id, full_name, avatar_url, company_name").in("user_id",i);o=new Map((h||[]).map(f=>[f.user_id,f]))}const{data:l}=await L.from("project_applications").select("project_id").in("project_id",n),d=new Map;l==null||l.forEach(h=>{d.set(h.project_id,(d.get(h.project_id)||0)+1)});const{data:{user:c}}=await L.auth.getUser();let u=new Set;if(c){const{data:h}=await L.from("project_applications").select("project_id").eq("applicant_id",c.id).in("project_id",n);u=new Set((h==null?void 0:h.map(f=>f.project_id))||[])}return(t||[]).map(h=>({...h,poster:o.get(h.poster_id)||null,application_count:d.get(h.id)||0,user_has_applied:u.has(h.id)}))},async getProject(s){const{data:e,error:t}=await L.from("marketplace_projects").select("*").eq("id",s).single();if(t)return null;let r=null;if(e.poster_id){const{data:n}=await L.from("profiles").select("user_id, full_name, avatar_url, company_name").eq("user_id",e.poster_id).single();r=n||null}return{...e,poster:r}},async getMyProjects(){const{data:{user:s}}=await L.auth.getUser();if(!s)return[];const{data:e,error:t}=await L.from("marketplace_projects").select("*").eq("poster_id",s.id).order("created_at",{ascending:!1});if(t)throw t;return e},async applyToProject(s,e,t){var n;const{error:r}=await L.from("project_applications").insert({project_id:s,applicant_id:(n=(await L.auth.getUser()).data.user)==null?void 0:n.id,bid_amount:e,cover_letter:t});return r?r.code==="23505"?{success:!1,error:"You have already applied to this project"}:{success:!1,error:r.message}:{success:!0}},async getProjectApplications(s){const{data:e,error:t}=await L.from("project_applications").select("*").eq("project_id",s).order("created_at",{ascending:!1});if(t)throw t;const r=[...new Set((e||[]).map(i=>i.applicant_id).filter(Boolean))];let n=new Map;if(r.length>0){const{data:i}=await L.from("profiles").select("user_id, full_name, avatar_url, company_name, company_position").in("user_id",r);n=new Map((i||[]).map(o=>[o.user_id,o]))}return(e||[]).map(i=>({...i,applicant:n.get(i.applicant_id)||null}))},async getMyApplications(){const{data:{user:s}}=await L.auth.getUser();if(!s)return[];const{data:e,error:t}=await L.from("project_applications").select(`
701        *,
702        project:marketplace_projects(*)
703      `).eq("applicant_id",s.id).order("created_at",{ascending:!1});if(t)throw t;return(e||[]).map(r=>({...r,project:Array.isArray(r.project)?r.project[0]:r.project}))},async confirmApplicant(s,e){const{data:t,error:r}=await L.rpc("confirm_project_applicant",{p_project_id:s,p_applicant_id:e});return r?{success:!1,error:r.message}:t},async completeProject(s){const{data:e,error:t}=await L.rpc("complete_project_and_release_funds",{p_project_id:s});return t?{success:!1,error:t.message}:e},async completeProjectWithSplit(s){const{data:e,error:t}=await L.rpc("complete_project_with_split_payment",{p_project_id:s});if(t)return{success:!1,error:t.message};const r=e;return{success:r.success,walletCharged:r.wallet_charged,balanceUsed:r.balance_used,manualPaymentRequired:r.manual_payment_required,
703completed:r.completed,awaitingManualPayment:r.awaiting_manual_payment,error:r.error}},async cancelProject(s){const{data:e,error:t}=await L.rpc("refund_project_escrow",{p_project_id:s,p_is_admin_action:!1});return t?{success:!1,error:t.message}:e},async getProjectEscrow(s){const{data:e,error:t}=await L.from("project_escrow").select("*").eq("project_id",s).single();return t?null:e},async updateApplicationStatus(s,e){const{error:t}=await L.from("project_applications").update({status:e}).eq("id",s);return t?{success:!1,error:t.message}:{success:!0}},async withdrawApplication(s){const{error:e}=await L.from("project_applications").delete().eq("id",s);return e?{success:!1,error:e.message}:{success:!0}},async payPendingWithSplit(s){const{data:e,error:t}=await L.rpc("pay_pending_project_with_split",{p_project_id:s});if(t)return{success:!1,error:t.message};const r=e;return{success:r.success,walletCharged:r.wallet_charged,balanceUsed:r.balance_used,manualPaymentRequired:r.manual_payment_required,activated:r.activated,error:r.error}},async shareProjectToFeed(s,e=""){const{data:{user:t}}=await L.auth.getUser();if(!t)return{success:!1,error:"Not authenticated"};const{error:r}=await L.from("social_posts").insert({author_id:t.id,content:e||"Check out this project!",shared_project_id:s,visibility:"public"});return r?{success:!1,error:r.message}:{success:!0}},async prePayCompletion(s,e){const{data:t,error:r}=await L.rpc("pre_pay_project_completion",{p_project_id:s,p_amount:e});return r?{success:!1,error:r.message}:t},async getProjectEscrowDetails(s){const{data:e,error:t}=await L.from("project_escrow").select("*").eq("project_id",s).single();if(t||!e)return{escrow:null,prePaidAmount:0,remainingAmount:0,upfrontPaid:0};const r=e.wallet_charged_amount||0,n=e.manual_payment_amount||0,i=r+n,o=e.pre_paid_completion_amount||0,l=e.amount||0,d=Math.max(0,l-i-o);return{escrow:e,prePaidAmount:o,remainingAmount:d,upfrontPaid:i}},async markWorkComplete(s,e){const{data:t,error:r}=await L.rpc("mark_work_complete",{p_project_id:s,p_notes:e??null});return r?{success:!1,error:r.message}:t},async deliverProject(s,e){const{data:t,error:r}=await L.rpc("deliver_project",{p_project_id:s,p_delivery_message:e??null});return r?{success:!1,error:r.message}:t},async getConfirmedApplication(s){const{data:e}=await L.from("project_applications").select("applicant_id, status, work_completed_at, delivery_notes").eq("project_id",s).in("status",["confirmed","work_completed","delivered"]).single();return e?{applicantId:e.applicant_id,status:e.status,workCompletedAt:e.work_completed_at,deliveryNotes:e.delivery_notes}:{applicantId:null,status:null,workCompletedAt:null,deliveryNotes:null}},async acceptDelivery(s){const{data:e,error:t}=await L.rpc("accept_project_delivery",{p_project_id:s});return t?{success:!1,error:t.message}:e},async raiseDispute(s,e,t=[]){const{data:r,error:n}=await L.rpc("raise_project_dispute",{p_project_id:s,p_reason:e,p_evidence_urls:t});if(n)return{success:!1,error:n.message};const i=r;return{success:i.success,disputeId:i.dispute_id,error:i.error}},async getEscrowStatus(s){const{data:e}=await L.from("project_escrow").select("status, dispute_deadline, dispute_id").eq("project_id",s).single();return e?{status:e.status,disputeDeadline:e.dispute_deadline,disputeId:e.dispute_id}:{status:null,disputeDeadline:null,disputeId:null}},async addDisputeMessage(s,e){const{data:{user:t}}=await L.auth.getUser();if(!t)return{success:!1,error:"Not authenticated"};const{data:r}=await L.from("project_disputes").select("complainant_id, freelancer_id").eq("id",s).single();if(!r)return{success:!1,error:"Dispute not found"};let n="admin";t.id===r.complainant_id?n="owner":t.id===r.freelancer_id&&(n="freelancer");const{error:i}=await L.from("dispute_messages").insert({dispute_id:s,sender_id:t.id,sender_type:n,message:e});return i?{success:!1,error:i.message}:{success:!0}},async resolveDispute(s,e,t){const{data:r,error:n}=await L.rpc("resolve_project_dispute",{p_dispute_id:s,p_resolution:e,p_admin_notes:t});return n?{success:!1,error:n.message}:r}},t2=[/(?:(?:\+?\s*8\s*8\s*0\s*)|(?:0\s*))1\s*[0-9০-৯\s\-\.]{8,12}/gi,/০১\s*[০-৯\s\-\.]{8,12}/gi,/\(\s*8\s*8\s*0\s*\)\s*1\s*[0-9\s\-\.]{8,11}
703/gi,/(?:^|[^\d০-৯])([0-9০-৯]\s*){10,11}(?:[^\d০-৯]|$)/gi],s2=[/[a-zA-Z0-9._%+-]+\s*[@@]\s*[a-zA-Z0-9.-]+\s*[..]\s*(?:com|net|org|io|bd|edu|gov|info|xyz|co)/gi,/[a-zA-Z0-9._%+-]+\s+(?:at|@)\s+[a-zA-Z0-9.-]+\s+(?:dot|\.)\s+(?:com|net|org|io|bd|edu|gov|info|xyz|co)/gi,/[a-zA-Z0-9._%+-]+\s*(?:@|at)\s*g\s*m\s*a\s*i\s*l/gi,/[a-zA-Z0-9._%+-]+\s*(?:@|at)\s*y\s*a\s*h\s*o\s*o/gi],r2=[/w\s*h\s*a\s*t\s*s\s*a\s*p\s*p/gi,/w\s*a\s*t\s*s\s*a\s*p\s*p/gi,/w\s*a\s*\.?\s*m\s*e/gi,/what'?\s*s?\s*up\s+(?:me|number|no|id)/gi,/w\s*p\s+(?:me|number|no|id)/gi],n2=[/f\s*a\s*c\s*e\s*b\s*o\s*o\s*k/gi,/f\s*b\s*[.।]\s*(?:com|me)/gi,/f\s*b\s+(?:me|id|link|page|profile)/gi,/m\s*e\s*s\s*s\s*e\s*n\s*g\s*e\s*r/gi,/fb\.me/gi,/facebook\.com/gi,/m\.me/gi],i2=[/t\s*e\s*l\s*e\s*g\s*r\s*a\s*m/gi,/t\s*\.?\s*m\s*e\s*\//gi,/t\s*g\s+(?:me|id|link|username)/gi,/@[a-zA-Z][a-zA-Z0-9_]{4,31}/g],a2=[/i\s*m\s*o\s+(?:me|id|number|no)/gi,/v\s*i\s*b\s*e\s*r/gi,/s\s*i\s*g\s*n\s*a\s*l\s+(?:me|id|number|no)/gi,/i\s*n\s*s\s*t\s*a\s*(?:gram)?/gi,/instagram\.com/gi,/l\s*i\s*n\s*k\s*e\s*d\s*i\s*n/gi,/linkedin\.com/gi,/twitter\.com/gi,/x\.com/gi,/snapchat/gi,/tiktok\.com/gi,/discord(?:\.gg|\.com)?/gi,/skype/gi],o2=[/https?:\/\/[^\s]+/gi,/www\.[^\s]+/gi,/bit\.ly\/[^\s]+/gi,/tinyurl\.com\/[^\s]+/gi,/goo\.gl\/[^\s]+/gi],l2=[{type:"phone",patterns:t2},{type:"email",patterns:s2},{type:"whatsapp",patterns:r2},{type:"facebook",patterns:n2},{type:"telegram",patterns:i2},{type:"social",patterns:a2},{type:"website",patterns:o2}];function c2(s){const e={"০":"0","১":"1","২":"2","৩":"3","৪":"4","৫":"5","৬":"6","৭":"7","৮":"8","৯":"9"};let t=s;for(const[r,n]of Object.entries(e))t=t.replace(new RegExp(r,"g"),n);return t}function d2(s){if(!s||typeof s!="string")return{hasViolation:!1,violationType:null,matchedPattern:null};const e=c2(s);for(const{type:t,patterns:r}of l2)for(const n of r){n.lastIndex=0;const i=n.exec(e);if(i)return{hasViolation:!0,violationType:t,matchedPattern:i[0].trim()}}return{hasViolation:!1,violationType:null,matchedPattern:null}}function u2(s){return{phone:"Phone Number",email:"Email Address",whatsapp:"WhatsApp",facebook:"Facebook/Messenger",telegram:"Telegram",social:"Social Media",website:"Website URL"}[s]||s}function h2(){const{user:s}=$t(),[e,t]=g.useState([]),[r,n]=g.useState(null),[i,o]=g.useState([]),[l,d]=g.useState(!0),[c,u]=g.useState(!1),[h,f]=g.useState(!1),[m,p]=g.useState(new Set),[x,y]=g.useState(new Set),v=g.useRef(),_=g.useRef(null),b=g.useRef(null),w=g.useRef(new Map),T=g.useRef(null);g.useEffect(()=>{if(!s)return;(async()=>{const{data:N}=await L.from("profiles").select("user_id, full_name, avatar_url, gender, is_verified, verification_type").eq("user_id",s.id).single();N&&(T.current=N,w.current.set(s.id,N))})()},[s]);const A=g.useCallback(async()=>{if(s)try{const{data:P,error:N}=await L.from("conversation_participants").select("conversation_id, last_read_at, is_muted").eq("user_id",s.id);if(N)throw N;if(!P||P.length===0){t([]),d(!1);return}const O=P.map(fe=>fe.conversation_id),{data:$,error:B}=await L.from("conversations").select("*").in("id",O).order("last_message_at",{ascending:!1});if(B)throw B;const{data:U}=await L.from("conversation_participants").select("conversation_id, user_id").in("conversation_id",O),K=[...new Set((U==null?void 0:U.map(fe=>fe.user_id))||[])],{data:ee}=await L.from("profiles").select("user_id, full_name, avatar_url, gender, is_verified, verification_type").in("user_id",K);ee==null||ee.forEach(fe=>{w.current.set(fe.user_id,fe)});const ce=new Map((ee==null?void 0:ee.map(fe=>[fe.user_id,fe]))||[]),Q=new Map(P.map(fe=>[fe.conversation_id,fe])),{data:re}=await L.rpc("get_unread_counts",{p_user_id:s.id,p_conversation_ids:O}),ve=new Map((re||[]).map(fe=>[fe.conversation_id,fe.unread_count])),Ce=($==null?void 0:$.filter(fe=>fe.type==="project_interview"&&fe.project_id))||[],Pe=[...new Set(Ce.map(fe=>fe.project_id).filter(Boolean))];let Me=new Map,le=new Map;if(Pe.length>0){const{data:fe}=await L.from("marketplace_projects").select("id, title, poster_id, confirmed_applicant_id, payment_status, status").in("id",Pe);Me=new Map((fe==null?void 0:fe.map(rt=>[rt.id,rt]))||[]);const et=(fe==null?void 0:fe.filter(rt=>rt.confirmed_applicant_id))||[];if(et.length>0){const rt=et.map(dt=>({project_id:dt.id,applicant_id:dt.confirmed_applicant_id})),{data:We}=await L.from("project_applications").select("project_id, status").in("project_id",et.map(dt=>dt.id));We==null||We.forEach(dt=>{le.set(dt.project_id,dt.status)})}}const oe=($==null?void 0:$.filter(fe=>fe.page_id))||[],He=[...new Set(oe.map(fe=>
703fe.page_id).filter(Boolean))];let ct=new Map;if(He.length>0){const{data:fe}=await L.from("pages").select("id, name, slug, logo_url").in("id",He);ct=new Map((fe==null?void 0:fe.map(et=>[et.id,et]))||[])}const se=($==null?void 0:$.filter(fe=>fe.type==="mentorship"&&fe.mentorship_booking_id))||[],Be=[...new Set(se.map(fe=>fe.mentorship_booking_id).filter(Boolean))];let Ke=new Map;if(Be.length>0){const{data:fe}=await L.from("mentorship_bookings").select("id, status, pricing_type, contact_unlocked_at, mentor_id, mentee_id, listing_id").in("id",Be),et=[...new Set((fe||[]).map(We=>We.listing_id).filter(Boolean))];let rt=new Map;if(et.length>0){const{data:We}=await L.from("mentorship_listings").select("id, title").in("id",et);rt=new Map((We||[]).map(dt=>[dt.id,dt.title]))}Ke=new Map((fe||[]).map(We=>[We.id,{id:We.id,status:We.status,pricing_type:We.pricing_type,contact_unlocked_at:We.contact_unlocked_at,mentor_id:We.mentor_id,mentee_id:We.mentee_id,listing_title:rt.get(We.listing_id)||null}]))}const Ee=($||[]).map(fe=>{const rt=((U==null?void 0:U.filter(ie=>ie.conversation_id===fe.id))||[]).filter(ie=>ie.user_id!==s.id).map(ie=>ce.get(ie.user_id)).filter(Boolean),We=Q.get(fe.id),dt=fe.project_id?Me.get(fe.project_id):null,pe=fe.project_id?le.get(fe.project_id):null,ge=fe.page_id?ct.get(fe.page_id):null,be=fe.mentorship_booking_id?Ke.get(fe.mentorship_booking_id):null;return{...fe,status:fe.status||"active",participants:rt,unread_count:ve.get(fe.id)||0,is_muted:(We==null?void 0:We.is_muted)||!1,project:dt||null,application_status:pe||null,page:ge||null,mentorship_booking:be?{id:be.id,status:be.status,booking_type:be.pricing_type==="free"?"free":"paid",contact_unlocked:!!be.contact_unlocked_at,listing_title:be.listing_title,mentor_id:be.mentor_id,mentee_id:be.mentee_id}:null}});t(Ee)}catch(P){console.error("Error fetching conversations:",P)}finally{d(!1)}},[s]),S=g.useCallback(async P=>{if(s){u(!0);try{const{data:N,error:O}=await L.from("messages").select(`
704          *,
705          sender:profiles!sender_id(user_id, full_name, avatar_url, gender, is_verified, verification_type)
706        `).eq("conversation_id",P).order("created_at",{ascending:!0}).limit(100);if(O)throw O;const $=(N||[]).map(B=>{const U=Array.isArray(B.sender)?B.sender[0]:B.sender;return U&&w.current.set(U.user_id,U),{...B,sender:U,status:"sent"}});o($),await L.from("conversation_participants").update({last_read_at:new Date().toISOString()}).eq("conversation_id",P).eq("user_id",s.id),L.channel(`read:${P}`).send({type:"broadcast",event:"read",payload:{user_id:s.id,read_at:new Date().toISOString()}}),t(B=>B.map(U=>U.id===P?{...U,unread_count:0}:U))}catch(N){console.error("Error fetching messages:",N)}finally{u(!1)}}},[s]),I=g.useCallback(async(P,N)=>{var K;if(!s||!r)return null;const O=r.type==="project_interview"&&r.project&&!r.project.confirmed_applicant_id,$=r.type==="mentorship"&&!!r.mentorship_booking_id&&((K=r.mentorship_booking)==null?void 0:K.contact_unlocked)!==!0;if((O||$)&&P.trim()){const ee=d2(P);if(ee.hasViolation){try{await L.rpc("log_message_violation",{p_user_id:s.id,p_conversation_id:r.id,p_content:P,p_violation_type:ee.violationType,p_matched_pattern:ee.matchedPattern})}catch(re){console.error("Error logging violation:",re)}const ce=ee.violationType?u2(ee.violationType):"Contact information",Q=$?"Sharing contact information is not allowed before the booking is confirmed.":"Sharing contact information is not allowed before hiring.";return Ae.error(`Message blocked: ${ce} detected`,{description:`${Q} Violations may result in account suspension.`,duration:5e3}),null}}const B=`temp-${Date.now()}-${Math.random().toString(36).substring(7)}`,U={id:B,conversation_id:r.id,sender_id:s.id,content:P.trim()||null,message_type:N?"file":"text",attachment_url:N||null,is_edited:!1,is_deleted:!1,created_at:new Date().toISOString(),sender:T.current||{user_id:s.id,full_name:null,avatar_url:null},status:"sending"};o(ee=>[...ee,U]),f(!0);try{const{data:ee,error:ce}=await L.from("messages").insert({conversation_id:r.id,sender_id:s.id,content:P.trim()||null,message_type:N?"file":"text",attachment_url:N||null,status:"sent"}).select(`
707          *,
708          sender:profiles!sender_id(user_id, full_name, avatar_url, gender, is_verified, verification_type)
709        `).single();if(ce)throw ce;
709const Q={...ee,sender:Array.isArray(ee.sender)?ee.sender[0]:ee.sender,status:"sent"};return o(re=>re.map(ve=>ve.id===B?Q:ve)),Q}catch(ee){return console.error("Error sending message:",ee),o(ce=>ce.map(Q=>Q.id===B?{...Q,status:"failed"}:Q)),Ae.error("Failed to send message"),null}finally{f(!1)}},[s,r]);g.useCallback(async P=>{if(!s)return!1;const{data:N}=await L.from("user_connections").select("id").eq("status","accepted").eq("requester_id",s.id).eq("addressee_id",P).maybeSingle();if(N)return!0;const{data:O}=await L.from("user_connections").select("id").eq("status","accepted").eq("requester_id",P).eq("addressee_id",s.id).maybeSingle();return!!O},[s]);const j=g.useCallback(async P=>{if(!s)return null;try{const{data:N,error:O}=await L.rpc("create_or_get_direct_conversation",{p_other_user_id:P});if(O)throw O;const{data:$}=await L.from("conversations").select("*").eq("id",N).single();if(!$)throw new Error("Conversation not found");$.status==="pending"&&$.created_by===s.id&&Ae.success("Message request sent"),await A();const B=e.find(U=>U.id===N);return B&&(n(B),await S(B.id)),$}catch(N){return console.error("Error starting conversation:",N),Ae.error("Failed to start conversation"),null}},[s,e,A,S]),R=g.useCallback(async P=>{if(!s)return!1;try{const{error:N}=await L.from("conversations").update({status:"active"}).eq("id",P);if(N)throw N;return t(O=>O.map($=>$.id===P?{...$,status:"active"}:$)),(r==null?void 0:r.id)===P&&n(O=>O&&{...O,status:"active"}),!0}catch(N){return console.error("Error accepting request:",N),Ae.error("Failed to accept request"),!1}},[s,r]),k=g.useCallback(async P=>{if(!s)return!1;try{const{error:N}=await L.from("conversations").update({status:"declined"}).eq("id",P);if(N)throw N;return t(O=>O.filter($=>$.id!==P)),(r==null?void 0:r.id)===P&&(n(null),o([])),Ae.success("Message request declined"),!0}catch(N){return console.error("Error declining request:",N),Ae.error("Failed to decline request"),!1}},[s,r]),D=g.useCallback(async P=>{n(P),await S(P.id)},[S]),Y=g.useCallback(()=>{!b.current||!s||(b.current.send({type:"broadcast",event:"typing",payload:{user_id:s.id}}),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{var P;(P=b.current)==null||P.send({type:"broadcast",event:"stop_typing",payload:{user_id:s.id}})},3e3))},[s]);g.useEffect(()=>{s&&A()},[s,A]),g.useEffect(()=>{if(!s)return;const P=L.channel("inbox-updates").on("postgres_changes",{event:"INSERT",schema:"public",table:"messages"},N=>{N.new.sender_id!==s.id&&A()}).on("postgres_changes",{event:"UPDATE",schema:"public",table:"conversations"},()=>{A()}).subscribe();return()=>{L.removeChannel(P)}},[s,A]),g.useEffect(()=>{if(!r||!s)return;const P=L.channel(`messages:${r.id}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"messages",filter:`conversation_id=eq.${r.id}`},O=>{const $=O.new;if($.sender_id===s.id){o(K=>K.map(ee=>
709ee.id.startsWith("temp-")&&ee.sender_id===s.id?{...ee,id:$.id,status:"sent"}:ee));return}const B=w.current.get($.sender_id),U={id:$.id,conversation_id:$.conversation_id,sender_id:$.sender_id,content:$.content,message_type:$.message_type,attachment_url:$.attachment_url,is_edited:$.is_edited,is_deleted:$.is_deleted,created_at:$.created_at,sender:B||{user_id:$.sender_id,full_name:null,avatar_url:null},status:"delivered"};o(K=>K.some(ee=>ee.id===U.id)?K:[...K,U]),B||L.from("profiles").select("user_id, full_name, avatar_url").eq("user_id",$.sender_id).single().then(({data:K})=>{K&&(w.current.set(K.user_id,K),o(ee=>ee.map(ce=>ce.id===U.id?{...ce,sender:K}:ce)))}),L.from("conversation_participants").update({last_read_at:new Date().toISOString()}).eq("conversation_id",r.id).eq("user_id",s.id)}).subscribe();b.current=L.channel(`typing:${r.id}`).on("broadcast",{event:"typing"},O=>{O.payload.user_id!==s.id&&(p($=>new Set($).add(O.payload.user_id)),setTimeout(()=>{p($=>{const B=new Set($);return B.delete(O.payload.user_id),B})},4e3))}).on("broadcast",{event:"stop_typing"},O=>{p($=>{const B=new Set($);return B.delete(O.payload.user_id),B})}).subscribe();const N=L.channel(`read:${r.id}`).on("broadcast",{event:"read"},O=>{O.payload.user_id!==s.id&&o($=>$.map(B=>B.sender_id===s.id&&B.status!=="seen"?{...B,status:"seen"}:B))}).subscribe();return()=>{L.removeChannel(P),b.current&&(L.removeChannel(b.current),b.current=null),L.removeChannel(N),p(new Set)}},[r,s]),g.useEffect(()=>{if(!s)return;const P=L.channel("online-users",{config:{presence:{key:s.id}}});return P.on("presence",{event:"sync"},()=>{const N=P.presenceState(),O=new Set(Object.keys(N));y(O)}).subscribe(async N=>{N==="SUBSCRIBED"&&await P.track({online_at:new Date().toISOString()})}),_.current=P,()=>{L.removeChannel(P)}},[s]);const q=g.useCallback(async(P,N)=>{try{const O=await Na.confirmApplicant(P,N);if(O.success){if(Ae.success("Applicant hired successfully!"),await A(),r){const{data:$}=await L.from("marketplace_projects").select("id, title, poster_id, confirmed_applicant_id, payment_status, status").eq("id",P).single();$&&n(B=>B&&{...B,project:$})}return!0}else return Ae.error(O.error||"Failed to hire applicant"),!1}catch(O){return console.error("Error hiring applicant:",O),Ae.error("Failed to hire applicant"),!1}},[A,r]),X=g.useCallback(async P=>{try{const N=await Na.updateApplicationStatus(P,"rejected");return N.success?(Ae.success("Application rejected"),await A(),!0):(Ae.error(N.error||"Failed to reject applicant"),!1)}catch(N){return console.error("Error rejecting applicant:",N),Ae.error("Failed to reject applicant"),!1}},[A]),F=g.useCallback(async P=>{if(!s)return null;try{const{data:N}=await L.from("conversations").select("id").eq("page_id",P).eq("type","page_message");if(N&&N.length>0){const{data:ee}=await L.from("conversation_participants").select("conversation_id").eq("user_id",s.id).in("conversation_id",N.map(ce=>ce.id)).maybeSingle();if(ee)return await A(),{id:ee.conversation_id}}const{data:O}=await L.from("page_roles").select("user_id").eq("page_id",P).in("role",["admin","editor"]);if(!O||O.length===0)return Ae.error("This page has no managers to message"),null;const{data:$,error:B}=await L.from("conversations").insert({type:"page_message",page_id:P,created_by:s.id,status:"active",last_message_at:new Date().toISOString()}).select().single();if(B)throw B;const U=[{conversation_id:$.id,user_id:s.id,role:"member"},...O.filter(ee=>ee.user_id!==s.id).map(ee=>({conversation_id:$.id,user_id:ee.user_id,role:"member"}))],{error:K}=await L.from("conversation_participants").insert(U);if(K)throw K;return await A(),$}catch(N){return console.error("Error starting page conversation:",N),Ae.error("Failed to start conversation"),null}},[s,A]);return{conversations:e,activeConversation:r,messages:i,loading:l,messagesLoading:c,sending:h,typingUsers:m,onlineUsers:x,fetchConversations:A,selectConversation:D,sendMessage:I,startConversation:j,startPageConversation:F,sendTypingIndicator:Y,setActiveConversation:n,acceptMessageRequest:R,declineMessageRequest:k,hireApplicant:q,rejectApplicant:X}}const li=new Map;let Gd=[],zd=null;const f2=50,m2="https://mgfwdrpalgzacqncgvcx.supabase.co/functions/v1/get-media-url";async function p2(){var e;const s=[...Gd];if(Gd=[],zd=null,s.length!==0)try{const{data:t}=await L.auth.getSession(),r=(e=t==null?void 0:t.session)==null?void 0:e.access_token;
709if(!r){s.forEach(o=>o.resolve(null));return}const n=await fetch(m2,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({action:"batch",items:s.map(o=>({type:o.type,path:o.path}))})});if(!n.ok){s.forEach(o=>o.resolve(null));return}const{results:i}=await n.json();for(const o of s){const l=i[o.path];if(l){const d=Date.now()+l.expiresIn*1e3;li.set(o.path,{url:l.signedUrl,expiresAt:d}),o.resolve(l.signedUrl)}else o.resolve(null)}}catch{s.forEach(t=>t.resolve(null))}}function g2(s,e){return new Promise(t=>{const r=li.get(s);if(r&&r.expiresAt>Date.now()+5*6e4){t(r.url);return}Gd.push({path:s,type:e,resolve:t}),zd||(zd=setTimeout(p2,f2))})}const qd="https://media.gradzen.com",x2=["avatars/","cover-photos/","site-assets/","course-assets/","social-posts/"];function y2(s){for(const e of x2)if(s.startsWith(e))return`${qd}/${s}`;return null}const v2=/\.r2\.cloudflarestorage\.com\//,b2=["gradzen-reels-origin","gradzen-reels-public"];function _2(s){if(!v2.test(s))return null;try{const t=new URL(s).pathname.split("/").filter(Boolean);if(t.length<2)return null;const r=t[0];return b2.includes(r)?`${qd}/${t.slice(1).join("/")}`:`${qd}/${t.slice(1).join("/")}`}catch{return null}}function po(s){return s.startsWith("http://")||s.startsWith("https://")}function Ga(s,e="general"){const t=(()=>{if(!s)return null;if(po(s)){const u=_2(s);return u||s}const c=y2(s);return c||s})(),[r,n]=g.useState(()=>{if(!t)return null;if(po(t))return t;const c=li.get(t);return c&&c.expiresAt>Date.now()+5*6e4?c.url:null}),[i,o]=g.useState(()=>{if(!t||po(t))return!1;const c=li.get(t);return!(c&&c.expiresAt>Date.now()+5*6e4)}),l=g.useRef(),d=g.useCallback(async()=>{if(!t){n(null),o(!1);return}if(po(t)){n(t),o(!1);return}const c=li.get(t);if(c&&c.expiresAt>Date.now()+5*6e4){n(c.url),o(!1);const h=c.expiresAt-Date.now()-5*6e4;h>0&&(l.current=setTimeout(d,h));return}o(!0);const u=await g2(t,e);if(u){n(u);const h=li.get(t);if(h){const f=h.expiresAt-Date.now()-3e5;f>0&&(l.current=setTimeout(d,f))}}o(!1)},[t,e]);return g.useEffect(()=>(d(),()=>{l.current&&clearTimeout(l.current)}),[d]),{url:r,isLoading:i}}function ah({name:s,avatarUrl:e,gender:t,className:r,fallbackClassName:n,onClick:i}){const{url:o}=Ga(e,"avatar"),l=o||_i(t);return a.jsxs(Bs,{className:C(r),onClick:i,children:[a.jsx(Vs,{src:l||void 0}),a.jsx(Gs,{className:C(n),children:sn(s)})]})}function w2({conversation:s,isActive:e,onClick:t,onRemove:r}){var c;const{user:n}=$t(),i=s.participants.find(u=>u.user_id!==(n==null?void 0:n.id))||s.participants[0],o=s.type==="page_message"&&s.page?s.page.name:(i==null?void 0:i.full_name)||s.name||"Chat",l=s.type==="page_message"&&((c=s.page)!=null&&c.logo_url)?s.page.logo_url:(i==null?void 0:i.avatar_url)||null,d=(i==null?void 0:i.gender)||null;return a.jsxs("div",{className:"relative group",children:[a.jsxs("button",{onClick:t,className:`relative flex items-center justify-center h-12 w-12 rounded-full shadow-lg active:scale-95 transition-transform ring-2 overflow-hidden ${e?"ring-primary":"ring-background"}`,"aria-label":`Chat with ${o}`,children:[a.jsx(ah,{name:o,avatarUrl:l,gender:d,className:"h-12 w-12",fallbackClassName:"text-xs bg-muted text-muted-foreground"}),s.unread_count>0&&a.jsx("span",{className:"absolute -top-1 -right-1 min-w-[18px] h-[18px] flex items-center justify-center rounded-full bg-destructive text-destructive-foreground text-[10px] font-bold px-1",children:s.unread_count>9?"9+":s.unread_count})]}),a.jsx("button",{onClick:u=>{u.stopPropagation(),r()},className:"absolute -top-1 -left-1 h-5 w-5 rounded-full bg-muted text-muted-foreground flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity","aria-label":"Remove chat head",children:a.jsx(Fs,{className:"h-3 w-3"})})]})}function Po(s,e){if(s==="r2")return`https://media.gradzen.com/${e}`;if(s==="supabase"){const{data:t}=L.storage.from("stories").getPublicUrl(e);return t.publicUrl}return e}function E2(s,e=1080,t=.8){return new Promise((r,n)=>{const i=new Image;i.onload=()=>{const o=document.createElement("canvas");let{width:l,height:d}=i;l>e&&(d=Math.round(d*e/l),l=e),o.width=l,o.height=d;const c=o.getContext("2d");if(!c)return n(new Error("Canvas context unavailable"));c.drawImage(i,0,0,l,d),o.toBlob(u=>{u?r(u):n(new Error("Compression failed"))},"image/jpeg",t)},i.onerror=()=>n(new Error("Image load failed")),i.src=URL.createObjectURL(s)})}const S2=[{type:"like",emoji:"❤️"},{type:"thumbsup",emoji:"👍"},{type:"haha",emoji:"😂"},{type:"love",emoji:"😍"},{type:"wow",emoji:"😮"},{type:"sad",emoji:"😢"},{type:"fire",emoji:"🔥"},{type:"angry",emoji:"😡"}];function T2({currentReaction:s,onReact:e,onBurst:t,onInteractionStart:r,onInteractionEnd:n}){const i=g.useCallback((o,l,d)=>{r(),e(l);const c=o.currentTarget.getBoundingClientRect(),u=c.left+c.width/2,h=c.top;t(u,h,d),setTimeout(()=>n(),800)},[e,t,r,n]);return a.jsx("div",{className:"relative flex items-center",onClick:o=>o.stopPropagation(),children:a.jsx("div",{className:"flex items-center gap-1 overflow-x-auto scrollbar-hide",style:{maxWidth:120},children:S2.map(({type:o,emoji:l})=>a.jsx("button",{onClick:d=>{d.stopPropagation(),i(d,o,l)},className:"text-xl flex-shrink-0 transition-transform duration-150 active:scale-125 p-1 hover:scale-110",children:l},o))})})}function A2({onSend:s,onFocus:e,onBlur:t}){const[r,n]=g.useState(""),i=g.useRef(null),o=()=>{var c;const d=r.trim();
709d&&(s(d),n(""),(c=i.current)==null||c.blur())},l=d=>{d.stopPropagation(),d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),o())};return a.jsxs("div",{className:"relative flex-1 min-w-0",onClick:d=>d.stopPropagation(),children:[a.jsx("input",{ref:i,type:"text",value:r,onChange:d=>n(d.target.value),onFocus:e,onBlur:()=>{r.trim()||t()},onKeyDown:l,placeholder:"Send message...",className:"w-full bg-white/10 border border-white/20 rounded-full pl-4 pr-9 py-2 text-white text-sm placeholder:text-white/50 focus:outline-none focus:ring-1 focus:ring-white/40"}),r.trim()&&a.jsx("button",{onClick:d=>{d.stopPropagation(),o()},className:"absolute right-2 top-1/2 -translate-y-1/2 text-white/80 hover:text-white",children:a.jsx(s0,{className:"w-4 h-4"})})]})}let yp=0,vp=-1;function lr(s,e){return Math.random()*(e-s)+s}const Hd=[(s,e)=>e*Math.sin(s*Math.PI),(s,e)=>-e*Math.sin(s*Math.PI),(s,e)=>e*.4*Math.sin(s*2*Math.PI)],k2=[0,.22,.4,.55,.66,.75,.82,.88,.93,.97,1],R2={"❤️":["#ff4d6d","#ff758f","#ff8fa3"],"😍":["#ff4d6d","#ff758f","#ff8fa3"],"👍":["#4895ef","#56cfe1","#72efdd"],"😂":["#ffd166","#ffb347","#fee440"],"😮":["#ffd166","#ffb347","#fee440"],"🔥":["#ff6d00","#ff9e00","#ffbd00"],"😢":["#8ecae6","#a2d2ff","#bde0fe"],"😡":["#e63946","#ff6b6b","#ff8585"]},j2=["#fca311","#e9c46a","#f4a261"];function I2(){let s;do s=Math.floor(Math.random()*Hd.length);while(s===vp&&Hd.length>1);return vp=s,s}function bp(s,e,t,r,n,i,o){const l=Array.from({length:11},(d,c)=>{const u=c*10,h=c/10,f=i(h,n),m=r*k2[c];let p,x;return o?(p=h<=.1?.5+h*7:1.2-h*.3,x=h<=.1?h*10:h>=.7?1-(h-.7)/.3:1):(p=h<=.1?.3+h*7:1-h*.5,x=h<=.05?h*20:h>=.5?1-(h-.5)/.5:1),`${u}% { transform: translate3d(${(e+f).toFixed(1)}px, ${(t+m).toFixed(1)}px, 0) scale(${Math.max(0,p).toFixed(2)}); opacity: ${Math.max(0,Math.min(1,x)).toFixed(2)}; }`}).join(`
710            `);return`@keyframes ${s} { ${l} }`}const Vv=g.forwardRef((s,e)=>{const t=g.useRef(null);return g.useImperativeHandle(e,()=>({burst(r,n,i){const o=t.current;if(!o)return;const l=I2(),d=Hd[l],c=lr(1200,1500),u=-100,h=lr(20,40),f=R2[i]||j2,m=`r-${Date.now()}-${yp++}`,p=bp(m,r,n,u,h,d,!0),x=document.createElement("style");x.textContent=p,document.head.appendChild(x);const y=document.createElement("span");y.textContent=i,y.style.cssText=`
711          position: fixed; left: 0; top: 0;
712          font-size: 36px; line-height: 1;
713          pointer-events: none;
714          will-change: transform, opacity;
715          transform: translate3d(${r}px, ${n}px, 0) scale(0.5);
716          animation: ${m} ${c}ms cubic-bezier(0.16, 1, 0.3, 1) forwards;
717          opacity: 0; z-index: 61;
718        `,y.addEventListener("animationend",()=>{y.remove(),x.remove()},{once:!0}),o.appendChild(y);const v=Math.floor(lr(3,6)),_=c*.7,b=h*lr(.5,.7),w=u*lr(.6,.8);for(let T=0;T<v;T++){const A=`b-${Date.now()}-${yp++}`,S=T*lr(50,80),I=lr(8,14),j=f[T%f.length],R=b*lr(.8,1.2),k=bp(A,r+lr(-6,6),n+lr(0,8),w,R,d,!1),D=document.createElement("style");D.textContent=k,document.head.appendChild(D);const Y=document.createElement("div");Y.style.cssText=`
719            position: fixed; left: 0; top: 0;
720            width: ${I}px; height: ${I}px;
721            border-radius: 50%;
722            background: ${j};
723            pointer-events: none;
724            will-change: transform, opacity;
725            transform: translate3d(${r}px, ${n}px, 0) scale(0.3);
726            animation: ${A} ${_}ms cubic-bezier(0.16, 1, 0.3, 1) ${S}ms forwards;
727            opacity: 0; z-index: 60;
728          `,Y.addEventListener("animationend",()=>{Y.remove(),D.remove()},{once:!0}),o.appendChild(Y)}}})),a.jsx("div",{ref:t,className:"fixed inset-0 pointer-events-none",style:{zIndex:60}})});Vv.displayName="StoryReactionParticles";function C2(s){if(typeof document>"u")return;let e=document.head||document.getElementsByTagName("head")[0],t=document.createElement("style");t.type="text/css",e.appendChild(t),t.styleSheet?t.styleSheet.cssText=s:t.appendChild(document.createTextNode(s))}const Gv=J.createContext({drawerRef:{current:null},overlayRef:{current:null},onPress:()=>{},onRelease:()=>{},onDrag:()=>{},onNestedDrag:()=>{},onNestedOpenChange:()=>{},onNestedRelease:()=>{}
728,openProp:void 0,dismissible:!1,isOpen:!1,isDragging:!1,keyboardIsOpen:{current:!1},snapPointsOffset:null,snapPoints:null,handleOnly:!1,modal:!1,shouldFade:!1,activeSnapPoint:null,onOpenChange:()=>{},setActiveSnapPoint:()=>{},closeDrawer:()=>{},direction:"bottom",shouldScaleBackground:!1,setBackgroundColorOnScale:!0,noBodyStyles:!1,container:null,autoFocus:!1}),za=()=>{const s=J.useContext(Gv);if(!s)throw new Error("useDrawerContext must be used within a Drawer.Root");return s};C2(`[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,100%,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,-100%,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(-100%,0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(100%,0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not(
729[data-state=closed]
730){opacity:0}[data-vaul-overlay][data-vaul-snap-points-overlay=true]{opacity:1}[data-vaul-handle]{display:block;position:relative;opacity:.7;background:#e2e2e4;margin-left:auto;margin-right:auto;height:5px;width:32px;border-radius:1rem;touch-action:pan-y}[data-vaul-handle]:active,[data-vaul-handle]:hover{opacity:1}[data-vaul-handle-hitarea]{position:absolute;
730left:50%;top:50%;transform:translate(-50%,-50%);width:max(100%,2.75rem);height:max(100%,2.75rem);touch-action:inherit}@media (hover:hover) and (pointer:fine){[data-vaul-drawer]{user-select:none}}@media (pointer:fine){[data-vaul-handle-hitarea]:{width:100%;height:100%}}@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes fadeOut{to{opacity:0}}@keyframes slideFromBottom{from{transform:translate3d(0,100%,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToBottom{to{transform:translate3d(0,100%,0)}}@keyframes slideFromTop{from{transform:translate3d(0,-100%,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToTop{to{transform:translate3d(0,-100%,0)}}@keyframes slideFromLeft{from{transform:translate3d(-100%,0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToLeft{to{transform:translate3d(-100%,0,0)}}@keyframes slideFromRight{from{transform:translate3d(100%,0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToRight{to{transform:translate3d(100%,0,0)}}`);const N2=24,L2=typeof window<"u"?g.useLayoutEffect:g.useEffect;function _p(...s){return(...e)=>{for(let t of s)typeof t=="function"&&t(...e)}}function P2(){return oh(/^Mac/)}function D2(){return oh(/^iPhone/)}function wp(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function O2(){return oh(/^iPad/)||P2()&&navigator.maxTouchPoints>1}function zv(){return D2()||O2()}function oh(s){return typeof window<"u"&&window.navigator!=null?s.test(window.navigator.platform):void 0}const Mc=typeof document<"u"&&window.visualViewport;function Ep(s){let e=window.getComputedStyle(s);return/(auto|scroll)/.test(e.overflow+e.overflowX+e.overflowY)}function qv(s){for(Ep(s)&&(s=s.parentElement);s&&!Ep(s);)s=s.parentElement;return s||document.scrollingElement||document.documentElement}const M2=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);let go=0,Fc;function F2(s={}){let{isDisabled:e}=s;L2(()=>{if(!e)return go++,go===1&&zv()&&(Fc=$2()),()=>{go--,go===0&&(Fc==null||Fc())}},[e])}function $2(){let s,e=0,t=h=>{s=qv(h.target),!(s===document.documentElement&&s===document.body)&&(e=h.changedTouches[0].pageY)},r=h=>{if(!s||s===document.documentElement||s===document.body){h.preventDefault();return}let f=h.changedTouches[0].pageY,m=s.scrollTop,p=s.scrollHeight-s.clientHeight;p!==0&&((m<=0&&f>e||m>=p&&f<e)&&h.preventDefault(),e=f)},n=h=>{let f=h.target;Kd(f)&&f!==document.activeElement&&(h.preventDefault(),f.style.transform="translateY(-2000px)",f.focus(),requestAnimationFrame(()=>{f.style.transform=""}))},i=h=>{let f=h.target;Kd(f)&&(f.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{f.style.transform="",Mc&&(Mc.height<window.innerHeight?requestAnimationFrame(()=>{Sp(f)}):Mc.addEventListener("resize",()=>Sp(f),{once:!0}))}))},o=()=>{window.scrollTo(0,0)},l=window.pageXOffset,d=window.pageYOffset,c=_p(U2(document.documentElement,"paddingRight",`${window.innerWidth-document.documentElement.clientWidth}px`));window.scrollTo(0,0);let u=_p(Wi(document,"touchstart",t,{passive:!1,capture:!0}),Wi(document,"touchmove",r,{passive:!1,capture:!0}),Wi(document,"touchend",n,{passive:!1,capture:!0}),Wi(document,"focus",i,!0),Wi(window,"scroll",o));return()=>{c(),u(),window.scrollTo(l,d)}}function U2(s,e,t){let r=s.style[e];return s.style[e]=t,()=>{s.style[e]=r}}function Wi(s,e,t,r){return s.addEventListener(e,t,r),()=>{s.removeEventListener(e,t,r)}}function Sp(s){let e=document.scrollingElement||document.documentElement;for(;s&&s!==e;){let t=qv(s);if(t!==document.documentElement&&t!==document.body&&t!==s){let r=t.getBoundingClientRect().top,n=s.getBoundingClientRect().top,i=s.getBoundingClientRect().bottom;const o=t.getBoundingClientRect().bottom+N2;i>o&&(t.scrollTop+=n-r)}s=t.parentElement}}function Kd(s){return s instanceof HTMLInputElement&&!M2.has(s.type)||s instanceof HTMLTextAreaElement||s instanceof HTMLElement&&s.isContentEditable}function B2(s,e){typeof s=="function"?s(e):s!=null&&(s.current=e)}function V2(...s){return e=>s.forEach(t=>B2(t,e))}function Hv(...s){return g.useCallback(V2(...s),s)}const Kv=new WeakMap;function Jt(s,e,t=!1){if(!s||!(s instanceof HTMLElement))return;let r={};Object.entries(e).forEach(([n,i])=>{if(n.startsWith("--")){s.style.setProperty(n,i);return}r[n]=s.style[n],s.style[n]=i}),!t&&Kv.set(s,r)}function G2(s,e){if(!s||!(s instanceof HTMLElement))return;let t=Kv.get(s);t&&(s.style[e]=t[e])}const es=s=>{switch(s){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return s}};function xo(s,e){if(!s)return null;const t=window.getComputedStyle(s),r=t.transform||t.webkitTransform||t.mozTransform;let n=r.match(/^matrix3d\((.+)\)$/);return n?parseFloat(n[1].split(", ")[es(e)?13:12]):(n=r.match(/^matrix\((.+)\)$/),n?parseFloat(n[1].split(", ")[es(e)?5:4]):null)}function z2(s){return 8*(Math.log(s+1)-2)}function $c(s,e){if(!s)return()=>{};const t=s.style.cssText;return Object.assign(s.style,e),()=>{s.style.cssText=t}}function q2(...s){return(...e)=>{for(const t of s)typeof t=="function"&&t(...e)}}const Mt={DURATION:.5,EASE:[.32,.72,0,1]},Wv=.4,H2=.25,K2=100,Yv=8,pn=16,Wd=26,Uc="vaul-dragging";function Xv(s){const e=J.useRef(s);return J.useEffect(()=>{e.current=s}),J.useMemo(()=>(...t)=>e.current==null?void 0:e.current.call(e,...t),[])}function W2({defaultProp:s,onChange:e}){const t=J.useState(s),[r]=t,n=J.useRef(r),i=Xv(e);return J.useEffect(()=>{n.current!==r&&(i(r),n.current=r)},[r,n,i]),t}function Qv({prop:s,defaultProp:e,onChange:t=()=>{}}){const[r,n]=W2({defaultProp:e,onChange:t}),i=s!==void 0,o=i?s:r,l=Xv(t),d=J.useCallback(c=>{if(i){const h=typeof c=="function"?c(s):c;h!==s&&l(h)}else n(c)},[i,s,n,l]);return[o,d]}function Y2({activeSnapPointProp:s,setActiveSnapPointProp:e,snapPoints:t,drawerRef:r,overlayRef:n,fadeFromIndex:i,onSnapPointChange:o,direction:l="bottom",container:d,snapToSequentialPoint:c}){const[u,h]=Qv({prop:s,defaultProp:t==null?void 0:t[0],onChange:e}),[f,m]=J.useState(typeof window<"u"?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);J.useEffect(()=>{function S(){m({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",S),()=>window.removeEventListener("resize",S)},[]);const p=J.useMemo(()=>u===(t==null?void 0:t[t.length-1])||null,[t,u]),x=J.useMemo(()=>t==null?void 0:t.findIndex(S=>S===u),[t,u]),y=t&&t.length>0&&(i||i===0)&&!Number.isNaN(i)&&t[i]===u||!t,v=J.useMemo(()=>{const S=d?{width:d.getBoundingClientRect().width,height:d.getBoundingClientRect().height}:typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0};var I;return(I=t==null?void 0:t.map(j=>{const R=typeof j=="string";let k=0;if(R&&(k=parseInt(j,10)),es(l)){const Y=R?k:f?j*S.height:0;return f?l==="bottom"?S.height-Y:-S.height+Y:Y}const D=R?k:f?j*S.width:0;return f?l==="right"?S.width-D:-S.width+D:D}))!=null?I:[]},[t,f,d]),_=J.useMemo(()=>x!==null?v==null?void 0:v[x]:null,[v,x]),b=J.useCallback(S=>{var I;const j=(I=v==null?void 0:v.findIndex(R=>R===S))!=null?I:null;o(j),Jt(r.current,{transition:`transform ${Mt.DURATION}s cubic-bezier(${Mt.EASE.join(",")})`,transform:es(l)?`translate3d(0, ${S}px, 0)`:`translate3d(${S}px, 0, 0)`}),v&&j!==v.length-1&&j!==i&&j<i?Jt(n.current,{transition:`opacity ${Mt.DURATION}s cubic-bezier(${Mt.EASE.join(",")})`,opacity:"0"}):Jt(n.current,{transition:`opacity ${Mt.DURATION}s cubic-bezier(${Mt.EASE.join(",")})`,opacity:"1"}),h(t==null?void 0:t[Math.max(j,0)])},[r.current,t,v,i,n,h]);J.useEffect(()=>{if(u||s){var S;const I=(S=t==null?void 0:t.findIndex(j=>j===s||j===u))!=null?S:-1;v&&I!==-1&&typeof v[I]=="number"&&b(v[I])}},[u,s,t,v,b]);function w({draggedDistance:S,closeDrawer:I,velocity:j,dismissible:R}){if(i===void 0)return;const k=l==="bottom"||l==="right"?(_??0)-S:(_??0)+S,D=x===i-1,Y=x===0,q=S>0;if(D&&Jt(n.current,{transition:`opacity ${Mt.DURATION}s cubic-bezier(${Mt.EASE.join(",")})`}),!c&&j>2&&!q){R?I():b(v[0]);return}if(!c&&j>2&&q&&v&&t){b(v[t.length-1]);return}const X=v==null?void 0:v.reduce((P,N)=>typeof P!="number"||typeof N!="number"?P:Math.abs(N-k)<Math.abs(P-k)?N:P),F=es(l)?window.innerHeight:window.innerWidth;if(j>Wv&&Math.abs(S)<F*.4){const P=q?1:-1;if(P>0&&p){b(v[t.length-1]);return}if(Y&&P<0&&R&&I(),x===null)return;b(v[x+P]);return}b(X)}function T({draggedDistance:S}){if(_===null)return;const I=l==="bottom"||l==="right"?_-S:_+S;(l==="bottom"||l==="right")&&I<v[v.length-1]||(l==="top"||l==="left")&&I>v[v.length-1]||Jt(r.current,{transform:es(l)?`translate3d(0, ${I}
730px, 0)`:`translate3d(${I}px, 0, 0)`})}function A(S,I){if(!t||typeof x!="number"||!v||i===void 0)return null;const j=x===i-1;if(x>=i&&I)return 0;if(j&&!I)return 1;if(!y&&!j)return null;const k=j?x+1:x-1,D=j?v[k]-v[k-1]:v[k+1]-v[k],Y=S/Math.abs(D);return j?1-Y:Y}return{isLastSnapPoint:p,activeSnapPoint:u,shouldFade:y,getPercentageDragged:A,setActiveSnapPoint:h,activeSnapPointIndex:x,onRelease:w,onDrag:T,snapPointsOffset:v}}const X2=()=>()=>{};function Q2(){const{direction:s,isOpen:e,shouldScaleBackground:t,setBackgroundColorOnScale:r,noBodyStyles:n}=za(),i=J.useRef(null),o=g.useMemo(()=>document.body.style.backgroundColor,[]);function l(){return(window.innerWidth-Wd)/window.innerWidth}J.useEffect(()=>{if(e&&t){i.current&&clearTimeout(i.current);const d=document.querySelector("[data-vaul-drawer-wrapper]")||document.querySelector("[vaul-drawer-wrapper]");if(!d)return;q2(r&&!n?$c(document.body,{background:"black"}):X2,$c(d,{transformOrigin:es(s)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${Mt.DURATION}s`,transitionTimingFunction:`cubic-bezier(${Mt.EASE.join(",")})`}));const c=$c(d,{borderRadius:`${Yv}px`,overflow:"hidden",...es(s)?{transform:`scale(${l()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${l()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{c(),i.current=window.setTimeout(()=>{o?document.body.style.background=o:document.body.style.removeProperty("background")},Mt.DURATION*1e3)}}},[e,t,o])}let Yi=null;function J2({isOpen:s,modal:e,nested:t,hasBeenOpened:r,preventScrollRestoration:n,noBodyStyles:i}){const[o,l]=J.useState(()=>typeof window<"u"?window.location.href:""),d=J.useRef(0),c=J.useCallback(()=>{if(wp()&&Yi===null&&s&&!i){Yi={position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,height:document.body.style.height,right:"unset"};const{scrollX:h,innerHeight:f}=window;document.body.style.setProperty("position","fixed","important"),Object.assign(document.body.style,{top:`${-d.current}px`,left:`${-h}px`,right:"0px",height:"auto"}),window.setTimeout(()=>window.requestAnimationFrame(()=>{const m=f-window.innerHeight;m&&d.current>=f&&(document.body.style.top=`${-(d.current+m)}px`)}),300)}},[s]),u=J.useCallback(()=>{if(wp()&&Yi!==null&&!i){const h=-parseInt(document.body.style.top,10),f=-parseInt(document.body.style.left,10);Object.assign(document.body.style,Yi),window.requestAnimationFrame(()=>{if(n&&o!==window.location.href){l(window.location.href);return}window.scrollTo(f,h)}),Yi=null}},[o]);return J.useEffect(()=>{function h(){d.current=window.scrollY}return h(),window.addEventListener("scroll",h),()=>{window.removeEventListener("scroll",h)}},[]),J.useEffect(()=>{t||!r||(s?(!window.matchMedia("(display-mode: standalone)").matches&&c(),e||window.setTimeout(()=>{u()},500)):u())},[s,r,o,e,t,c,u]),{restorePositionSetting:u}}function Z2({open:s,onOpenChange:e,children:t,onDrag:r,onRelease:n,snapPoints:i,shouldScaleBackground:o=!1,setBackgroundColorOnScale:l=!0,closeThreshold:d=H2,scrollLockTimeout:c=K2,dismissible:u=!0,handleOnly:h=!1,fadeFromIndex:f=i&&i.length-1,activeSnapPoint:m,setActiveSnapPoint:p,fixed:x,modal:y=!0,onClose:v,nested:_,noBodyStyles:b,direction:w="bottom",defaultOpen:T=!1,disablePreventScroll:A=!0,snapToSequentialPoint:S=!1,preventScrollRestoration:I=!1,repositionInputs:j=!0,onAnimationEnd:R,container:k,autoFocus:D=!1}){var Y,q;const[X=!1,F]=Qv({defaultProp:T,prop:s,onChange:Ne=>{e==null||e(Ne),!Ne&&!_&&ge(),setTimeout(()=>{R==null||R(Ne)},Mt.DURATION*1e3),Ne&&!y&&typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),Ne||(document.body.style.pointerEvents="auto")}}),[P,N]=J.useState(!1),[O,$]=J.useState(!1),[B,U]=J.useState(!1),K=J.useRef(null),ee=J.useRef(null),ce=J.useRef(null),Q=J.useRef(null),re=J.useRef(null),ve=J.useRef(!1),Ce=J.useRef(null),Pe=J.useRef(0),Me=J.useRef(!1),le=J.useRef(0),oe=J.useRef(null),He=J.useRef(((Y=oe.current)==null?void 0:Y.getBoundingClientRect().height)||0),ct=J.useRef(((q=oe.current)==null?void 0:q.getBoundingClientRect().width)||0),se=J.useRef(0),Be=J.useCallback(Ne=>
730{i&&Ne===rt.length-1&&(ee.current=new Date)},[]),{activeSnapPoint:Ke,activeSnapPointIndex:Ee,setActiveSnapPoint:fe,onRelease:et,snapPointsOffset:rt,onDrag:We,shouldFade:dt,getPercentageDragged:pe}=Y2({snapPoints:i,activeSnapPointProp:m,setActiveSnapPointProp:p,drawerRef:oe,fadeFromIndex:f,overlayRef:K,onSnapPointChange:Be,direction:w,container:k,snapToSequentialPoint:S});F2({isDisabled:!X||O||!y||B||!P||!j||!A});const{restorePositionSetting:ge}=J2({isOpen:X,modal:y,nested:_,hasBeenOpened:P,preventScrollRestoration:I,noBodyStyles:b});function be(){return(window.innerWidth-Wd)/window.innerWidth}function ie(Ne){var Ge,ht;!u&&!i||oe.current&&!oe.current.contains(Ne.target)||(He.current=((Ge=oe.current)==null?void 0:Ge.getBoundingClientRect().height)||0,ct.current=((ht=oe.current)==null?void 0:ht.getBoundingClientRect().width)||0,$(!0),ce.current=new Date,zv()&&window.addEventListener("touchend",()=>ve.current=!1,{once:!0}),Ne.target.setPointerCapture(Ne.pointerId),Pe.current=es(w)?Ne.pageY:Ne.pageX)}function Qe(Ne,Ge){var ht,at;let Xe=Ne;const Pt=(ht=window.getSelection())==null?void 0:ht.toString(),Xt=oe.current?xo(oe.current,w):null,Ie=new Date;if(Xe.hasAttribute("data-vaul-no-drag")||Xe.closest("[data-vaul-no-drag]"))return!1;if(w==="right"||w==="left")return!0;if(ee.current&&Ie.getTime()-ee.current.getTime()<500)return!1;if(Xt!==null&&(w==="bottom"?Xt>0:Xt<0))return!0;if(Pt&&Pt.length>0)return!1;if(Ie.getTime()-((at=re.current)==null?void 0:at.getTime())<c&&Xt===0||Ge)return re.current=Ie,!1;for(;Xe;){if(Xe.scrollHeight>Xe.clientHeight){if(Xe.scrollTop!==0)return re.current=new Date,!1;if(Xe.getAttribute("role")==="dialog")return!0}Xe=Xe.parentNode}return!0}function Ve(Ne){if(oe.current&&O){const Ge=w==="bottom"||w==="right"?1:-1,ht=(Pe.current-(es(w)?Ne.pageY:Ne.pageX))*Ge,at=ht>0,Xe=i&&!u&&!at;if(Xe&&Ee===0)return;const Pt=Math.abs(ht),Xt=document.querySelector("[data-vaul-drawer-wrapper]"),Ie=w==="bottom"||w==="top"?He.current:ct.current;let $e=Pt/Ie;const lt=pe(Pt,at);if(lt!==null&&($e=lt),Xe&&$e>=1||!ve.current&&!Qe(Ne.target,at))return;if(oe.current.classList.add(Uc),ve.current=!0,Jt(oe.current,{transition:"none"}),Jt(K.current,{transition:"none"}),i&&We({draggedDistance:ht}),at&&!i){const Lt=z2(ht),fs=Math.min(Lt*-1,0)*Ge;Jt(oe.current,{transform:es(w)?`translate3d(0, ${fs}px, 0)`:`translate3d(${fs}px, 0, 0)`});return}const Ut=1-$e;if((dt||f&&Ee===f-1)&&(r==null||r(Ne,$e),Jt(K.current,{opacity:`${Ut}`,transition:"none"},!0)),Xt&&K.current&&o){const Lt=Math.min(be()+$e*(1-be()),1),fs=8-$e*8,Ts=Math.max(0,14-$e*14);Jt(Xt,{borderRadius:`${fs}px`,transform:es(w)?`scale(${Lt}) translate3d(0, ${Ts}px, 0)`:`scale(${Lt}) translate3d(${Ts}px, 0, 0)`,transition:"none"},!0)}if(!i){const Lt=Pt*Ge;Jt(oe.current,{transform:es(w)?`translate3d(0, ${Lt}px, 0)`:`translate3d(${Lt}px, 0, 0)`})}}}J.useEffect(()=>{var Ne;function Ge(){if(!oe.current||!j)return;const ht=document.activeElement;if(Kd(ht)||Me.current){var at;const Xe=((at=window.visualViewport)==null?void 0:at.height)||0,Pt=window.innerHeight;let Xt=Pt-Xe;const Ie=oe.current.getBoundingClientRect().height||0,$e=Ie>Pt*.8;se.current||(se.current=Ie);const lt=oe.current.getBoundingClientRect().top;if(Math.abs(le.current-Xt)>60&&(Me.current=!Me.current),i&&i.length>0&&rt&&Ee){const Ut=rt[Ee]||0;Xt+=Ut}if(le.current=Xt,Ie>Xe||Me.current){const Ut=oe.current.getBoundingClientRect().height;let Lt=Ut;Ut>Xe&&(Lt=Xe-($e?lt:Wd)),x?oe.current.style.height=`${Ut-Math.max(Xt,0)}px`:oe.current.style.height=`${Math.max(Lt,Xe-lt)}px`}else oe.current.style.height=`${se.current}px`;i&&i.length>0&&!Me.current?oe.current.style.bottom="0px":oe.current.style.bottom=`${Math.max(Xt,0)}px`}}return(Ne=window.visualViewport)==null||Ne.addEventListener("resize",Ge),()=>{var ht;return(ht=window.visualViewport)==null?void 0:ht.removeEventListener("resize",Ge)}},[Ee,i,rt]);function It(Ne){Yt(),v==null||v(),Ne||F(!1),setTimeout(()=>{i&&fe(i[0])},Mt.DURATION*1e3)}function At(){if(!oe.current)return;const Ne=document.querySelector("[data-vaul-drawer-wrapper]"),Ge=xo(oe.current,w);Jt(oe.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${Mt.DURATION}s cubic-bezier(${Mt.EASE.join(",")})`}),Jt(K.current,{transition:`opacity ${Mt.DURATION}s cubic-bezier(${Mt.EASE.join(",")})`,opacity:"1"}),o&&Ge&&Ge>0&&X&&Jt(Ne,{borderRadius:`${Yv}px`,overflow:"hidden",...es(w)?{transform:`scale(${be()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,transformOrigin:"top"}:{transform:`scale(${be()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,transformOrigin:"left"},transitionProperty:"transform, border-radius",transitionDuration:`${Mt.DURATION}s`,transitionTimingFunction:`cubic-bezier(${Mt.EASE.join(",")})`},!0)}function Yt(){!O||!oe.current||(oe.current.classList.remove(Uc),ve.current=!1,$(!1),Q.current=ne
730w Date)}function W(Ne){if(!O||!oe.current)return;oe.current.classList.remove(Uc),ve.current=!1,$(!1),Q.current=new Date;const Ge=xo(oe.current,w);if(!Qe(Ne.target,!1)||!Ge||Number.isNaN(Ge)||ce.current===null)return;const ht=Q.current.getTime()-ce.current.getTime(),at=Pe.current-(es(w)?Ne.pageY:Ne.pageX),Xe=Math.abs(at)/ht;if(Xe>.05&&(U(!0),setTimeout(()=>{U(!1)},200)),i){et({draggedDistance:at*(w==="bottom"||w==="right"?1:-1),closeDrawer:It,velocity:Xe,dismissible:u}),n==null||n(Ne,!0);return}if(w==="bottom"||w==="right"?at>0:at<0){At(),n==null||n(Ne,!0);return}if(Xe>Wv){It(),n==null||n(Ne,!1);return}var Pt;const Xt=Math.min((Pt=oe.current.getBoundingClientRect().height)!=null?Pt:0,window.innerHeight);var Ie;const $e=Math.min((Ie=oe.current.getBoundingClientRect().width)!=null?Ie:0,window.innerWidth),lt=w==="left"||w==="right";if(Math.abs(Ge)>=(lt?$e:Xt)*d){It(),n==null||n(Ne,!1);return}n==null||n(Ne,!0),At()}J.useEffect(()=>(X&&(Jt(document.documentElement,{scrollBehavior:"auto"}),ee.current=new Date),()=>{G2(document.documentElement,"scrollBehavior")}),[X]);function Se(Ne){const Ge=Ne?(window.innerWidth-pn)/window.innerWidth:1,ht=Ne?-pn:0;Ce.current&&window.clearTimeout(Ce.current),Jt(oe.current,{transition:`transform ${Mt.DURATION}s cubic-bezier(${Mt.EASE.join(",")})`,transform:`scale(${Ge}) translate3d(0, ${ht}px, 0)`}),!Ne&&oe.current&&(Ce.current=setTimeout(()=>{const at=xo(oe.current,w);Jt(oe.current,{transition:"none",transform:es(w)?`translate3d(0, ${at}px, 0)`:`translate3d(${at}px, 0, 0)`})},500))}function it(Ne,Ge){if(Ge<0)return;const ht=(window.innerWidth-pn)/window.innerWidth,at=ht+Ge*(1-ht),Xe=-pn+Ge*pn;Jt(oe.current,{transform:es(w)?`scale(${at}) translate3d(0, ${Xe}px, 0)`:`scale(${at}) translate3d(${Xe}px, 0, 0)`,transition:"none"})}function Ct(Ne,Ge){const ht=es(w)?window.innerHeight:window.innerWidth,at=Ge?(ht-pn)/ht:1,Xe=Ge?-pn:0;Ge&&Jt(oe.current,{transition:`transform ${Mt.DURATION}s cubic-bezier(${Mt.EASE.join(",")})`,transform:es(w)?`scale(${at}) translate3d(0, ${Xe}px, 0)`:`scale(${at}) translate3d(${Xe}px, 0, 0)`})}return J.createElement(_l,{defaultOpen:T,onOpenChange:Ne=>{!u&&!Ne||(Ne?N(!0):It(!0),F(Ne))},open:X},J.createElement(Gv.Provider,{value:{activeSnapPoint:Ke,snapPoints:i,setActiveSnapPoint:fe,drawerRef:oe,overlayRef:K,onOpenChange:e,onPress:ie,onRelease:W,onDrag:Ve,dismissible:u,handleOnly:h,isOpen:X,isDragging:O,shouldFade:dt,closeDrawer:It,onNestedDrag:it,onNestedOpenChange:Se,onNestedRelease:Ct,keyboardIsOpen:Me,modal:y,snapPointsOffset:rt,direction:w,shouldScaleBackground:o,setBackgroundColorOnScale:l,noBodyStyles:b,container:k,autoFocus:D}},t))}const Jv=J.forwardRef(function({...s},e){const{overlayRef:t,snapPoints:r,onRelease:n,shouldFade:i,isOpen:o,modal:l}=za(),d=Hv(e,t),c=r&&r.length>0;return l?J.createElement(Di,{onMouseUp:n,ref:d,"data-vaul-overlay":"","data-vaul-snap-points":o&&c?"true":"false","data-vaul-snap-points-overlay":o&&i?"true":"false",...s}):(typeof window<"u"&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),null)});Jv.displayName="Drawer.Overlay";const Zv=J.forwardRef(function({onPointerDownOutside:s,style:e,onOpenAutoFocus:t,...r},n){const{drawerRef:i,onPress:o,onRelease:l,onDrag:d,keyboardIsOpen:c,snapPointsOffset:u,modal:h,isOpen:f,direction:m,snapPoints:p,container:x,handleOnly:y,autoFocus:v}=za(),[_,b]=J.useState(!1),w=Hv(n,i),T=J.useRef(null),A=J.useRef(null),S=J.useRef(!1),I=p&&p.length>0;Q2();const j=(k,D,Y=0)=>{if(S.current)return!0;const q=Math.abs(k.y),X=Math.abs(k.x),F=X>q,P=["bottom","right"].includes(D)?1:-1;if(D==="left"||D==="right"){if(!(k.x*P<0)&&X>=0&&X<=Y)return F}else if(!(k.y*P<0)&&q>=0&&q<=Y)return!F;return S.current=!0,!0};J.useEffect(()=>{I&&window.requestAnimationFrame(()=>{b(!0)})},[]);function R(k){T.current=null,S.current=!1,l(k)}return J.createElement(Oi,{"data-vaul-drawer-direction":m,"data-vaul-drawer":"","data-vaul-delayed-snap-points":_?"true":"false","data-vaul-snap-points":f&&I?"true":"false","data-vaul-custom-container":x?"true":"false",...r,ref:w,style:u&&u.length>0?{"--snap-point-height":`${u[0]}px`,...e}:e,onPointerDown:k=>{y||(r.onPointerDown==null||r.onPointerDown.call(r,k),T.current={x:k.pageX,y:k.pageY},o(k))},onOpenAutoFocus:k=>{t==null||t(k),v||k.preventDefault()},onPointerDownOutside:k=>{if(s==null||s(k),!h||k.defaultPrevented){k.preventDefault();return}c.current&&(c.current=!1)},onFocusOutside:k=>{if(!h){k.preventDefault();return}},onPointerMove:k=>{if(A.current=k,y||(r.onPointerMove==null||r.onPointerMove.call(r,k),!T.current))return;const D=k.pageY-T.current.y,Y=k.pageX-T.current.x,q=k.pointerType==="touch"?10:2;j({x:Y,y:D},m,q)?d(k):(Math.abs(Y)>q||Math.abs(D)>q)&&(T.current=null)},onPointerUp:k=>{r.onPointerUp==null||r.onPointerUp.call(r,k),T.current=null,S.current=!1,l(k)},onPointerOut:k=>{r.onPointerOut==null||r.onPointerOut.call(r,k),R(A.current)},onContextMenu:k=>{r.onContextMenu==null||r.onContextMenu.call(r,k),R(A.current)}})});Zv.displayName="Drawer.Content";
730const eO=250,tO=120,sO=J.forwardRef(function({preventCycle:s=!1,children:e,...t},r){const{closeDrawer:n,isDragging:i,snapPoints:o,activeSnapPoint:l,setActiveSnapPoint:d,dismissible:c,handleOnly:u,isOpen:h,onPress:f,onDrag:m}=za(),p=J.useRef(null),x=J.useRef(!1);function y(){if(x.current){b();return}window.setTimeout(()=>{v()},tO)}function v(){if(i||s||x.current){b();return}if(b(),(!o||o.length===0)&&c){n();return}if(l===o[o.length-1]&&c){n();return}const T=o.findIndex(S=>S===l);if(T===-1)return;const A=o[T+1];d(A)}function _(){p.current=window.setTimeout(()=>{x.current=!0},eO)}function b(){window.clearTimeout(p.current),x.current=!1}return J.createElement("div",{onClick:y,onPointerCancel:b,onPointerDown:w=>{u&&f(w),_()},onPointerMove:w=>{u&&m(w)},ref:r,"data-vaul-drawer-visible":h?"true":"false","data-vaul-handle":"","aria-hidden":"true",...t},J.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},e))});sO.displayName="Drawer.Handle";function rO(s){const e=za(),{container:t=e.container,...r}=s;return J.createElement(bl,{container:t,...r})}const Er={Root:Z2,Content:Zv,Overlay:Jv,Portal:rO,Close:Ma,Title:Mi,Description:Fi},Dl=({shouldScaleBackground:s=!0,...e})=>a.jsx(Er.Root,{shouldScaleBackground:s,...e});Dl.displayName="Drawer";const nO=Er.Portal,n3=Er.Close,eb=g.forwardRef(({className:s,...e},t)=>a.jsx(Er.Overlay,{ref:t,className:C("fixed inset-0 z-50 bg-black/80",s),...e}));eb.displayName=Er.Overlay.displayName;const Ol=g.forwardRef(({className:s,children:e,...t},r)=>a.jsxs(nO,{children:[a.jsx(eb,{}),a.jsxs(Er.Content,{ref:r,className:C("fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",s),...t,children:[a.jsx("div",{className:"mx-auto mt-2 h-2 w-[100px] rounded-full bg-muted"}),e]})]}));Ol.displayName="DrawerContent";const Ml=({className:s,...e})=>a.jsx("div",{className:C("grid gap-1.5 p-4 text-center sm:text-left",s),...e});Ml.displayName="DrawerHeader";const Fl=g.forwardRef(({className:s,...e},t)=>a.jsx(Er.Title,{ref:t,className:C("text-lg font-semibold leading-none tracking-tight",s),...e}));Fl.displayName=Er.Title.displayName;const iO=g.forwardRef(({className:s,...e},t)=>a.jsx(Er.Description,{ref:t,className:C("text-sm text-muted-foreground",s),...e}));iO.displayName=Er.Description.displayName;const aO={like:"❤️",love:"😍",haha:"😂",wow:"😮",sad:"😢",fire:"🔥",thumbsup:"👍",angry:"😡"};function oO({open:s,onOpenChange:e,storyId:t}){const[r,n]=g.useState([]),[i,o]=g.useState([]),[l,d]=g.useState(!0);g.useEffect(()=>{!s||!t||(d(!0),Promise.all([L.from("story_views").select("viewer_id").eq("story_id",t).then(async({data:u})=>{if(!u||u.length===0)return[];const h=[...new Set(u.map(m=>m.viewer_id))],{data:f}=await L.from("profiles").select("user_id, full_name, avatar_url").in("user_id",h);return f||[]}),L.from("story_reactions").select("reactor_id, reaction_type, created_at").eq("story_id",t).order("created_at",{ascending:!0}).then(async({data:u})=>{if(!u||u.length===0)return{reactions:[],profiles:[]};const h=[...new Set(u.map(m=>m.reactor_id))],{data:f}=await L.from("profiles").select("user_id, full_name, avatar_url").in("user_id",h);return{reactions:u,profiles:f||[]}}),L.from("story_replies").select("sender_id, message, created_at").eq("story_id",t).order("created_at",{ascending:!1}).then(async({data:u})=>{if(!u||u.length===0)return[];const h=[...new Set(u.map(p=>p.sender_id))],{data:f}=await L.from("profiles").select("user_id, full_name, avatar_url").in("user_id",h),m=new Map((f||[]).map(p=>[p.user_id,p]));return u.map(p=>({...p,profile:m.get(p.sender_id)||null}))})]).then(([u,h,f])=>{const{reactions:m,profiles:p}=h,x=new Map;for(const w of u)x.set(w.user_id,w);for(const w of p)x.has(w.user_id)||x.set(w.user_id,w);const y=new Map;for(const w of m){y.has(w.reactor_id)||y.set(w.reactor_id,[]);const T=y.get(w.reactor_id);T.length<5&&T.push(aO[w.reaction_type]||"❤️")}const v=new Set;for(const w of u)v.add(w.user_id);for(const w of m)v.add(w.reactor_id);const _=new Set(y.keys()),b=[];for(const w of _){const T=x.get(w);b.push({user_id:w,full_name:(T==null?void 0:T.full_name)||null,avatar_url:(T==null?void 0:T.avatar_url)||null,reactions:y.get(w)||[]})}for(const w of v)if(!_.has(w)){const T=x.get(w);b.push({user_id:w,full_name:(T==null?void 0:T.full_name)||null,avatar_url:(T==null?void 0:T.avatar_url)||null,reactions:[]})}n(b),o(f),d(!1)}))},[s,t]);const c=(u,h)=>a.jsx("div",{className:"w-8 h-8 rounded-full overflow-hidden bg-muted flex-shrink-0",children:u?a.jsx("img",{src:u,alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-xs text-muted-foreground",children:(h||"U").charAt(0).toUpperCase()})});return a.jsx(Dl,{open:s,onOpenChange:e,children:a.jsxs(Ol,{className:"max-h-[70vh]",children:[a.jsx(Ml,{children:a.jsx(Fl,{children:"Story Details"})}),a.jsxs("div",{className:"px-4 pb-4 space-y-4 max-h-[55vh] overflow-y-auto",children:[!l&&i.length>0&&a.jsxs("div",{children:[a.jsxs("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:["Replies (",i.length,")"]}),a.jsx("div",{className:"space-y-2",children:i.map((u,h)=>{var f,m,p;return a.jsxs("div",{className:"flex items-start gap-2 py-1",children:[c(((f=u.profile)==null?void 0:f.avatar_url)||null,((m=u.profile)==null?void 0:m.full_name)||null),a.jsxs("div",{className:"min-w-0",children:[a.jsx("span",{className:"text-sm font-medium",children:((p=u.profile)==null?void 0:p.full_name)||"User"}),a.jsx("p",{className:"text-sm text-muted-foreground",children:u.message})]})]},h)})})]}),l?a.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading..."}):r.length===0?a.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No viewers yet"}):a.jsx("div",{className:"space-y-1",children:r.map(u=>a.jsxs("div",{className:"flex items-center gap-2 py-1.5",children:[c(u.avatar_url,u.full_name),a.jsx("span",{className:"text-sm flex-1 truncate",children:u.full_name||"User"}),u.reactions.length>0&&a.jsx("div",{className:"flex items-center gap-0.5 flex-shrink-0",children:u.reactions.map((h,f)=>a.jsx("span",{className:"text-base",children:h},f))})]},u.user_id))})]})]})})}var tb="AlertDialog",[lO]=cn(tb,[vg]),Fr=vg(),sb=s=>{const{__scopeAlertDialog:e,...t}=s,r=Fr(e);return a.jsx(_l,{...r,...t,modal:!0})};sb.displayName=tb;var cO="AlertDialogTrigger",rb=g.forwardRef((s,e)=>{const{__scopeAlertDialog:t,...r}=s,n=Fr(t);return a.jsx(bg,{...n,...r,ref:e})});rb.displayName=cO;var dO="AlertDialogPortal",nb=s=>{const{__scopeAlertDialog:e,...t}=s,r=Fr(e);return a.jsx(bl,{...r,...t})};nb.displayName=dO;var uO="AlertDialogOverlay",ib=g.forwardRef((s,e)=>{const{__scopeAlertDialog:t,...r}=s,n=Fr(t);return a.jsx(Di,{...n,...r,ref:e})});ib.displayName=uO;var gi="AlertDialogContent",[hO,fO]=lO(gi),mO=A_("AlertDialogContent"),ab=g.forwardRef((s,e)=>{const{__scopeAlertDialog:t,children:r,...n}=s,i=Fr(t),o=g.useRef(null),l=qt(e,o),d=g.useRef(null);return a.jsx(T_,{contentName:gi,titleName:ob,docsSlug:"alert-dialog",children:a.jsx(hO,{scope:t,cancelRef:d,children:a.jsxs(Oi,{role:"alertdialog",...i,...n,ref:l,onOpenAutoFocus:Et(n.onOpenAutoFocus,c=>{var u;c.preventDefault(),(u=d.current)==null||u.focus({preventScroll:!0})}),onPointerDownOutside:c=>c.preventDefault(),onInteractOutside:c=>c.preventDefault(),children:[a.jsx(mO,{children:r}),a.jsx(gO,{contentRef:o})]})})})});ab.displayName=gi;var ob="AlertDialogTitle",lb=g.forwardRef((s,e)=>{const{__scopeAlertDialog:t,...r}=s,n=Fr(t);return a.jsx(Mi,{...n,...r,ref:e})});
730lb.displayName=ob;var cb="AlertDialogDescription",db=g.forwardRef((s,e)=>{const{__scopeAlertDialog:t,...r}=s,n=Fr(t);return a.jsx(Fi,{...n,...r,ref:e})});db.displayName=cb;var pO="AlertDialogAction",ub=g.forwardRef((s,e)=>{const{__scopeAlertDialog:t,...r}=s,n=Fr(t);return a.jsx(Ma,{...n,...r,ref:e})});ub.displayName=pO;var hb="AlertDialogCancel",fb=g.forwardRef((s,e)=>{const{__scopeAlertDialog:t,...r}=s,{cancelRef:n}=fO(hb,t),i=Fr(t),o=qt(e,n);return a.jsx(Ma,{...i,...r,ref:o})});fb.displayName=hb;var gO=({contentRef:s})=>{const e=`\`${gi}\` requires a description for the component to be accessible for screen reader users.
731
732You can add a description to the \`${gi}\` by passing a \`${cb}\` component as a child, which also benefits sighted users by adding visible context to the dialog.
733
734Alternatively, you can use your own component as a description by assigning it an \`id\` and passing the same value to the \`aria-describedby\` prop in \`${gi}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component.
735
736For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return g.useEffect(()=>{var r;document.getElementById((r=s.current)==null?void 0:r.getAttribute("aria-describedby"))||console.warn(e)},[e,s]),null},xO=sb,yO=rb,vO=nb,mb=ib,pb=ab,gb=ub,xb=fb,yb=lb,vb=db;const bO=xO,i3=yO,_O=vO,bb=g.forwardRef(({className:s,...e},t)=>a.jsx(mb,{className:C("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...e,ref:t}));bb.displayName=mb.displayName;const _b=g.forwardRef(({className:s,...e},t)=>a.jsxs(_O,{children:[a.jsx(bb,{}),a.jsx(pb,{ref:t,className:C("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",s),...e})]}));_b.displayName=pb.displayName;const wb=({className:s,...e})=>a.jsx("div",{className:C("flex flex-col space-y-2 text-center sm:text-left",s),...e});wb.displayName="AlertDialogHeader";const Eb=({className:s,...e})=>a.jsx("div",{className:C("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...e});Eb.displayName="AlertDialogFooter";const Sb=g.forwardRef(({className:s,...e},t)=>a.jsx(yb,{ref:t,className:C("text-lg font-semibold",s),...e}));Sb.displayName=yb.displayName;const Tb=g.forwardRef(({className:s,...e},t)=>a.jsx(vb,{ref:t,className:C("text-sm text-muted-foreground",s),...e}));Tb.displayName=vb.displayName;const Ab=g.forwardRef(({className:s,...e},t)=>a.jsx(gb,{ref:t,className:C(_u(),s),...e}));Ab.displayName=gb.displayName;const kb=g.forwardRef(({className:s,...e},t)=>a.jsx(xb,{ref:t,className:C(_u({variant:"outline"}),"mt-2 sm:mt-0",s),...e}));kb.displayName=xb.displayName;const wO=5e3;function Rb({storyGroups:s,initialGroupIndex:e,currentUserId:t,onClose:r,onMarkViewed:n,onReact:i,onReply:o,onShareStory:l}){const[d,c]=g.useState(e),[u,h]=g.useState(0),[f,m]=g.useState(!1),[p,x]=g.useState(!1),[y,v]=g.useState(!1),[_,b]=g.useState(null),[w,T]=g.useState(!1),[A,S]=g.useState(!1),[I,j]=g.useState(null),R=g.useRef([]),k=g.useRef(0),D=g.useRef(0),Y=g.useRef(0),q=g.useRef(null),X=g.useRef(null),F=g.useRef(null),P=s[d],N=P==null?void 0:P.stories[u],O=(P==null?void 0:P.stories.length)||0;g.useEffect(()=>{if(!N)return;if(N.media_provider!=="r2"){b(null),T(!0),j(N.id),S(!1);return}T(!1),b(null),j(null),S(!1);let le=!1;return ba("story",N.id).then(oe=>{le||(b(oe),T(!0),j(N.id))}),()=>{le=!0}},[N==null?void 0:N.id,N==null?void 0:N.media_provider]),g.useEffect(()=>{const le=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=le}},[]),g.useEffect(()=>{const le=oe=>
736{oe.key==="Escape"&&r(),oe.key==="ArrowLeft"&&ee(),oe.key==="ArrowRight"&&K()};return window.addEventListener("keydown",le),()=>window.removeEventListener("keydown",le)},[d,u]);const $=g.useCallback((le=0)=>{cancelAnimationFrame(k.current);const oe=performance.now()-le;D.current=oe;const He=ct=>{const se=ct-oe;Y.current=se;const Be=Math.min(se/wO,1),Ke=R.current[u];Ke&&(Ke.style.width=`${Be*100}%`),Be<1?k.current=requestAnimationFrame(He):K()};k.current=requestAnimationFrame(He)},[u]),B=g.useCallback(()=>{cancelAnimationFrame(k.current),m(!0)},[]),U=g.useCallback(()=>{m(!1),$(Y.current)},[$]);g.useEffect(()=>{if(N)return N.user_id!==t&&n(N.id),R.current.forEach((le,oe)=>{le&&(le.style.width=oe<u?"100%":"0%")}),Y.current=0,cancelAnimationFrame(k.current),()=>cancelAnimationFrame(k.current)},[d,u,N==null?void 0:N.id]),g.useEffect(()=>(A&&w&&I===(N==null?void 0:N.id)&&(Y.current=0,$(0)),()=>cancelAnimationFrame(k.current)),[A,w]),g.useEffect(()=>{const le=[];if(P&&u+1<P.stories.length){const oe=P.stories[u+1];le.push({id:oe.id,provider:oe.media_provider,path:oe.media_path})}if(d+1<s.length){const oe=s[d+1];if(oe.stories.length>0){const He=oe.stories[0];le.push({id:He.id,provider:He.media_provider,path:He.media_path})}}le.forEach(oe=>{if(oe.provider==="r2")ba("story",oe.id).then(He=>{if(He){const ct=Po(oe.provider,oe.path),se=new Image;se.src=_a(ct,He)}});else{const He=new Image;He.src=Po(oe.provider,oe.path)}})},[d,u]);const K=g.useCallback(()=>{cancelAnimationFrame(k.current),u+1<O?h(le=>le+1):d+1<s.length?(c(le=>le+1),h(0)):r()},[u,O,d,s.length,r]),ee=g.useCallback(()=>{if(cancelAnimationFrame(k.current),u>0)h(le=>le-1);else if(d>0){const le=s[d-1];c(oe=>oe-1),h(le.stories.length-1)}},[u,d,s]),ce=le=>{const oe=le.currentTarget.getBoundingClientRect();le.clientX-oe.left<oe.width*.3?ee():K()},Q=le=>{X.current={x:le.touches[0].clientX,y:le.touches[0].clientY}},re=le=>{if(!X.current)return;const oe=le.changedTouches[0].clientX-X.current.x,He=le.changedTouches[0].clientY-X.current.y;X.current=null,Math.abs(oe)>Math.abs(He)&&Math.abs(oe)>50&&(cancelAnimationFrame(k.current),oe<0?d+1<s.length?(c(ct=>ct+1),h(0)):r():d>0&&(c(ct=>ct-1),h(0)))};if(!P||!N)return null;const ve=w&&I===(N==null?void 0:N.id),Ce=Po(N.media_provider,N.media_path),Pe=_?_a(Ce,_):Ce,Me=N.user_id===t;return yl.createPortal(a.jsxs("div",{className:"fixed inset-0 z-50 bg-black flex flex-col",onClick:ce,onTouchStart:Q,onTouchEnd:re,children:[a.jsx("div",{className:"absolute top-0 left-0 right-0 z-10 flex gap-1 p-2 pt-3",children:P.stories.map((le,oe)=>a.jsx("div",{className:"flex-1 h-[3px] bg-white/30 rounded-full overflow-hidden",children:a.jsx("div",{ref:He=>{R.current[oe]=He},className:"h-full bg-white rounded-full",style:{width:oe<u?"100%":"0%",transition:"none"}})},oe))}),a.jsxs("div",{className:"absolute top-6 left-0 right-0 z-10 flex items-center justify-between px-4",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"w-8 h-8 rounded-full overflow-hidden bg-muted flex-shrink-0",children:P.userProfile.avatar_url?a.jsx("img",{src:pr(P.userProfile.avatar_url),alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-white text-xs",children:(P.userProfile.full_name||"U").charAt(0).toUpperCase()})}),a.jsx("span",{className:"text-white text-sm font-medium",children:P.userProfile.full_name||"User"}),a.jsx("span",{className:"text-white/60 text-xs",children:Nu(new Date(N.created_at),{addSuffix:!0})})]}),a.jsx("button",{onClick:le=>{le.stopPropagation(),r()},className:"text-white p-1",children:a.jsx(Fs,{className:"w-6 h-6"})})]}),a.jsx("div",{className:"flex-1 flex items-center justify-center min-h-0",children:ve?a.jsx("img",{ref:q,src:Pe,alt:N.caption||"Story",className:"max-w-full max-h-full object-contain select-none pointer-events-none",draggable:!1,onLoad:()=>S(!0)}):a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx("div",{className:"w-10 h-10 border-2 border-white/30 border-t-white rounded-full animate-spin"})})}),N.caption&&a.jsx("div",{className:"absolute bottom-20 left-0 right-0 z-10 px-6 text-center",children:a.jsx("p",{className:"text-white text-base font-medium drop-shadow-lg bg-black/30 rounded-lg px-4 py-2 inline-block",children:N.caption})}),a.jsx("div",{className:"relative z-10 pb-4 pt-2",onClick:le=>le.stopPropagation(),children:Me?a.jsxs("button",{onClick:le=>{le.stopPropagation(),B(),x(!0)},className:"w-full flex items-center justify-center gap-4 text-white/80 text-sm py-2",children:[a.jsxs("span",{children:["👁 ",N.view_count||0," views"]}
736),a.jsxs("span",{children:["❤️ ",N.reaction_count||0]}),a.jsxs("span",{children:["💬 ",N.reply_count||0]})]}):a.jsxs("div",{className:"flex items-center gap-2 px-4",children:[a.jsx("button",{onClick:le=>{le.stopPropagation(),B(),v(!0)},className:"flex-shrink-0 w-10 h-10 rounded-full border border-white/30 bg-white/10 flex items-center justify-center text-white hover:bg-white/20 transition-colors",children:a.jsx(Qr,{className:"w-5 h-5"})}),a.jsx(A2,{onSend:le=>{o(N.id,le,P.userId),U()},onFocus:B,onBlur:U}),a.jsx(T2,{currentReaction:N.user_reaction||null,onReact:le=>i(N.id,le),onBurst:(le,oe,He)=>{var ct;return(ct=F.current)==null?void 0:ct.burst(le,oe,He)},onInteractionStart:B,onInteractionEnd:U})]})}),a.jsx(bO,{open:y,onOpenChange:le=>{v(le),le||U()},children:a.jsxs(_b,{onClick:le=>le.stopPropagation(),children:[a.jsxs(wb,{children:[a.jsx(Sb,{children:"Share to your story?"}),a.jsx(Tb,{children:"This will repost this image as your own story."})]}),a.jsxs(Eb,{children:[a.jsx(kb,{children:"Cancel"}),a.jsx(Ab,{onClick:()=>{l==null||l(Pe,N.caption||void 0),v(!1),U()},children:"Share"})]})]})}),p&&N&&a.jsx(oO,{open:p,onOpenChange:le=>{x(le),le||U()},storyId:N.id}),a.jsx(Vv,{ref:F})]}),document.body)}const Bc=new Map;function EO({storyId:s,size:e="small",onViewStory:t}){const[r,n]=g.useState(void 0),[i,o]=g.useState(null),[l,d]=g.useState(!1);g.useEffect(()=>{if(!s){n(null);return}if(Bc.has(s)){n(Bc.get(s));return}let m=!1;return(async()=>{const{data:p}=await L.from("stories").select("id, media_provider, media_path, expires_at, user_id").eq("id",s).maybeSingle();if(m)return;const x=p;Bc.set(s,x),n(x)})(),()=>{m=!0}},[s]),g.useEffect(()=>{if(!r){d(!1),o(null);return}if(r.media_provider!=="r2"){d(!0),o(null);return}d(!1);let m=!1;return ba("story",r.id).then(p=>{m||(o(p),d(!0))}),()=>{m=!0}},[r==null?void 0:r.id,r==null?void 0:r.media_provider]);const c=r&&new Date(r.expires_at)>new Date,u=e==="large"?"w-48 h-64":e==="medium"?"w-32 h-44":"w-12 h-20";if(r===void 0)return a.jsx("div",{className:`${u} rounded-lg bg-muted animate-pulse mb-1`});if(!r||!c)return a.jsx("div",{className:`${u} rounded-lg bg-muted/60 flex items-center justify-center mb-1`,children:a.jsxs("div",{className:"text-center",children:[a.jsx(Gw,{className:"h-4 w-4 text-muted-foreground mx-auto"}),a.jsx("p",{className:"text-[8px] text-muted-foreground mt-0.5",children:"Expired"})]})});const h=Po(r.media_provider,r.media_path),f=i?_a(h,i):h;return l?a.jsx("div",{className:`${u} rounded-lg overflow-hidden mb-1 cursor-pointer hover:opacity-80 transition-opacity border border-border`,onClick:()=>t==null?void 0:t(r.id),children:a.jsx("img",{src:f,alt:"Story",className:"w-full h-full object-cover"})}):a.jsx("div",{className:`${u} rounded-lg bg-muted animate-pulse mb-1`})}const SO={reels:{provider:"r2",r2Bucket:"iambd-reels",isPublic:!1,r2Target:"output"},"course-videos":{provider:"r2",isPublic:!1,r2Target:"output"},stories:{provider:"r2",isPublic:!1,r2Target:"output"},"social-posts":{provider:"r2",isPublic:!1,r2Target:"output"},"course-thumbnails":{provider:"r2",isPublic:!1,r2Target:"output"},"course-assets":{provider:"r2",isPublic:!1,r2Target:"output"},avatars:{provider:"r2",isPublic:!1,r2Target:"output"},"cover-photos":{provider:"r2",isPublic:!1,r2Target:"output"},"chat-attachments":{provider:"r2",isPublic:!1,r2Target:"output"},"report-attachments":{provider:"r2",isPublic:!1,r2Target:"output"},"question-images":{provider:"r2",isPublic:!1,r2Target:"output"},"site-assets":{provider:"r2",isPublic:!1,r2Target:"output"},"course-materials":{provider:"r2",isPublic:!1,r2Target:"output"},"identity-documents":{provider:"r2",isPublic:!1,r2Target:"output"},"assignment-submissions":{provider:"r2",isPublic:!1,r2Target:"output"},"uploads-quarantine":{provider:"supabase",isPublic:!1},"cv-uploads":{provider:"supabase",isPublic:!1}};function $l(s){return SO[s]||{provider:"supabase",isPublic:!1}}async function TO(s,e,t,r){const{error:n}=await L.storage.from(s).upload(e,t,{contentType:r==null?void 0:r.contentType,upsert:(r==null?void 0:r.upsert)??!1});if(n)throw new Error(`Supabase upload failed: ${n.message}`);const{data:i}=L.storage.from(s).getPublicUrl(e);return{url:i.publicUrl,path:e,provider:"supabase"}}function AO(s,e){const{data:t}=L.storage.from(s).getPublicUrl(e);return t.publicUrl}async function kO(s,e,t){const{data:r,error:n}=await L.storage.from(s).createSignedUrl(e,t);if(n)throw new Error(`Signed URL failed: ${n.message}`);return r.signedUrl}async function RO(s,e){const{error:t}=await L.storage.from(s).remove(e);
736if(t)throw new Error(`Remove failed: ${t.message}`)}async function jO(s,e,t,r){var h;const n=(r==null?void 0:r.contentType)||(t instanceof File?t.type:"application/octet-stream"),{data:i}=await L.auth.getSession(),o=(h=i==null?void 0:i.session)==null?void 0:h.access_token,l=await fetch("https://mgfwdrpalgzacqncgvcx.supabase.co/functions/v1/storage-service",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({action:"presign_put",bucket:s,path:e,contentType:n})});if(!l.ok){const f=await l.json().catch(()=>({error:"Unknown error"}));throw new Error(`Presign failed: ${f.error}`)}const{presignedUrl:d,path:c}=await l.json(),u=await fetch(d,{method:"PUT",headers:{"Content-Type":n},body:t});if(!u.ok)throw new Error(`R2 upload failed: ${u.status} ${u.statusText}`);return{url:c||e,path:c||e,provider:"r2"}}async function IO(s,e,t){var l;const{data:r}=await L.auth.getSession(),n=(l=r==null?void 0:r.session)==null?void 0:l.access_token,i=await fetch("https://mgfwdrpalgzacqncgvcx.supabase.co/functions/v1/storage-service",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({action:"presign_get",bucket:s,path:e,expiresIn:t})});if(!i.ok){const d=await i.json().catch(()=>({error:"Unknown error"}));throw new Error(`Signed URL failed: ${d.error}`)}const{signedUrl:o}=await i.json();return o}async function CO(s,e){var i;const{data:t}=await L.auth.getSession(),r=(i=t==null?void 0:t.session)==null?void 0:i.access_token,n=await fetch("https://mgfwdrpalgzacqncgvcx.supabase.co/functions/v1/storage-service",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({action:"delete",bucket:s,paths:e})});if(!n.ok){const o=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(`Delete failed: ${o.error}`)}}async function NO(s,e,t,r){const n=$l(s);if(n.provider==="r2"){const i=n.r2Bucket||s;return jO(i,e,t,r)}return TO(s,e,t,r)}function LO(s,e){return $l(s).provider==="r2"?e:AO(s,e)}async function PO(s,e,t=3600){const r=$l(s);return r.provider==="r2"?IO(r.r2Bucket||s,e,t):kO(s,e,t)}async function DO(s,e){const t=$l(s);return t.provider==="r2"?CO(t.r2Bucket||s,e):RO(s,e)}const jb={upload:NO,getPublicUrl:LO,getSignedUrl:PO,remove:DO},Ai=_l,a3=bg,OO=bl,Ib=g.forwardRef(({className:s,...e},t)=>a.jsx(Di,{ref:t,className:C("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...e}));Ib.displayName=Di.displayName;const Rn=g.forwardRef(({className:s,children:e,...t},r)=>a.jsxs(OO,{children:[a.jsx(Ib,{}),a.jsxs(Oi,{ref:r,className:C("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",s),...t,children:[e,a.jsxs(Ma,{className:"absolute right-4 top-4 roun
736ded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-accent data-[state=open]:text-muted-foreground hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[a.jsx(Fs,{className:"h-4 w-4"}),a.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Rn.displayName=Oi.displayName;const jn=({className:s,...e})=>a.jsx("div",{className:C("flex flex-col space-y-1.5 text-center sm:text-left",s),...e});jn.displayName="DialogHeader";const an=({className:s,...e})=>a.jsx("div",{className:C("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...e});an.displayName="DialogFooter";const In=g.forwardRef(({className:s,...e},t)=>a.jsx(Mi,{ref:t,className:C("text-lg font-semibold leading-none tracking-tight",s),...e}));In.displayName=Mi.displayName;const Cn=g.forwardRef(({className:s,...e},t)=>a.jsx(Fi,{ref:t,className:C("text-sm text-muted-foreground",s),...e}));Cn.displayName=Fi.displayName;const lh=g.forwardRef(({className:s,...e},t)=>a.jsx("textarea",{className:C("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm r
736ing-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",s),ref:t,...e}));lh.displayName="Textarea";var MO="Label",Cb=g.forwardRef((s,e)=>a.jsx(bt.label,{...s,ref:e,onMouseDown:t=>{var n;t.target.closest("button, input, select, textarea")||((n=s.onMouseDown)==null||n.call(s,t),!t.defaultPrevented&&t.detail>1&&t.preventDefault())}}));Cb.displayName=MO;var Nb=Cb;const FO=Pn("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),hr=g.forwardRef(({className:s,...e},t)=>a.jsx(Nb,{ref:t,className:C(FO(),s),...e}));hr.displayName=Nb.displayName;const $O=Pn("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),ki=g.forwardRef(({className:s,variant:e,...t},r)=>a.jsx("div",{ref:r,role:"alert",className:C($O({variant:e}),s),...t}));ki.displayName="Alert";const UO=g.forwardRef(({className:s,...e},t)=>a.jsx("h5",{ref:t,className:C("mb-1 font-medium leading-none tracking-tight",s),...e}));UO.displayName="AlertTitle";const Ri=g.forwardRef(({className:s,...e},t)=>a.jsx("div",{ref:t,className:C("text-sm [&_p]:leading-relaxed",s),...e}));Ri.displayName="AlertDescription";function BO({open:s,onOpenChange:e,projectId:t,projectTitle:r,onSuccess:n}){const[i,o]=g.useState(""),[l,d]=g.useState(!1),c=async()=>{d(!0);try{const u=await Na.markWorkComplete(t,i||void 0);u.success?(Ae.success("Work marked as complete!",{description:"The project owner has been notified to pay."}),e(!1),o(""),n==null||n()):Ae.error("Failed to mark work complete",{description:u.error})}catch{Ae.error("An error occurred")}finally{d(!1)}};return a.jsx(Ai,{open:s,onOpenChange:e,children:a.jsxs(Rn,{className:"sm:max-w-md",children:[a.jsxs(jn,{children:[a.jsxs(In,{className:"flex items-center gap-2",children:[a.jsx(bi,{className:"h-5 w-5 text-primary"}),"Mark Work as Complete"]}),a.jsxs(Cn,{children:['Confirm that you have completed all work for "',r,'"']})]}),a.jsxs("div",{className:"space-y-4 py-4",children:[a.jsxs(ki,{children:[a.jsx(lu,{className:"h-4 w-4"}),a.jsx(Ri,{children:"Once you mark work as complete, the project owner will be notified to pay the remaining amount. You can deliver the project after payment is verified."})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(hr,{htmlFor:"notes",children:"Delivery Notes (Optional)"}),a.jsx(lh,{id:"notes",placeholder:"Add any notes about the completed work, deliverables, or instructions for the project owner...",value:i,onChange:u=>o(u.target.value),rows:4})]})]}),a.jsxs(an,{className:"flex-col sm:flex-row gap-2",children:[a.jsx(ye,{variant:"outline",onClick:()=>e(!1),disabled:l,children:"Cancel"}),a.jsx(ye,{onClick:c,disabled:l,children:l?a.jsxs(a.Fragment,{children:[a.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Submitting..."]}):a.jsxs(a.Fragment,{children:[a.jsx(bi,{className:"h-4 w-4 mr-2"}),"Mark Complete"]})})]})]})})}function VO({open:s,onOpenChange:e,projectId:t,projectTitle:r,onSuccess:n}){const i=Da(),[o,l]=g.useState(!1),d=async()=>{l(!0);try{const c=await Na.deliverProject(t);c.success?(Ae.success("Project delivered!",{description:"The project owner has been notified."}),i.invalidateQueries({queryKey:["projects"]}),i.invalidateQueries({queryKey:["marketplace-projects"]}),e(!1),n==null||n()):Ae.error("Failed to deliver project",{description:c.error})}catch{Ae.error("An error occurred")}finally{l(!1)}};return a.jsx(Ai,{open:s,onOpenChange:e,children:a.jsxs(Rn,{className:"sm:max-w-md",children:[a.jsxs(jn,{children:[a.jsxs(In,{className:"flex items-center gap-2",children:[a.jsx(na,{className:"h-5 w-5 text-primary"}),"Deliver Project"]}),a.jsxs(Cn,{children:['Confirm delivery of "',r,'"']})]}),a.jsx("div",{className:"py-4",children:a.jsxs(ki,{className:"bg-primary/10 border-primary/20",children:[a.jsx(bi,{className:"h-4 w-4 text-primary"}),a.jsx(Ri,{children:"Payment has been verified. By clicking deliver, you confirm that all deliverables have been handed over to the project owner."})]})}),a.jsxs(an,{className:"flex-col sm:flex-row gap-2",children:[a.jsx(ye,{variant:"outline",onClick:()=>e(!1),disabled:o,children:"Cancel"}),a.jsx(ye,{onClick:d,disabled:o,children:o?a.jsxs(a.Fragment,{children:[a.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Delivering..."]}):a.jsxs(a.Fragment,{children:[a.jsx(na,{className:"h-4 w-4 mr-2"}),"Confirm Delivery"]})})]})]})})}function GO({open:s,onOpenChange:e,projectId:t,projectTitle:r,onSuccess:n,onContactFreelancer:i}){const[o,l]=g.useState(!1),[d,c]=g.useState(""),[u,h]=g.useState(!1),f=()=>{e(!1),i==null||i()},m=async()=>
736{if(!d.trim()){Ae.error("Please provide a reason for the dispute");return}l(!0);try{const{data:x,error:y}=await L.rpc("raise_project_dispute",{p_project_id:t,p_reason:d.trim(),p_evidence_urls:[]});if(y)throw y;const v=x;if(!v.success)throw new Error(v.error||"Failed to raise dispute");Ae.success("Dispute raised successfully",{description:"An admin will review your case shortly."}),c(""),h(!1),e(!1),n==null||n()}catch(x){Ae.error("Failed to raise dispute",{description:x.message})}finally{l(!1)}},p=()=>{c(""),h(!1),e(!1)};return u?a.jsx(Ai,{open:s,onOpenChange:p,children:a.jsxs(Rn,{className:"sm:max-w-lg",children:[a.jsxs(jn,{children:[a.jsxs(In,{className:"flex items-center gap-2",children:[a.jsx(Lr,{className:"h-5 w-5 text-destructive"}),"File Dispute"]}),a.jsxs(Cn,{children:['Explain why you believe the project was not delivered as agreed for "',r,'".']})]}),a.jsxs("div",{className:"space-y-4",children:[a.jsxs(ki,{variant:"destructive",className:"border-destructive/50",children:[a.jsx(Lr,{className:"h-4 w-4"}),a.jsxs(Ri,{className:"text-sm",children:[a.jsx("strong",{children:"Warning:"})," Filing a dispute will freeze the payment until an admin reviews your case. This may take 1-3 business days."]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(hr,{htmlFor:"reason",children:"Reason for Dispute"}),a.jsx(lh,{id:"reason",placeholder:"Describe what was agreed vs. what was delivered. Be specific about missing or incorrect deliverables...",value:d,onChange:x=>c(x.target.value),rows:5,disabled:o}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"Provide as much detail as possible to help the admin make a fair decision."})]})]}),a.jsxs(an,{className:"flex-col gap-2 sm:flex-row",children:[a.jsx(ye,{variant:"outline",onClick:()=>h(!1),disabled:o,children:"Back"}),a.jsx(ye,{variant:"destructive",onClick:m,disabled:o||!d.trim(),children:o?a.jsxs(a.Fragment,{children:[a.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Submitting..."]}):"Submit Dispute"})]})]})}):a.jsx(Ai,{open:s,onOpenChange:p,children:a.jsxs(Rn,{className:"sm:max-w-md",children:[a.jsxs(jn,{children:[a.jsxs(In,{className:"flex items-center gap-2",children:[a.jsx(Lr,{className:"h-5 w-5 text-warning"}),"Raise a Dispute"]}),a.jsxs(Cn,{children:['Before raising a dispute for "',r,'", we recommend contacting the freelancer first.']})]}),a.jsxs(ki,{variant:"default",className:"border-warning/50 bg-warning/10",children:[a.jsx(ed,{className:"h-4 w-4 text-warning"}),a.jsx(Ri,{className:"text-sm",children:"Most issues can be resolved through direct communication. Try messaging the freelancer to clarify any concerns before escalating."})]}),a.jsxs(an,{className:"flex-col gap-2 sm:flex-row",children:[a.jsxs(ye,{variant:"outline",onClick:f,className:"w-full sm:w-auto",children:[a.jsx(ed,{className:"h-4 w-4 mr-2"}),"Contact Freelancer First"]}),a.jsx(ye,{variant:"destructive",onClick:()=>h(!0),className:"w-full sm:w-auto",children:"Proceed to Dispute"})]})]})})}function zO({open:s,onOpenChange:e,projectId:t,projectTitle:r,escrowAmount:n,onSuccess:i}){const o=Da(),[l,d]=g.useState(!1),c=async()=>{d(!0);try{const{data:u,error:h}=await L.rpc("accept_project_delivery",{p_project_id:t});if(h)throw h;const f=u;if(!f.success)throw new Error(f.error||"Failed to accept delivery");Ae.success("Delivery accepted!",{description:`Payment of à§³${f.amount_released||n||0} will be released to the freelancer after a 7-day holding period.`}),o.invalidateQueries({queryKey:["projects"]}),o.invalidateQueries({queryKey:["marketplace-projects"]}),o.invalidateQueries({queryKey:["billing-wallet"]}),e(!1),i==null||i()}catch(u){Ae.error("Failed to accept delivery",{description:u.message})}finally{d(!1)}};return a.jsx(Ai,{open:s,onOpenChange:e,children:a.jsxs(Rn,{className:"sm:max-w-md",children:[a.jsxs(jn,{children:[a.jsxs(In,{className:"flex items-center gap-2",children:[a.jsx(sr,{className:"h-5 w-5 text-success"}),"Accept Delivery"]}),a.jsxs(Cn,{children:['Confirm that you have received the deliverables for "',r,'".']})]}),a.jsxs(ki,{className:"border-success/50 bg-success/10",children:[a.jsx(zr,{className:"h-4 w-4 text-success"}),a.jsx(Ri,{className:"text-sm",children:n?a.jsxs(a.Fragment,{children:[a.jsxs("strong",{children:["à§³",n.toLocaleStr
736ing()]})," will be released to the freelancer after a 7-day holding period."]}):"The escrowed payment will be released to the freelancer after a 7-day holding period."})]}),a.jsx("p",{className:"text-sm text-muted-foreground",children:"By accepting, you confirm that:"}),a.jsxs("ul",{className:"text-sm text-muted-foreground list-disc list-inside space-y-1",children:[a.jsx("li",{children:"You have received all agreed deliverables"}),a.jsx("li",{children:"The work meets your requirements"}),a.jsx("li",{children:"You approve releasing the payment"})]}),a.jsxs(an,{className:"flex-col gap-2 sm:flex-row",children:[a.jsx(ye,{variant:"outline",onClick:()=>e(!1),disabled:l,children:"Cancel"}),a.jsx(ye,{onClick:c,disabled:l,className:"bg-success hover:bg-success/90 text-success-foreground",children:l?a.jsxs(a.Fragment,{children:[a.jsx(ts,{className:"h-4 w-4 mr-2 animate-spin"}),"Processing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(sr,{className:"h-4 w-4 mr-2"}),"Accept Delivery"]})})]})]})})}async function o3(){const{data:s,error:e}=await L.from("currency_exchange_rates").select("target_currency, rate");return e?(console.error("Failed to fetch exchange rates:",e),[]):(s||[]).map(t=>({targetCurrency:t.target_currency,rate:Number(t.rate)}))}function Lb(s,e,t,r){var l,d;if(e===t||r.length===0)return s;const n=((l=r.find(c=>c.targetCurrency===e))==null?void 0:l.rate)||1,i=((d=r.find(c=>c.targetCurrency===t))==null?void 0:d.rate)||1;return s/n*i}function l3(s,e,t,r){const n=t||e;if(n===e||r.length===0)return Ca(s,e);const i=Lb(s,e,n,r);return Ca(i,n)}const qO={bkash:{primary:"#E2136E",dark:"#D11062"},rocket:{primary:"#8B3A9B",dark:"#722E82"},nagad:{primary:"#F6921E",dark:"#E58413"}},gn=s=>{const e=s.toLowerCase();return qO[e]||{primary:"#6B7280",dark:"#4B5563"}};function HO({open:s,onOpenChange:e,dueAmount:t,currency:r,displayCurrency:n,exchangeRates:i=[],userId:o,projectId:l,onSuccess:d}){const c=dn(),u=Da(),[h,f]=g.useState(1),[m,p]=g.useState([]),[x,y]=g.useState(""),[v,_]=g.useState(""),[b,w]=g.useState(!0),[T,A]=g.useState(!1),S=n&&n!==r&&i.length>0,I=S?Lb(t,r,n,i):t,j=S?n:r,R=Ca(t,r),k=Ca(I,j),D=g.useRef(null);g.useEffect(()=>{if(c&&s){const re=document.querySelector(".swipe-content-scrollable")||document.documentElement;return D.current={scrollEl:re,scrollTop:re.scrollTop,overflow:re.style.overflow,touchAction:re.style.touchAction,overscrollBehavior:re.style.overscrollBehavior},re.style.overflow="hidden",re.style.touchAction="none",re.style.overscrollBehavior="none",document.body.style.overflow="hidden",()=>{if(D.current){const{scrollEl:ve,scrollTop:Ce,overflow:Pe,touchAction:Me,overscrollBehavior:le}=D.current;ve&&(ve.style.overflow=Pe,ve.style.touchAction=Me,ve.style.overscrollBehavior=le,ve.scrollTop=Ce),D.current=null}document.body.style.overflow=""}}},[c,s]),g.useEffect(()=>{s&&(Y(),f(1),y(""),_(""))},[s]);const Y=async()=>{w(!0);try{const{data:Q,error:re}=await L.from("manual_payment_methods").select("*").eq("is_active",!0).order("display_order");if(re)throw re;p(Q||[]),Q&&Q.length>0&&y(Q[0].method_key)}catch(Q){console.error("Error fetching payment methods:",Q),Ae.error("Failed to load payment methods")}finally{w(!1)}},q=Q=>{navigator.clipboard.writeText(Q),Ae.success("Account number copied!")},X=async()=>{if(!v.trim()){Ae.error("Please enter your transaction ID");return}A(!0);try{const{data:Q,error:re}=await L.from("manual_payment_submissions").insert({user_id:o,amount:t,currency:r,payment_method:x,transaction_id:v.trim(),status:"pending"}).select("id").single();if(re){if(re.message.includes("already been submitted"))Ae.error("This transaction ID has already been submitted");else throw re;return}if(l&&(Q!=null&&Q.id)){const{error:ve}=await L.from("pending_project_payments").update({manual_payment_submission_id:Q.id,status:"submitted"}).eq("project_id",l).eq("user_id",o).eq("status","pending");ve&&console.error("Failed to link payment to project:",ve)}f(3),u.invalidateQueries({queryKey:["payment-submissions"]}
736),u.invalidateQueries({queryKey:["billing-wallet"]}),u.invalidateQueries({queryKey:["user-wallet"]}),d==null||d()}catch(Q){console.error("Error submitting payment:",Q),Ae.error(Q.message||"Failed to submit payment")}finally{A(!1)}},F=m.find(Q=>Q.method_key===x),P=()=>h===1?"Select Payment Method":h===2?"Enter Transaction ID":"Payment Submitted",N=()=>h===1?"Choose your preferred mobile payment method":h===2?"Complete the payment and enter your transaction ID":"Your payment is being verified",O=()=>a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ts,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),$=()=>a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex flex-col items-center justify-center p-4 rounded-xl bg-muted/50 border",children:[a.jsx("span",{className:"text-sm text-muted-foreground",children:"Amount to Pay"}),a.jsx("span",{className:"text-2xl font-bold text-foreground mt-1",children:R}),S&&a.jsxs("span",{className:"text-sm text-muted-foreground mt-0.5",children:["≈ ",k]})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Choose payment method"}),m.map(Q=>{const re=gn(Q.method_key),ve=x===Q.method_key;return a.jsx("div",{onClick:()=>y(Q.method_key),className:"rounded-xl cursor-pointer transition-all active:scale-[0.98] overflow-hidden",style:{background:ve?`linear-gradient(135deg, ${re.primary}, ${re.dark})`:"transparent",border:`2px solid ${ve?re.primary:"hsl(var(--border))"}`},children:a.jsx("div",{className:"p-4 transition-all",style:{backgroundColor:ve?"transparent":`${re.primary}08`},children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-12 h-12 rounded-xl flex items-center justify-center font-bold text-lg shadow-sm",style:{backgroundColor:ve?"rgba(255,255,255,0.2)":re.primary,color:"white"},children:Q.display_name.charAt(0)}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"font-semibold text-base",style:{color:ve?"white":"inherit"},children:Q.display_name}),a.jsx("p",{className:"text-sm font-mono mt-0.5",style:{color:ve?"rgba(255,255,255,0.85)":"hsl(var(--muted-foreground))"},children:Q.account_number})]}),ve&&a.jsx(sr,{className:"h-6 w-6 text-white"})]})})},Q.id)})]})]}),B=()=>{if(!F)return null;const Q=gn(F.method_key);return a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"rounded-xl overflow-hidden shadow-md",style:{border:`2px solid ${Q.primary}`},children:[a.jsxs("div",{className:"p-3 text-center",style:{background:`linear-gradient(135deg, ${Q.primary}, ${Q.dark})`},children:[a.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center text-base font-bold mx-auto mb-1 shadow-sm",style:{backgroundColor:"rgba(255,255,255,0.2)",color:"white"},children:F.display_name.charAt(0)}),a.jsx("p",{className:"text-base font-bold text-white",children:F.display_name}),a.jsx("p",{className:"text-white/80 text-xs",children:F.account_name||"Business Account"})]}),a.jsxs("div",{className:"p-3 space-y-2 bg-background",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"p-2 rounded-lg",style:{backgroundColor:`${Q.primary}12`},children:[a.jsxs("div",{className:"flex items-center justify-between mb-0.5",children:[a.jsx("span",{className:"text-xs text-muted-foreground",children:"Send To"}),a.jsx(ye,{variant:"ghost",size:"sm",className:"h-5 px-1 text-xs",style:{color:Q.primary},onClick:()=>q(F.account_number),children:a.jsx(Mh,{className:"h-3 w-3"})})]}),a.jsx("p",{className:"font-mono text-sm font-bold text-center",style:{color:Q.dark},children:F.account_number})]}),a.jsxs("div",{className:"p-2 rounded-lg",style:{backgroundColor:`${Q.primary}12`},children:[a.jsxs("div",{className:"flex items-center justify-between mb-0.5",children:[a.jsx("span",{className:"text-xs text-muted-foreground",children:"Amount"}),a.jsx(ye,{variant:"ghost",size:"sm",className:"h-5 px-1 text-xs",style:{color:Q.primary},onClick:()=>q(t.toString()),children:a.jsx(Mh,{className:"h-3 w-3"})})]}),a.jsx("p",{className:"font-mono text-sm font-bold text-center",style:{color:Q.dark},children:R})]})]}),F.instructions&&a.jsxs("div",{className:"p-2 rounded-lg text-xs",style:{backgroundColor:`${Q.primary}08`,borderLeft:`2px solid ${Q.primary}`},children:[a.jsx("span",{className:"font-medium",style:{color:Q.dark},children:"Steps: "}),a.jsx("span",{className:"text-muted-foreground",children:F.instructions})]})]})]}),a.jsxs("div",{className:"space-y-1.5",children:[a.jsx(hr,{htmlFor:"transactionId",className:"text-sm font-medium",children:"Transaction ID / TrxID"}
736),a.jsx(rr,{id:"transactionId",value:v,onChange:re=>_(re.target.value),placeholder:"Enter your Transaction ID",className:"font-mono h-11 text-base"}),a.jsxs("p",{className:"text-xs text-muted-foreground",children:["Find this in your ",F.display_name," app history"]})]}),a.jsxs("div",{className:"flex items-center gap-2 p-2.5 rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800",children:[a.jsx(lu,{className:"h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400"}),a.jsx("p",{className:"text-xs text-amber-800 dark:text-amber-200",children:"Send exact amount. Incorrect amounts delay verification."})]})]})},U=()=>{if(!F)return null;const Q=gn(F.method_key);return a.jsxs("div",{className:"py-6 text-center space-y-4",children:[a.jsx("div",{className:"mx-auto w-16 h-16 rounded-full flex items-center justify-center shadow-lg",style:{background:`linear-gradient(135deg, ${Q.primary}, ${Q.dark})`},children:a.jsx(sr,{className:"h-8 w-8 text-white"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-xl font-semibold",children:"Payment Submitted!"}),a.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:[R,S&&` (≈ ${k})`," pending verification"]})]}),a.jsxs("div",{className:"p-4 rounded-xl text-left space-y-2",style:{backgroundColor:`${Q.primary}10`},children:[a.jsxs("p",{className:"text-sm",children:[a.jsx("span",{className:"font-medium",children:"Transaction ID:"})," ",a.jsx("span",{className:"font-mono",children:v})]}),a.jsxs("p",{className:"text-sm",children:[a.jsx("span",{className:"font-medium",children:"Method:"})," ",F.display_name]})]}),a.jsx("p",{className:"text-sm text-muted-foreground",children:"Verification usually takes 1-24 hours"})]})},K=(Q=!1)=>a.jsxs(a.Fragment,{children:[a.jsx(ye,{variant:"outline",onClick:()=>e(!1),className:Q?"flex-1 h-12":"",children:"Cancel"}),a.jsx(ye,{onClick:()=>f(2),disabled:!x,className:Q?"flex-1 h-12":"",children:"Continue"})]}),ee=(Q=!1)=>
736{if(!F)return null;const re=gn(F.method_key);return a.jsxs(a.Fragment,{children:[a.jsx(ye,{variant:"outline",onClick:()=>f(1),className:Q?"flex-1 h-12":"",children:"Back"}),a.jsx(ye,{onClick:X,disabled:!v.trim()||T,className:Q?"flex-1 h-12":"",style:{background:`linear-gradient(135deg, ${re.primary}, ${re.dark})`},children:T?a.jsxs(a.Fragment,{children:[a.jsx(ts,{className:"mr-2 h-4 w-4 animate-spin"}),"Submitting..."]}):"Submit Payment"})]})},ce=(Q=!1)=>{if(!F)return null;const re=gn(F.method_key);return a.jsx(ye,{onClick:()=>e(!1),className:Q?"w-full h-12 text-base":"w-full h-9 text-sm",style:{background:`linear-gradient(135deg, ${re.primary}, ${re.dark})`},children:"Done"})};if(c&&s){const Q=a.jsxs("div",{className:"fixed inset-0 flex flex-col animate-in slide-in-from-bottom duration-300 overscroll-none",style:{zIndex:9999,backgroundColor:"hsl(var(--background))",position:"fixed",top:0,left:0,right:0,bottom:0,width:"100vw",height:"100dvh"},children:[a.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b shrink-0",style:{backgroundColor:"hsl(var(--background))"},children:[h>1&&h<3?a.jsx(ye,{variant:"ghost",size:"icon",className:"h-10 w-10 -ml-2",onClick:()=>f(h===2?1:2),children:a.jsx(yi,{className:"h-5 w-5"})}):a.jsx("div",{className:"w-10"}),a.jsx("div",{className:"flex-1 text-center",children:a.jsx("h1",{className:"text-lg font-semibold",children:P()})}),a.jsx(ye,{variant:"ghost",size:"icon",className:"h-10 w-10 -mr-2",onClick:()=>e(!1),children:a.jsx(Fs,{className:"h-5 w-5"})})]}),h<3&&a.jsxs("div",{className:"px-4 py-2 bg-muted/30 border-b shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"h-1.5 flex-1 rounded-full transition-colors",style:{backgroundColor:h>=1?gn(x||"bkash").primary:"hsl(var(--border))"}}),a.jsx("div",{className:"h-1.5 flex-1 rounded-full transition-colors",style:{backgroundColor:h>=2?gn(x||"bkash").primary:"hsl(var(--border))"}})]}),a.jsx("p",{className:"text-xs text-muted-foreground text-center mt-1.5",children:N()})]}),a.jsx("div",{className:"flex-1 overflow-y-auto overscroll-contain",style:{touchAction:"pan-y",WebkitOverflowScrolling:"touch",padding:"16px",paddingBottom:"24px"},children:b?O():a.jsxs(a.Fragment,{children:[h===1&&$(),h===2&&B(),h===3&&U()]})}),!b&&a.jsxs("div",{className:"p-4 border-t shrink-0 flex gap-3",style:{backgroundColor:"hsl(var(--background))"},children:[h===1&&K(!0),h===2&&ee(!0),h===3&&ce(!0)]})]});return yl.createPortal(Q,document.body)}return a.jsx(Ai,{open:s,onOpenChange:e,children:a.jsxs(Rn,{className:"sm:max-w-[500px] max-h-[85vh] overflow-y-auto",children:[a.jsxs(jn,{children:[a.jsx(In,{children:P()}),a.jsx(Cn,{children:N()})]}),b?O():a.jsxs(a.Fragment,{children:[h===1&&a.jsxs("div",{className:"space-y-3 py-2",children:[$(),a.jsx(an,{children:K()})]}),h===2&&a.jsxs("div",{className:"space-y-2 py-2",children:[B(),a.jsx(an,{children:ee()})]}),h===3&&a.jsxs(a.Fragment,{children:[U(),ce()]})]})]})})}function Tp({messageId:s,url:e,alt:t,className:r}){const{signedUrl:n,isLoading:i}=P0("chat_attachment",s,e);let o=n||e;const l=L0("chat_attachment",s);return l&&o&&(o=_a(o,l)),i&&!n?a.jsx("div",{className:`bg-muted animate-pulse rounded ${r}`,style:{minHeight:120}}):a.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",className:"cursor-pointer",children:a.jsx("img",{src:o,alt:t,className:r})})}function KO({messageId:s,url:e,isMe:t}){const{signedUrl:r}=P0("chat_attachment",s,e);let n=r||e;const i=L0("chat_attachment",s);return i&&n&&(n=_a(n,i)),a.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:`flex items-center gap-2 p-2 rounded-lg border ${t?"bg-primary-foreground/10 border-primary-foreground/20":"bg-background/50 border-border"}`,children:[a.jsx(Dn,{className:"h-8 w-8 shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-medium truncate",children:decodeURIComponent(e.split("/").pop()||"Document")}),a.jsx("p",{className:"text-xs opacity-70",children:"Click to download"})]}),a.jsx(Mw,{className:"h-4 w-4 shrink-0"})]})}function Pb({conversation:s,messages:e,loading:t,sending:r,typingUsers:n,onlineUsers:i,onSendMessage:o,onTyping:l,onBack:d,onAcceptRequest:c,onDeclineRequest:u,onHireApplicant:h,onRejectApplicant:f,hideHeader:m}){var gh,xh,yh,vh;const{user:p}=$t(),x=hs(),[y,v]=g.useState(""),[_,b]=g.useState(!1),[w,T]=g.useState(!1),[A,S]=g.useState(!1),[I,j]=g.useState(!1),[R,k]=g.useState(!1),[D,Y]=g.useState(!1),[q,X]=g.useState([]),[F,P]=g.useState([]),[N,O]=g.useState(null),[$,B]=g.useState(((gh=s==null?void 0:s.project)==null?void 0:gh.payment_status)||null),[U,K]=g.useState(!1),[ee,ce]=g.useState(!1),[Q,re]=g.useState(!1),[ve,Ce]=g.useState(!1),[Pe,Me]=g.useState(!1),[le,oe]=g.useState(!1),[He,ct]=g.useState(0),[se,Be]=g.useState(null),[Ke,Ee]=g.useState(null),fe=g.useRef(null),et=g.useRef(null),rt=g.useRef(null),We=g.useRef(null),[dt,pe]=g.useState(null),[ge,be]=g.useState(null);g.useEffect(()=>{if(!dt){be(null);return}(async()=>{const{data:Z}=await L.from("stories").select("*").eq("id",dt).maybeSingle();if(!Z)return;const{data:ne}=await L.from("profiles").select("full_name, avatar_url").eq("user_id",Z.user_id
736).maybeSingle();be([{userId:Z.user_id,userProfile:{full_name:(ne==null?void 0:ne.full_name)||null,avatar_url:(ne==null?void 0:ne.avatar_url)||null},stories:[Z],hasUnviewed:!0}])})()},[dt]);const ie=g.useCallback(async()=>{if((s==null?void 0:s.type)==="project_interview"&&s.project&&s.project.confirmed_applicant_id&&(p!=null&&p.id)){const{data:Z}=await L.from("project_applications").select("status").eq("project_id",s.project.id).eq("applicant_id",s.project.confirmed_applicant_id).single();O((Z==null?void 0:Z.status)||null)}else O(null)},[s,p]),Qe=g.useCallback(async()=>{if((s==null?void 0:s.type)==="project_interview"&&s.project){const{data:Z}=await L.from("marketplace_projects").select("payment_status").eq("id",s.project.id).single();Z&&B(Z.payment_status)}},[s]),Ve=g.useCallback(async()=>{if((s==null?void 0:s.type)==="project_interview"&&s.project&&(p==null?void 0:p.id)===s.project.poster_id){const{data:Z}=await L.from("project_escrow").select("amount, status, dispute_deadline").eq("project_id",s.project.id).single();Z&&Be({amount:Z.amount,status:Z.status,disputeDeadline:Z.dispute_deadline})}},[s,p]);g.useEffect(()=>{ie(),Ve(),Qe()},[ie,Ve,Qe]),g.useEffect(()=>{if(!(se!=null&&se.disputeDeadline)||se.status!=="pending_dispute_window"){Ee(null);return}const Z=()=>{const pt=new Date(se.disputeDeadline),ns=Fx(pt,new Date);if(ns<=0){Ee(null),Ve();return}const Ws=Math.floor(ns/3600),Bt=Math.floor(ns%3600/60),ks=ns%60;Ws>0?Ee(`${Ws}h ${Bt}m remaining`):Bt>0?Ee(`${Bt}m ${ks}s remaining`):Ee(`${ks}s remaining`)};Z();const ne=setInterval(Z,1e3);return()=>clearInterval(ne)},[se==null?void 0:se.disputeDeadline,se==null?void 0:se.status,Ve]),g.useEffect(()=>{var ne;if(!((ne=s==null?void 0:s.project)!=null&&ne.id))return;const Z=L.channel(`project-payment-${s.project.id}`).on("postgres_changes",{event:"UPDATE",schema:"public",table:"marketplace_projects",filter:`id=eq.${s.project.id}`},()=>{ie(),Ve(),Qe()}).on("postgres_changes",{event:"UPDATE",schema:"public",table:"project_applications",filter:`project_id=eq.${s.project.id}`},()=>{ie(),Ve()}).on("postgres_changes",{event:"UPDATE",schema:"public",table:"project_escrow",filter:`project_id=eq.${s.project.id}`},()=>{Ve()}).on("postgres_changes",{event:"UPDATE",schema:"public",table:"pending_project_payments",filter:`project_id=eq.${s.project.id}`},()=>{ie(),Ve(),Qe()}).subscribe();return()=>{L.removeChannel(Z)}},[(xh=s==null?void 0:s.project)==null?void 0:xh.id,ie,Ve,Qe]);const It=10*1024*1024,At=["image/jpeg","image/png","image/gif","image/webp"],Yt=["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],W=()=>{if((s==null?void 0:s.type)==="direct"&&s.participants.length===1){const Z=s.participants[0].user_id;x(`/profile/${Z}`)}else if((s==null?void 0:s.type)==="project_interview"&&s.project){const Z=(p==null?void 0:p.id)===s.project.poster_id,ne=!!s.project.confirmed_applicant_id;if(Z&&ne&&s.participants.length>0){const pt=s.participants[0].user_id;x(`/profile/${pt}`)}else if(!Z){const pt=s.project.poster_id;x(`/profile/${pt}?context=project&projectId=${s.project.id}`)}}},Se=(s==null?void 0:s.type)==="direct"&&(s==null?void 0:s.participants.length)===1||(s==null?void 0:s.type)==="project_interview"&&(s==null?void 0:s.project)&&((p==null?void 0:p.id)===s.project.poster_id&&!!s.project.confirmed_applicant_id||(p==null?void 0:p.id)!==s.project.poster_id),it=Z=>Z?Z.split(" ").map(ne=>ne[0]).join("").toUpperCase().slice(0,2):"U",Ct=()=>{var Z;if(!s)return"";if(s.type==="mentorship"&&((Z=s.mentorship_booking)!=null&&Z.listing_title))return s.mentorship_booking.listing_title;if(s.type==="project_interview"&&s.project){const ne=(p==null?void 0:p.id)===s.project.poster_id,pt=s.participants.some(ut=>{var ns;return((ns=s.project)==null?void 0:ns.confirmed_applicant_id)===ut.user_id});if(ne&&!pt)return"Applicant";if(!ne)return s.project.title}return s.name?s.name:s.participants.length===0?"Unknown":s.participants.length===1?s.participants[0].full_name||"Unknown":s.participants.slice(0,2).map(ne=>{var pt;return((pt=ne.full_name)==null?void 0:pt.split(" ")[0])||"Unknown"}).join(", ")},Ne=()=>!s||s.type==="project_interview"&&s.project&&!!!s.project.confirmed_applicant_id?null:s.avatar_url?s.avatar_url:s.participants.length>0?s.participants[0].avatar_url:null,Ge=(s==null?void 0:s.type)==="project_interview"&&(s==null?void 0:s.project),ht=(s==null?void 0:s.type)==="mentorship",at=()=>s?s.participants.some(Z=>
736i.has(Z.user_id)):!1,Xe=Z=>{const ne=new Date(Z);return el(ne)?nr(ne,"h:mm a"):tl(ne)?`Yesterday ${nr(ne,"h:mm a")}`:nr(ne,"MMM d, h:mm a")},Pt=()=>{const Z=[];let ne="";return e.forEach(pt=>{const ut=nr(new Date(pt.created_at),"yyyy-MM-dd");ut!==ne?(ne=ut,Z.push({date:ut,messages:[pt]})):Z[Z.length-1].messages.push(pt)}),Z},Xt=Z=>{const ne=new Date(Z);return el(ne)?"Today":tl(ne)?"Yesterday":nr(ne,"MMMM d, yyyy")},Ie=Z=>{if(Z.sender_id!==(p==null?void 0:p.id))return null;switch(Z.status){case"sending":return a.jsx(ts,{className:"h-3 w-3 animate-spin text-muted-foreground"});case"sent":return a.jsx(vi,{className:"h-3 w-3 text-muted-foreground"});case"delivered":return a.jsx(Dh,{className:"h-3 w-3 text-muted-foreground"});case"seen":return a.jsx(Dh,{className:"h-3 w-3 text-primary"});case"failed":return a.jsx(lu,{className:"h-3 w-3 text-destructive"});default:return a.jsx(vi,{className:"h-3 w-3 text-muted-foreground"})}},$e=10,lt=(Z,ne,pt)=>{const ut=$e-q.length;if(ut<=0){Ae.error("Maximum 10 files allowed");return}const ns=[],Ws=[];if(Array.from(Z).slice(0,ut).forEach(Bt=>{if(!ne.includes(Bt.type)){Ae.error(pt);return}if(Bt.size>It){Ae.error(`${Bt.name} exceeds 10MB limit`);return}ns.push(Bt),Ws.push(At.includes(Bt.type)?URL.createObjectURL(Bt):"")}),ns.length>0){if(ns.length+q.length>$e){Ae.error(`You can select up to ${$e} files`);return}X(Bt=>[...Bt,...ns]),P(Bt=>[...Bt,...Ws])}},Ut=Z=>{var ne;(ne=Z.target.files)!=null&&ne.length&&(lt(Z.target.files,At,"Please select valid image files (JPEG, PNG, GIF, or WebP)"),Z.target.value="")},Lt=Z=>{var ne;(ne=Z.target.files)!=null&&ne.length&&(lt(Z.target.files,[...At,...Yt],"Please select valid files (JPEG, PNG, GIF, WebP, PDF, Word, Text, or Excel)"),Z.target.value="")},fs=Z=>{X(ne=>ne.filter((pt,ut)=>ut!==Z)),P(ne=>(ne[Z]&&URL.revokeObjectURL(ne[Z]),ne.filter((pt,ut)=>ut!==Z)))},Ts=()=>{F.forEach(Z=>{Z&&URL.revokeObjectURL(Z)}),X([]),P([])},As=async Z=>{if(!p)return null;const ne=Z.name.split(".").pop(),pt=`${p.id}/${Date.now()}-${Math.random().toString(36).substring(7)}.${ne}`;try{const{url:ut}=await jb.upload("chat-attachments",pt,Z,{contentType:Z.type});return ut}catch(ut){return console.error("Upload error:",ut),Ae.error("Failed to upload file"),null}},ir=async Z=>{var ns,Ws;if(Z.preventDefault(),!y.trim()&&q.length===0||r||I)return;const ne=[...q],pt=y.trim();if(v(""),b(!1),et.current&&(et.current.style.height="auto"),Ts(),ne.length===0){await o(pt),(ns=et.current)==null||ns.focus();return}j(!0);const ut=[];for(const Bt of ne){const ks=await As(Bt);ks&&ut.push({url:ks,file:Bt})}if(j(!1),ut.length!==0){pt&&await o(pt);for(const{url:Bt,file:ks}of ut){const Bi=At.includes(ks.type)?"Sent a photo":"Sent a file";await o(Bi,Bt)}(Ws=et.current)==null||Ws.focus()}},Jb=async()=>{!s||!c||(T(!0),await c(s.id),T(!1))},Zb=async()=>{!s||!u||(S(!0),await u(s.id),S(!1))},e_=async()=>{var Z;!(s!=null&&s.project_id)||!((Z=s==null?void 0:s.participants[0])!=null&&Z.user_id)||!h||(k(!0),await h(s.project_id,s.participants[0].user_id),k(!1))},t_=async()=>{!(s!=null&&s.application_id)||!f||(Y(!0),await f(s.application_id),Y(!1))},s_=Z=>{v(Z.target.value),l()},mh=(s==null?void 0:s.status)==="pending"&&(s==null?void 0:s.created_by)!==(p==null?void 0:p.id),r_=(s==null?void 0:s.status)==="pending"&&(s==null?void 0:s.created_by)===(p==null?void 0:p.id);g.useEffect(()=>{fe.current&&(fe.current.scrollTop=fe.current.scrollHeight)},[e]);const ph=()=>{if(!s||n.size===0)return null;const Z=s.participants.filter(ne=>n.has(ne.user_id)).map(ne=>{var pt;return((pt=ne.full_name)==null?void 0:pt.split(" ")[0])||"Someone"});return Z.length===0?null:Z.length===1?`${Z[0]} is typing...`:`${Z.join(", ")} are typing...`};return s?a.jsxs("div",{className:"flex-1 flex flex-col h-full min-h-0",children:[!m&&a.jsxs("div",{className:"border-b bg-card shrink-0",children:[Ge&&s.project&&a.jsxs("div",{className:"px-4 py-2 bg-muted/50 cursor-pointer hover:bg-muted transition-colors border-b",onClick:()=>x(`/project/${s.project.id}`),children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Es,{className:"h-4 w-4 text-primary shrink-0"}),a.jsx("span",{className:"text-sm font-medium text-primary truncate flex-1",children:s.project.title}),a.jsx(sa,{className:"h-3 w-3 text-muted-foreground shrink-0"})]}),a.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Project Interview • Click to view details"})]}),Ge&&s.project&&!s.project.confirmed_applicant_id&&a.jsxs("div",{className:"px-4 py-2.5 bg-warning/10 border-b border-warning/30 flex items-center gap-3",children:[a.jsx(eE,{className:"h-4 w-4 text-warning shrink-0"}),a.jsxs("p",{className:"text-xs text-warning",children:[a.jsx("span",{className:"font-medium",children:"Contact sharing is prohibited before hiring."})," ",a.jsx("span",{className:"text-warning/80",children:"Violations may result in account suspension."})]})]}),ht&&s.mentorship_booking&&a.jsxs("div",{className:"px-4 py-2 bg-emerald-500/10 border-b border-emerald-500/20",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Nr,{className:"h-4 w-4 text-emerald-600 dark:text-emerald-400 shrink-0"}),a.jsx("span",{className:"text-sm font-medium text-emerald-700 dark:text-emerald-300 truncate flex-1",children:s.mentorship_booking.listing_title||"Mentorship session"}),a.jsx("button",{onClick:()=>x("/mentorship/manage?tab=mine"),className:"text-xs text-muted-foreground hover:text-foreground shrink-0 underline-offset-2 hover:underline",children:"Manage"})]}),a.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Coordinate the time and meeting link (Zoom, Google Meet, etc.) here. Funds are held in escrow until the session is marked complete."})]}),Ge&&s.project&&(p==null?void 0:p.id)===s.project.poster_id&&s.application_id&&a.jsx(a.Fragment,{children:s.project.confirmed_applicant_id?(se==null?void 0:se.status)==="pending_dispute_window"&&N==="delivered"?a.jsxs("div",{className:"px-4 py-3 bg-warning/10 border-b border-warning/30",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[a.jsx(na,{className:"h-5 w-5 text-warning shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm font-medium text-warning",children:"Project Delivered - Review Required"}),a.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[a.jsx(nE,{className:"h-3 w-3 text-muted-foreground"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:Ke||"Calculating..."})]})]})]}),a.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Review the deliverables. If satisfied, accept to release payment. If there are issues, contact the freelancer or raise a dispute."}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(ye,{size:"sm",variant:"outline",onClick:()=>re(!0),className:"border-destructive/30 text-destructive hover:bg-destructive/10",children:[a.jsx(Lr,{className:"h-4 w-4 mr-1"}),"Raise Dispute"]}),a.jsxs(ye,{size:"sm",onClick:()=>Ce(!0),className:"bg-success hover:bg-success/90 text-success-foreground",children:[a.jsx(sr,{className:"h-4 w-4 mr-1"}),"Accept & Pay"]})]})]}):(se==null?void 0:se.status)==="disputed"?a.jsxs("div",{className:"px-4 py-3 bg-destructive/10 border-b border-destructive/30 flex items-center gap-3",children:[a.jsx(Lr,{className:"h-5 w-5 text-destructive shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm font-medium text-destructive",children:"Dispute Under Review"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"An admin is reviewing your dispute. Payment is frozen until resolved."})]})]}):(se==null?void 0:se.status)==="released_to_freelancer"||N==="delivered"?a.jsxs("div",{className:"px-4 py-3 bg-success/10 border-b border-success/30 flex items-center gap-3",children:[a.jsx(sr,{className:"h-5 w-5 text-success shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm font-medium text-success",children:"Project Completed!"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"Payment has been released to the freelancer."})]}),a.jsxs(ye,{size:"sm",variant:"outline",onClick:()=>{var Z;return x(`/profile/${(Z=s.participants[0])==null?void 0:Z.user_id}`)},className:"border-success/30 hover:bg-success/10",children:[a.jsx(sa,{className:"h-4 w-4 mr-1"}),"View Profile"]})]}):N==="work_completed"?$!=="fully_paid"?a.jsxs("div",{className:"px-4 py-3 bg-orange-500/10 border-b border-orange-500/30 flex items-center gap-3",children:[a.jsx(Lr,{className:"h-5 w-5 text-orange-500 shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm font-medium text-orange-600",children:"Work Completed – Payment Due"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"The freelancer has completed the work. Pay the remaining amount to receive the delivery."})]}),a.jsxs(ye,{size:"sm",onClick:async()=>
736{if(s.project){Me(!0);try{const Z=await Na.completeProjectWithSplit(s.project.id);Z.awaitingManualPayment?(ct(Z.manualPaymentRequired||0),oe(!0)):Z.completed?Ae.success("Payment complete! The freelancer can now deliver the project."):Z.error&&Ae.error(Z.error),ie(),Ve()}catch(Z){Ae.error(Z.message||"Payment failed")}finally{Me(!1)}}},disabled:Pe,className:"bg-orange-600 hover:bg-orange-700 text-white shrink-0",children:[Pe?a.jsx(ts,{className:"h-4 w-4 animate-spin mr-1"}):a.jsx(na,{className:"h-4 w-4 mr-1"}),"Pay & Complete"]})]}):a.jsxs("div",{className:"px-4 py-3 bg-success/10 border-b border-success/30 flex items-center gap-3",children:[a.jsx(sr,{className:"h-5 w-5 text-success shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm font-medium text-success",children:"Work Completed – Awaiting Delivery"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"Payment verified. Waiting for the freelancer to deliver the project."})]})]}):a.jsxs("div",{className:"px-4 py-3 bg-success/10 border-b border-success/30 flex items-center gap-3",children:[a.jsx(sr,{className:"h-5 w-5 text-success shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm font-medium text-success",children:"Hired"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"You can now see the candidate's full profile"})]}),a.jsxs(ye,{size:"sm",variant:"outline",onClick:()=>{var Z;return x(`/profile/${(Z=s.participants[0])==null?void 0:Z.user_id}`)},className:"border-success/30 hover:bg-success/10",children:[a.jsx(sa,{className:"h-4 w-4 mr-1"}),"View Profile"]})]}):a.jsxs("div",{className:"px-4 py-3 bg-blue-500/5 border-b border-blue-500/20 flex items-center justify-between gap-3",children:[a.jsx("p",{className:"text-sm text-muted-foreground",children:"Ready to make a decision?"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(ye,{size:"sm",variant:"outline",onClick:t_,disabled:R||D,className:"text-destructive border-destructive/30 hover:bg-destructive/10",children:[D?a.jsx(ts,{className:"h-4 w-4 animate-spin mr-1"}):a.jsx(cu,{className:"h-4 w-4 mr-1"}),"Reject"]}),a.jsxs(ye,{size:"sm",onClick:e_,disabled:R||D,className:"bg-green-600 hover:bg-green-700 text-white",children:[R?a.jsx(ts,{className:"h-4 w-4 animate-spin mr-1"}):a.jsx(sr,{className:"h-4 w-4 mr-1"}),"Hire"]})]})]})}),Ge&&s.project&&(p==null?void 0:p.id)!==s.project.poster_id&&N&&a.jsxs(a.Fragment,{children:[N==="confirmed"&&a.jsx("div",{className:"px-4 py-3 bg-primary/10 border-b border-primary/30",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Es,{className:"h-5 w-5 text-primary shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm font-medium text-primary",children:"You're working on this project!"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"Once you complete the work, mark it as complete to notify the owner for payment."})]}),a.jsx(ye,{size:"sm",onClick:()=>K(!0),children:"Mark Complete"})]})}),N==="work_completed"&&$!=="fully_paid"&&a.jsx("div",{className:"px-4 py-3 bg-warning/10 border-b border-warning/30",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Dw,{className:"h-5 w-5 text-warning shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm font-medium text-warning",children:"Awaiting Payment"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"Work marked as complete. Waiting for the project owner to pay."})]})]})}),N==="work_completed"&&$==="fully_paid"&&a.jsx("div",{className:"px-4 py-3 bg-success/10 border-b border-success/30",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(sr,{className:"h-5 w-5 text-success shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm font-medium text-success",children:"Payment Verified!"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"The project owner has paid. You can now deliver your project."})]}),a.jsx(ye,{size:"sm",onClick:()=>ce(!0),className:"bg-success hover:bg-success/90 text-success-foreground",children:"Deliver Project"})]})}),N==="delivered"&&a.jsx("div",{className:"px-4 py-3 bg-success/10 border-b border-success/30",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(na,{className:"h-5 w-5 text-success shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm font-medium text-success",children:"Project Delivered!"}),a.jsx("p",{className:"text-xs text-muted-foreground",children:"This project has been successfully completed and delivered."})]})]})})]}),a.jsxs("div",{className:"flex items-center gap-3 p-4",children:[d&&a.jsx(ye,{variant:"ghost",size:"icon",onClick:d,children:a.jsx(yi,{className:"h-5 w-5"})}),a.jsxs("div",{className:`flex items-center gap-3 flex-1 ${Se?"cursor-pointer hover:opacity-80 transition-opacity":""}`,onClick:W,role:Se?"button":void 0,children:[a.jsxs("div",{className:"relative",children:[a.jsxs(Bs,{className:"h-10 w-10",children:[a.jsx(Vs,{src:pr(Ne())}),a.jsx(Gs,{children:Ge&&s.project&&!s.project.confirmed_applicant_id?"👤":it(Ct())})]}),at()&&a.jsx("span",{className:"absolute bottom-0 right-0 h-2.5 w-2.5 rounded-full bg-green-500 border-2 border-card"})]}),a.jsxs("div",{className:"flex-1",children:[a.jsxs("p",{className:"font-medium flex items-center gap-1",children:[Ct(),Se&&a.jsx(wa,{isVerified:((yh=s.participants[0])==null?void 0:yh.is_verified)||!1,verificationType:(vh=s.participants[0])==null?void 0:vh.verification_type,size:"sm"})]}),a.jsx("p",{className:"text-xs text-muted-foreground",children:at()?"Online":"Offline"})]})]}),a.jsx(ye,{variant:"ghost",size:"icon",children:a.jsx(Fw,{className:"h-5 w-5"})})]})]}),a.jsxs("div",{ref:fe,className:"flex-1 min-h-0 overflow-y-auto p-4 scrollbar-hide",children:[t?a.jsx("div",{className:"space-y-4",children:[1,2,3].map(Z=>a.jsxs("div",{className:`flex gap-2 ${Z%2===0?"justify-end":""}`,children:[Z%2!==0&&a.jsx(H,{className:"h-8 w-8 rounded-full"}),a.jsx(H,{className:`h-12 ${Z%2===0?"w-48":"w-64"} rounded-2xl`})]},Z))}):e.length===0?a.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:a.jsx("p",{children:"No messages yet. Start the conversation!"})}):a.jsx("div",{className:"space-y-4",children:Pt().map(Z=>a.jsxs("div",{children:[a.jsx("div",{className:"flex items-center justify-center mb-4",children:a.jsx("span",{className:"px-3 py-1 text-xs text-muted-foreground bg-muted rounded-full",children:Xt(Z.date)})}),a.jsx("div",{className:"space-y-2",children:Z.messages.map((ne,pt)=>{var Ws,Bt;const ut=ne.sender_id===(p==null?void 0:p.id),ns=!ut&&(pt===0||Z.messages[pt-1].sender_id!==ne.sender_id);return a.jsxs("div",{className:`flex gap-2 ${ut?"justify-end":""}`,children:[!ut&&a.jsx("div",{className:"w-8",children:ns&&a.jsxs(Bs,{className:"h-8 w-8",children:[a.jsx(Vs,{src:((Ws=ne.sender)==null?void 0:Ws.avatar_url)||void 0}),a.jsx(Gs,{className:"text-xs",children:it((Bt=ne.sender)==null?void 0:Bt.full_name)})]})}),a.jsxs("div",{className:`max-w-[70%] ${ut?"order-1":"order-2"}`,children:[(()=>{var _h;const ks=ut?ne.status==="failed"?"bg-destructive/20 text-destructive-foreground rounded-br-md":ne.status==="sending"?"bg-primary/70 text-primary-foreground rounded-br-md":"bg-primary text-primary-foreground rounded-br-md":"bg-muted rounded-bl-md",Bi=(_h=ne.attachment_url)==null?void 0:_h.match(/\.(jpg|jpeg|png|gif|webp)$/i),bh=ne.content&&!ne.content.startsWith("Sent a "),Bl=ne.message_type==="story_reply",n_=Bi&&!bh&&!ne.is_deleted&&ne.message_type!=="shared_job"&&ne.message_type!=="shared_post"&&!Bl,i_=Bi&&bh&&!ne.is_deleted&&ne.message_type!=="shared_job"&&ne.message_type!=="shared_post"&&!Bl;return Bl&&!ne.is_deleted?a.jsxs("div",{className:`flex flex-col ${ut?"items-end":"items-start"} gap-1`,children:[a.jsx("p",{className:"text-xs text-muted-foreground",children:ut?"You replied to their story":"Replied to your story"}),a.jsxs("div",{className:"relative",children:[a.jsx(EO,{storyId:ne.story_id||null,size:"medium",onViewStory:ms=>pe(ms)}),ne.content&&a.jsx("div",{className:`absolute bottom-[-8px] ${ut?"right-0":"left-0"}`,children:a.jsx("div",{className:`px-3 py-1.5 rounded-2xl ${ks} text-sm shadow-sm`,children:a.jsx("p",{className:"whitespace-pre-wrap break-words",children:ne.content})})})]})]}):n_?a.jsx("div",{className:`rounded-2xl overflow-hidden ${ks} p-0`,children:a.jsx(Tp,{messageId:ne.id,url:ne.attachment_url,alt:"Shared image",className:"max-w-full max-h-48 cursor-pointer hover:opacity-90 transition-opacity"})}):i_?a.jsxs("div",{className:`rounded-2xl overflow-hidden ${ks} p-0`,children:[a.jsx(Tp,{messageId:ne.id,url:ne.attachment_url,alt:"Shared image",className:"max-w-full max-h-48 cursor-pointer hover:opacity-90 transition-opacity"}),a.jsx("div",{className:"px-4 py-2",children:a.jsx("p",{className:"whitespace-pre-wrap break-words",children:ne.content})})]}):a.jsx("div",{className:`px-4 py-2 rounded-2xl ${ks}`,children:ne.is_deleted?a.jsx("p",{className:"italic text-muted-foreground",children:"Message deleted"}):ne.message_type==="shared_job"?(()=>{try{const ms=JSON.parse(ne.content||"{}");return a.jsxs("div",{className:"space-y-1",children:[a.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Shared a job"}),a.jsxs("div",{className:`border rounded-lg p-2 ${ut?"bg-primary-foreground
736/10":"bg-background/50"}`,children:[a.jsx("p",{className:"font-semibold text-sm",children:ms.position}),a.jsx("p",{className:"text-xs text-muted-foreground",children:ms.company_name}),ms.location&&a.jsx("p",{className:"text-xs text-muted-foreground",children:ms.location})]})]})}catch{return a.jsx("p",{className:"whitespace-pre-wrap break-words",children:ne.content})}})():ne.message_type==="shared_post"?(()=>{try{const ms=JSON.parse(ne.content||"{}");return a.jsxs("div",{className:"space-y-1",children:[ms.message&&a.jsx("p",{className:"text-sm",children:ms.message}),a.jsxs("div",{className:`border rounded-lg p-2 ${ut?"bg-primary-foreground/10":"bg-background/50"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx("div",{className:"h-5 w-5 rounded-full bg-muted overflow-hidden",children:ms.author_avatar&&a.jsx("img",{src:ms.author_avatar,alt:"",className:"h-full w-full object-cover"})}),a.jsx("span",{className:"text-xs font-medium",children:ms.author_name||"Someone"})]}),a.jsx("p",{className:"text-xs line-clamp-2",children:ms.content_preview}),ms.image_url&&a.jsx("img",{src:ms.image_url,alt:"",className:"mt-1 h-16 w-full rounded object-cover"})]})]})}catch{return a.jsx("p",{className:"whitespace-pre-wrap break-words",children:ne.content})}})():a.jsxs("div",{children:[ne.attachment_url&&!Bi&&a.jsx("div",{className:"mb-2",children:a.jsx(KO,{messageId:ne.id,url:ne.attachment_url,isMe:ut})}),ne.content&&!ne.content.startsWith("Sent a ")&&a.jsx("p",{className:"whitespace-pre-wrap break-words",children:ne.content})]})})})(),a.jsxs("div",{className:`flex items-center gap-1 mt-1 ${ut?"justify-end":"justify-start"}`,children:[a.jsx("p",{className:"text-[10px] text-muted-foreground",children:Xe(ne.created_at)}),Ie(ne)]})]})]},ne.id)})})]},Z.date))}),ph()&&a.jsxs("div",{className:"flex items-center gap-2 mt-4 text-sm text-muted-foreground",children:[a.jsxs("div",{className:"flex gap-1",children:[a.jsx("span",{className:"w-2 h-2 bg-muted-foreground rounded-full animate-bounce"}),a.jsx("span",{className:"w-2 h-2 bg-muted-foreground rounded-full animate-bounce",style:{animationDelay:"0.1s"}}),a.jsx("span",{className:"w-2 h-2 bg-muted-foreground rounded-full animate-bounce",style:{animationDelay:"0.2s"}})]}),a.jsx("span",{children:ph()})]})]}),mh&&a.jsxs("div",{className:"p-4 border-t bg-amber-500/5 border-amber-500/20",children:[a.jsxs("div",{className:"text-center mb-3",children:[a.jsxs("p",{className:"text-sm font-medium text-foreground",children:[Ct()," wants to send you a message"]}),a.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Accept to start chatting or decline to ignore"})]}),a.jsxs("div",{className:"flex gap-2 justify-center",children:[a.jsxs(ye,{variant:"outline",size:"sm",onClick:Zb,disabled:A||w,children:[A?a.jsx(ts,{className:"h-4 w-4 animate-spin mr-1"}):null,"Decline"]}),a.jsxs(ye,{size:"sm",onClick:Jb,disabled:w||A,children:[w?a.jsx(ts,{className:"h-4 w-4 animate-spin mr-1"}):null,"Accept"]})]})]}),r_&&a.jsx("div",{className:"p-4 border-t bg-muted/50",children:a.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["Your message request is pending. Waiting for ",Ct()," to accept."]})}),!mh&&a.jsxs("form",{onSubmit:ir,className:"border-t bg-card shrink-0",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:[q.length>0&&a.jsxs("div",{className:"px-4 pt-3 pb-2",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("p",{className:"text-xs text-muted-foreground",children:[q.length,"/",$e," files selected"]}),a.jsx(ye,{type:"button",variant:"ghost",size:"sm",onClick:Ts,className:"h-6 text-xs px-2",children:"Clear all"})]}),a.jsx("div",{className:"flex gap-2 overflow-x-auto pb-1 scrollbar-hide",children:q.map((Z,ne)=>a.jsxs("div",{className:"relative shrink-0 h-20 w-20 rounded-lg overflow-hidden bg-muted",children:[F[ne]?a.jsx("img",{src:F[ne],alt:"Preview",className:"h-full w-full object-cover"}):a.jsx("div",{className:"h-full w-full flex items-center justify-center",children:a.jsx(Dn,{className:"h-7 w-7 text-muted-foreground"})}),a.jsx("span",{className:"absolute bottom-0 inset-x-0 text-center text-[9px] leading-tight py-0.5 bg-black/40 text-white",children:Z.size<1024*1024?`${(Z.size/1024).toFixed(0)} KB`:`${(Z.size/(1024*1024)).toFixed(1)} MB`}),a.jsx("button",{type:"button",onClick:()=>fs(ne),className:"absolute top-0.5 right-0.5 h-5 w-5 flex items-center justify-center rounded-full bg-black/50 text-white hover:bg-black/70 transition-colors",children:a.jsx(Fs,{className:"h-3 w-3"})})]},ne))})]}),a.jsx("input",{type:"file",ref:rt,accept:"image/*",multiple:!0,className:"hidden",onChange:Ut}),a.jsx("input",{type:"file",ref:We,accept:".pdf,.doc,.docx,.txt,.xls,.xlsx,image/jpeg,image/png,image/gif,image/webp",multiple:!0,className:"hidden",onChange:Lt}),a.jsxs("div",{className:"flex items-end gap-1 px-3 pt-3 pb-4",children:[a.jsxs("div",{className:C("flex items-center shrink-0 overflow-hidden transition-all duration-200",_?"w-0 opacity-0":"w-[104px] opacity-100"),children:[a.jsx(ye,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>{var Z;return(Z=We.current)==null?void 0:Z.click()},disabled:I,children:a.jsx(Xw,{className:"h-4 w-4"})}),a.jsx(ye,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>{var Z;return(Z=rt.current)==null?void 0:Z.click()},disabled:I,children:a.jsx(Zc,{className:"h-4 w-4"})}),a.jsx(ye,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",children:a.jsx(tE,{className:"h-4 w-4"})})]}),a.jsx("textarea",{ref:et,placeholder:"Aa",value:y,onChange:Z=>{s_(Z);const ne=Z.target;ne.style.height="auto",ne.style.height=`${Math.min(ne.scrollHeight,240)}px`},rows:1,className:"flex-1 mr-1 min-h-[40px] max-h-[240px] resize-none overflow-y-auto rounded-md border border-input bg-background px-3 py-2 text-sm placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",disabled:I,onFocus:()=>b(!0),onBlur:()=>{y.trim()||b(!1)},onKeyDown:Z=>{var ne;Z.key==="Enter"&&!Z.shiftKey&&(Z.preventDefault(),(ne=Z.target.form)==null||ne.requestSubmit())}}),a.jsx(ye,{type:"submit",size:"icon",disabled:!y.trim()&&q.length===0||I,children:I?a.jsx(ts,{className:"h-5 w-5 animate-spin"}):a.jsx(s0,{className:"h-5 w-5"})})]})]}),(s==null?void 0:s.project)&&a.jsxs(a.Fragment,{children:[a.jsx(BO,{open:U,onOpenChange:K,projectId:s.project.id,projectTitle:s.project.title,onSuccess:()=>{ie()}}),a.jsx(VO,{open:ee,onOpenChange:ce,projectId:s.project.id,projectTitle:s.project.title,onSuccess:()=>{ie(),Ve()}}),a.jsx(GO,{open:Q,onOpenChange:re,projectId:s.project.id,projectTitle:s.project.title,onSuccess:()=>{Ve()},onContactFreelancer:()=>{var Z;(Z=et.current)==null||Z.focus()}}),a.jsx(zO,{open:ve,onOpenChange:Ce,projectId:s.project.id,projectTitle:s.project.title,escrowAmount:se==null?void 0:se.amount,onSuccess:()=>{Ve(),ie()}})]}),ge&&a.jsx(Rb,{storyGroups:ge,initialGroupIndex:0,currentUserId:(p==null?void 0:p.id)||"",onClose:()=>{pe(null),be(null)},onMarkViewed:Z=>{L.from("story_views").upsert({story_id:Z,viewer_id:p==null?void 0:p.id})},onReact:(Z,ne)=>{L.from("story_reactions").insert({story_id:Z,reactor_id:p==null?void 0:p.id,reaction_type:ne})},onReply:(Z,ne)=>{o(ne)}}),(s==null?void 0:s.project)&&p&&a.jsx(HO,{open:le,onOpenChange:oe,dueAmount:He,currency:"BDT",userId:p.id,projectId:s.project.id,onSuccess:()=>{oe(!1),ie(),Ve(),Ae.success("Payment submitted! It will be verified shortly.")}})]}):a.jsx("div",{className:"flex-1 flex items-center justify-center bg-muted/30",children:a.jsxs("div",{className:"text-center text-muted-foreground",children:[a.jsx("p",{className:"text-lg font-medium",children:"Select a conversation"}),a.jsx("p",{className:"text-sm",children:"Choose from your existing conversations"})]})})}function WO({avatarUrl:s,gender:e,name:t}){const{url:r}=Ga(s,"avatar"),n=r||_i(e)||void 0;return a.jsxs(Bs,{className:"h-14 w-14",children:[a.jsx(Vs,{src:n}),a.jsx(Gs,{className:"text-xs",children:sn(t)})]})}function YO({avatar:s,name:e,gender:t,hasUnviewedStory:r,isOnline:n,onClick:i}){const{url:o}=Ga(s,"avatar"),l=e.split(" ")[0],d=l.length>8?l.slice(0,8)+"…":l;return a.jsxs("button",{onClick:i,className:"flex flex-col items-center gap-1 min-w-[60px]",children:[a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"w-[56px] h-[56px] rounded-full p-[2.5px]",style:{background:r?"linear-gradient(135deg, #833AB4, #FD1D1D, #F77737)":"hsl(var(--muted-foreground) / 0.3)"},children:a.jsx("div",{className:"w-full h-full rounded-full bg-background p-[2px]",children:a.jsx("div",{className:"w-full h-full rounded-full overflow-hidden bg-muted",children:o?a.jsx("img",{src:o,alt:e,className:"w-full h-full object-cover",loading:"lazy"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground text-sm font-medium",children:e.charAt(0).toUpperCase()})})})}),n&&a.jsx("span",{className:"absolute bottom-0 right-0 h-3.5 w-3.5 rounded-full bg-green-500 border-2 border-background"})]}),a.jsx("span",{className:"text-[11px] text-muted-foreground truncate max-w-[60px] text-center",children:d})]})}function XO({avatar:s,name:e,gender:t,onClick:r}){const{url:n}=Ga(s,"avatar");return a.jsxs("button",{onClick:r,className:"flex flex-col items-center gap-1 min-w-[60px]",children:[a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"w-[56px] h-[56px] rounded-full p-[2.5px]",style:{background:"hsl(var(--muted))"},children:a.jsx("div",{className:"w-full h-full rounded-full bg-background p-[2px]",children:a.jsx("div",{className:"w-full h-full rounded-full overflow-hidden bg-muted",children:n?a.jsx("img",{src:n,alt:e,className:"w-full h-full object-cover",loading:"lazy"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground text-sm font-medium",children:e.charAt(0).toUpperCase()})})})}),a.jsx("div",{className:"absolute bottom-0 right-0 w-5 h-5 rounded-full bg-primary flex items-center justify-center border-2 border-background",children:a.jsx(Qr,{className:"w-3 h-3 text-primary-foreground"})})]}),a.jsx("span",{className:"text-[11px] text-muted-foreground truncate max-w-[60px] text-center",children:"Your story"})]})}function QO({conversations:s,loading:e,onSelectConversation:t,onClose:r,onlineUsers:n,activeChat:i,messages:o,messagesLoading:l,sending:d,typingUsers:c,onSendMessage:u,onTyping:h,onBackToList:f,onAcceptRequest:m,onDeclineRequest:p,onHireApplicant:x,onRejectApplicant:y,activeBubbleIndex:v,totalBubbles:_,storyGroups:b,onOpenStoryViewer:w,onOpenStoryComposer:T,closing:A}){const{user:S}=$t(),I=hs(),[j,R]=g.useState(""),{data:k}=Wt({queryKey:["my-profile-mini",S==null?void 0:S.id],queryFn:async()=>
736{if(!(S!=null&&S.id))return null;const{data:F}=await L.from("profiles").select("avatar_url, full_name, gender").eq("user_id",S.id).maybeSingle();return F},enabled:!!(S!=null&&S.id),staleTime:5*60*1e3}),D=F=>{if(F.type==="page_message"&&F.page)return{name:F.page.name,avatar:F.page.logo_url,gender:null,userId:null};const P=F.participants.find(N=>N.user_id!==(S==null?void 0:S.id))||F.participants[0];return{name:(P==null?void 0:P.full_name)||F.name||"Chat",avatar:P==null?void 0:P.avatar_url,gender:P==null?void 0:P.gender,userId:(P==null?void 0:P.user_id)||null}},Y=F=>{const P=new Date(F);return el(P)?nr(P,"h:mm a"):tl(P)?"Yesterday":Vx(P)?nr(P,"EEE"):nr(P,"MMM d")},q=g.useMemo(()=>{const F=new Map;return s.forEach(P=>{const N=P.participants.find($=>$.user_id!==(S==null?void 0:S.id));if(!N)return;const O=F.get(N.user_id);(!O||P.last_message_at>O.lastMessageAt)&&F.set(N.user_id,{userId:N.user_id,name:N.full_name||"User",avatar:N.avatar_url,gender:N.gender,lastMessageAt:P.last_message_at})}),Array.from(F.values()).sort((P,N)=>{const O=n.has(P.userId),$=n.has(N.userId);return O!==$?O?-1:1:new Date(N.lastMessageAt).getTime()-new Date(P.lastMessageAt).getTime()})},[s,n,S==null?void 0:S.id]),X=g.useMemo(()=>{if(!j.trim())return s;const F=j.toLowerCase();return s.filter(P=>{const{name:N}=D(P);return N.toLowerCase().includes(F)})},[s,j,S==null?void 0:S.id]);return a.jsxs("div",{className:`fixed inset-x-0 bottom-0 z-[85] h-[88dvh] rounded-t-2xl bg-background flex flex-col duration-300 fill-mode-forwards shadow-2xl ${A?"animate-out slide-out-to-bottom":"animate-in slide-in-from-bottom"}`,children:[(()=>{const B=_-1;let U;return v===-1?U=16+B*56+56/2:U=16+(B-1-v)*56+48/2,a.jsx("div",{className:"absolute -top-[8px] translate-x-1/2 w-0 h-0 border-l-[8px] border-r-[8px] border-b-[8px] border-l-transparent border-r-transparent border-b-background z-[1]",style:{right:`${U}px`}})})(),i?a.jsx(Pb,{conversation:i,messages:o,loading:l,sending:d,typingUsers:c,onlineUsers:n,onSendMessage:u,onTyping:h,onBack:f,onAcceptRequest:m,onDeclineRequest:p,onHireApplicant:x,onRejectApplicant:y}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"px-4 pt-4 pb-2 flex items-center justify-between shrink-0",children:[a.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"messenger"}),a.jsx("button",{onClick:()=>{r(),I("/messenger")},className:"h-9 w-9 flex items-center justify-center rounded-full bg-muted","aria-label":"New message",children:a.jsx(r0,{className:"h-4 w-4 text-foreground"})})]}),a.jsx("div",{className:"px-4 pb-2 shrink-0",children:a.jsxs("div",{className:"relative",children:[a.jsx(Ds,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a.jsx("input",{type:"text",placeholder:"Search",value:j,onChange:F=>R(F.target.value),className:"w-full h-9 pl-9 pr-3 rounded-full bg-muted text-sm text-foreground placeholder:text-muted-foreground outline-none border-none"})]})}),!j&&a.jsx("div",{className:"px-4 py-2 shrink-0",children:a.jsxs("div",{className:"flex gap-3 overflow-x-auto",style:{scrollbarWidth:"none",msOverflowStyle:"none",WebkitOverflowScrolling:"touch"},children:[a.jsx("style",{children:".friends-scroll::-webkit-scrollbar { display: none; }"}),a.jsx(XO,{avatar:(k==null?void 0:k.avatar_url)??null,name:(k==null?void 0:k.full_name)??"You",gender:(k==null?void 0:k.gender)??null,onClick:()=>{const F=b.find(P=>P.userId===(S==null?void 0:S.id));F?w(b.indexOf(F)):T()}}),q.map(F=>{const P=b.find($=>$.userId===F.userId),N=(P==null?void 0:P.hasUnviewed)??!1,O=()=>{if(N){const $=b.findIndex(B=>B.userId===F.userId);$!==-1&&w($)}else{const $=s.find(B=>B.participants.some(U=>U.user_id===F.userId));$&&t($)}};return a.jsx(YO,{avatar:F.avatar,name:F.name,gender:F.gender,hasUnviewedStory:N,isOnline:n.has(F.userId),onClick:O},F.userId)})]})}),a.jsx(jl,{className:"flex-1",children:e?a.jsx("div",{className:"p-4 space-y-4",children:[1,2,3,4,5].map(F=>a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(H,{className:"h-14 w-14 rounded-full"}),a.jsxs("div",{className:"flex-1 space-y-1.5",children:[a.jsx(H,{className:"h-4 w-28"}),a.jsx(H,{className:"h-3 w-40"})]})]},F))}):X.length===0?a.jsxs("div",{className:"p-10 text-center text-muted-foreground text-sm",children:[a.jsx(Tn,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),j?"No results found":"No conversations yet"]}):a.jsx("div",{className:"py-1",children:X.map(F=>{const{name:P,avatar:N,gender:O,userId:$}=D(F),B=$?n.has($):!1;return a.jsxs("button",{onClick:()=>t(F),className:"w-full flex items-center gap-3 px-4 py-2.5 hover:bg-accent/50 active:bg-accent/70 transition-colors text-left",children:[a.jsxs("div",{className:"relative shrink-0",children:[a.jsx(WO,{avatarUrl:N,gender:O,name:P}),B&&a.jsx("span",{className:"absolute bottom-0 right-0 h-3.5 w-3.5 rounded-full bg-green-500 border-2 border-background"})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:`text-base truncate ${F.unread_count>0?"font-bold text-foreground":"font-medium text-foreground"}`,children:P}),a.jsx("span",{className:`text-xs shrink-0 ml-2 ${F.unread_count>0?"text-foreground font-semibold":"text-muted-foreground"}`,children:Y(F.last_message_at)})]}),a.jsx("p",{className:`text-sm truncate ${F.unread_count>0?"text-foreground font-medium":"text-muted-foreground"}`,children:F.last_message_preview||"No messages yet"})]}),F.unread_count>
7360&&a.jsx("span",{className:"min-w-[10px] h-[10px] rounded-full bg-primary shrink-0"})]},F.id)})})})]})]})}function JO({avatarUrl:s,gender:e,name:t}){const{url:r}=Ga(s,"avatar"),n=r||_i(e)||void 0;return a.jsxs(Bs,{className:"h-12 w-12",children:[a.jsx(Vs,{src:n}),a.jsx(Gs,{className:"text-xs",children:sn(t)})]})}function ZO({conversations:s,loading:e,onlineUsers:t,onSelectConversation:r,onClose:n}){const{user:i}=$t(),o=hs(),[l,d]=g.useState(""),c=f=>{if(f.type==="page_message"&&f.page)return{name:f.page.name,avatar:f.page.logo_url,gender:null,userId:null};const m=f.participants.find(p=>p.user_id!==(i==null?void 0:i.id))||f.participants[0];return{name:(m==null?void 0:m.full_name)||f.name||"Chat",avatar:m==null?void 0:m.avatar_url,gender:m==null?void 0:m.gender,userId:(m==null?void 0:m.user_id)||null}},u=f=>{const m=new Date(f);return el(m)?nr(m,"h:mm a"):tl(m)?"Yesterday":Vx(m)?nr(m,"EEE"):nr(m,"MMM d")},h=g.useMemo(()=>{if(!l.trim())return s;const f=l.toLowerCase();return s.filter(m=>{const{name:p}=c(m);return p.toLowerCase().includes(f)})},[s,l,i==null?void 0:i.id]);return a.jsxs("div",{className:"fixed top-14 bottom-0 right-0 z-[95] w-[328px] flex flex-col bg-background border-l border-border shadow-2xl animate-in slide-in-from-right-2 fade-in duration-200 overflow-hidden",children:[a.jsxs("div",{className:"px-4 pt-3 pb-2 flex items-center justify-between shrink-0 border-b border-border",children:[a.jsx("h2",{className:"text-lg font-bold text-foreground",children:"Messenger"}),a.jsx("button",{onClick:()=>{n(),o("/messenger")},className:"h-8 w-8 flex items-center justify-center rounded-full bg-muted hover:bg-accent transition-colors","aria-label":"Open full messenger",children:a.jsx(r0,{className:"h-3.5 w-3.5 text-foreground"})})]}),a.jsx("div",{className:"px-3 py-2 shrink-0",children:a.jsxs("div",{className:"relative",children:[a.jsx(Ds,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),a.jsx("input",{type:"text",placeholder:"Search",value:l,onChange:f=>d(f.target.value),className:"w-full h-8 pl-8 pr-3 rounded-full bg-muted text-sm text-foreground placeholder:text-muted-foreground outline-none border-none"})]})}),a.jsx(jl,{className:"flex-1",children:e?a.jsx("div",{className:"p-3 space-y-3",children:[1,2,3,4,5].map(f=>a.jsxs("div",{className:"flex items-center gap-2.5",children:[a.jsx(H,{className:"h-12 w-12 rounded-full"}),a.jsxs("div",{className:"flex-1 space-y-1",children:[a.jsx(H,{className:"h-3.5 w-24"}),a.jsx(H,{className:"h-3 w-36"})]})]},f))}):h.length===0?a.jsxs("div",{className:"p-8 text-center text-muted-foreground text-sm",children:[a.jsx(Tn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),l?"No results found":"No conversations yet"]}):a.jsx("div",{className:"py-1",children:h.map(f=>{const{name:m,avatar:p,gender:x,userId:y}=c(f),v=y?t.has(y):!1;return a.jsxs("button",{onClick:()=>r(f),className:"w-full flex items-center gap-2.5 px-3 py-2 hover:bg-accent/50 active:bg-accent/70 transition-colors text-left",children:[a.jsxs("div",{className:"relative shrink-0",children:[a.jsx(JO,{avatarUrl:p,gender:x,name:m}),v&&a.jsx("span",{className:"absolute bottom-0 right-0 h-3 w-3 rounded-full bg-green-500 border-2 border-background"})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:`text-sm truncate ${f.unread_count>0?"font-bold text-foreground":"font-medium text-foreground"}`,children:m}),a.jsx("span",{className:`text-[11px] shrink-0 ml-2 ${f.unread_count>0?"text-foreground font-semibold":"text-muted-foreground"}`,children:u(f.last_message_at)})]}),a.jsx("p",{className:`text-xs truncate ${f.unread_count>0?"text-foreground font-medium":"text-muted-foreground"}`,children:f.last_message_preview||"No messages yet"})]}),f.unread_count>0&&a.jsx("span",{className:"min-w-[8px] h-[8px] rounded-full bg-primary shrink-0"})]},f.id)})})})]})}function eM({conversation:s,messages:e,loading:t,sending:r,typingUsers:n,onlineUsers:i,onSendMessage:o,onTyping:l,onClose:d,onMinimize:c,onAcceptRequest:u,onDeclineRequest:h,onHireApplicant:f,onRejectApplicant:m,style:p}){const{user:x}=$t(),y=()=>
736{if(s.type==="page_message"&&s.page)return{name:s.page.name,avatar:s.page.logo_url,gender:null,userId:null};const A=s.participants.find(S=>S.user_id!==(x==null?void 0:x.id))||s.participants[0];return{name:(A==null?void 0:A.full_name)||s.name||"Chat",avatar:(A==null?void 0:A.avatar_url)||null,gender:(A==null?void 0:A.gender)||null,userId:(A==null?void 0:A.user_id)||null}},{name:v,avatar:_,gender:b,userId:w}=y(),T=w?i.has(w):!1;return a.jsxs("div",{className:"fixed bottom-0 z-[90] w-[328px] h-[480px] flex flex-col bg-background border border-border rounded-t-xl shadow-2xl animate-in slide-in-from-bottom-4 fade-in duration-200 overflow-hidden",style:p,children:[a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5 border-b border-border bg-card shrink-0",children:[a.jsxs("div",{className:"relative shrink-0",children:[a.jsx(ah,{name:v,avatarUrl:_,gender:b,className:"h-7 w-7",fallbackClassName:"text-[10px]"}),T&&a.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full bg-green-500 border-2 border-card"})]}),a.jsx("span",{className:"flex-1 text-sm font-semibold text-foreground truncate",children:v}),a.jsx("button",{onClick:c,className:"h-7 w-7 flex items-center justify-center rounded-full hover:bg-accent transition-colors shrink-0","aria-label":"Minimize chat",children:a.jsx(Kw,{className:"h-4 w-4 text-muted-foreground"})}),a.jsx("button",{onClick:d,className:"h-7 w-7 flex items-center justify-center rounded-full hover:bg-accent transition-colors shrink-0","aria-label":"Close chat",children:a.jsx(Fs,{className:"h-4 w-4 text-muted-foreground"})})]}),a.jsx(Pb,{conversation:s,messages:e,loading:t,sending:r,typingUsers:n,onlineUsers:i,onSendMessage:o,onTyping:l,onAcceptRequest:u,onDeclineRequest:h,onHireApplicant:f,onRejectApplicant:m,hideHeader:!0})]})}function tM(s){const e=Da(),{data:t=[],isLoading:r}=Wt({queryKey:["stories",s],enabled:!!s,staleTime:3e4,queryFn:async()=>{const{data:c,error:u}=await L.from("stories").select("*").gt("expires_at",new Date().toISOString()).order("created_at",{ascending:!0});if(u)throw u;if(!c||c.length===0)return[];const h=[...new Set(c.map(k=>k.user_id))],{data:f}=await L.from("profiles").select("user_id, full_name, avatar_url").in("user_id",h),m=new Map((f||[]).map(k=>[k.user_id,{full_name:k.full_name,avatar_url:k.avatar_url}])),p=c.map(k=>k.id),[x,y,v,_]=await Promise.all([L.from("story_views").select("story_id").eq("viewer_id",s).in("story_id",p),L.from("story_reactions").select("story_id").in("story_id",p),L.from("story_replies").select("story_id").in("story_id",p),L.from("story_reactions").select("story_id, reaction_type").eq("reactor_id",s).in("story_id",p)]),b=new Set((x.data||[]).map(k=>k.story_id)),w=new Map;for(const k of y.data||[])w.set(k.story_id,(w.get(k.story_id)||0)+1);const T=new Map;for(const k of v.data||[])T.set(k.story_id,(T.get(k.story_id)||0)+1);const A=new Map;for(const k of _.data||[])A.set(k.story_id,k.reaction_type);const S=new Map,I=c.filter(k=>k.user_id===s).map(k=>k.id);if(I.length>0){const{data:k}=await L.from("story_views").select("story_id").in("story_id",I);if(k)for(const D of k)S.set(D.story_id,(S.get(D.story_id)||0)+1)}const j=new Map;for(const k of c)j.has(k.user_id)||j.set(k.user_id,[]),j.get(k.user_id).push({...k,visibility:k.visibility||"public",view_count:S.get(k.id)||0,reaction_count:w.get(k.id)||0,reply_count:T.get(k.id)||0,user_reaction:A.get(k.id)||null});const R=[];for(const[k,D]of j){const Y=D.some(q=>!b.has(q.id));R.push({userId:k,userProfile:m.get(k)||{full_name:null,avatar_url:null},stories:D,hasUnviewed:Y})}return R.sort((k,D)=>k.userId===s?-1:D.userId===s?1:k.hasUnviewed&&!D.hasUnviewed?-1:!k.hasUnviewed&&D.hasUnviewed?1:0),R}}),n=Kc({mutationFn:async({file:c,caption:u,visibility:h="public",customAudienceUserIds:f})=>{if(!s)throw new Error("Not authenticated");const m=crypto.randomUUID(),p=`${s}/${m}.jpg`,x=await E2(c),{url:y}=await jb.upload("stories",p,x,{contentType:"image/jpeg"}),{error:v}=await L.from("stories").insert({id:m,user_id:s,media_provider:"r2",media_path:y,caption:u||null,visibility:h});if(v)throw v;if(h==="custom"&&f&&f.length>0){const _=f.map(b=>({story_id:m,user_id:b}));await L.from("story_custom_audience").insert(_)}return m},onSuccess:()=>
736{e.invalidateQueries({queryKey:["stories"]}),Ae.success("Story posted!")},onError:c=>{Ae.error(`Failed to post story: ${c.message}`)}}),i=g.useCallback(async c=>{if(s)try{await L.from("story_views").upsert({story_id:c,viewer_id:s},{onConflict:"story_id,viewer_id"})}catch{}},[s]),o=Kc({mutationFn:async c=>{const{error:u}=await L.from("stories").delete().eq("id",c);if(u)throw u},onSuccess:()=>{e.invalidateQueries({queryKey:["stories"]}),Ae.success("Story deleted")}}),l=g.useCallback(async(c,u)=>{s&&(await L.from("story_reactions").insert({story_id:c,reactor_id:s,reaction_type:u}),e.invalidateQueries({queryKey:["stories"]}))},[s,e]),d=g.useCallback(async(c,u,h)=>{if(s){await L.from("story_replies").insert({story_id:c,sender_id:s,message:u});try{const{data:f}=await L.rpc("create_or_get_direct_conversation",{p_other_user_id:h});f&&await L.from("messages").insert({conversation_id:f,sender_id:s,content:u,message_type:"story_reply",story_id:c})}catch(f){console.warn("Failed to deliver story reply as DM:",f)}Ae.success("Reply sent"),e.invalidateQueries({queryKey:["stories"]})}},[s,e]);return{storyGroups:t,isLoading:r,uploadStory:n,markViewed:i,deleteStory:o,reactToStory:l,replyToStory:d}}const sM=k_,rM=R_,Db=g.forwardRef(({className:s,children:e,...t},r)=>a.jsxs(_g,{ref:r,className:C("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm r
736ing-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",s),...t,children:[e,a.jsx(j_,{asChild:!0,children:a.jsx(ri,{className:"h-4 w-4 opacity-50"})})]}));Db.displayName=_g.displayName;const Ob=g.forwardRef(({className:s,...e},t)=>a.jsx(Sg,{ref:t,className:C("flex cursor-default items-center justify-center py-1",s),...e,children:a.jsx(Nw,{className:"h-4 w-4"})}));Ob.displayName=Sg.displayName;const Mb=g.forwardRef(({className:s,...e},t)=>a.jsx(Tg,{ref:t,className:C("flex cursor-default items-center justify-center py-1",s),...e,children:a.jsx(ri,{className:"h-4 w-4"})}));Mb.displayName=Tg.displayName;const Fb=g.forwardRef(({className:s,children:e,position:t="popper",...r},n)=>a.jsx(I_,{children:a.jsxs(wg,{ref:n,className:C("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",s),position:t,...r,children:[a.jsx(Ob,{}),a.jsx(C_,{className:C("p-1",t==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:e}),a.jsx(Mb,{})]})}));Fb.displayName=wg.displayName;const nM=g.forwardRef(({className:s,...e},t)=>a.jsx(Ag,{ref:t,className:C("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...e}));nM.displayName=Ag.displayName;const Zi=g.forwardRef(({className:s,children:e,...t},r)=>a.jsxs(Eg,{ref:r,className:C("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",s),...t,children:[a.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a.jsx(N_,{children:a.jsx(vi,{className:"h-4 w-4"})})}),a.jsx(L_,{children:e})]}));Zi.displayName=Eg.displayName;const iM=g.forwardRef(({className:s,...e},t)=>a.jsx(kg,{ref:t,className:C("-mx-1 my-1 h-px bg-muted",s),...e}));iM.displayName=kg.displayName;var Ul="Checkbox",[aM]=cn(Ul),[oM,ch]=aM(Ul);function lM(s){const{__scopeCheckbox:e,checked:t,children:r,defaultChecked:n,disabled:i,form:o,name:l,onCheckedChange:d,required:c,value:u="on",internal_do_not_use_render:h}=s,[f,m]=Oa({prop:t,defaultProp:n??!1,onChange:d,caller:Ul}),[p,x]=g.useState(null),[y,v]=g.useState(null),_=g.useRef(!1),b=p?!!o||!!p.closest("form"):!0,w={checked:f,disabled:i,setChecked:m,control:p,setControl:x,name:l,form:o,value:u,hasConsumerStoppedPropagationRef:_,required:c,defaultChecked:en(n)?!1:n,isFormControl:b,bubbleInput:y,setBubbleInput:v};return a.jsx(oM,{scope:e,...w,children:cM(h)?h(w):r})}var $b="CheckboxTrigger",Ub=g.forwardRef(({__scopeCheckbox:s,onKeyDown:e,onClick:t,...r},n)=>{const{control:i,value:o,disabled:l,checked:d,required:c,setControl:u,setChecked:h,hasConsumerStoppedPropagationRef:f,isFormControl:m,bubbleInput:p}=ch($b,s),x=qt(n,u),y=g.useRef(d);return g.useEffect(()=>{const v=i==null?void 0:i.form;if(v){const _=()=>h(y.current);return v.addEventListener("reset",_),()=>v.removeEventListener("reset",_)}},[i,h]),a.jsx(bt.button,{type:"button",role:"checkbox","aria-checked":en(d)?"mixed":d,"aria-required":c,"data-state":qb(d),"data-disabled":l?"":void 0,disabled:l,value:o,...r,ref:x,onKeyDown:Et(e,v=>{v.key==="Enter"&&v.preventDefault()}),onClick:Et(t,v=>{h(_=>en(_)?!0:!_),p&&m&&(f.current=v.isPropagationStopped(),f.current||v.stopPropagation())})})});Ub.displayName=$b;var dh=g.forwardRef((s,e)=>{const{__scopeCheckbox:t,name:r,checked:n,defaultChecked:i,required:o,disabled:l,value:d,onCheckedChange:c,form:u,...h}=s;return a.jsx(lM,{__scopeCheckbox:t,checked:n,defaultChecked:i,disabled:l,required:o,onCheckedChange:c,name:r,form:u,value:d,internal_do_not_use_render:({isFormControl:f})=>a.jsxs(a.Fragment,{children:[a.jsx(Ub,{...h,ref:e,__scopeCheckbox:t}),f&&a.jsx(zb,{__scopeCheckbox:t})]})})});dh.displayName=Ul;var Bb="CheckboxIndicator",Vb=g.forwardRef((s,e)=>{const{__scopeCheckbox:t,forceMount:r,...n}=s,i=ch(Bb,t);return a.jsx(Ln,{present:r||en(i.checked)||i.checked===!0,children:a.jsx(bt.span,{"data-state":qb(i.checked),"data-disabled":i.disabled?"":void 0,...n,ref:e,style:{pointerEvents:"none",...s.style}})})});Vb.displayName=Bb;var Gb="CheckboxBubbleInput",zb=g.forwardRef(({__scopeCheckbox:s,...e},t)=>{const{control:r,hasConsumerStoppedPropagationRef:n,checked:i,defaultChecked:o,required:l,disabled:d,name:c,value:u,form:h,bubbleInput:f,setBubbleInput:m}=ch(Gb,s),p=qt(t,m),x=su(i),y=ru(r);g.useEffect(()=>{const _=f;if(!_)return;const b=window.HTMLInputElement.prototype,T=Object.getOwnPropertyDescriptor(b,"checked").set,A=!n.current;if(x!==i&&T){const S=new Event("click",{bubbles:A});_.indeterminate=en(i),T.call(_,en(i)?!1:i),_.dispatchEvent(S)}},[f,x,i,n]);const v=g.useRef(en(i)?!1:i);return a.jsx(bt.input,{type:"checkbox","aria-hidden":!0,defaultChecked:o??v.current,required:l,disabled:d,name:c,value:u,form:h,...e,tabIndex:-1,ref:p,style:{...e.style,...y,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});zb.displayName=Gb;function cM(s){return typeof s=="function"}function en(s){return s==="indeterminate"}
736function qb(s){return en(s)?"indeterminate":s?"checked":"unchecked"}const uh=g.forwardRef(({className:s,...e},t)=>a.jsx(dh,{ref:t,className:C("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",s),...e,children:a.jsx(Vb,{className:C("flex items-center justify-center text-current"),children:a.jsx(vi,{className:"h-4 w-4"})})}));uh.displayName=dh.displayName;function dM({value:s,onChange:e}){const{user:t}=$t(),[r,n]=g.useState(!1),[i,o]=g.useState([]),[l,d]=g.useState(new Set),[c,u]=g.useState(""),[h,f]=g.useState(!1),m=_=>{if(_==="custom"){n(!0);return}e(_)};g.useEffect(()=>{!r||!t||(f(!0),Promise.all([L.from("user_connections").select("addressee_id").eq("requester_id",t.id).eq("status","accepted"),L.from("user_connections").select("requester_id").eq("addressee_id",t.id).eq("status","accepted")]).then(async([{data:_},{data:b}])=>{const w=[...(_||[]).map(S=>S.addressee_id),...(b||[]).map(S=>S.requester_id)],T=[...new Set(w)];if(T.length===0){o([]),f(!1);return}const{data:A}=await L.from("profiles").select("user_id, full_name, avatar_url").in("user_id",T);o((A||[]).map(S=>({userId:S.user_id,fullName:S.full_name||"User",avatarUrl:S.avatar_url}))),f(!1)}))},[r,t]);const p=i.filter(_=>_.fullName.toLowerCase().includes(c.toLowerCase())),x=_=>{d(b=>{const w=new Set(b);return w.has(_)?w.delete(_):w.add(_),w})},y=()=>{e("custom",Array.from(l)),n(!1)},v={public:a.jsx(ra,{className:"w-4 h-4"}),connections:a.jsx(Ss,{className:"w-4 h-4"}),private:a.jsx($o,{className:"w-4 h-4"}),custom:a.jsx(Uo,{className:"w-4 h-4"})};return a.jsxs(a.Fragment,{children:[a.jsxs(sM,{value:s,onValueChange:m,children:[a.jsx(Db,{className:"w-full",children:a.jsxs("div",{className:"flex items-center gap-2",children:[v[s],a.jsx(rM,{})]})}),a.jsxs(Fb,{children:[a.jsx(Zi,{value:"public",children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ra,{className:"w-4 h-4"})," Public"]})}),a.jsx(Zi,{value:"connections",children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ss,{className:"w-4 h-4"})," Connections"]})}),a.jsx(Zi,{value:"private",children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx($o,{className:"w-4 h-4"})," Only Me"]})}),a.jsx(Zi,{value:"custom",children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Uo,{className:"w-4 h-4"})," Custom"]})})]})]}),a.jsx(Dl,{open:r,onOpenChange:n,children:a.jsxs(Ol,{className:"max-h-[80vh]",children:[a.jsx(Ml,{children:a.jsx(Fl,{children:"Select Audience"})}),a.jsxs("div",{className:"px-4 pb-4 space-y-3",children:[a.jsx(rr,{placeholder:"Search connections...",value:c,onChange:_=>u(_.target.value)}),a.jsx("div",{className:"max-h-[40vh] overflow-y-auto space-y-2",children:h?a.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading..."}):p.length===0?a.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No connections found"}):p.map(_=>a.jsxs("label",{className:"flex items-center gap-3 py-2 px-2 rounded hover:bg-muted cursor-pointer",children:[a.jsx(uh,{checked:l.has(_.userId),onCheckedChange:()=>x(_.userId)}),a.jsx("div",{className:"w-8 h-8 rounded-full overflow-hidden bg-muted flex-shrink-0",children:_.avatarUrl?a.jsx("img",{src:_.avatarUrl,alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-xs",children:_.fullName.charAt(0).toUpperCase()})}),a.jsx("span",{className:"text-sm",children:_.fullName})]},_.userId))}),a.jsxs(ye,{onClick:y,disabled:l.size===0,className:"w-full",children:["Confirm (",l.size," selected)"]})]})]})})]})}function uM({open:s,onOpenChange:e,onUpload:t}){const[r,n]=g.useState(null),[i,o]=g.useState(null),[l,d]=g.useState(""),[c,u]=g.useState(!1),[h,f]=g.useState("public"),[m,p]=g.useState([]),x=g.useRef(null),y=w=>{var S;const T=(S=w.target.files)==null?void 0:S[0];if(!T)return;n(T);const A=URL.createObjectURL(T);o(A)},v=async()=>
736{if(r){u(!0);try{await t(r,l||void 0,h,m),n(null),o(null),d(""),f("public"),p([]),e(!1)}finally{u(!1)}}},_=w=>{w||(n(null),o(null),d(""),f("public"),p([])),e(w)},b=(w,T)=>{f(w),T&&p(T)};return a.jsx(Dl,{open:s,onOpenChange:_,children:a.jsxs(Ol,{className:"max-h-[85vh]",children:[a.jsx(Ml,{children:a.jsx(Fl,{children:"Create Story"})}),a.jsxs("div",{className:"px-4 pb-6 space-y-4",children:[i?a.jsx("div",{className:"relative w-full aspect-[9/16] max-h-[50vh] rounded-xl overflow-hidden bg-black flex items-center justify-center",children:a.jsx("img",{src:i,alt:"Story preview",className:"max-w-full max-h-full object-contain"})}):a.jsxs("button",{onClick:()=>{var w;return(w=x.current)==null?void 0:w.click()},className:"w-full aspect-[9/16] max-h-[50vh] rounded-xl border-2 border-dashed border-muted-foreground/30 flex flex-col items-center justify-center gap-3 hover:border-primary/50 transition-colors",children:[a.jsx(zw,{className:"w-10 h-10 text-muted-foreground"}),a.jsx("span",{className:"text-sm text-muted-foreground",children:"Tap to select a photo"})]}),a.jsx("input",{ref:x,type:"file",accept:"image/*",className:"hidden",onChange:y}),i&&a.jsxs(a.Fragment,{children:[a.jsx(rr,{placeholder:"Add a caption (optional)",value:l,onChange:w=>d(w.target.value),maxLength:200}),a.jsx(dM,{value:h,onChange:b}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(ye,{variant:"outline",className:"flex-1",onClick:()=>{n(null),o(null)},children:"Change Photo"}),a.jsx(ye,{className:"flex-1",onClick:v,disabled:c,children:c?a.jsxs(a.Fragment,{children:[a.jsx(ts,{className:"w-4 h-4 mr-2 animate-spin"}),"Posting..."]}):"Post Story"})]})]})]})]})})}const hM=3,Ap=2;function fM(){const{user:s}=$t(),e=dn(),t=br(),{totalUnread:r}=e2(),{data:n}=Wt({queryKey:["my-profile-bubble",s==null?void 0:s.id],queryFn:async()=>{const{data:pe}=await L.from("profiles").select("avatar_url, full_name, gender").eq("user_id",s.id).maybeSingle();return pe},enabled:!!(s!=null&&s.id),staleTime:5*60*1e3}),[i,o]=g.useState([]),[l,d]=g.useState(null),[c,u]=g.useState(null),[h,f]=g.useState(!1),[m,p]=g.useState(!1),[x,y]=g.useState([]),[v,_]=g.useState([]),[b,w]=g.useState(!1),[T,A]=g.useState(null),{storyGroups:S,markViewed:I,reactToStory:j,replyToStory:R,uploadStory:k}=tM(s==null?void 0:s.id),{conversations:D,activeConversation:Y,messages:q,loading:X,messagesLoading:F,sending:P,typingUsers:N,onlineUsers:O,selectConversation:$,sendMessage:B,sendTypingIndicator:U,acceptMessageRequest:K,declineMessageRequest:ee,hireApplicant:ce,rejectApplicant:Q}=h2(),re=!s||t.pathname.startsWith("/messenger")||t.pathname.startsWith("/reels"),ve=l==="list",Ce=g.useCallback(()=>{if(l==="list"&&c){u(null);return}if(l==="list"){d(null);return}d("list")},[l,c]),Pe=g.useCallback(pe=>{o(ge=>{if(ge.find(ie=>ie.id===pe.id))return ge;const be=[...ge,pe];return be.length>hM&&be.shift(),be}),$(pe),u(pe)},[$]),Me=g.useCallback(pe=>{if((c==null?void 0:c.id)===pe){d(null),u(null);return}const ge=i.find(be=>be.id===pe)||D.find(be=>be.id===pe);ge&&($(ge),u(ge))},[c,i,D,$]),le=g.useCallback(pe=>{o(ge=>ge.filter(be=>be.id!==pe)),(c==null?void 0:c.id)===pe&&u(null)},[c]),oe=g.useCallback(()=>{f(!0),u(null),setTimeout(()=>{d(null),f(!1)},300)},[]),He=g.useCallback(()=>{u(null)},[]),ct=g.useCallback(pe=>{d(null),u(null),A(pe)},[]),se=g.useCallback(()=>{d(null),u(null),w(!0)},[]),Be=g.useCallback(()=>{p(pe=>!pe)},[]),Ke=g.useCallback(pe=>{if(p(!1),x.find(ge=>ge.id===pe.id)){$(pe);return}_(ge=>ge.filter(be=>be.id!==pe.id)),y(ge=>{const be=[...ge,pe];return be.length>Ap&&be.shift(),be}),$(pe)},[x,$]),Ee=g.useCallback(pe=>{y(ge=>ge.filter(be=>be.id!==pe)),_(ge=>ge.filter(be=>be.id!==pe))},[]),fe=g.useCallback(pe=>{y(ge=>ge.filter(be=>be.id!==pe.id)),_(ge=>ge.find(be=>be.id===pe.id)?ge:[...ge,pe])},[]),et=g.useCallback(pe=>{_(ge=>ge.filter(be=>be.id!==pe.id)),y(ge=>{if(ge.find(ie=>ie.id===pe.id))return ge;const be=[...ge,pe];return be.length>Ap&&be.shift(),be}),$(pe)},[$]),rt=pe=>D.find(ge=>ge.id===pe.id)||pe,We=pe=>{if(pe.type==="page_message"&&pe.page)return{name:pe.page.name,avatar:pe.page.logo_url,gender:null};const ge=pe.participants.find(be=>be.user_id!==(s==null?void 0:s.id))||pe.participants[0];return{name:(ge==null?void 0:ge.full_name)||pe.name||"Chat",avatar:(ge==null?void 0:ge.avatar_url)||null,gender:(ge==null?void 0:ge.gender)||null}};if(re)return null;const dt=a.jsxs("button",{onClick:e?Ce:Be,className:"relative flex items-center justify-center h-14 w-14 roun
736ded-full bg-primary text-primary-foreground shadow-lg active:scale-95 transition-transform overflow-hidden","aria-label":e?ve?"Close messages":"Open messages":m?"Close messages":"Open messages",children:[a.jsx(Tn,{className:"h-6 w-6"}),r>0&&a.jsx("span",{className:"absolute -top-1 -right-1 min-w-[20px] h-5 flex items-center justify-center rounded-full bg-destructive text-destructive-foreground text-xs font-bold px-1",children:r>99?"99+":r})]});return e?a.jsxs(a.Fragment,{children:[(ve||h)&&a.jsx("div",{className:C("fixed inset-0 z-[80] bg-black/50 duration-200",h?"animate-out fade-out fill-mode-forwards":"animate-in fade-in"),onClick:h?void 0:oe}),ve||h?a.jsxs("div",{className:"fixed top-4 right-4 z-[90] flex flex-row items-center gap-2",children:[dt,i.map(pe=>{const ge=rt(pe);return a.jsx(w2,{conversation:ge,isActive:(c==null?void 0:c.id)===pe.id,onClick:()=>Me(pe.id),onRemove:()=>le(pe.id)},pe.id)})]}):a.jsx("div",{className:"fixed bottom-6 right-4 z-[90]",children:dt}),(ve||h)&&a.jsx(QO,{closing:h,conversations:D,loading:X,onSelectConversation:Pe,onClose:oe,onlineUsers:O,activeChat:c,messages:q,messagesLoading:F,sending:P,typingUsers:N,onSendMessage:B,onTyping:U,onBackToList:He,onAcceptRequest:K,onDeclineRequest:ee,onHireApplicant:ce,onRejectApplicant:Q,activeBubbleIndex:c?i.findIndex(pe=>pe.id===c.id):-1,totalBubbles:i.length+1,storyGroups:S,onOpenStoryViewer:ct,onOpenStoryComposer:se}),T!==null&&(s==null?void 0:s.id)&&a.jsx(Rb,{storyGroups:S,initialGroupIndex:T,currentUserId:s.id,onClose:()=>A(null),onMarkViewed:I,onReact:j,onReply:R}),a.jsx(uM,{open:b,onOpenChange:w,onUpload:async(pe,ge,be,ie)=>{await k.mutateAsync({file:pe,caption:ge,visibility:be,customAudienceUserIds:ie})}})]}):a.jsxs(a.Fragment,{children:[v.map((pe,ge)=>{const be=D.find(At=>At.id===pe.id)||pe,{name:ie,avatar:Qe,gender:Ve}=We(be),It=88+ge*60;return a.jsx("button",{onClick:()=>et(be),className:"fixed right-6 z-[100] h-12 w-12 rounded-full shadow-lg active:scale-95 transition-transform border-2 border-background hover:scale-105",style:{bottom:`${It}px`},"aria-label":`Open chat with ${ie}`,children:a.jsx(ah,{name:ie,avatarUrl:Qe,gender:Ve,className:"h-full w-full",fallbackClassName:"text-xs"})},pe.id)}),a.jsx("div",{className:"fixed bottom-6 right-6 z-[100]",children:dt}),m&&a.jsx(ZO,{conversations:D,loading:X,onlineUsers:O,onSelectConversation:Ke,onClose:()=>p(!1)}),x.map((pe,ge)=>{const be=D.find(Qe=>Qe.id===pe.id)||pe,ie=90+ge*340;return a.jsx(mM,{conversation:be,rightOffset:ie,selectConversation:$,activeConversation:Y,messages:q,messagesLoading:F,sending:P,typingUsers:N,onlineUsers:O,sendMessage:B,sendTypingIndicator:U,onClose:()=>Ee(pe.id),onMinimize:()=>fe(be),acceptMessageRequest:K,declineMessageRequest:ee,hireApplicant:ce,rejectApplicant:Q},pe.id)})]})}function mM({conversation:s,rightOffset:e,selectConversation:t,activeConversation:r,messages:n,messagesLoading:i,sending:o,typingUsers:l,onlineUsers:d,sendMessage:c,sendTypingIndicator:u,onClose:h,onMinimize:f,acceptMessageRequest:m,declineMessageRequest:p,hireApplicant:x,rejectApplicant:y}){const v=(r==null?void 0:r.id)===s.id,_=v?n:[],b=g.useCallback(()=>{v||t(s)},[v,t,s]);return a.jsx("div",{onMouseDown:b,onFocus:b,children:a.jsx(eM,{conversation:s,messages:_,loading:v?i:!0,sending:o,typingUsers:l,onlineUsers:d,onSendMessage:c,onTyping:u,onClose:h,onMinimize:f,onAcceptRequest:m,onDeclineRequest:p,onHireApplicant:x,onRejectApplicant:y,style:{right:`${e}px`}})})}function pM(s={}){const{immediate:e=!1,onNeedRefresh:t,onOfflineReady:r,onRegistered:n,onRegisteredSW:i,onRegisterError:o}=s;let l,d,c;const u=async(f=!0)=>{await d,c==null||c()};async function h(){if("serviceWorker"in navigator){if(l=await M(async()=>{const{Workbox:f}=await import("./workbox-window.prod.es5-vqzQaGvo.js");return{Workbox:f}},[]).then(({Workbox:f})=>new f("/sw.js",{scope:"/",type:"classic"})).catch(f=>{o==null||o(f)}),!l)return;c=()=>{l==null||l.messageSkipWaiting()};{let f=!1;const m=()=>{f=!0,l==null||l.addEventListener("controlling",p=>{p.isUpdate&&window.location.reload()}),t==null||t()};l.addEventListener("installed",p=>{typeof p.isUpdate>"u"?typeof p.isExternal<"u"&&p.isExternal?m():!f&&(r==null||r()):p.isUpdate||r==null||r()}),l.addEventListener("waiting",m)}l.register({immediate:e}).then(f=>{i?i("/sw.js",f):n==null||n(f)}).catch(f=>{o==null||o(f)})}}return d=h(),u}function gM(s={}){const{immediate:e=!0,onNeedRefresh:t,onOfflineReady:r,onRegistered:n,onRegisteredSW:i,onRegisterError:o}=s,[l,d]=g.useState(!1),[c,u]=g.useState(!1),[h]=g.useState(()=>pM({immediate:e,onOfflineReady(){u(!0),r==null||r()},onNeedRefresh(){d(!0),t==null||t()},onRegistered:n,onRegisteredSW:i,onRegisterError:o}));return{needRefresh:[l,d],offlineReady:[c,u],updateServiceWorker:h}}function xM(){const[s,e]=g.useState(()=>sessionStorage.getItem("pwa-update-dismissed")==="true"),{needRefresh:[t,r],offlineReady:[n],updateServiceWorker:i}
736=gM({onRegisteredSW(d,c){},onRegisterError(d){console.error("SW registration error:",d)}}),o=g.useCallback(async()=>{sessionStorage.removeItem("pwa-update-dismissed"),await i(!0)},[i]),l=g.useCallback(()=>{e(!0),sessionStorage.setItem("pwa-update-dismissed","true"),r(!1)},[r]);return g.useEffect(()=>{},[t,s]),{needRefresh:t&&!s,offlineReady:n,updateServiceWorker:o,dismissUpdate:l}}function yM(){const{needRefresh:s,offlineReady:e,updateServiceWorker:t,dismissUpdate:r}=xM(),[n,i]=g.useState(!1),[o,l]=g.useState(!1);g.useEffect(()=>{if(s){const c=setTimeout(()=>{i(!0)},3e3);return()=>clearTimeout(c)}else i(!1)},[s]),g.useEffect(()=>{e&&console.log("App is ready for offline use")},[e]);const d=async()=>{l(!0);try{await t()}catch(c){console.error("Failed to update:",c),l(!1)}};return n?a.jsx("div",{className:"fixed bottom-4 right-4 z-[100] animate-in slide-in-from-bottom-4 fade-in duration-300",children:a.jsxs("div",{className:"flex items-center gap-3 rounded-lg border bg-background p-4 shadow-lg max-w-sm",children:[a.jsx("div",{className:"flex-shrink-0",children:a.jsx(ha,{className:"h-5 w-5 text-primary"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-medium text-foreground",children:"New version available"}),a.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Refresh to get the latest features"})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(ye,{size:"sm",onClick:d,disabled:o,className:"h-8",children:o?a.jsx(ha,{className:"h-4 w-4 animate-spin"}):"Update"}),a.jsx(ye,{size:"sm",variant:"ghost",onClick:r,className:"h-8 w-8 p-0","aria-label":"Dismiss",children:a.jsx(Fs,{className:"h-4 w-4"})})]})]})}):null}function Hb(){const[s,e]=g.useState(typeof navigator<"u"?navigator.onLine:!0),[t,r]=g.useState(!1);return g.useEffect(()=>{const n=()=>{e(!0),r(!0),setTimeout(()=>r(!1),5e3)},i=()=>{e(!1),r(!1)};return window.addEventListener("online",n),window.addEventListener("offline",i),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",i)}},[]),{isOnline:s,wasOffline:t}}let kp=!1;function Vc(s){return Promise.all(s.map(e=>e().catch(()=>{})))}function vM(){const{user:s,loading:e}=$t(),t=g.useRef(!1);g.useEffect(()=>{if(e||!s||kp||t.current)return;t.current=!0,kp=!0;const r=setTimeout(async()=>{await Vc([()=>M(()=>import("./Dashboard-BNaOI6f7.js"),__vite__mapDeps([67,1,2,3,68,48,69,18,16,17,20,21,22,23,24,25,26,27,11,12,28,70,29,71,72,73,39,74,40,13,43,31,32,45,42,46,57,75,76,77,78,5,6,7,8,50,58,47,51,52,53,79,41,35,80,59])),()=>M(()=>import("./SocialFeed-ZU-nwGdt.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59])),()=>M(()=>import("./MobileMenu-BXWOBUOQ.js"),__vite__mapDeps([155,1,2,3,79,14,42,46,59])),()=>M(()=>import("./MyNetwork-BteNVmKD.js"),__vite__mapDeps([81,1,2,3,23,82,33,29,56,83,55,48,79,84,85,59])),()=>M(()=>import("./Courses-G4zYTDmd.js"),__vite__mapDeps([86,1,23,3,87,58,88,89,90,47,91,92,26,93,94,46,95,52,10,96,97,2,98,99,100,12,101,102,8,103,104,105,17,106,107,108,62,14,109,28,110,21,111,112,113,27,114,65,115,116,32,117,118,119,63,120,13,121,122,123,124,125,126,29,64,127,128,75,129,130,11,131,132,133,134,135,136,137,138,139,45,140,77,30,141,72,42,142,143,37,144,145,43,31,146,22,53,66,85,55,147,148,149,150,151,152,153,154,25,59])),()=>M(()=>import("./Profile-C3xP_qzj.js"),__vite__mapDeps([160,1,161,162,163,164,3,59,2,165,83,58,76,16,17,68,166,150,149,96,97,98,117,137,63,82,55,85,15,18,19,20,21,22,23,24,25,26,27,11,12,28,8,29,30,31,32,33,34,35,9,36,37,38,39,40,41,42,43,13,44,45,46,153,84,167,101,127,77,47,168,169,126,66,144,116]))]);const n=setTimeout(async()=>{await Vc([()=>M(()=>import("./Messenger-yqI0Jz-Q.js"),__vite__mapDeps([170,1,3,2,59])),()=>M(()=>import("./AppliedJobs-CWxbHjgD.js"),__vite__mapDeps([171,1,23,3,16,17,70,48,2,28,12,22,79,73,11,137,147,100,105,59])),()=>M(()=>import("./JobDetail-DfEO-WCi.js"),__vite__mapDeps([172,1,35,2,3,69,18,16,17,20,21,22,23,24,25,26,27,11,12,28,70,29,71,72,73,39,74,40,13,43,31,32,45,42,46,80,59])),()=>M(()=>import("./BillingSummary-DbSLbKy3.js"),__vite__mapDeps([173,1,2,3,157,93,14,13,58,12,174,47,25,17,22,107,92,175,167,59,74])),()=>M(()=>import("./PaymentSettings-B6J7Pd8C.js"),__vite__mapDeps([176,1,74,174,12,3,59,2])),()=>M(()=>import("./Invoices-JHXpEZ1s.js"),__vite__mapDeps([177,1,157,74,178,151,14,3,59,2])),()=>M(()=>import("./Transactions-tvOqtdNG.js"),__vite__mapDeps([179,1,157,23,3,74,178,151,125,59,2])),()=>M(()=>import("./BrowseProjects-YzFHJteO.js"),__vite__mapDeps([180,1,34,35,2,3,9,36,28,37,38,11,12,4,5,6,7,8,10,13,14,23,94,59])),()=>M(()=>import("./MyProjects-CFOeczPy.js"),__vite__mapDeps([181,1,2,3,23,58,14,12,59])),()=>M(()=>import("./MyCourses-FzknNj7L.js"),__vite__mapDeps([182,1,87,58,3,151,152,2,59])),()=>M(()=>import("./SearchResults-DhxgGN33.js"),__vite__mapDeps([183,1,2,3,23,11,83,184,73,28,12,59]))]);const i=setTimeout(()=>{Vc([()=>M(()=>import("./AccountSettings-Qem27ryN.js"),__vite__mapDeps([185,1,186,25,3,17,66,101,47,12,59,2])),()=>M(()=>import("./SecuritySettings-sNpBDMJy.js"),__vite__mapDeps([187,1,2,3,59])),()=>M(()=>import("./PipelineOverview-qFScsTqe.js"),__vite__mapDeps([188,1,2,3,137,147,59])),()=>M(()=>import("./HiddenJobs-DAelIQT8.js"),__vite__mapDeps([189,1,2,3,11,28,12,59])),()=>M(()=>import("./BlockedUsers-DK3WQPjk.js"),__vite__mapDeps([190,1,2,3,26,59])),()=>M(()=>import("./ActivityLog-DwIrHkUf.js"),__vite__mapDeps([191,1,16,3,17,2,122,130,46,85,55,37,63,10,21,22,5,6,7,8,115,12,192,193,59])),()=>M(()=>
736import("./AccountDeletion-Bnh71sDD.js"),__vite__mapDeps([194,1,2,3,22,59])),()=>M(()=>import("./RequestVerification-B3z2ZAnD.js"),__vite__mapDeps([195,1,3,59,2])),()=>M(()=>import("./AvailableTests-wAAUOx7k.js"),__vite__mapDeps([196,1,184,73,11,28,12,2,3,105,59])),()=>M(()=>import("./PersonalityGameLanding-C-NmgL_d.js"),__vite__mapDeps([197,1,2,3,175,117,128,47,43,148,59])),()=>M(()=>import("./PersonalityResults-BWSnxO2v.js"),__vite__mapDeps([198,1,58,3,2,175,47,43,126,59])),()=>M(()=>import("./TestSubmission-CC2WddVq.js"),__vite__mapDeps([199,1,58,3,157,2,6,7,175,47,12,59])),()=>M(()=>import("./AptitudeTests-BE2ljUNm.js"),__vite__mapDeps([158,1,16,3,17,2,12,22,59])),()=>M(()=>import("./CreateAptitudeTest-Bp_3yJSe.js"),__vite__mapDeps([200,1,2,3,23,201,149,66,64,118,22,142,138,59])),()=>M(()=>import("./JobAnalytics-C-VyCni3.js"),__vite__mapDeps([156,1,157,2,3,43,59,90])),()=>M(()=>import("./LearningCenter-Cg9e6b86.js"),__vite__mapDeps([159,1,147,43,126,3,59,2])),()=>M(()=>import("./PipelineJobs-DF4i2Uc_.js"),__vite__mapDeps([202,1,2,3,78,5,6,7,8,12,11,59])),()=>M(()=>import("./ActivityLog-DveGrEyN.js"),__vite__mapDeps([203,1,193,3,59,2])),()=>M(()=>import("./BoostCampaigns-i8N2GdFk.js"),__vite__mapDeps([204,1,23,3,41,58,42,135,28,2,65,116,59])),()=>M(()=>import("./CreateBoost-CS49hnXy.js"),__vite__mapDeps([205,1,25,3,17,83,41,157,2,175,148,42,28,143,12,43,116,47,65,59])),()=>M(()=>import("./MyReports-DrqQKDat.js"),__vite__mapDeps([206,1,2,3,59])),()=>M(()=>import("./ReportDetail-BvRc1Wwg.js"),__vite__mapDeps([207,1,208,149,2,3,59])),()=>M(()=>import("./CourseDetail-Cq7kP4T7.js"),__vite__mapDeps([209,1,210,152,58,3,211,212,213,2,129,151,59])),()=>M(()=>import("./CourseWatch-B45U_m6R.js"),__vite__mapDeps([214,1,210,23,3,58,211,215,66,113,111,88,38,216,2,212,213,151,75,8,59])),()=>M(()=>import("./PostDetail-D_w8BcD9.js"),__vite__mapDeps([217,1,19,20,16,3,17,2,21,22,23,24,25,26,27,11,12,28,8,29,33,31,32,59])),()=>M(()=>import("./ProjectDetail-82L50UxW.js"),__vite__mapDeps([218,1,35,2,3,9,36,28,37,38,11,12,59])),()=>M(()=>import("./UserActivity-DPYRPbJb.js"),__vite__mapDeps([219,1,15,16,3,17,18,19,20,2,21,22,23,24,25,26,27,11,12,28,8,29,30,31,32,33,34,35,9,36,37,38,39,40,41,42,43,13,44,45,46,48,59])),()=>M(()=>import("./PublicProfile-7EclJQr1.js"),__vite__mapDeps([220,1,2,3,165,83,58,76,16,17,68,166,150,149,96,97,98,117,137,63,82,55,85,15,18,19,20,21,22,23,24,25,26,27,11,12,28,8,29,30,31,32,33,34,35,9,36,37,38,39,40,41,42,43,13,44,45,46,153,84,167,101,127,77,47,59,168,169,126,66,144,116])),()=>M(()=>import("./ProfileDispatcher-C7tQgw2z.js"),__vite__mapDeps([221,1,2,3,160,161,162,163,164,59,165,83,58,76,16,17,68,166,150,149,96,97,98,117,137,63,82,55,85,15,18,19,20,21,22,23,24,25,26,27,11,12,28,8,29,30,31,32,33,34,35,9,36,37,38,39,40,41,42,43,13,44,45,46,153,84,167,101,127,77,47,168,169,126,66,144,116,220])),()=>M(()=>import("./EnableHRAccess-BxYQCePu.js"),__vite__mapDeps([222,1,2,3,59])),()=>M(()=>import("./Applicants-B9CeaZag.js"),__vite__mapDeps([223,1,2,3,161,169,11,58,12,43,142,23,55,109,115,140,148,77,59])),()=>M(()=>import("./CandidateProfile-Dodty7S4.js"),__vite__mapDeps([224,1,163,161,162,168,169,164,3,59,2,77,11,127,12])),()=>M(()=>import("./AdminOverview-1lE2SYer.js"),__vite__mapDeps([225,1,226,157,132,59,3,144,2])),()=>M(()=>import("./AdminUsers-26t8tN7y.js"),__vite__mapDeps([227,1,226,157,16,3,17,26,13,21,22,59,2])),()=>M(()=>import("./AdminJobs-4fmOvpmI.js"),__vite__mapDeps([228,1,2,3,226,5,6,7,8,157,229,63,59,73,11,28,12,39,51,52,53,13,146,22])),()=>M(()=>import("./AdminApplications-DhOk0KlE.js"),__vite__mapDeps([230,1,226,157,3,59,2])),()=>M(()=>import("./CourseManagement-BuY28AYE.js"),__vite__mapDeps([231,1,226,157,16,3,17,232,66,64,147,22,2,28,21,59])),()=>M(()=>import("./ExpertDashboard-DdMDTies.js"),__vite__mapDeps([233,1,226,2,3,59])),()=>M(()=>import("./TrainerDashboard-BkXx-MR-.js"),__vite__mapDeps([234,1,28,3,59,2])),()=>M(()=>import("./TrainerCourses-CzYGizht.js"),__vite__mapDeps([235,1,140,12,3,59,2])),()=>M(()=>import("./TrainerEarnings-DmomXfzX.js"),__vite__mapDeps([236,1,157,93,28,13,3,59,2]))])},1e3);return()=>clearTimeout(i)},1e3);return()=>clearTimeout(n)},2e3);return()=>clearTimeout(r)},[s,e])}const Gc="Gradzen - Find Your Dream Job or Hire Top Talent",zc="Gradzen is your professional job marketplace. Connect with top employers, discover career opportunities, and hire exceptional talent.",Rp="https://talentmatch-flow.lovable.app/placeholder.svg",qc="Gradzen",jp="https://talentmatch-flow.lovable.app";function bM(s={}){const e=g.useCallback(()=>{const{title:t,description:r=zc,image:n=Rp,url:i=window.location.href,type:o="website",author:l,publishedTime:d,modifiedTime:c,canonicalUrl:u}=s,h=t?`${t} | ${qc}`:Gc;document.title=h;const f=(x,y,v=!1)=>{const _=v?"property":"name";let b=document.querySelector(`meta[${_}="${x}"]`);b||(b=document.createElement("meta"),b.setAttribute(_,x),document.head.appendChild(b)),b.setAttribute("content",y)},m=(x,y)=>
736{let v=document.querySelector(`link[rel="${x}"]`);v||(v=document.createElement("link"),v.setAttribute("rel",x),document.head.appendChild(v)),v.setAttribute("href",y)};f("description",r),f("author",l||qc);const p=u||i;m("canonical",p),f("og:title",h,!0),f("og:description",r,!0),f("og:image",n,!0),f("og:url",p,!0),f("og:type",o,!0),f("og:site_name",qc,!0),f("twitter:card","summary_large_image"),f("twitter:title",h),f("twitter:description",r),f("twitter:image",n),f("twitter:site","@Gradzen"),o==="article"&&(d&&f("article:published_time",d,!0),c&&f("article:modified_time",c,!0),l&&f("article:author",l,!0)),o==="profile"&&l&&f("profile:username",l,!0)},[s]);return g.useEffect(()=>(e(),()=>{document.title=Gc;const t=(n,i,o=!1)=>{const l=o?"property":"name",d=document.querySelector(`meta[${l}="${n}"]`);d&&d.setAttribute("content",i)},r=(n,i)=>{const o=document.querySelector(`link[rel="${n}"]`);o&&o.setAttribute("href",i)};t("description",zc),t("og:title",Gc,!0),t("og:description",zc,!0),t("og:image",Rp,!0),t("og:url",jp,!0),t("og:type","website",!0),r("canonical",jp)}),[e]),{updateMetaTags:e}}function hh(s,e){const t=JSON.stringify(s);g.useEffect(()=>{const r=document.getElementById(e);r&&r.remove();const n=document.createElement("script");return n.id=e,n.type="application/ld+json",n.textContent=t,document.head.appendChild(n),()=>{const i=document.getElementById(e);i&&i.remove()}},[t,e])}function _M({name:s,url:e,logo:t,description:r,sameAs:n=[]}){const i={"@context":"https://schema.org","@type":"Organization",name:s,url:e,...t&&{logo:t},...r&&{description:r},...n.length>0&&{sameAs:n}};return hh(i,"organization-schema"),null}function c3({name:s,url:e,image:t,jobTitle:r,worksFor:n,description:i}){const o={"@context":"https://schema.org","@type":"Person",name:s,url:e,...t&&{image:t},...r&&{jobTitle:r},...n&&{worksFor:{"@type":"Organization",name:n}},...i&&{description:i}};return hh(o,"person-schema"),null}function d3({headline:s,description:e,image:t,authorName:r,authorUrl:n,datePublished:i,dateModified:o,url:l}){const d={"@context":"https://schema.org","@type":"Article",headline:s,description:e,url:l,...t&&{image:t},author:{"@type":"Person",name:r,...n&&{url:n}},datePublished:i,...o&&{dateModified:o},publisher:{"@type":"Organization",name:"Gradzen",url:"https://talentmatch-flow.lovable.app",logo:"https://talentmatch-flow.lovable.app/placeholder.svg"}};return hh(d,"article-schema"),null}var mt;(function(s){s.assertEqual=n=>{};function e(n){}s.assertIs=e;function t(n){throw new Error}s.assertNever=t,s.arrayToEnum=n=>{const i={};for(const o of n)i[o]=o;return i},s.getValidEnumValues=n=>{const i=s.objectKeys(n).filter(l=>typeof n[n[l]]!="number"),o={};for(const l of i)o[l]=n[l];return s.objectValues(o)},s.objectValues=n=>s.objectKeys(n).map(function(i){return n[i]}),s.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const i=[];for(const o in n)Object.prototype.hasOwnProperty.call(n,o)&&i.push(o);return i},s.find=(n,i)=>{for(const o of n)if(i(o))return o},s.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function r(n,i=" | "){return n.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}s.joinValues=r,s.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var Ip;(function(s){s.mergeShapes=(e,t)=>({...e,...t})})(Ip||(Ip={}));const ke=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Wr=s=>{switch(typeof s){case"undefined":return ke.undefined;case"string":return ke.string;case"number":return Number.isNaN(s)?ke.nan:ke.number;case"boolean":return ke.boolean;case"function":return ke.function;case"bigint":return ke.bigint;case"symbol":return ke.symbol;case"object":return Array.isArray(s)?ke.array:s===null?ke.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?ke.promise:typeof Map<"u"&&s instanceof Map?ke.map:typeof Set<"u"&&s instanceof Set?ke.set:typeof Date<"u"&&s instanceof Date?ke.date:ke.object;default:return ke.unknown}}
vendor: 4,703 bytes, line 736
736,he=mt.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class vr extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(i){return i.message},r={_errors:[]},n=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(n);else if(o.code==="invalid_return_type")n(o.returnTypeError);else if(o.code==="invalid_arguments")n(o.argumentsError);else if(o.path.length===0)r._errors.push(t(o));else{let l=r,d=0;for(;d<o.path.length;){const c=o.path[d];d===o.path.length-1?(l[c]=l[c]||{_errors:[]},l[c]._errors.push(t(o))):l[c]=l[c]||{_errors:[]},l=l[c],d++}}};return n(this),r}static assert(e){if(!(e instanceof vr))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,mt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},r=[];for(const n of this.issues)if(n.path.length>0){const i=n.path[0];t[i]=t[i]||[],t[i].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}vr.create=s=>new vr(s);const Yd=(s,e)=>{let t;switch(s.code){case he.invalid_type:s.received===ke.undefined?t="Required":t=`Expected ${s.expected}, received ${s.received}`;break;case he.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(s.expected,mt.jsonStringifyReplacer)}`;break;case he.unrecognized_keys:t=`Unrecognized key(s) in object: ${mt.joinValues(s.keys,", ")}`;break;case he.invalid_union:t="Invalid input";break;case he.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${mt.joinValues(s.options)}`;break;case he.invalid_enum_value:t=`Invalid enum value. Expected ${mt.joinValues(s.options)}, received '${s.received}'`;break;case he.invalid_arguments:t="Invalid function arguments";break;case he.invalid_return_type:t="Invalid function return type";break;case he.invalid_date:t="Invalid date";break;case he.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(t=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?t=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?t=`Invalid input: must end with "${s.validation.endsWith}"`:mt.assertNever(s.validation):s.validation!=="regex"?t=`Invalid ${s.validation}`:t="Invalid";break;case he.too_small:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="bigint"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:t="Invalid input";break;case he.too_big:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?t=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:t="Invalid input";break;case he.custom:t="Invalid input";break;case he.invalid_intersection_types:t="Intersection results could not be merged";break;case he.not_multiple_of:t=`Number must be a multiple of ${s.multipleOf}`;break;case he.not_finite:t="Number must be finite";break;default:t=e.defaultError,mt.assertNever(s)}return{message:t}};let wM=Yd;function EM(){return wM}const SM=s=>
vendor: 29,252 bytes, line 736
736{const{data:e,path:t,errorMaps:r,issueData:n}=s,i=[...t,...n.path||[]],o={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let l="";const d=r.filter(c=>!!c).slice().reverse();for(const c of d)l=c(o,{data:e,defaultError:l}).message;return{...n,path:i,message:l}};function _e(s,e){const t=EM(),r=SM({issueData:e,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,t,t===Yd?void 0:Yd].filter(n=>!!n)});s.common.issues.push(r)}class Ms{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if(n.status==="aborted")return ze;n.status==="dirty"&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const n of t){const i=await n.key,o=await n.value;r.push({key:i,value:o})}return Ms.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:i,value:o}=n;if(i.status==="aborted"||o.status==="aborted")return ze;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||n.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}}const ze=Object.freeze({status:"aborted"}),ea=s=>({status:"dirty",value:s}),Ks=s=>({status:"valid",value:s}),Cp=s=>s.status==="aborted",Np=s=>s.status==="dirty",ji=s=>s.status==="valid",fl=s=>typeof Promise<"u"&&s instanceof Promise;var je;(function(s){s.errToObj=e=>typeof e=="string"?{message:e}:e||{},s.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(je||(je={}));class on{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Lp=(s,e)=>{if(ji(e))return{success:!0,data:e.value};if(!s.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new vr(s.common.issues);return this._error=t,this._error}}};function st(s){if(!s)return{};const{errorMap:e,invalid_type_error:t,required_error:r,description:n}=s;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(o,l)=>{const{message:d}=s;return o.code==="invalid_enum_value"?{message:d??l.defaultError}:typeof l.data>"u"?{message:d??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:d??t??l.defaultError}},description:n}}class ft{get description(){return this._def.description}_getType(e){return Wr(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Wr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ms,ctx:{common:e.parent.common,data:e.data,parsedType:Wr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(fl(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:(t==null?void 0:t.async)??!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Wr(e)},n=this._parseSync({data:e,path:r.path,parent:r});return Lp(r,n)}"~validate"(e){var r,n;const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Wr(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:t});return ji(i)?{value:i.value}:{issues:t.common.issues}}catch(i){(n=(r=i==null?void 0:i.message)==null?void 0:r.toLowerCase())!=null&&n.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(i=>ji(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Wr(e)},n=this._parse({data:e,path:r.path,parent:r}),i=await(fl(n)?n:Promise.resolve(n));return Lp(r,i)}refine(e,t){const r=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,i)=>{const o=e(n),l=()=>i.addIssue({code:he.custom,...r(n)});return typeof Promise<"u"&&o instanceof Promise?o.then(d=>d?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(e,t){return this._refinement((r,n)=>e(r)?!0:(n.addIssue(typeof t=="function"?t(r,n):t),!1))}_refinement(e){return new Ni({schema:this,typeName:qe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return tn.create(this,this._def)}nullable(){return Li.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return gr.create(this)}promise(){return xl.create(this,this._def)}or(e){return pl.create([this,e],this._def)}and(e){return gl.create(this,e,this._def)}transform(e){return new Ni({...st(this._def),schema:this,typeName:qe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Jd({...st(this._def),innerType:this,defaultValue:t,typeName:qe.ZodDefault})}brand(){return new KM({typeName:qe.ZodBranded,type:this,...st(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Zd({...st(this._def),innerType:this,catchValue:t,typeName:qe.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return fh.create(this,e)}readonly(){return eu.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const TM=/^c[^\s-]{8,}$/i,AM=/^[0-9a-z]+$/,kM=/^[0-9A-HJKMNP-TV-Z]{26}$/i,RM=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,jM=/^[a-z0-9_-]{21}$/i,IM=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,CM=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,NM=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,LM="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Hc;const PM=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,DM=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,OM=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,MM=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,FM=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$M=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Kb="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",UM=new RegExp(`^${Kb}$`);function Wb(s){let e="[0-5]\\d";s.precision?e=`${e}\\.\\d{${s.precision}}`:s.precision==null&&(e=`${e}(\\.\\d+)?`);const t=s.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function BM(s){return new RegExp(`^${Wb(s)}$`)}function VM(s){let e=`${Kb}T${Wb(s)}`;const t=[];return t.push(s.local?"Z?":"Z"),s.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function GM(s,e){return!!((e==="v4"||!e)&&PM.test(s)||(e==="v6"||!e)&&OM.test(s))}function zM(s,e){if(!IM.test(s))return!1;try{const[t]=s.split(".");if(!t)return!1;const r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(r));return!(typeof n!="object"||n===null||"typ"in n&&(n==null?void 0:n.typ)!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function qM(s,e){return!!((e==="v4"||!e)&&DM.test(s)||(e==="v6"||!e)&&MM.test(s))}class Jr extends ft{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ke.string){const i=this._getOrReturnCtx(e);return _e(i,{code:he.invalid_type,expected:ke.string,received:i.parsedType}),ze}const r=new Ms;let n;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),_e(n,{code:he.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(n=this._getOrReturnCtx(e,n),_e(n,{code:he.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const o=e.data.length>i.value,l=e.data.length<i.value;(o||l)&&(n=this._getOrReturnCtx(e,n),o?_e(n,{code:he.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&_e(n,{code:he.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")NM.test(e.data)||(n=this._getOrReturnCtx(e,n),_e(n,{validation:"email",code:he.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Hc||(Hc=new RegExp(LM,"u")),Hc.test(e.data)||(n=this._getOrReturnCtx(e,n),_e(n,{validation:"emoji",code:he.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")RM.test(e.data)||(n=this._getOrReturnCtx(e,n),_e(n,{validation:"uuid",code:he.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")jM.test(e.data)||(n=this._getOrReturnCtx(e,n),_e(n,{validation:"nanoid",code:he.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")TM.test(e.data)||(n=this._getOrReturnCtx(e,n),_e(n,{validation:"cuid",code:he.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")AM.test(e.data)||(n=this._getOrReturnCtx(e,n),_e(n,{validation:"cuid2",code:he.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")kM.test(e.data)||(n=this._getOrReturnCtx(e,n),_e(n,{validation:"ulid",code:he.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),_e(n,{validation:"url",code:he.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),_e(n,{validation:"regex",code:he.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(e,n),_e(n,{code:he.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(n=this._getOrReturnCtx(e,n),_e(n,{code:he.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),_e(n,{code:he.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?VM(i).test(e.data)||(n=this._getOrReturnCtx(e,n),_e(n,{code:he.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?UM.test(e.data)||(n=this._getOrReturnCtx(e,n),_e(n,{code:he.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?BM(i).test(e.data)||(n=this._getOrReturnCtx(e,n),_e(n,{code:he.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?CM.test(e.data)||(n=this._getOrReturnCtx(e,n),_e(n,{validation:"duration",code:he.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?GM(e.data,i.version)||(n=this._getOrReturnCtx(e,n),_e(n,{validation:"ip",code:he.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?zM(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),_e(n,{validation:"jwt",code:he.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?qM(e.data,i.version)||(n=this._getOrReturnCtx(e,n),_e(n,{validation:"cidr",code:he.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?FM.test(e.data)||(n=this._getOrReturnCtx(e,n),_e(n,{validation:"base64",code:he.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?$M.test(e.data)||(n=this._getOrReturnCtx(e,n),_e(n,{validation:"base64url",code:he.invalid_string,message:i.message}),r.dirty()):mt.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(n=>e.test(n),{validation:t,code:he.invalid_string,...je.errToObj(r)})}_addCheck(e){return new Jr({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...je.errToObj(e)})}url(e){return this._addCheck({kind:"url",...je.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...je.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...je.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...je.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...je.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...je.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...je.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...je.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...je.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...je.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...je.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...je.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...je.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...je.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...je.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...je.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...je.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...je.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...je.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...je.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...je.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...je.errToObj(t)})}nonempty(e){return this.min(1,je.errToObj(e))}trim(){return new Jr({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Jr({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Jr({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Jr.create=s=>new Jr({checks:[],typeName:qe.ZodString,coerce:(s==null?void 0:s.coerce)??!1,...st(s)});function HM(s,e){const t=(s.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,n=t>r?t:r,i=Number.parseInt(s.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return i%o/10**n}class Ii extends ft{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ke.number){const i=this._getOrReturnCtx(e);return _e(i,{code:he.invalid_type,expected:ke.number,received:i.parsedType}),ze}let r;const n=new Ms;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),_e(r,{code:he.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),_e(r,{code:he.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),_e(r,{code:he.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?HM(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),_e(r,{code:he.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),_e(r,{code:he.not_finite,message:i.message}),n.dirty()):mt.assertNever(i);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,je.toString(t))}gt(e,t){return this.setLimit("min",e,!1,je.toString(t))}lte(e,t){return this.setLimit("max",e,!0,je.toString(t))}lt(e,t){return this.setLimit("max",e,!1,je.toString(t))}setLimit(e,t,r,n){return new Ii({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:je.toString(n)}]})}_addCheck(e){return new Ii({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:je.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:je.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:je.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:je.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:je.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:je.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:je.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:je.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:je.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&mt.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Ii.create=s=>new Ii({checks:[],typeName:qe.ZodNumber,coerce:(s==null?void 0:s.coerce)||!1,...st(s)});class La extends ft{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ke.bigint)return this._getInvalidInput(e);let r;const n=new Ms;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),_e(r,{code:he.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),_e(r,{code:he.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),_e(r,{code:he.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):mt.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return _e(t,{code:he.invalid_type,expected:ke.bigint,received:t.parsedType}),ze}gte(e,t){return this.setLimit("min",e,!0,je.toString(t))}gt(e,t){return this.setLimit("min",e,!1,je.toString(t))}lte(e,t){return this.setLimit("max",e,!0,je.toString(t))}lt(e,t){return this.setLimit("max",e,!1,je.toString(t))}setLimit(e,t,r,n){return new La({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:je.toString(n)}]})}_addCheck(e){return new La({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:je.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:je.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:je.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:je.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:je.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}La.create=s=>new La({checks:[],typeName:qe.ZodBigInt,coerce:(s==null?void 0:s.coerce)??!1,...st(s)});class Pp extends ft{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ke.boolean){const r=this._getOrReturnCtx(e);return _e(r,{code:he.invalid_type,expected:ke.boolean,received:r.parsedType}),ze}return Ks(e.data)}}Pp.create=s=>new Pp({typeName:qe.ZodBoolean,coerce:(s==null?void 0:s.coerce)||!1,...st(s)});class ml extends ft{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ke.date){const i=this._getOrReturnCtx(e);return _e(i,{code:he.invalid_type,expected:ke.date,received:i.parsedType}),ze}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return _e(i,{code:he.invalid_date}),ze}const r=new Ms;let n;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),_e(n,{code:he.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(n=this._getOrReturnCtx(e,n),_e(n,{code:he.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ml({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:je.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:je.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}ml.create=s=>new ml({checks:[],coerce:(s==null?void 0:s.coerce)||!1,typeName:qe.ZodDate,...st(s)});class Dp extends ft{_parse(e){if(this._getType(e)!==ke.symbol){const r=this._getOrReturnCtx(e);return _e(r,{code:he.invalid_type,expected:ke.symbol,received:r.parsedType}),ze}return Ks(e.data)}}Dp.create=s=>new Dp({typeName:qe.ZodSymbol,...st(s)});class Op extends ft{_parse(e){if(this._getType(e)!==ke.undefined){const r=this._getOrReturnCtx(e);return _e(r,{code:he.invalid_type,expected:ke.undefined,received:r.parsedType}),ze}return Ks(e.data)}}Op.create=s=>new Op({typeName:qe.ZodUndefined,...st(s)});class Mp extends ft{_parse(e){if(this._getType(e)!==ke.null){const r=this._getOrReturnCtx(e);return _e(r,{code:he.invalid_type,expected:ke.null,received:r.parsedType}),ze}return Ks(e.data)}}Mp.create=s=>new Mp({typeName:qe.ZodNull,...st(s)});class Fp extends ft{constructor(){super(...arguments),this._any=!0}_parse(e){return Ks(e.data)}}Fp.create=s=>new Fp({typeName:qe.ZodAny,...st(s)});class $p extends ft{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ks(e.data)}}$p.create=s=>new $p({typeName:qe.ZodUnknown,...st(s)});class ln extends ft{_parse(e){const t=this._getOrReturnCtx(e);return _e(t,{code:he.invalid_type,expected:ke.never,received:t.parsedType}),ze}}ln.create=s=>new ln({typeName:qe.ZodNever,...st(s)});class Up extends ft{_parse(e){if(this._getType(e)!==ke.undefined){const r=this._getOrReturnCtx(e);return _e(r,{code:he.invalid_type,expected:ke.void,received:r.parsedType}),ze}return Ks(e.data)}}Up.create=s=>new Up({typeName:qe.ZodVoid,...st(s)});class gr extends ft{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==ke.array)return _e(t,{code:he.invalid_type,expected:ke.array,received:t.parsedType}),ze;if(n.exactLength!==null){const o=t.data.length>n.exactLength.value,l=t.data.length<n.exactLength.value;(o||l)&&(_e(t,{code:o?he.too_big:he.too_small,minimum:l?n.exactLength.value:void 0,maximum:o?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(n.minLength!==null&&t.data.length<n.minLength.value&&(_e(t,{code:he.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(_e(t,{code:he.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((o,l)=>n.type._parseAsync(new on(t,o,t.path,l)))).then(o=>Ms.mergeArray(r,o));const i=[...t.data].map((o,l)=>n.type._parseSync(new on(t,o,t.path,l)));return Ms.mergeArray(r,i)}
vendor: 5,951 bytes, line 736
736get element(){return this._def.type}min(e,t){return new gr({...this._def,minLength:{value:e,message:je.toString(t)}})}max(e,t){return new gr({...this._def,maxLength:{value:e,message:je.toString(t)}})}length(e,t){return new gr({...this._def,exactLength:{value:e,message:je.toString(t)}})}nonempty(e){return this.min(1,e)}}gr.create=(s,e)=>new gr({type:s,minLength:null,maxLength:null,exactLength:null,typeName:qe.ZodArray,...st(e)});function ti(s){if(s instanceof Kt){const e={};for(const t in s.shape){const r=s.shape[t];e[t]=tn.create(ti(r))}return new Kt({...s._def,shape:()=>e})}else return s instanceof gr?new gr({...s._def,type:ti(s.element)}):s instanceof tn?tn.create(ti(s.unwrap())):s instanceof Li?Li.create(ti(s.unwrap())):s instanceof Nn?Nn.create(s.items.map(e=>ti(e))):s}class Kt extends ft{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=mt.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ke.object){const c=this._getOrReturnCtx(e);return _e(c,{code:he.invalid_type,expected:ke.object,received:c.parsedType}),ze}const{status:r,ctx:n}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof ln&&this._def.unknownKeys==="strip"))for(const c in n.data)o.includes(c)||l.push(c);const d=[];for(const c of o){const u=i[c],h=n.data[c];d.push({key:{status:"valid",value:c},value:u._parse(new on(n,h,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof ln){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of l)d.push({key:{status:"valid",value:u},value:{status:"valid",value:n.data[u]}});else if(c==="strict")l.length>0&&(_e(n,{code:he.unrecognized_keys,keys:l}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of l){const h=n.data[u];d.push({key:{status:"valid",value:u},value:c._parse(new on(n,h,n.path,u)),alwaysSet:u in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of d){const h=await u.key,f=await u.value;c.push({key:h,value:f,alwaysSet:u.alwaysSet})}return c}).then(c=>Ms.mergeObjectSync(r,c)):Ms.mergeObjectSync(r,d)}get shape(){return this._def.shape()}strict(e){return je.errToObj,new Kt({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{var i,o;const n=((o=(i=this._def).errorMap)==null?void 0:o.call(i,t,r).message)??r.defaultError;return t.code==="unrecognized_keys"?{message:je.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new Kt({...this._def,unknownKeys:"strip"})}passthrough(){return new Kt({...this._def,unknownKeys:"passthrough"})}extend(e){return new Kt({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Kt({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:qe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Kt({...this._def,catchall:e})}pick(e){const t={};for(const r of mt.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new Kt({...this._def,shape:()=>t})}omit(e){const t={};for(const r of mt.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new Kt({...this._def,shape:()=>t})}deepPartial(){return ti(this)}partial(e){const t={};for(const r of mt.objectKeys(this.shape)){const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}return new Kt({...this._def,shape:()=>t})}required(e){const t={};for(const r of mt.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof tn;)i=i._def.innerType;t[r]=i}return new Kt({...this._def,shape:()=>t})}keyof(){return Yb(mt.objectKeys(this.shape))}}Kt.create=(s,e)=>new Kt({shape:()=>s,unknownKeys:"strip",catchall:ln.create(),typeName:qe.ZodObject,...st(e)});Kt.strictCreate=(s,e)=>new Kt({shape:()=>s,unknownKeys:"strict",catchall:ln.create(),typeName:qe.ZodObject,...st(e)});Kt.lazycreate=(s,e)=>new Kt({shape:s,unknownKeys:"strip",catchall:ln.create(),typeName:qe.ZodObject,...st(e)});class pl extends ft{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;function n(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return t.common.issues.push(...l.ctx.common.issues),l.result;const o=i.map(l=>new vr(l.ctx.common.issues));return _e(t,{code:he.invalid_union,unionErrors:o}),ze}if(t.common.async)return Promise.all(r.map(async i=>{const o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(n);{let i;const o=[];for(const d of r){const c={...t,common:{...t.common,issues:[]},parent:null},u=d._parseSync({data:t.data,path:t.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;const l=o.map(d=>new vr(d));return _e(t,{code:he.invalid_union,unionErrors:l}),ze}}get options(){return this._def.options}}pl.create=(s,e)=>new pl({options:s,typeName:qe.ZodUnion,...st(e)});function Xd(s,e){const t=Wr(s),r=Wr(e);if(s===e)return{valid:!0,data:s};if(t===ke.object&&r===ke.object){const n=mt.objectKeys(e),i=mt.objectKeys(s).filter(l=>n.indexOf(l)!==-1),o={...s,...e};for(const l of i){const d=Xd(s[l],e[l]);if(!d.valid)return{valid:!1};o[l]=d.data}return{valid:!0,data:o}}else if(t===ke.array&&r===ke.array){if(s.length!==e.length)return{valid:!1};const n=[];for(let i=0;i<s.length;i++){const o=s[i],l=e[i],d=Xd(o,l);if(!d.valid)return{valid:!1};n.push(d.data)}return{valid:!0,data:n}}else return t===ke.date&&r===ke.date&&+s==+e?{valid:!0,data:s}:{valid:!1}}class gl extends ft{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(i,o)=>
vendor: 4,181 bytes, line 736
736{if(Cp(i)||Cp(o))return ze;const l=Xd(i.value,o.value);return l.valid?((Np(i)||Np(o))&&t.dirty(),{status:t.value,value:l.data}):(_e(r,{code:he.invalid_intersection_types}),ze)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>n(i,o)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}gl.create=(s,e,t)=>new gl({left:s,right:e,typeName:qe.ZodIntersection,...st(t)});class Nn extends ft{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ke.array)return _e(r,{code:he.invalid_type,expected:ke.array,received:r.parsedType}),ze;if(r.data.length<this._def.items.length)return _e(r,{code:he.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ze;!this._def.rest&&r.data.length>this._def.items.length&&(_e(r,{code:he.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...r.data].map((o,l)=>{const d=this._def.items[l]||this._def.rest;return d?d._parse(new on(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>Ms.mergeArray(t,o)):Ms.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new Nn({...this._def,rest:e})}}Nn.create=(s,e)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Nn({items:s,typeName:qe.ZodTuple,rest:null,...st(e)})};class Bp extends ft{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ke.map)return _e(r,{code:he.invalid_type,expected:ke.map,received:r.parsedType}),ze;const n=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,d],c)=>({key:n._parse(new on(r,l,r.path,[c,"key"])),value:i._parse(new on(r,d,r.path,[c,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const d of o){const c=await d.key,u=await d.value;if(c.status==="aborted"||u.status==="aborted")return ze;(c.status==="dirty"||u.status==="dirty")&&t.dirty(),l.set(c.value,u.value)}return{status:t.value,value:l}})}else{const l=new Map;for(const d of o){const c=d.key,u=d.value;if(c.status==="aborted"||u.status==="aborted")return ze;(c.status==="dirty"||u.status==="dirty")&&t.dirty(),l.set(c.value,u.value)}return{status:t.value,value:l}}}}Bp.create=(s,e,t)=>new Bp({valueType:e,keyType:s,typeName:qe.ZodMap,...st(t)});class Pa extends ft{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ke.set)return _e(r,{code:he.invalid_type,expected:ke.set,received:r.parsedType}),ze;const n=this._def;n.minSize!==null&&r.data.size<n.minSize.value&&(_e(r,{code:he.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&r.data.size>n.maxSize.value&&(_e(r,{code:he.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const i=this._def.valueType;function o(d){const c=new Set;for(const u of d){if(u.status==="aborted")return ze;u.status==="dirty"&&t.dirty(),c.add(u.value)}return{status:t.value,value:c}}const l=[...r.data.values()].map((d,c)=>i._parse(new on(r,d,r.path,c)));return r.common.async?Promise.all(l).then(d=>o(d)):o(l)}min(e,t){return new Pa({...this._def,minSize:{value:e,message:je.toString(t)}})}max(e,t){return new Pa({...this._def,maxSize:{value:e,message:je.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Pa.create=(s,e)=>new Pa({valueType:s,minSize:null,maxSize:null,typeName:qe.ZodSet,...st(e)});class Vp extends ft{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Vp.create=(s,e)=>new Vp({getter:s,typeName:qe.ZodLazy,...st(e)});class Qd extends ft{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return _e(t,{received:t.data,code:he.invalid_literal,expected:this._def.value}),ze}
vendor: 5,385 bytes, line 736
736return{status:"valid",value:e.data}}get value(){return this._def.value}}Qd.create=(s,e)=>new Qd({value:s,typeName:qe.ZodLiteral,...st(e)});function Yb(s,e){return new Ci({values:s,typeName:qe.ZodEnum,...st(e)})}class Ci extends ft{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),r=this._def.values;return _e(t,{expected:mt.joinValues(r),received:t.parsedType,code:he.invalid_type}),ze}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return _e(t,{received:t.data,code:he.invalid_enum_value,options:r}),ze}return Ks(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Ci.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ci.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}}Ci.create=Yb;class Gp extends ft{_parse(e){const t=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ke.string&&r.parsedType!==ke.number){const n=mt.objectValues(t);return _e(r,{expected:mt.joinValues(n),received:r.parsedType,code:he.invalid_type}),ze}if(this._cache||(this._cache=new Set(mt.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const n=mt.objectValues(t);return _e(r,{received:r.data,code:he.invalid_enum_value,options:n}),ze}return Ks(e.data)}get enum(){return this._def.values}}Gp.create=(s,e)=>new Gp({values:s,typeName:qe.ZodNativeEnum,...st(e)});class xl extends ft{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ke.promise&&t.common.async===!1)return _e(t,{code:he.invalid_type,expected:ke.promise,received:t.parsedType}),ze;const r=t.parsedType===ke.promise?t.data:Promise.resolve(t.data);return Ks(r.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}xl.create=(s,e)=>new xl({type:s,typeName:qe.ZodPromise,...st(e)});class Ni extends ft{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===qe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:o=>{_e(r,o),o.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){const o=n.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(t.value==="aborted")return ze;const d=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return d.status==="aborted"?ze:d.status==="dirty"||t.value==="dirty"?ea(d.value):d});{if(t.value==="aborted")return ze;const l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?ze:l.status==="dirty"||t.value==="dirty"?ea(l.value):l}}if(n.type==="refinement"){const o=l=>{const d=n.refinement(l,i);if(r.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?ze:(l.status==="dirty"&&t.dirty(),o(l.value),{status:t.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?ze:(l.status==="dirty"&&t.dirty(),o(l.value).then(()=>({status:t.value,value:l.value}))))}if(n.type==="transform")if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ji(o))return ze;const l=n.transform(o.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>ji(o)?Promise.resolve(n.transform(o.value,i)).then(l=>({status:t.value,value:l})):ze);mt.assertNever(n)}}Ni.create=(s,e,t)=>new Ni({schema:s,typeName:qe.ZodEffects,effect:e,...st(t)});Ni.createWithPreprocess=(s,e,t)=>new Ni({schema:e,effect:{type:"preprocess",transform:s},typeName:qe.ZodEffects,...st(t)});class tn extends ft{_parse(e){return this._getType(e)===ke.undefined?Ks(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}tn.create=(s,e)=>new tn({innerType:s,typeName:qe.ZodOptional,...st(e)});class Li extends ft{_parse(e){return this._getType(e)===ke.null?Ks(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Li.create=(s,e)=>new Li({innerType:s,typeName:qe.ZodNullable,...st(e)});class Jd extends ft{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===ke.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Jd.create=(s,e)=>new Jd({innerType:s,typeName:qe.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...st(e)});class Zd extends ft{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return fl(n)?n.then(i=>
736({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new vr(r.common.issues)},input:r.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new vr(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Zd.create=(s,e)=>new Zd({innerType:s,typeName:qe.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...st(e)});class zp extends ft{_parse(e){if(this._getType(e)!==ke.nan){const r=this._getOrReturnCtx(e);return _e(r,{code:he.invalid_type,expected:ke.nan,received:r.parsedType}),ze}return{status:"valid",value:e.data}}}zp.create=s=>new zp({typeName:qe.ZodNaN,...st(s)});class KM extends ft{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class fh extends ft{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?ze:i.status==="dirty"?(t.dirty(),ea(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return n.status==="aborted"?ze:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,t){return new fh({in:e,out:t,typeName:qe.ZodPipeline})}}class eu extends ft{_parse(e){const t=this._def.innerType._parse(e),r=n=>(ji(n)&&(n.value=Object.freeze(n.value)),n);return fl(t)?t.then(n=>r(n)):r(t)}unwrap(){return this._def.innerType}}eu.create=(s,e)=>new eu({innerType:s,typeName:qe.ZodReadonly,...st(e)});var qe;(function(s){s.ZodString="ZodString",s.ZodNumber="ZodNumber",s.ZodNaN="ZodNaN",s.ZodBigInt="ZodBigInt",s.ZodBoolean="ZodBoolean",s.ZodDate="ZodDate",s.ZodSymbol="ZodSymbol",s.ZodUndefined="ZodUndefined",s.ZodNull="ZodNull",s.ZodAny="ZodAny",s.ZodUnknown="ZodUnknown",s.ZodNever="ZodNever",s.ZodVoid="ZodVoid",s.ZodArray="ZodArray",s.ZodObject="ZodObject",s.ZodUnion="ZodUnion",s.ZodDiscriminatedUnion="ZodDiscriminatedUnion",s.ZodIntersection="ZodIntersection",s.ZodTuple="ZodTuple",s.ZodRecord="ZodRecord",s.ZodMap="ZodMap",s.ZodSet="ZodSet",s.ZodFunction="ZodFunction",s.ZodLazy="ZodLazy",s.ZodLiteral="ZodLiteral",s.ZodEnum="ZodEnum",s.ZodEffects="ZodEffects",s.ZodNativeEnum="ZodNativeEnum",s.ZodOptional="ZodOptional",s.ZodNullable="ZodNullable",s.ZodDefault="ZodDefault",s.ZodCatch="ZodCatch",s.ZodPromise="ZodPromise",s.ZodBranded="ZodBranded",s.ZodPipeline="ZodPipeline",s.ZodReadonly="ZodReadonly"})(qe||(qe={}));const yo=Jr.create,u3=Ii.create;ln.create;gr.create;const WM=Kt.create;pl.create;gl.create;Nn.create;const h3=Qd.create;Ci.create;xl.create;tn.create;Li.create;const YM=({met:s,text:e})=>a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[s?a.jsx(sr,{className:"h-3.5 w-3.5 text-green-500 flex-shrink-0"}):a.jsx(cu,{className:"h-3.5 w-3.5 text-muted-foreground flex-shrink-0"}),a.jsx("span",{className:C(s?"text-green-600":"text-muted-foreground"),children:e})]}),XM=({password:s})=>{const e=[{met:s.length>=8,text:"At least 8 characters"},{met:/[A-Z]/.test(s),text:"One uppercase letter"},{met:/[a-z]/.test(s),text:"One lowercase letter"},{met:/[0-9]/.test(s),text:"One number"}];return a.jsxs("div",{className:"space-y-2 mt-2 p-3 rounded-lg bg-muted/50 border",children:[a.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Password requirements:"}),a.jsx("div",{className:"grid grid-cols-2 gap-1.5",children:e.map((t,r)=>a.jsx(YM,{met:t.met,text:t.text},r))})]})},QM=s=>s.length>=8&&/[A-Z]/.test(s)&&/[a-z]/.test(s)&&/[0-9]/.test(s);function JM(){return Wt({queryKey:["site-settings","username_settings"],queryFn:async()=>{const{data:s,error:e}=await L.from("site_settings").select("setting_value").eq("setting_key","username_settings").maybeSingle();if(e)throw e;return s?s.setting_value:{name_change_cooldown_days:30,username_change_cooldown_days:30,username_placeholder:"johndoe",fullname_placeholder:"John Doe"}}})}const ZM={job_search:{category:"search",canDelete:!0,isVisible:!0},profile_search:{category:"search",canDelete:!0,isVisible:!0}
736,company_search:{category:"search",canDelete:!0,isVisible:!0},post_created:{category:"social",canDelete:!1,isVisible:!0},post_reaction:{category:"social",canDelete:!0,isVisible:!0},post_comment:{category:"social",canDelete:!0,isVisible:!0},post_share:{category:"social",canDelete:!0,isVisible:!0},connection_request_sent:{category:"connections",canDelete:!1,isVisible:!0},connection_request_accepted:{category:"connections",canDelete:!1,isVisible:!0},connection_request_rejected:{category:"connections",canDelete:!1,isVisible:!0},connection_removed:{category:"connections",canDelete:!1,isVisible:!0},job_applied:{category:"applications",canDelete:!1,isVisible:!0},job_withdrawn:{category:"applications",canDelete:!1,isVisible:!0},job_saved:{category:"applications",canDelete:!0,isVisible:!0},job_unsaved:{category:"applications",canDelete:!0,isVisible:!0},profile_viewed:{category:"profile",canDelete:!0,isVisible:!0},cv_downloaded:{category:"profile",canDelete:!0,isVisible:!0},profile_updated:{category:"profile",canDelete:!1,isVisible:!0},login:{category:"account",canDelete:!1,isVisible:!0},password_changed:{category:"account",canDelete:!1,isVisible:!0},settings_updated:{category:"account",canDelete:!1,isVisible:!0}},f3={job_search:"Searched for jobs",profile_search:"Searched for people",company_search:"Searched for companies",post_created:"Created a post",post_reaction:"Reacted to a post",post_comment:"Commented on a post",post_share:"Shared a post",connection_request_sent:"Sent a connection request",connection_request_accepted:"Accepted a connection request",connection_request_rejected:"Declined a connection request",connection_removed:"Removed a connection",job_applied:"Applied to a job",job_withdrawn:"Withdrew application",job_saved:"Saved a job",job_unsaved:"Unsaved a job",profile_viewed:"Viewed a profile",cv_downloaded:"Downloaded a CV",profile_updated:"Updated profile",login:"Logged in",password_changed:"Changed password",settings_updated:"Updated settings"},m3={candidate_profile_viewed:"Viewed candidate profile",candidate_cv_downloaded:"Downloaded candidate CV",candidate_notes_added:"Added notes to candidate",candidate_stage_changed:"Changed candidate stage",candidate_rejected:"Rejected candidate",candidate_hired:"Hired candidate",test_assigned:"Assigned aptitude test",test_reviewed:"Reviewed test results",job_posted:"Posted a job",job_edited:"Edited job posting",job_closed:"Closed job posting",job_republished:"Republished job"};async function eF(s,e,t){try{const r=ZM[e],{error:n}=await L.from("user_activity_log").insert([{user_id:s,activity_type:e,activity_category:r.category,target_type:(t==null?void 0:t.targetType)||null,target_id:(t==null?void 0:t.targetId)||null,metadata:JSON.parse(JSON.stringify((t==null?void 0:t.metadata)||{})),is_visible_to_user:r.isVisible,can_user_delete:r.canDelete}]);if(n)throw n;return{success:!0}}catch(r){return console.error("Error logging activity:",r),{success:!1,error:r.message}}}async function p3(s,e,t){try{const{error:r}=await L.from("hr_activity_log").insert([{hr_user_id:s,activity_type:e,target_user_id:(t==null?void 0:t.targetUserId)||null,job_id:(t==null?void 0:t.jobId)||null,application_id:(t==null?void 0:t.applicationId)||null,action_details:JSON.parse(JSON.stringify((t==null?void 0:t.details)||{}))}]);if(r)throw r;return{success:!0}}catch(r){return console.error("Error logging HR activity:",r),{success:!1,error:r.message}}}async function g3(s){try{const{error:e}=await L.from("user_activity_log").update({deleted_at:new Date().toISOString()}).eq("id",s).eq("can_user_delete",!0);if(e)throw e;return{success:!0}}catch(e){return console.error("Error hiding activity:",e),{success:!1,error:e.message}}}async function x3(s,e){try{const{data:t,error:r}=await L.from("user_activity_log").update({deleted_at:new Date().toISOString()}).eq("user_id",s).eq("activity_category",e).eq("can_user_delete",!0).is("deleted_at",null).select("id");if(r)throw r;return{success:!0,count:(t==null?void 0:t.length)||0}}catch(t){return console.error("Error clearing activities:",t),{success:!1,error:t.message}}}async function y3(s,e){try{let t=L.from("user_activity_log").select("*",{count:"exact"}).eq("user_id",s).eq("is_visible_to_user",!0).is("deleted_at",null).order("created_at",{ascending:!1});e!=null&&e.category&&(t=t.eq("activity_category",e.category)),e!=null&&e.startDate&&(t=t.gte("created_at",e.startDate.toISOString())),e!=null&&e.endDate&&(t=t.lte("created_at",e.endDate.toISOString())),e!=null&&e.limit&&(t=t.limit(e.limit)),e!=null&&e.offset&&(t=t.range(e.offset,e.offset+(e.limit||20)-1));const{data:r,count:n,error:i}=await t;if(i)throw i;
736return{data:r||[],count:n||0}}catch(t){return console.error("Error fetching activities:",t),{data:[],count:0,error:t.message}}}async function v3(s,e){try{let t=L.from("hr_activity_log").select("*",{count:"exact"}).eq("hr_user_id",s).order("created_at",{ascending:!1});e!=null&&e.jobId&&(t=t.eq("job_id",e.jobId)),e!=null&&e.startDate&&(t=t.gte("created_at",e.startDate.toISOString())),e!=null&&e.endDate&&(t=t.lte("created_at",e.endDate.toISOString())),e!=null&&e.limit&&(t=t.limit(e.limit)),e!=null&&e.offset&&(t=t.range(e.offset,e.offset+(e.limit||20)-1));const{data:r,count:n,error:i}=await t;if(i)throw i;return{data:r||[],count:n||0}}catch(t){return console.error("Error fetching HR activities:",t),{data:[],count:0,error:t.message}}}async function b3(s){try{const{data:e,error:t}=await L.from("user_activity_log").select("*").eq("user_id",s).order("created_at",{ascending:!1});if(t)throw t;return{data:e||[]}}catch(e){return console.error("Error exporting activities:",e),{data:[],error:e.message}}}const tF=()=>{var P,N,O;const s=hs(),e=br(),{signUp:t,signIn:r,user:n,loading:i}=$t(),o=((P=e.state)==null?void 0:P.email)||"";g.useEffect(()=>{if(!i&&n){const $=Ji();s($||"/social",{replace:!0})}},[i,n,s]);const{data:l}=JM(),{isOnline:d}=Hb(),c=$=>$.split(" ").map(B=>B.charAt(0).toUpperCase()+B.slice(1).toLowerCase()).join(" "),[u,h]=g.useState("login"),[f,m]=g.useState(o),[p,x]=g.useState(""),[y,v]=g.useState(""),[_,b]=g.useState(!1),[w,T]=g.useState(!1),[A,S]=g.useState(!1),[I,j]=g.useState(!1),{data:R,isLoading:k}=Wt({queryKey:["security-settings"],queryFn:async()=>{const{data:$,error:B}=await L.from("security_settings").select("*");if(B)throw B;return $}}),D=((N=R==null?void 0:R.find($=>$.setting_key==="require_strong_password"))==null?void 0:N.setting_value)??!0,Y=((O=R==null?void 0:R.find($=>$.setting_key==="require_email_verification"))==null?void 0:O.setting_value)??!1,q=()=>{const $=D?yo().min(8,"Password must be at least 8 characters").regex(/[A-Z]/,"Must contain at least one uppercase letter").regex(/[a-z]/,"Must contain at least one lowercase letter").regex(/[0-9]/,"Must contain at least one number"):yo().min(6,"Password must be at least 6 characters");return WM({email:yo().email("Please enter a valid email address"),password:$,fullName:yo().optional()})},X=async $=>{$.preventDefault();const B=u==="login";if(!B&&k){Ae.info("Loading settings, please wait...");return}try{const K=q().parse({email:f,password:p,fullName:B?void 0:y});if(!B&&!w){Ae.error("Please agree to the terms and conditions");return}if(S(!0),B){const{error:ee}=await r(K.email,K.password);if(ee){ee.message.includes("Invalid login credentials")?Ae.error("Invalid email or password"):ee.message.includes("Email not confirmed")?Ae.error("Please verify your email before signing in"):Ae.error("An unexpected error occurred. Please try again.");return}const{data:{user:ce}}=await L.auth.getUser();if(ce){const{data:re}=await L.from("profiles").select("is_banned, ban_reason, banned_at, user_id, account_status").eq("user_id",ce.id).single();if(re!=null&&re.is_banned){await L.auth.signOut(),sessionStorage.setItem("lockInfo",JSON.stringify(re)),j(!0),s("/account-locked");return}if((re==null?void 0:re.account_status)==="deleted"){await L.auth.signOut(),Ae.error("This account has been deleted");return}if((re==null?void 0:re.account_status)==="deactivated"){await L.from("profiles").update({account_status:"active",deactivated_at:null,profile_visibility:"public"}).eq("user_id",ce.id),Ae.success("Welcome back! Your account has been reactivated.");const ve=Ji();j(!0),s(ve||"/social");return}}eF(ce.id,"login",{metadata:{method:"email"}}),Ae.success("Welcome back!");const Q=Ji();j(!0),s(Q||"/social")}else{Y&&(sessionStorage.setItem("signup_pending_verification","1"),j(!0));const{error:ee,needsEmailConfirmation:ce,alreadyExists:Q,confirmed:re}=await t(K.email,K.password,K.fullName);if(ee){if(sessionStorage.removeItem("signup_pending_verification"),j(!1),Q&&re){Ae.error("This email is already registered. Please sign in instead."),h("login");return}if(Q&&!re){const{data:Pe,error:Me}=await L.functions.invoke("send-otp-code",{body:{email:K.email,purpose:"signup"}});if(Me||!(Pe!=null&&Pe.ok)){Ae.error("This email already has an unverified account, but we could not resend the code. Please try again.");return}sessionStorage.setItem("temp_password",K.password),sessionStorage.setItem("signup_pending_verification","1"),Ae.success("This email already has an unverified account. We sent a new verification code."),j(!0),s("/verify-email",{state:{email:K.email}});return}ee.message.includes("already registered")||ee.message.includes("already exists")?(Ae.error("This email is already registered. Please sign in instead."),h("login")):Ae.error(ee.message);return}const ve=localStorage.getItem("referral_employer_id"),Ce=localStorage.getItem("referral_job_id");if(Y){await L.auth.signOut();const{data:Pe,error:Me}=await L.functions.invoke("send-otp-code",{body:{email:K.email,purpose:"signup"}});if(Me||!(Pe!=null&&Pe.ok)){console.error("Failed to send verification email:",Me),sessionStorage.removeItem("signup_pending_verification"),j(!1),Ae.error("Failed to send verification email. Please try again.");return}ve&&Ce&&(localStorage.setItem("pending_referral_employer_id",ve),localStorage.setItem("pending_referral_job_id",Ce)),sessionStorage.setItem("temp_password",K.password),Ae.success("Verification code sent! Check your email for a 6-digit code to complete signup."),j(!0),s("/verify-email",{state:{email:K.email}})}else{if(ve&&Ce){const{data:{user:Me}}=await L.auth.getUser();Me&&await L.from("pending_referrals").insert({user_id:Me.id,referrer_user_id:ve,job_id:Ce}),localStorage.removeItem("referral_employer_id"),localStorage.removeItem("referral_job_id")}Ae.success("Account created successfully! Welcome to the platform.");const Pe=Ji();j(!0),s(Pe||"/social")}}}catch(U){sessionStorage.removeItem("signup_pending_verification"),j(!1),U instanceof vr?Ae.error(U.errors[0].message):Ae.error("Something went wrong. Please try again.")}finally{S(!1)}},F=!D||QM(p);return I?a.jsx("div",{className:"w-full flex justify-center py-8",children:a.jsxs("svg",{className:"animate-spin h-6 w-6 text-primary",viewBox:"0 0 24 24",children:[a.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4",fill:"none"}),a.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})}):a.jsxs("div",{className:"w-full",children:[!d&&a.jsxs("p",{className:"text-sm text-destructive flex items-center gap-2 mb-4",children:[a.jsx(n0,{className:"h-4 w-4"}),"You're offline. Connect to the internet to continue."]}),u==="login"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"text-center mb-6",children:[a.jsx("h2",{className:"text-xl font-display font-bold text-foreground",children:"Welcome"}),a.jsx("p",{className:"text-muted-foreground mt-1 text-sm",children:"Sign in to your account"})]}),a.jsxs("form",{onSubmit:X,className:"space-y-4",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsx(hr,{htmlFor:"email",className:"text-foreground text-sm",children:"Email Address"}
736),a.jsxs("div",{className:"relative",children:[a.jsx(Vh,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),a.jsx(rr,{id:"email",type:"email",placeholder:"[email protected]",value:f,onChange:$=>m($.target.value),className:"pl-10 h-11 input-enhanced",autoFocus:!0})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(hr,{htmlFor:"password",className:"text-foreground text-sm",children:"Password"}),a.jsxs("div",{className:"relative",children:[a.jsx($o,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),a.jsx(rr,{id:"password",type:_?"text":"password",placeholder:"••••••••",value:p,onChange:$=>x($.target.value),className:"pl-10 pr-10 h-11 input-enhanced",required:!0}),a.jsx("button",{type:"button",onClick:()=>b(!_),className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:_?a.jsx(Jc,{className:"w-4 h-4"}):a.jsx(Fh,{className:"w-4 h-4"})})]})]}),a.jsx(ye,{type:"submit",className:"w-full h-11 btn-primary-gradient text-base font-medium",disabled:A||!f,children:A?a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsxs("svg",{className:"animate-spin h-4 w-4",viewBox:"0 0 24 24",children:[a.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4",fill:"none"}),a.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Signing in..."]}):"Log In"}),a.jsx("div",{className:"text-center",children:a.jsx("button",{type:"button",className:"text-sm text-primary hover:underline",onClick:()=>s("/forgot-password"),children:"Forgotten password?"})}),a.jsxs("div",{className:"relative my-2",children:[a.jsx("div",{className:"absolute inset-0 flex items-center",children:a.jsx("span",{className:"w-full border-t border-border"})}),a.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:a.jsx("span",{className:"bg-background px-2 text-muted-foreground",children:"or"})})]}),a.jsx(ye,{type:"button",variant:"outline",className:"w-full h-11 text-base font-medium border-primary text-primary hover:bg-primary/10",onClick:()=>{h("signup"),x(""),b(!1)},children:"Create new account"})]})]}),u==="signup"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"text-center mb-6",children:[a.jsx("h2",{className:"text-xl font-display font-bold text-foreground",children:"Create your account"}),a.jsx("p",{className:"text-muted-foreground mt-1 text-sm",children:"Fill in your details to get started"})]}),a.jsxs("form",{onSubmit:X,className:"space-y-4",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsx(hr,{htmlFor:"signup-email",className:"text-foreground text-sm",children:"Email Address"}),a.jsxs("div",{className:"relative",children:[a.jsx(Vh,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),a.jsx(rr,{id:"signup-email",type:"email",placeholder:"[email protected]",value:f,onChange:$=>m($.target.value),className:"pl-10 h-11 input-enhanced",autoFocus:!0})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(hr,{htmlFor:"fullName",className:"text-foreground text-sm",children:"Full Name"}),a.jsxs("div",{className:"relative",children:[a.jsx(lE,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),a.jsx(rr,{id:"fullName",type:"text",placeholder:(l==null?void 0:l.fullname_placeholder)||"John Doe",value:y,onChange:$=>v(c($.target.value)),className:"pl-10 h-11 input-enhanced"})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(hr,{htmlFor:"signup-password",className:"text-foreground text-sm",children:"Password"}),a.jsxs("div",{className:"relative",children:[a.jsx($o,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),a.jsx(rr,{id:"signup-password",type:_?"text":"password",placeholder:"••••••••",value:p,onChange:$=>x($.target.value),className:"pl-10 pr-10 h-11 input-enhanced",required:!0}),a.jsx("button",{type:"button",onClick:()=>b(!_),className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:_?a.jsx(Jc,{className:"w-4 h-4"}):a.jsx(Fh,{className:"w-4 h-4"})})]}),D&&p.length>0&&a.jsx(XM,{password:p})]}),a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(uh,{id:"terms",checked:w,onCheckedChange:$=>T($),className:"mt-0.5"}),a.jsxs(hr,{htmlFor:"terms",className:"text-xs text-muted-foreground leading-relaxed",children:["I agree to the"," ",a.jsx("a",{href:"/terms",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"Terms"})," ","and"," ",a.jsx("a",{href:"/privacy",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"Privacy Policy"})]})]}),a.jsx(ye,{type:"submit",className:"w-full h-11 btn-primary-gradient text-base font-medium",disabled:A||D&&!F,children:A?a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsxs("svg",{className:"animate-spin h-4 w-4",viewBox:"0 0 24 24",children:[a.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4",fill:"none"}),a.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Creating account..."]}):"Create Account"}),a.jsxs("div",{className:"text-center text-sm text-muted-foreground",children:["Already have an account?"," ",a.jsx("button",{type:"button",onClick:()=>{h("login"),x(""),b(!1)},className:"text-primary font-medium hover:underline",children:"Sign in"})]})]})]})]})},sF=()=>{const{user:s,loading:e}=$t(),t=hs();g.useEffect(()=>{if(!e&&s){if(sessionStorage.getItem("signup_pending_verification"))return;const d=Ji();t(d||"/social",{replace:!0})}},[e,s,t]);const{data:r,isLoading:n}=Wt({queryKey:["homepage-settings-combined"],queryFn:async()=>{const{data:d,error:c}=await L.from("site_settings").select("setting_key, setting_value").in("setting_key",["brand","footer"]);if(c)throw c;return(d==null?void 0:d.reduce((u,h)=>(u[h.setting_key]=h.setting_value,u),{}))||{}},staleTime:10*60*1e3,gcTime:30*60*1e3}),i=r==null?void 0:r.brand,o=r==null?void 0:r.footer;bM({});const l=typeof window<"u"&&sessionStorage.getItem("signup_pending_verification");return e||s||l?a.jsx(pd,{}):a.jsxs("div",{className:"min-h-screen bg-background flex flex-col",children:[a.jsx(_M,{name:"Gradzen",url:"https://talentmatch-flow.lovable.app",logo:"https://talentmatch-flow.lovable.app/placeholder.svg",description:"Gradzen is your professional job marketplace. Connect with top employers, discover career opportunities, and hire exceptional talent."}),a.jsx("main",{className:"flex-1 flex items-center justify-center px-4 py-8",children:a.jsx("div",{className:"w-full max-w-5xl mx-auto",children:a.jsxs("div",{className:"flex flex-col lg:flex-row items-center lg:items-start justify-between gap-12 lg:gap-16",children:[a.jsx("div",{className:"text-center lg:text-left lg:flex-1 lg:pt-8",children:n?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center gap-3 justify-center lg:justify-start mb-4",children:[a.jsx(H,{className:"h-10 w-10 md:h-12 md:w-12 rounded-xl"}),a.jsx(H,{className:"h-10 w-40"})]}),a.jsx(H,{className:"h-8 w-72 mx-auto lg:mx-0"})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center gap-3 justify-center lg:justify-start mb-4",children:[(i==null?void 0:i.logo_url)&&a.jsx("img",{src:i.logo_url,alt:i==null?void 0:i.company_name,className:"h-10 w-10 md:h-12 md:w-12 rounded-xl object-contain"}),a.jsx("h1",{className:"text-3xl md:text-4xl lg:text-5xl font-display font-bold text-primary",children:(i==null?void 0:i.company_name)||"Gradzen"})]}),a.jsx("p",{className:"text-xl md:text-2xl text-foreground font-medium max-w-md mx-auto lg:mx-0",children:(i==null?void 0:i.tagline)||"Find Your Dream Job or Hire Top Talent"})]})}),a.jsx("div",{className:"w-full max-w-sm lg:flex-shrink-0",children:a.jsx("div",{className:"bg-card border border-border rounded-xl p-6 shadow-lg",children:a.jsx(tF,{})})})]})})}),a.jsx("footer",{className:"py-6 px-4 border-t border-border",children:a.jsxs("div",{className:"max-w-5xl mx-auto flex flex-col sm:flex-row items-center justify-between gap-4",children:[a.jsxs("nav",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-2 text-sm text-muted-foreground",children:[a.jsx(er,{to:"/terms",className:"hover:text-foreground transition-colors",children:"Terms"}),a.jsx("span",{className:"hidden sm:inline",children:"·"}),a.jsx(er,{to:"/privacy",className:"hover:text-foreground transition-colors",children:"Privacy"}),a.jsx("span",{className:"hidden sm:inline",children:"·"}),a.jsx(er,{to:"/community-guidelines",className:"hover:text-foreground transition-colors",children:"Community Guidelines"})]}),n?a.jsx(H,{className:"h-5 w-48"}):a.jsx("p",{className:"text-sm text-muted-foreground",children:(o==null?void 0:o.copyright_text)||`© ${new Date().getFullYear()} ${(i==null?void 0:i.company_name)||"Gradzen"}. All rights reserved.`})]})})]})},Xb=g.forwardRef(({className:s,...e},t)=>a.jsx("div",{ref:t,className:C("rounded-lg border bg-card text-card-foreground shadow-sm",s),...e}));
736Xb.displayName="Card";const rF=g.forwardRef(({className:s,...e},t)=>a.jsx("div",{ref:t,className:C("flex flex-col space-y-1.5 p-6",s),...e}));rF.displayName="CardHeader";const nF=g.forwardRef(({className:s,...e},t)=>a.jsx("h3",{ref:t,className:C("text-2xl font-semibold leading-none tracking-tight",s),...e}));nF.displayName="CardTitle";const iF=g.forwardRef(({className:s,...e},t)=>a.jsx("p",{ref:t,className:C("text-sm text-muted-foreground",s),...e}));iF.displayName="CardDescription";const Qb=g.forwardRef(({className:s,...e},t)=>a.jsx("div",{ref:t,className:C("p-6 pt-0",s),...e}));Qb.displayName="CardContent";const aF=g.forwardRef(({className:s,...e},t)=>a.jsx("div",{ref:t,className:C("flex items-center p-6 pt-0",s),...e}));aF.displayName="CardFooter";const oF=()=>{const s=br(),e=hs();g.useEffect(()=>{console.error("404 Error: User attempted to access non-existent route:",s.pathname)},[s.pathname]);const t=()=>{window.history.length>1?e(-1):e("/dashboard")},r=[{to:"/dashboard",icon:Es,label:"Browse Jobs"},{to:"/social",icon:Tn,label:"Social Feed"},{to:"/profile",icon:Ss,label:"My Profile"}];return a.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-background to-muted/30 flex flex-col",children:[a.jsx("div",{className:"p-4 sm:p-6",children:a.jsxs(ye,{variant:"ghost",size:"sm",onClick:t,className:"gap-2 text-muted-foreground hover:text-foreground",children:[a.jsx(yi,{className:"h-4 w-4"}),"Go back"]})}),a.jsx("div",{className:"flex-1 flex items-center justify-center px-4 pb-16",children:a.jsxs("div",{className:"text-center max-w-md w-full space-y-8",children:[a.jsxs("div",{className:"relative mx-auto w-32 h-32",children:[a.jsx("div",{className:"absolute inset-0 bg-primary/10 rounded-full animate-pulse"}),a.jsx("div",{className:"absolute inset-2 bg-primary/5 rounded-full flex items-center justify-center",children:a.jsx(Jw,{className:"h-16 w-16 text-primary/60"})})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("h1",{className:"text-6xl sm:text-7xl font-bold text-primary/80",children:"404"}),a.jsx("h2",{className:"text-2xl sm:text-3xl font-semibold text-foreground",children:"Page Not Found"}),a.jsx("p",{className:"text-muted-foreground text-base sm:text-lg max-w-sm mx-auto",children:"The page you're looking for doesn't exist or may have been moved."})]}),a.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 justify-center",children:[a.jsxs(ye,{variant:"outline",size:"lg",onClick:t,className:"gap-2",children:[a.jsx(yi,{className:"h-4 w-4"}),"Go Back"]}),a.jsxs(ye,{size:"lg",onClick:()=>e("/"),className:"gap-2",children:[a.jsx(ua,{className:"h-4 w-4"}),"Go to Home"]})]}),a.jsx(Xb,{className:"bg-card/50 border-border/50",children:a.jsxs(Qb,{className:"p-6",children:[a.jsx("p",{className:"text-sm font-medium text-muted-foreground mb-4",children:"Looking for something? Try these:"}),a.jsx("div",{className:"flex flex-wrap justify-center gap-2",children:r.map(n=>a.jsx(er,{to:n.to,children:a.jsxs(ye,{variant:"secondary",size:"sm",className:"gap-2",children:[a.jsx(n.icon,{className:"h-4 w-4"}),n.label]})},n.to))})]})}),a.jsxs("p",{className:"text-xs text-muted-foreground/50",children:["Requested: ",s.pathname]})]})})]})},lF=g.lazy(()=>M(()=>import("./Dashboard-BNaOI6f7.js"),__vite__mapDeps([67,1,2,3,68,48,69,18,16,17,20,21,22,23,24,25,26,27,11,12,28,70,29,71,72,73,39,74,40,13,43,31,32,45,42,46,57,75,76,77,78,5,6,7,8,50,58,47,51,52,53,79,41,35,80,59]))),cF=g.lazy(()=>M(()=>import("./SocialFeed-ZU-nwGdt.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59]))),dF=g.lazy(()=>M(()=>import("./Reels-DAyEXCdz.js"),__vite__mapDeps([60,1,61,16,3,17,25,27,26,62,2,63,32,21,64,45,22,58,65,66,20,23,59]))),uF=g.lazy(()=>M(()=>import("./MobileMenu-BXWOBUOQ.js"),__vite__mapDeps([155,1,2,3,79,14,42,46,59]))),hF=g.lazy(()=>M(()=>import("./Profile-C3xP_qzj.js"),__vite__mapDeps([160,1,161,162,163,164,3,59,2,165,83,58,76,16,17,68,166,150,149,96,97,98,117,137,63,82,55,85,15,18,19,20,21,22,23,24,25,26,27,11,12,28,8,29,30,31,32,33,34,35,9,36,37,38,39,40,41,42,43,13,44,45,46,153,84,167,101,127,77,47,168,169,126,66,144,116]))),qp=g.lazy(()=>M(()=>import("./Messenger-yqI0Jz-Q.js"),__vite__mapDeps([170,1,3,2,59]))),fF=g.lazy(()=>M(()=>import("./MyNetwork-BteNVmKD.js"),__vite__mapDeps([81,1,2,3,23,82,33,29,56,83,55,48,79,84,85,59]))),mF=g.lazy(()=>M(()=>import("./AppliedJobs-CWxbHjgD.js"),__vite__mapDeps([171,1,23,3,16,17,70,48,2,28,12,22,79,73,11,137,147,100,105,59]))),pF=g.lazy(()=>M(()=>import("./JobDetail-DfEO-WCi.js"),__vite__mapDeps([172,1,35,2,3,69,18,16,17,20,21,22,23,24,25,26,27,11,12,28,70,29,71,72,73,39,74,40,13,43,31,32,45,42,46,80,59]))),gF=g.lazy(()=>M(()=>import("./AdminOverview-1lE2SYer.js"),__vite__mapDeps([225,1,226,157,132,59,3,144,2]))),Hp=g.lazy(()=>M(()=>import("./AdminUsers-26t8tN7y.js"),__vite__mapDeps([227,1,226,157,16,3,17,26,13,21,22,59,2]))),Kp=g.lazy(()=>M(()=>import("./AdminJobs-4fmOvpmI.js"),__vite__mapDeps([228,1,2,3,226,5,6,7,8,157,229,63,59,73,11,28,12,39,51,52,53,13,146,22]))),xF=g.lazy(()=>M(()=>
736import("./AlgorithmDebug-CuH3bqWP.js"),__vite__mapDeps([237,1,226,157,39,2,3,51,52,53,229,63,59,73,11,28,12,13]))),Wp=g.lazy(()=>M(()=>import("./AdminApplications-DhOk0KlE.js"),__vite__mapDeps([230,1,226,157,3,59,2]))),vo=g.lazy(()=>M(()=>import("./AptitudeCategories-C2brYh-E.js"),__vite__mapDeps([238,1,226,157,2,3,90,45,22,59]))),Yp=g.lazy(()=>M(()=>import("./AptitudeQuestions-CAvOfhEn.js"),__vite__mapDeps([239,1,226,25,3,17,201,23,149,66,64,22,157,2,90,45,59]))),Xp=g.lazy(()=>M(()=>import("./PersonalityGameSettings-Ch-bBoGH.js"),__vite__mapDeps([240,1,226,2,3,142,128,59]))),Qp=g.lazy(()=>M(()=>import("./PersonalityTraitSections-BjON4Lsa.js"),__vite__mapDeps([241,1,226,2,3,139,142,59]))),Jp=g.lazy(()=>M(()=>import("./PersonalityTraitQuestions-CgcpEjqG.js"),__vite__mapDeps([242,1,226,201,23,3,149,66,64,2,139,22,142,59]))),Zp=g.lazy(()=>M(()=>import("./PersonalityGameOverview-DmzZOk9I.js"),__vite__mapDeps([243,1,226,157,58,3,244,59,2]))),eg=g.lazy(()=>M(()=>import("./AdminSecuritySettings-D9BlDgSM.js"),__vite__mapDeps([245,1,226,13,3,59,2]))),tg=g.lazy(()=>M(()=>import("./BrandSettings-CxMHCmai.js"),__vite__mapDeps([246,1,226,66,3,59,2]))),sg=g.lazy(()=>M(()=>import("./FooterSettings-DC0hT0WE.js"),__vite__mapDeps([247,1,226,3,59,2]))),rg=g.lazy(()=>M(()=>import("./LegalSettings-COqb77v3.js"),__vite__mapDeps([248,1,226,23,3,76,59,2]))),yF=g.lazy(()=>M(()=>import("./CertificateSettings-B4t60f7h.js"),__vite__mapDeps([249,1,226,66,142,3,59,2]))),vF=g.lazy(()=>M(()=>import("./MaintenanceMode-CAWeKOb-.js"),__vite__mapDeps([250,1,226,12,142,3,59,2]))),bF=g.lazy(()=>M(()=>import("./DatabaseBackup-CMY1mEFQ.js"),__vite__mapDeps([251,1,226,157,58,3,13,66,144,119,59,2]))),_F=g.lazy(()=>M(()=>import("./AISettings-DheFLKm0.js"),__vite__mapDeps([252,1,226,25,3,17,13,122,59,2]))),wF=g.lazy(()=>M(()=>import("./FeedAlgorithmSettings-Ci_jjvnK.js"),__vite__mapDeps([253,1,157,134,59,3,142,2]))),EF=g.lazy(()=>M(()=>import("./CrossLearningDashboard-OgcvbAek.js"),__vite__mapDeps([254,1,23,3,157,63,143,142,59,136,148,2]))),SF=g.lazy(()=>M(()=>import("./AdminReports-CUyboH12.js"),__vite__mapDeps([255,1,226,157,2,3,59]))),TF=g.lazy(()=>M(()=>import("./ReportedJobs-DRZSpqFl.js"),__vite__mapDeps([256,1,226,157,13,22,26,27,3,59,2]))),AF=g.lazy(()=>M(()=>import("./AdminAppeals-BcmDuS8b.js"),__vite__mapDeps([257,1,226,157,2,3,59]))),kF=g.lazy(()=>M(()=>import("./AdminAppealDetail-WP3TBmMs.js"),__vite__mapDeps([258,1,226,2,3,12,59]))),RF=g.lazy(()=>M(()=>import("./ContentModeration-CZ0a_agO.js"),__vite__mapDeps([259,1,226,23,3,157,2,95,77,26,59]))),jF=g.lazy(()=>M(()=>import("./UsernameSettings-BiakSltG.js"),__vite__mapDeps([260,1,226,2,3,142,59]))),IF=g.lazy(()=>M(()=>import("./VerifiedUsers-UaMeWBFf.js"),__vite__mapDeps([261,1,226,157,23,3,59,2]))),ng=g.lazy(()=>M(()=>import("./VerifiedPages-D1EeOxo_.js"),__vite__mapDeps([262,1,226,157,23,3,59,2]))),CF=g.lazy(()=>M(()=>import("./BroadcastNotifications-BOkLsv_L.js"),__vite__mapDeps([263,1,226,25,3,17,157,13,59,2]))),NF=g.lazy(()=>M(()=>import("./ProjectDisputes-rronfLe3.js"),__vite__mapDeps([264,1,157,2,3,59]))),LF=g.lazy(()=>M(()=>import("./ProjectDisputeDetail-DkABke9F.js"),__vite__mapDeps([265,1,2,3,59]))),PF=g.lazy(()=>M(()=>import("./MarketplaceProjects-ChhLmP1Q.js"),__vite__mapDeps([266,1,23,3,2,9,12,11,59]))),DF=g.lazy(()=>M(()=>import("./MentorshipModeration-BNbkavg4.js"),__vite__mapDeps([267,1,2,3,23,97,105,104,88,59]))),OF=g.lazy(()=>M(()=>import("./AdReview-lcCDDbXU.js"),__vite__mapDeps([268,1,23,3,65,116,28,43,12,42,59,2]))),MF=g.lazy(()=>M(()=>import("./AdminAnalytics-DzcgrZc9.js"),__vite__mapDeps([269,1,226,244,59,3,55,2]))),FF=g.lazy(()=>M(()=>import("./PersonalityGameLanding-C-NmgL_d.js"),__vite__mapDeps([197,1,2,3,175,117,128,47,43,148,59]))),$F=g.lazy(()=>M(()=>import("./PersonalityResults-BWSnxO2v.js"),__vite__mapDeps([198,1,58,3,2,175,47,43,126,59]))),UF=g.lazy(()=>M(()=>import("./TestSubmission-CC2WddVq.js"),__vite__mapDeps([199,1,58,3,157,2,6,7,175,47,12,59]))),BF=g.lazy(()=>M(()=>import("./AvailableTests-wAAUOx7k.js"),__vite__mapDeps([196,1,184,73,11,28,12,2,3,105,59]))),VF=g.lazy(()=>M(()=>import("./PipelineOverview-qFScsTqe.js"),__vite__mapDeps([188,1,2,3,137,147,59]))),ig=g.lazy(()=>M(()=>import("./AccountSettings-Qem27ryN.js"),__vite__mapDeps([185,1,186,25,3,17,66,101,47,12,59,2]))),GF=g.lazy(()=>M(()=>
736import("./AccountDeletion-Bnh71sDD.js"),__vite__mapDeps([194,1,2,3,22,59]))),ag=g.lazy(()=>M(()=>import("./SecuritySettings-sNpBDMJy.js"),__vite__mapDeps([187,1,2,3,59]))),zF=g.lazy(()=>M(()=>import("./HiddenJobs-DAelIQT8.js"),__vite__mapDeps([189,1,2,3,11,28,12,59]))),qF=g.lazy(()=>M(()=>import("./RequestVerification-B3z2ZAnD.js"),__vite__mapDeps([195,1,3,59,2]))),HF=g.lazy(()=>M(()=>import("./BlockedUsers-DK3WQPjk.js"),__vite__mapDeps([190,1,2,3,26,59]))),KF=g.lazy(()=>M(()=>import("./ActivityLog-DwIrHkUf.js"),__vite__mapDeps([191,1,16,3,17,2,122,130,46,85,55,37,63,10,21,22,5,6,7,8,115,12,192,193,59]))),WF=g.lazy(()=>M(()=>import("./SavedItems-Bxbh2hEo.js"),__vite__mapDeps([270,1,23,3,40,2,46,22,59]))),YF=g.lazy(()=>M(()=>import("./AptitudeTests-BE2ljUNm.js"),__vite__mapDeps([158,1,16,3,17,2,12,22,59]))),og=g.lazy(()=>M(()=>import("./CreateAptitudeTest-Bp_3yJSe.js"),__vite__mapDeps([200,1,2,3,23,201,149,66,64,118,22,142,138,59]))),XF=g.lazy(()=>M(()=>import("./JobAnalytics-C-VyCni3.js"),__vite__mapDeps([156,1,157,2,3,43,59,90]))),QF=g.lazy(()=>M(()=>import("./LearningCenter-Cg9e6b86.js"),__vite__mapDeps([159,1,147,43,126,3,59,2]))),JF=g.lazy(()=>M(()=>import("./PipelineJobs-DF4i2Uc_.js"),__vite__mapDeps([202,1,2,3,78,5,6,7,8,12,11,59]))),ZF=g.lazy(()=>M(()=>import("./ActivityLog-DveGrEyN.js"),__vite__mapDeps([203,1,193,3,59,2]))),e$=g.lazy(()=>M(()=>import("./BoostCampaigns-i8N2GdFk.js"),__vite__mapDeps([204,1,23,3,41,58,42,135,28,2,65,116,59]))),lg=g.lazy(()=>M(()=>import("./CreateBoost-CS49hnXy.js"),__vite__mapDeps([205,1,25,3,17,83,41,157,2,175,148,42,28,143,12,43,116,47,65,59]))),t$=g.lazy(()=>M(()=>import("./BoostAnalytics-BW-4WLYv.js"),__vite__mapDeps([271,1,23,3,2,28,135,59]))),s$=g.lazy(()=>M(()=>import("./BoostDisputes-B0PNV7Ky.js"),__vite__mapDeps([272,1,273,41,2,3,59]))),r$=g.lazy(()=>M(()=>import("./AdDisputes-BMlDP_Dv.js"),__vite__mapDeps([274,1,273,2,3,59]))),n$=g.lazy(()=>M(()=>import("./DocsAds-BdHJR5QA.js"),__vite__mapDeps([275,1,157,124,43,134,148,3,59,2]))),i$=g.lazy(()=>M(()=>import("./DocsAdsAnalytics-jhaDcXnl.js"),__vite__mapDeps([276,1,226,42,28,148,124,43,135,47,3,59,2]))),a$=g.lazy(()=>M(()=>import("./DocsMarketplaceEscrow-h9IMLbxW.js"),__vite__mapDeps([277,1,226,42,28,43,47,124,14,148,3,59,2]))),o$=g.lazy(()=>M(()=>import("./DocsLearningRevenue-CbzEE7CS.js"),__vite__mapDeps([278,1,226,157,42,28,43,148,47,3,59,2]))),l$=g.lazy(()=>M(()=>import("./DocsProfileMatch-DrKUbsok.js"),__vite__mapDeps([279,1,226,157,42,148,28,43,126,3,59,2]))),c$=g.lazy(()=>M(()=>import("./DocsTotalRevenue-B__X4URw.js"),__vite__mapDeps([280,1,226,157,2,3,42,47,133,148,43,14,59]))),d$=g.lazy(()=>M(()=>import("./WalletAdmin-CbYIGBij.js"),__vite__mapDeps([281,1,226,157,14,28,58,3,53,11,2,25,17,129,142,59]))),u$=g.lazy(()=>M(()=>import("./WalletTransactions-Dmcd9PV5.js"),__vite__mapDeps([282,1,226,157,3,59,2]))),h$=g.lazy(()=>M(()=>import("./WalletInvoices-DNHc1Iga.js"),__vite__mapDeps([283,1,226,157,115,3,59,2]))),f$=g.lazy(()=>M(()=>import("./RegionalPricing-DFeoqrQl.js"),__vite__mapDeps([284,1,226,157,22,47,93,140,99,13,142,143,53,124,3,59,2]))),m$=g.lazy(()=>M(()=>import("./RevenueOverview-CCwuIDzm.js"),__vite__mapDeps([285,1,226,157,58,3,167,175,28,14,140,47,114,59,2]))),p$=g.lazy(()=>M(()=>import("./IdentityVerifications-6c4URMKx.js"),__vite__mapDeps([286,1,157,186,3,59,2]))),g$=g.lazy(()=>M(()=>import("./PaymentProviderSettings-BosIYRKc.js"),__vite__mapDeps([287,1,157,14,3,59,2]))),x$=g.lazy(()=>M(()=>import("./CloudStorageSettings-XbOQbmRL.js"),__vite__mapDeps([288,1,157,142,119,3,59,2]))),y$=g.lazy(()=>M(()=>import("./PaymentVerification-D4WGt834.js"),__vite__mapDeps([289,1,23,3,157,59,2]))),v$=g.lazy(()=>M(()=>import("./PaymentMethodSettings-VnVWp1O-.js"),__vite__mapDeps([290,1,142,3,59,2]))),b$=g.lazy(()=>M(()=>import("./WithdrawalRequests-BeK3uOlO.js"),__vite__mapDeps([291,1,23,3,157,16,17,21,103,26,59,2]))),_$=g.lazy(()=>M(()=>import("./EscrowManagement-DgfRuuc7.js"),__vite__mapDeps([292,1,157,16,3,17,89,21,59,2]))),w$=g.lazy(()=>M(()=>import("./ExpertDashboard-DdMDTies.js"),__vite__mapDeps([233,1,226,2,3,59]))),E$=g.lazy(()=>M(()=>import("./MyReports-DrqQKDat.js"),__vite__mapDeps([206,1,2,3,59]))),cg=g.lazy(()=>M(()=>import("./ReportDetail-BvRc1Wwg.js"),__vite__mapDeps([207,1,208,149,2,3,59]))),S$=g.lazy(()=>M(()=>import("./BillingSummary-DbSLbKy3.js"),__vite__mapDeps([173,1,2,3,157,93,14,13,58,12,174,47,25,17,22,107,92,175,167,59,74]))
736),T$=g.lazy(()=>M(()=>import("./PaymentSettings-B6J7Pd8C.js"),__vite__mapDeps([176,1,74,174,12,3,59,2]))),A$=g.lazy(()=>M(()=>import("./Invoices-JHXpEZ1s.js"),__vite__mapDeps([177,1,157,74,178,151,14,3,59,2]))),k$=g.lazy(()=>M(()=>import("./Transactions-tvOqtdNG.js"),__vite__mapDeps([179,1,157,23,3,74,178,151,125,59,2]))),R$=g.lazy(()=>M(()=>import("./MyProjects-CFOeczPy.js"),__vite__mapDeps([181,1,2,3,23,58,14,12,59]))),j$=g.lazy(()=>M(()=>import("./BrowseProjects-YzFHJteO.js"),__vite__mapDeps([180,1,34,35,2,3,9,36,28,37,38,11,12,4,5,6,7,8,10,13,14,23,94,59]))),I$=g.lazy(()=>M(()=>import("./MentorshipDetail-O9MQZ4xl.js"),__vite__mapDeps([293,1,153,97,74,2,3,43,98,123,145,59]))),C$=g.lazy(()=>M(()=>import("./MentorshipManage-Bn5-TMBW.js"),__vite__mapDeps([294,1,2,3,23,153,97,154,25,17,147,66,22,58,77,127,74,14,59]))),N$=g.lazy(()=>M(()=>import("./Courses-G4zYTDmd.js"),__vite__mapDeps([86,1,23,3,87,58,88,89,90,47,91,92,26,93,94,46,95,52,10,96,97,2,98,99,100,12,101,102,8,103,104,105,17,106,107,108,62,14,109,28,110,21,111,112,113,27,114,65,115,116,32,117,118,119,63,120,13,121,122,123,124,125,126,29,64,127,128,75,129,130,11,131,132,133,134,135,136,137,138,139,45,140,77,30,141,72,42,142,143,37,144,145,43,31,146,22,53,66,85,55,147,148,149,150,151,152,153,154,25,59]))),L$=g.lazy(()=>M(()=>import("./MyCourses-FzknNj7L.js"),__vite__mapDeps([182,1,87,58,3,151,152,2,59]))),P$=g.lazy(()=>M(()=>import("./CourseDetail-Cq7kP4T7.js"),__vite__mapDeps([209,1,210,152,58,3,211,212,213,2,129,151,59]))),D$=g.lazy(()=>M(()=>import("./CourseWatch-B45U_m6R.js"),__vite__mapDeps([214,1,210,23,3,58,211,215,66,113,111,88,38,216,2,212,213,151,75,8,59]))),O$=g.lazy(()=>M(()=>import("./TakeQuiz-Du_VYwcU.js"),__vite__mapDeps([295,1,58,3,25,17,216,296,2,8,59]))),M$=g.lazy(()=>M(()=>import("./QuizResults-BKXf9DVV.js"),__vite__mapDeps([297,1,58,3,216,2,17,59]))),F$=g.lazy(()=>M(()=>import("./TakeFinalExam-CcO9Tupk.js"),__vite__mapDeps([298,1,25,3,17,58,212,2,47,59]))),$$=g.lazy(()=>M(()=>import("./FinalExamResults-B2grBRLf.js"),__vite__mapDeps([299,1,58,3,68,212,213,151,12,37,2,47,59]))),U$=g.lazy(()=>M(()=>import("./CourseManagement-BuY28AYE.js"),__vite__mapDeps([231,1,226,157,16,3,17,232,66,64,147,22,2,28,21,59]))),B$=g.lazy(()=>M(()=>import("./CourseLessons-tg53g2ge.js"),__vite__mapDeps([300,1,226,23,3,157,16,17,25,210,232,215,66,21,22,112,113,76,12,118,58,212,142,301,71,151,13,2,64,59]))),V$=g.lazy(()=>M(()=>import("./CourseCategories-DCynrieg.js"),__vite__mapDeps([302,1,226,157,145,22,3,59,2]))),G$=g.lazy(()=>M(()=>import("./TrainerRoyalties-B2eR1Bi5.js"),__vite__mapDeps([303,1,226,157,192,7,28,99,13,3,59,2]))),z$=g.lazy(()=>M(()=>import("./TrainerApplications-CIh3B2qe.js"),__vite__mapDeps([304,1,226,23,3,77,12,59,2]))),q$=g.lazy(()=>M(()=>import("./TrainerDashboard-BkXx-MR-.js"),__vite__mapDeps([234,1,28,3,59,2]))),H$=g.lazy(()=>M(()=>import("./TrainerCourses-CzYGizht.js"),__vite__mapDeps([235,1,140,12,3,59,2]))),K$=g.lazy(()=>M(()=>import("./TrainerEarnings-DmomXfzX.js"),__vite__mapDeps([236,1,157,93,28,13,3,59,2]))),W$=()=>{const{slug:s}=M_();return a.jsx(da,{to:`/page/${s}`,replace:!0})},Y$=g.lazy(()=>M(()=>import("./SignupSuccess-BDyUM5mf.js"),__vite__mapDeps([305,1,2,3,47,59]))),X$=g.lazy(()=>M(()=>import("./ResendVerification-Bclpq6NZ.js"),__vite__mapDeps([306,1,2,3,59]))),Q$=g.lazy(()=>M(()=>import("./VerifyEmail-B7bBK4Rt.js"),__vite__mapDeps([307,1,2,3,308,110,59]))),J$=g.lazy(()=>M(()=>import("./ForgotPassword-BW4nkqXw.js"),__vite__mapDeps([309,1,2,3,47,59]))),Z$=g.lazy(()=>M(()=>import("./ResetPassword-CKSoSe16.js"),__vite__mapDeps([310,1,2,3,308,110,121,59]))),e4=g.lazy(()=>M(()=>import("./EnableHRAccess-BxYQCePu.js"),__vite__mapDeps([222,1,2,3,59]))),t4=g.lazy(()=>M(()=>import("./Applicants-B9CeaZag.js"),__vite__mapDeps([223,1,2,3,161,169,11,58,12,43,142,23,55,109,115,140,148,77,59]))),s4=g.lazy(()=>M(()=>import("./CandidateProfile-Dodty7S4.js"),__vite__mapDeps([224,1,163,161,162,168,169,164,3,59,2,77,11,127,12]))),r4=g.lazy(()=>M(()=>import("./SharedCV-acPfWURF.js"),__vite__mapDeps([311,1,162,163,2,3,77,11,127,12,116,59]))),n4=g.lazy(()=>M(()=>import("./CVBuilder-BYi6bmat.js"),__vite__mapDeps([312,1,164,162,3,59,2,108,166,150,149,142,120,37,22,101,77,11,127,29]))),i4=g.lazy(()=>M(()=>import("./SharedCVPage-CneQdgPH.js"),__vite__mapDeps([313,1,164,162,3,59,2]))),a4=g.lazy(()=>M(()=>import("./CVThemes-BLrY6dvL.js"),__vite__mapDeps([314,1,164,162,3,59,2,45]))),dg=g.lazy(()=>M(()=>import("./CVThemeBuilder-DSaTQEht.js"),__vite__mapDeps([315,1,3,118,108,131,164,162,59,2,150,149,66,142]))),o4=g.lazy(()=>M(()=>import("./CustomQuestions-BljjlDdO.js"),__vite__mapDeps([316,1,2,3,142,118,22,59]))),l4=g.lazy(()=>M(()=>import("./SectionQuestions-C7lOn7dM.js"),__vite__mapDeps([317,1,2,3,142,118,22,59]))),c4=g.lazy(()=>M(()=>import("./TestResults-B_IcikT8.js"),__vite__mapDeps([318,1,58,3,157,2,115,92,132,59]))),d4=g.lazy(()=>M(()=>import("./StageAdvancement-fpp4m2rY.js"),__vite__mapDeps([319,1,2,3,137,11,147,12,64,141,59]))),u4=g.lazy(()=>M(()=>import("./FGDSetup-DNqKCk3a.js"),__vite__mapDeps([320,1,23,3,118,45,22,91,12,11,105,8,142,47,157,137,147,64,141,115,90,2,128,106,59]))),h4=g.lazy(()=>M(()=>import("./InterviewBoardSetup-BnK-AdCe.js"),__vite__mapDeps([321,1,2,3,23,118,45,22,55,76,12,11,106,8,142,157,92,128,59]))),f4=g.lazy(()=>M(()=>import("./TakeTest-BNVh8HTB.js"),__vite__mapDeps([322,1,58,3,25,17,208,149,296,2,8,59]))),m4=g.lazy(()=>M(()=>import("./TestResultsView-6JrCBGqR.js"),__vite__mapDeps([323,1,58,3,2,59]))),p4=g.lazy(()=>M(()=>import("./TakePersonalityGame-CtaNHGol.js"),__vite__mapDeps([324,1,58,3,296,68,2,8,59]))),g4=g.lazy(()=>M(()=>import("./PersonalityGameResults-Cs5XRLKd.js"),__vite__mapDeps([325,1,58,3,2,132,59]))),x4=g.lazy(()=>M(()=>import("./TermsOfService-CC8KYLgK.js"),__vite__mapDeps([326,1,2,3,59]))),y4=g.lazy(()=>M(()=>import("./PrivacyPolicy-COQBal_h.js"),__vite__mapDeps([327,1,2,3,59]))),v4=g.lazy(()=>M(()=>import("./AccountLocked-CvJgZuvA.js"),__vite__mapDeps([328,1,2,3,12,59]))),b4=g.lazy(()=>M(()=>import("./CommunityGuidelines-tBX2u6Id.js"),__vite__mapDeps([329,1,2,3,59])));g.lazy(()=>M(()=>import("./PublicProfile-7EclJQr1.js"),__vite__mapDeps([220,1,2,3,165,83,58,76,16,17,68,166,150,149,96,97,98,117,137,63,82,55,85,15,18,19,20,21,22,23,24,25,26,27,11,12,28,8,29,30,31,32,33,34,35,9,36,37,38,39,40,41,42,43,13,44,45,46,153,84,167,101,127,77,47,59,168,169,126,66,144,116])));const ug=g.lazy(()=>M(()=>import("./ProfileDispatcher-C7tQgw2z.js"),__vite__mapDeps([221,1,2,3,160,161,162,163,164,59,165,83,58,76,16,17,68,166,150,149,96,97,98,117,137,63,82,55,85,15,18,19,20,21,22,23,24,25,26,27,11,12,28,8,29,30,31,32,33,34,35,9,36,37,38,39,40,41,42,43,13,44,45,46,153,84,167,101,127,77,47,168,169,126,66,144,116,220]))),_4=g.lazy(()=>M(()=>import("./PostDetail-D_w8BcD9.js"),__vite__mapDeps([217,1,19,20,16,3,17,2,21,22,23,24,25,26,27,11,12,28,8,29,33,31,32,59]))),w4=g.lazy(()=>M(()=>import("./ProjectDetail-82L50UxW.js"),__vite__mapDeps([218,1,35,2,3,9,36,28,37,38,11,12,59]))),hg=g.lazy(()=>M(()=>import("./UserActivity-DPYRPbJb.js"),__vite__mapDeps([219,1,15,16,3,17,18,19,20,2,21,22,23,24,25,26,27,11,12,28,8,29,30,31,32,33,34,35,9,36,37,38,39,40,41,42,43,13,44,45,46,48,59]))),E4=g.lazy(()=>M(()=>import("./SearchResults-DhxgGN33.js"),__vite__mapDeps([183,1,2,3,23,11,83,184,73,28,12,59]))),S4=g.lazy(()=>M(()=>import("./UserJourney-hhPBa87C.js"),__vite__mapDeps([330,1,2,3,57,55,102,147,141,43,137,115,47,14,37,63,22,59]))),T4=g.lazy(()=>M(()=>import("./CertificateVerify-pf2PaX8X.js"),__vite__mapDeps([331,1,213,301,2,3,10,12,59]))),A4=g.lazy(()=>M(()=>import("./BecomeTeacher-CPa2DBiv.js"),__vite__mapDeps([332,1,2,3,28,59]))),k4=g.lazy(()=>M(()=>import("./CreatePage-BVDzHRPp.js"),__vite__mapDeps([333,1,2,3,44,59]))),R4=g.lazy(()=>M(()=>import("./PageProfile-Y6RNxOQI.js"),__vite__mapDeps([334,1,2,3,335,44,15,16,17,18,19,20,21,22,23,24,25,26,27,11,12,28,8,29,30,31,32,33,34,35,9,36,37,38,39,40,41,42,43,13,45,46,84,49,61,69,70,71,72,73,74,144,83,77,59]))),j4=g.lazy(()=>M(()=>import("./DiscoverPages-BIlawh6i.js"),__vite__mapDeps([336,1,54,44,2,3,55,59]))),I4=g.lazy(()=>M(()=>import("./PageSettings-DydVm4-z.js"),__vite__mapDeps([337,1,2,3,44,23,338,335,244,59,166,150,149,101,55,109,45,22]))),C4=g.lazy(()=>M(()=>import("./PageAnalytics-ReRVFCCK.js"),__vite__mapDeps([339,1,44,338,335,244,59,3,2])));function N4(){const{isOnline:s,wasOffline:e}=Hb();return vM(),a.jsxs(a.Fragment,{children:[a.jsx(ZD,{isOnline:s,wasOffline:e}),a.jsx(yM,{}),a.jsxs(Vo,{children:[a.jsx(KE,{}),a.jsx(RS,{}),a.jsxs(D_,{children:[a.jsx(lk,{children:a.jsx(dk,{children:a.jsx(g.Suspense,{fallback:a.jsx(O0,{}),children:a.jsxs(O_,{children:[a.jsx(V,{path:"/",element:a.jsx(sF,{})}),a.jsx(V,{path:"/auth",element:a.jsx(da,{to:"/",replace:!0})}),a.jsx(V,{path:"/terms",element:a.jsx(x4,{})}),a.jsx(V,{path:"/privacy",element:a.jsx(y4,{})}),a.jsx(V,{path:"/signup-success",element:a.jsx(Y$,{})}),a.jsx(V,{path:"/verify-email",element:a.jsx(Q$,{})}),a.jsx(V,{path:"/resend-verification",element:a.jsx(X$,{})}),a.jsx(V,{path:"/forgot-password",element:a.jsx(J$,{})}),a.jsx(V,{path:"/reset-password",element:a.jsx(Z$,{})}),a.jsx(V,{path:"/cv/:shareToken",element:a.jsx(r4,{})}),a.jsx(V,{path:"/cv/s/:shareToken",element:a.jsx(i4,{})}),a.jsx(V,{path:"/account-locked",element:a.jsx(v4,{})}),a.jsx(V,{path:"/community-guidelines",element:a.jsx(b4,{})}),a.jsx(V,{path:"/user-journey",element:a.jsx(S4,{})}),a.jsx(V,{path:"/become-teacher",element:a.jsx(A4,{})}),a.jsx(V,{path:"/verify/:certificateNumber",element:a.jsx(T4,{})}),a.jsx(V,{path:"/job/:jobId",element:a.jsx(pF,{})}),a.jsx(V,{path:"/cv/themes/builder",element:a.jsx(dg,{})}),a.jsx(V,{path:"/cv/themes/builder/:id",element:a.jsx(dg,{})}),a.jsxs(V,{element:a.jsx(JD,{children:a.jsx(Qj,{children:a.jsx(KD,{})})}),children:[a.jsx(V,{path:"/settings/enable-hr",element:a.jsx(e4,{})}),a.jsx(V,{path:"/reels",element:a.jsx(dF,{})}),a.jsx(V,{path:"/dashboard",element:a.jsx(lF,{})}),a.jsx(V,{path:"/profile",element:a.jsx(hF,{})}),a.jsx(V,{path:"/applied-jobs",element:a.jsx(mF,{})}),a.jsx(V,{path:"/applicants/:jobId",element:a.jsx(t4,{})}),a.jsx(V,{path:"/applicants/:jobId/advance-stage",element:a.jsx(d4,{})}),a.jsx(V,{path:"/applicants/:jobId/candidate/:applicantId",element:a.jsx(s4,{})}),a.jsx(V,{path:"/cv/builder/:cvId",element:a.jsx(n4,{})}),a.jsx(V,{path:"/cv/themes",element:a.jsx(a4,{})}),a.jsx(V,{path:"/admin",element:a.jsx(Te,{children:a.jsx(gF,{})})}),a.jsx(V,{path:"/admin/analytics",element:a.jsx(Te,{children:a.jsx(MF,{})})}),a.jsx(V,{path:"/admin/users",element:a.jsx(Te,{children:a.jsx(Hp,{})})}),a.jsx(V,{path:"/admin/verified-users",element:a.jsx(Te,{children:a.jsx(IF,{})})}),a.jsx(V,{path:"/admin/verified-pages",element:a.jsx(Te,{children:a.jsx(ng,{})})}),a.jsx(V,{path:"/admin/jobs",element:a.jsx(Te,{children:a.jsx(Kp,{})})}),a.jsx(V,{path:"/admin/algorithm-debug",element:a.jsx(Te,{children:a.jsx(xF,{})})}),a.jsx(V,{path:"/admin/applications",element:a.jsx(Te,{children:a.jsx(Wp,{})})}),a.jsx(V,{path:"/admin/security",element:a.jsx(Te,{children:a.jsx(eg,{})})}),a.jsx(V,{path:"/admin/maintenance",element:a.jsx(Te,{children:a.jsx(vF,{})})}),a.jsx(V,{path:"/admin/database-backup",element:a.jsx(Te,{children:a.jsx(bF,{})})}),a.jsx(V,{path:"/admin/ai-settings",element:a.jsx(Te,{children:a.jsx(_F,{})})}),a.jsx(V,{path:"/admin/reports",element:a.jsx(Te,{children:a.jsx(SF,{})})}),a.jsx(V,{path:"/admin/reports/:reportId",element:a.jsx(Te,{children:a.jsx(cg,{isAdmin:!0})})}),a.jsx(V,{path:"/admin/community/reported-jobs",element:a.jsx(Te,{children:a.jsx(TF,{})})}),a.jsx(V,{path:"/admin/community/content-moderation",element:a.jsx(Te,{children:a.jsx(RF,{})})}),a.jsx(V,{path:"/admin/community/username-settings",element:a.jsx(Te,{children:a.jsx(jF,{})})}),a.jsx(V,{path:"/admin/appeals",element:a.jsx(Te,{children:a.jsx(AF,{})})}),a.jsx(V,{path:"/admin/broadcast",element:a.jsx(Te,{children:a.jsx(CF,{})})}),a.jsx(V,{path:"/admin/appeals/:appealId",element:a.jsx(Te,{children:a.jsx(kF,{})})}),a.jsx(V,{path:"/admin/customization/brand",element:a.jsx(Te,{children:a.jsx(tg,{})})}),a.jsx(V,{path:"/admin/customization/footer",element:a.jsx(Te,{children:a.jsx(sg,{})})}),a.jsx(V,{path:"/admin/customization/legal",element:a.jsx(Te,{children:a.jsx(rg,{})})}),a.jsx(V,{path:"/admin/customization/certificate",element:a.jsx(Te,{children:a.jsx(yF,{})})}),a.jsx(V,{path:"/admin/aptitude",element:a.jsx(Te,{children:a.jsx(vo,{})})}),a.jsx(V,{path:"/admin/aptitude/new",element:a.jsx(Te,{children:a.jsx(vo,{})})}),a.jsx(V,{path:"/admin/aptitude/:categoryId",element:a.jsx(Te,{children:a.jsx(Yp,{})})}),a.jsx(V,{path:"/admin/personality-game",element:a.jsx(Te,{children:a.jsx(Xp,{})})}),a.jsx(V,{path:"/admin/personality-game/overview",element:a.jsx(Te,{children:a.jsx(Zp,{})})}),a.jsx(V,{path:"/admin/billing",element:a.jsx(Te,{children:a.jsx(d$,{})})}),a.jsx(V,{path:"/admin/billing/revenue",element:a.jsx(Te,{children:a.jsx(m$,{})})}),a.jsx(V,{path:"/admin/billing/transactions",element:a.jsx(Te,{children:a.jsx(u$,{})})}),a.jsx(V,{path:"/admin/billing/invoices",element:a.jsx(Te,{children:a.jsx(h$,{})})}),a.jsx(V,{path:"/admin/billing/regional-pricing",element:a.jsx(Te,{children:a.jsx(f$,{})})}),a.jsx(V,{path:"/admin/billing/payment-provider",element:a.jsx(Te,{children:a.jsx(g$,{})})}),a.jsx(V,{path:"/admin/cloud-storage",element:a.jsx(Te,{children:a.jsx(x$,{})})}),a.jsx(V,{path:"/admin/billing/payment-verification",element:a.jsx(Te,{children:a.jsx(y$,{})})}),a.jsx(V,{path:"/admin/billing/payment-methods",element:a.jsx(Te,{children:a.jsx(v$,{})})}),a.jsx(V,{path:"/admin/billing/withdrawals",element:a.jsx(Te,{children:a.jsx(b$,{})})}),a.jsx(V,{path:"/admin/billing/escrow",element:a.jsx(Te,{children:a.jsx(_$,{})})}),a.jsx(V,{path:"/admin/identity-verifications",element:a.jsx(Te,{children:a.jsx(p$,{})})}),a.jsx(V,{path:"/admin/personality-game/sections",element:a.jsx(Te,{children:a.jsx(Qp,{})})}),a.jsx(V,{path:"/admin/personality-game/sections/:sectionId",element:a.jsx(Te,{children:a.jsx(Jp,{})})}),a.jsx(V,{path:"/admin/feed-algorithm",element:a.jsx(Te,{children:a.jsx(wF,{})})}),a.jsx(V,{path:"/admin/cross-learning",element:a.jsx(Te,{children:a.jsx(EF,{})})}),a.jsx(V,{path:"/admin/projects",element:a.jsx(Te,{children:a.jsx(PF,{})})}),a.jsx(V,{path:"/admin/mentorship",element:a.jsx(Te,{children:a.jsx(DF,{})})}),a.jsx(V,{path:"/admin/ads",element:a.jsx(Te,{children:a.jsx(OF,{})})}),a.jsx(V,{path:"/admin/ads/disputes",element:a.jsx(Te,{children:a.jsx(r$,{})})}),a.jsx(V,{path:"/admin/disputes",element:a.jsx(Te,{children:a.jsx(NF,{})})}),a.jsx(V,{path:"/admin/disputes/:disputeId",element:a.jsx(Te,{children:a.jsx(LF,{})})}),a.jsx(V,{path:"/admin/courses",element:a.jsx(Te,{children:a.jsx(U$,{})})}),a.jsx(V,{path:"/admin/courses/:courseId/lessons",element:a.jsx(Te,{children:a.jsx(B$,{})})}),a.jsx(V,{path:"/admin/course-categories",element:a.jsx(Te,{children:a.jsx(V$,{})})}),a.jsx(V,{path:"/admin/trainer-royalties",element:a.jsx(Te,{children:a.jsx(G$,{})})}),a.jsx(V,{path:"/admin/trainer-applications",element:a.jsx(Te,{children:a.jsx(z$,{})})}),a.jsx(V,{path:"/admin/docs/total-revenue",element:a.jsx(Te,{children:a.jsx(c$,{})})}),a.jsx(V,{path:"/admin/docs/ads",element:a.jsx(Te,{children:a.jsx(n$,{})})}),a.jsx(V,{path:"/admin/docs/ads-analytics",element:a.jsx(Te,{children:a.jsx(i$,{})})}),a.jsx(V,{path:"/admin/docs/marketplace-escrow",element:a.jsx(Te,{children:a.jsx(a$,{})})}),a.jsx(V,{path:"/admin/docs/learning-revenue",element:a.jsx(Te,{children:a.jsx(o$,{})})}),a.jsx(V,{path:"/admin/docs/profile-match",element:a.jsx(Te,{children:a.jsx(l$,{})})}),a.jsx(V,{path:"/hr/aptitude",element:a.jsx(YF,{})}),a.jsx(V,{path:"/hr/aptitude/create",element:a.jsx(og,{})}),a.jsx(V,{path:"/hr/aptitude/:testId/edit",element:a.jsx(og,{})}),a.jsx(V,{path:"/hr/aptitude/:testId/questions",element:a.jsx(o4,{})}),a.jsx(V,{path:"/hr/aptitude/:testId/sections/:sectionId/questions",element:a.jsx(l4,{})}),a.jsx(V,{path:"/hr/aptitude/:testId/results",element:a.jsx(c4,{})}),a.jsx(V,{path:"/hr/analytics",element:a.jsx(XF,{})}),a.jsx(V,{path:"/hr/boosts",element:a.jsx(e$,{})}),a.jsx(V,{path:"/hr/boosts/create",element:a.jsx(lg,{})}),a.jsx(V,{path:"/hr/boosts/:boostId/edit",element:a.jsx(lg,{})}),a.jsx(V,{path:"/hr/boosts/analytics",element:a.jsx(t$,{})}),a.jsx(V,{path:"/hr/boosts/disputes",element:a.jsx(s$,{})}),a.jsx(V,{path:"/hr/learning",element:a.jsx(QF,{})}),a.jsx(V,{path:"/hr/pipeline/:
736stage",element:a.jsx(JF,{})}),a.jsx(V,{path:"/hr/fgd/:jobId",element:a.jsx(u4,{})}),a.jsx(V,{path:"/hr/interview-board/:jobId",element:a.jsx(h4,{})}),a.jsx(V,{path:"/hr/account",element:a.jsx(ig,{})}),a.jsx(V,{path:"/hr/security",element:a.jsx(ag,{})}),a.jsx(V,{path:"/hr/activity-log",element:a.jsx(ZF,{})}),a.jsx(V,{path:"/applicant/tests",element:a.jsx(BF,{})}),a.jsx(V,{path:"/applicant/test/:testId",element:a.jsx(f4,{})}),a.jsx(V,{path:"/applicant/test-results/:attemptId",element:a.jsx(m4,{})}),a.jsx(V,{path:"/applicant/personality-game",element:a.jsx(FF,{})}),a.jsx(V,{path:"/applicant/personality-game/take",element:a.jsx(p4,{})}),a.jsx(V,{path:"/applicant/personality-game/results/:attemptId",element:a.jsx(g4,{})}),a.jsx(V,{path:"/applicant/pipeline",element:a.jsx(VF,{})}),a.jsx(V,{path:"/applicant/personality-results",element:a.jsx($F,{})}),a.jsx(V,{path:"/applicant/security",element:a.jsx(ag,{})}),a.jsx(V,{path:"/applicant/test-submission",element:a.jsx(UF,{})}),a.jsx(V,{path:"/applicant/hidden-jobs",element:a.jsx(zF,{})}),a.jsx(V,{path:"/applicant/account",element:a.jsx(ig,{})}),a.jsx(V,{path:"/applicant/account-deletion",element:a.jsx(GF,{})}),a.jsx(V,{path:"/applicant/blocked-users",element:a.jsx(HF,{})}),a.jsx(V,{path:"/applicant/request-verification",element:a.jsx(qF,{})}),a.jsx(V,{path:"/applicant/activity-log",element:a.jsx(KF,{})}),a.jsx(V,{path:"/applicant/saved-items",element:a.jsx(WF,{})}),a.jsx(V,{path:"/billing/summary",element:a.jsx(S$,{})}),a.jsx(V,{path:"/billing/settings",element:a.jsx(T$,{})}),a.jsx(V,{path:"/billing/invoices",element:a.jsx(A$,{})}),a.jsx(V,{path:"/billing/transactions",element:a.jsx(k$,{})}),a.jsx(V,{path:"/projects",element:a.jsx(j$,{})}),a.jsx(V,{path:"/my-projects",element:a.jsx(R$,{})}),a.jsx(V,{path:"/mentorship/manage",element:a.jsx(C$,{})}),a.jsx(V,{path:"/mentorship/:listingId",element:a.jsx(I$,{})}),a.jsx(V,{path:"/courses",element:a.jsx(N$,{})}),a.jsx(V,{path:"/my-courses",element:a.jsx(L$,{})}),a.jsx(V,{path:"/courses/:courseId",element:a.jsx(P$,{})}),a.jsx(V,{path:"/courses/:courseId/watch/:lessonId",element:a.jsx(D$,{})}),a.jsx(V,{path:"/courses/:courseId/quiz/:quizId",element:a.jsx(O$,{})}),a.jsx(V,{path:"/courses/:courseId/quiz/:quizId/results/:attemptId",element:a.jsx(M$,{})}),a.jsx(V,{path:"/courses/:courseId/final-exam",element:a.jsx(F$,{})}),a.jsx(V,{path:"/courses/:courseId/final-exam/results/:attemptId",element:a.jsx($$,{})}),a.jsx(V,{path:"/trainer",element:a.jsx(ac,{children:a.jsx(q$,{})})}),a.jsx(V,{path:"/trainer/courses",element:a.jsx(ac,{children:a.jsx(H$,{})})}),a.jsx(V,{path:"/trainer/earnings",element:a.jsx(ac,{children:a.jsx(K$,{})})}),a.jsx(V,{path:"/search",element:a.jsx(E4,{})}),a.jsx(V,{path:"/menu",element:a.jsx(uF,{})}),a.jsx(V,{path:"/page/create",element:a.jsx(k4,{})}),a.jsx(V,{path:"/page/:slug",element:a.jsx(R4,{})}),a.jsx(V,{path:"/page/:slug/settings",element:a.jsx(I4,{})}),a.jsx(V,{path:"/page/:slug/analytics",element:a.jsx(C4,{})}),a.jsx(V,{path:"/pages/discover",element:a.jsx(j4,{})}),a.jsx(V,{path:"/pages/:slug",element:a.jsx(W$,{})}),a.jsx(V,{path:"/social",element:a.jsx(cF,{})}),a.jsx(V,{path:"/post/:postId",element:a.jsx(_4,{})}),a.jsx(V,{path:"/project/:id",element:a.jsx(w4,{})}),a.jsx(V,{path:"/my-network",element:a.jsx(fF,{})}),a.jsx(V,{path:"/messenger",element:a.jsx(qp,{})}),a.jsx(V,{path:"/messenger/:conversationId",element:a.jsx(qp,{})}),a.jsx(V,{path:"/profile/:userId",element:a.jsx(ug,{})}),a.jsx(V,{path:"/profile/:userId/activity",element:a.jsx(hg,{})}),a.jsx(V,{path:"/u/:username",element:a.jsx(ug,{})}),a.jsx(V,{path:"/u/:username/activity",element:a.jsx(hg,{})}),a.jsx(V,{path:"/reports",element:a.jsx(E$,{})}),a.jsx(V,{path:"/reports/:reportId",element:a.jsx(cg,{})}),a.jsx(V,{path:"/expert",element:a.jsx(ds,{children:a.jsx(w$,{})})}),a.jsx(V,{path:"/expert/users",element:a.jsx(ds,{requiredPermission:"main_menu.users",children:a.jsx(Hp,{layoutType:"expert"})})}),a.jsx(V,{path:"/expert/jobs",element:a.jsx(ds,{requiredPermission:"main_menu.jobs",children:a.jsx(Kp,{layoutType:"expert"})})}),a.jsx(V,{path:"/expert/applications",element:a.jsx(ds,{requiredPermission:"main_menu.applications",children:a.jsx(Wp,{layoutType:"expert"})})}),a.jsx(V,{path:"/expert/security",element:a.jsx(ds,{requiredPermission:"main_menu.security",children:a.jsx(eg,{layoutType:"expert"})})}),a.jsx(V,{path:"/expert/aptitude",element:a.jsx(ds,{requiredPermission:"aptitude.categories",children:a.jsx(vo,{layoutType:"expert"})})}),a.jsx(V,{path:"/expert/aptitude/new",element:a.jsx(ds,{requiredPermission:"aptitude.categories",children:a.jsx(vo,{layoutType:"expert"})})}),a.jsx(V,{path:"/expert/aptitude/:categoryId",element:a.jsx(ds,{requiredPermission:"aptitude.questions",children:a.jsx(Yp,{layoutType:"expert"})})}),a.jsx(V,{path:"/expert/personality-game",element:a.jsx(ds,{requiredPermission:"personality.settings",children:a.jsx(Xp,{layoutType:"expert"})})}),a.jsx(V,{path:"/expert/personality-game/overview",element:a.jsx(ds,{requiredPermission:"personality.overview",children:a.jsx(Zp,{layoutType:"expert"})})}),a.jsx(V,{path:"/expert/personality-game/sections",element:a.jsx(ds,{requiredPermission:"personality.sections",children:a.jsx(Qp,{layoutType:"expert"})})}),a.jsx(V,{path:"/expert/personality-game/sections/:sectionId",element:a.jsx(ds,{requiredPermission:"personality.sections",children:a.jsx(Jp,{layoutType:"expert"})})}),a.jsx(V,{path:"/expert/customization/brand",element:a.jsx(ds,{requiredPermission:"customization.brand",children:a.jsx(tg,{layoutType:"expert"})})}),a.jsx(V,{path:"/expert/customization/footer",element:a.jsx(ds,{requiredPermission:"customization.footer",children:a.jsx(sg,{layoutType:"expert"})})}),a.jsx(V,{path:"/expert/customization/legal",element:a.jsx(ds,{requiredPermission:"customization.legal",children:a.jsx(rg,{layoutType:"expert"})})}),a.jsx(V,{path:"/expert/verified-pages",element:a.jsx(ds,{requiredPermission:"community.verified_users",children:a.jsx(ng,{layoutType:"expert"})})})]}),a.jsx(V,{path:"*",element:a.jsx(oF,{})})]})})})}),a.jsx(fM,{})]})]})]})}const L4=()=>a.jsx(ek,{children:a.jsx(XE,{attribute:"class",defaultTheme:"system",enableSystem:!0,children:a.jsx(nk,{children:a.jsx(ik,{children:a.jsx(N4,{})})})})}),P4=new u_({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1,staleTime:5*60*1e3,gcTime:1e3*60*60*24}}}
736),D4=Z_({storage:window.localStorage,key:"tm_rq_cache"});jg(document.getElementById("root")).render(a.jsx(Y_,{client:P4,persistOptions:{persister:D4,maxAge:1e3*60*60*24,buster:"v1"},children:a.jsx(L4,{})}));export{sa as $,Bs as A,ye as B,sr as C,Dl as D,Jc as E,Dn as F,yo as G,u3 as H,rr as I,Nr as J,Nu as K,hr as L,Vh as M,cr as N,p3 as O,ni as P,Eo as Q,Uo as R,yx as S,lh as T,lE as U,wa as V,H as W,us as X,Ss as Y,vr as Z,Qr as _,bu as a,rE as a$,nr as a0,LR as a1,Cn as a2,jl as a3,ts as a4,Bd as a5,tx as a6,Nw as a7,ri as a8,an as a9,Dw as aA,Ga as aB,Rb as aC,uM as aD,ha as aE,tM as aF,ua as aG,xA as aH,Fo as aI,eE as aJ,Fh as aK,Lw as aL,ba as aM,P0 as aN,_s as aO,pD as aP,_a as aQ,uE as aR,dE as aS,Tn as aT,lw as aU,s0 as aV,Q4 as aW,Mo as aX,p0 as aY,Xj as aZ,_i as a_,U0 as aa,Hb as ab,oI as ac,$a as ad,bO as ae,_b as af,wb as ag,Sb as ah,Lr as ai,Tb as aj,Eb as ak,kb as al,Ab as am,ZD as an,Ds as ao,yA as ap,jb as aq,M as ar,qh as as,Fs as at,n3 as au,ra as av,$o as aw,Zc as ax,Xb as ay,Qb as az,dn as b,X4 as b$,Ww as b0,bn as b1,Cr as b2,ed as b3,jk as b4,Oo as b5,aE as b6,Wl as b7,e0 as b8,si as b9,VO as bA,Na as bB,QD as bC,bM as bD,iO as bE,rF as bF,nF as bG,Ca as bH,ps as bI,uh as bJ,gs as bK,xs as bL,ki as bM,Ri as bN,ow as bO,yR as bP,vR as bQ,bx as bR,iF as bS,Kw as bT,Lk as bU,rx as bV,Ok as bW,Mk as bX,Fk as bY,Yh as bZ,Y4 as b_,iE as ba,Zw as bb,Kl as bc,Dr as bd,Mn as be,Bw as bf,oE as bg,kr as bh,Hw as bi,r0 as bj,Pb as bk,ah as bl,G4 as bm,h2 as bn,yi as bo,Vo as bp,Go as bq,zo as br,fa as bs,vi as bt,na as bu,bi as bv,cu as bw,sE as bx,lu as by,BO as bz,C as c,el as c$,Iw as c0,du as c1,nA as c2,UO as c3,Mw as c4,Zg as c5,Kh as c6,Lh as c7,Gh as c8,Px as c9,Qf as cA,Z4 as cB,J4 as cC,e3 as cD,DD as cE,aF as cF,eF as cG,zr as cH,HO as cI,JM as cJ,$R as cK,GR as cL,L0 as cM,W4 as cN,K4 as cO,Qg as cP,Xn as cQ,i3 as cR,Qc as cS,NA as cT,Vw as cU,QM as cV,XM as cW,IA as cX,CA as cY,Il as cZ,f3 as c_,Mh as ca,Fw as cb,ae as cc,Df as cd,o3 as ce,l3 as cf,St as cg,An as ch,Zo as ci,Dx as cj,Va as ck,Or as cl,zR as cm,Jo as cn,UR as co,Mx as cp,Kj as cq,OR as cr,$x as cs,KR as ct,Qo as cu,kj as cv,jj as cw,FR as cx,_u as cy,uc as cz,wo as d,tl as d0,Vx as d1,y3 as d2,g3 as d3,x3 as d4,b3 as d5,v3 as d6,LA as d7,DA as d8,m3 as d9,Gw as dA,zw as dB,qw as dC,t0 as dD,Yw as dE,Hh as dF,Jw as dG,tE as dH,Xh as dI,cE as dJ,n0 as dK,jw as dL,Ji as dM,B4 as dN,nR as dO,q4 as dP,H4 as dQ,z4 as dR,Pn as dS,c3 as dT,d3 as dU,h3 as dV,V4 as dW,Qw as da,$w as db,a3 as dc,Uh as dd,Wh as de,Cw as df,r3 as dg,nE as dh,jf as di,Ow as dj,zh as dk,Xw as dl,VR as dm,BR as dn,Rf as dp,TA as dq,SA as dr,EA as ds,Ph as dt,Jg as du,Dh as dv,Oh as dw,$h as dx,Uw as dy,Bh as dz,Vs as e,pr as f,Gs as g,sn as h,Pw as i,Es as j,sM as k,Db as l,rM as m,Fb as n,Zi as o,Ol as p,Ml as q,Fl as r,L as s,Ai as t,$t as u,Rn as v,jn as w,In as x,Ae as y,WM as z};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.