1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/docBinaryImporter-DYZkN9Fd.js","assets/vendor-supabase-BfoV2C50.js","assets/vendor-react-7PyNDetJ.js","assets/pdfTextExtractor-ezac6Ghx.js"])))=>i.map(i=>d[i]); 2var Ta=Object.defineProperty;var Kt=e=>{throw TypeError(e)};var Sa=(e,t,r)=>t in e?Ta(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Qt=(e,t,r)=>Sa(e,typeof t!="symbol"?t+"":t,r),Zt=(e,t,r)=>t.has(e)||Kt("Cannot "+r);var er=(e,t,r)=>(Zt(e,t,"read from private field"),r?r.call(e):t.get(e)),tr=(e,t,r)=>t.has(e)?Kt("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),rr=(e,t,r,n)=>(Zt(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);import{r as S}from"./vendor-react-7PyNDetJ.js";import{a as pt,u as ke,b as me}from"./vendor-query-CmFN4-M1.js";import{u as Ia}from"./settingsNavItems-CTDhSt42.js";import{u as Ge,b as $,c as N,X as Ae,a$ as Aa,aJ as nr,V as Ma,W as ka}from"./index-BZSaBQD0.js";import{compressToWebP as ar}from"./imageCompression-DJQX-S_h.js";import{r as ir}from"./useUserProfile-4gVj-B2T.js";import{a as Ca}from"./useTrialStatus-BHA4YoRQ.js";import{C as Ze}from"./queryConfig-Bk25iP63.js";import{a as Ie}from"./errorTranslations-lTGRyFpS.js";import{B as Fa}from"./vendor-supabase-BfoV2C50.js";import{i as Na}from"./edgeFunctionClient-DsSOOeYY.js";const kt="radreport:clinica-ativa";let lt=null;const Ct=new Set;function $a(e){if(!e)return null;try{return window.localStorage.getItem(`${kt}:${e}`)}catch{return null}}function Ue(e,t){if(lt!==e){lt=e;try{t&&(e?window.localStorage.setItem(`${kt}:${t}`,e):window.localStorage.removeItem(`${kt}:${t}`))}catch{}Ct.forEach(r=>r())}}function La(e){return Ct.add(e),()=>{Ct.delete(e)}}function or(e){return{...e,logo_format:e.logo_format||"retangular",footer_alignment:e.footer_alignment||"center",clinic_email:e.clinic_email||"",clinic_website:e.clinic_website||"",clinic_cnpj:e.clinic_cnpj||"",clinic_hours:e.clinic_hours||"",footer_message:e.footer_message||"",stationery_image_url:e.stationery_image_url||null,stationery_opacity:e.stationery_opacity??.15,stationery_fit:e.stationery_fit||"cover"}}const Pa={profile_name:"",is_default:!1,logo_url:null,logo_format:"retangular",invert_logo:!1,clinic_name:"",clinic_address:"",clinic_phone:"",clinic_email:"",clinic_website:"",clinic_cnpj:"",clinic_hours:"",footer_message:"",footer_alignment:"center",use_physical_stationery:!1,stationery_image_url:null,stationery_opacity:.15,stationery_fit:"cover"},Ra=e=>{const t=(e==null?void 0:e.enabled)??!0,{user:r}=Ge(),n=pt(),a=()=>{if(!(r!=null&&r.id))return null;const I=n.getQueryData(["user-boot-data",r.id]),T=I==null?void 0:I.clinic_profiles;return Array.isArray(T)?T.map(or):null},{data:i,isLoading:o,refetch:s}=ke({queryKey:["clinic-profiles",r==null?void 0:r.id],queryFn:async()=>{const{data:I,error:T}=await $.from("user_clinic_profiles").select("*").eq("user_id",r.id).order("created_at",{ascending:!0});if(T)throw T;return(I||[]).map(or)},enabled:t&&!!(r!=null&&r.id),initialData:a()??void 0,staleTime:5*60*1e3}),c=i??[],[m,g]=S.useState(!1),d=S.useSyncExternalStore(La,()=>lt,()=>lt),f=S.useRef(r==null?void 0:r.id);S.useEffect(()=>
2{f.current!==(r==null?void 0:r.id)&&(f.current=r==null?void 0:r.id,Ue(null,null))},[r==null?void 0:r.id]),S.useEffect(()=>{var R,L;if(c.length===0||d&&c.some(j=>j.id===d))return;const T=$a(r==null?void 0:r.id),M=(T&&c.some(j=>j.id===T)?T:null)??((R=c.find(j=>j.is_default))==null?void 0:R.id)??((L=c[0])==null?void 0:L.id)??null;Ue(M,r==null?void 0:r.id)},[c,d,r==null?void 0:r.id]);const y=d,b=S.useCallback(async I=>{if(!(r!=null&&r.id))return null;g(!0);try{I.is_default&&await $.from("user_clinic_profiles").update({is_default:!1}).eq("user_id",r.id);const T=c.length===0,C={...I};I.logo_url&&!I.logo_storage_path&&(C.logo_storage_path=I.logo_url);const{data:M,error:R}=await $.from("user_clinic_profiles").insert({user_id:r.id,...C,is_default:I.is_default||T}).select().single();if(R)throw R;const L={...M,logo_format:M.logo_format||"retangular",footer_alignment:M.footer_alignment||"center",clinic_email:M.clinic_email||"",clinic_website:M.clinic_website||"",clinic_cnpj:M.clinic_cnpj||"",clinic_hours:M.clinic_hours||"",footer_message:M.footer_message||"",stationery_image_url:M.stationery_image_url||null,stationery_opacity:M.stationery_opacity??.15,stationery_fit:M.stationery_fit||"cover"};return n.setQueryData(["clinic-profiles",r.id],j=>[...j??[],L]),(L.is_default||T)&&Ue(L.id,r.id),n.invalidateQueries({queryKey:["clinic-profiles",r.id]}),N.success("ClÃnica cadastrada com sucesso!"),L}catch(T){return console.error("Error creating clinic profile:",T),N.error("Erro ao cadastrar clÃnica"),null}finally{g(!1)}},[r==null?void 0:r.id,c.length]),A=S.useCallback(async(I,T)=>{if(!(r!=null&&r.id))return!1;g(!0);try{T.is_default&&await $.from("user_clinic_profiles").update({is_default:!1}).eq("user_id",r.id).neq("id",I);const C={...T};T.logo_url&&!T.logo_storage_path&&(C.logo_storage_path=T.logo_url);const{error:M}=await $.from("user_clinic_profiles").update({...C,updated_at:new Date().toISOString()}).eq("id",I).eq("user_id",r.id);if(M)throw M;return n.setQueryData(["clinic-profiles",r.id],R=>(R??[]).map(L=>L.id===I?{...L,...C,updated_at:new Date().toISOString()}:L)),n.invalidateQueries({queryKey:["clinic-profiles",r.id]}),N.success("ClÃnica atualizada!"),!0}catch(C){return console.error("Error updating clinic profile:",C),N.error("Erro ao atualizar clÃnica"),!1}finally{g(!1)}},[r==null?void 0:r.id]),p=S.useCallback(async I=>{if(!(r!=null&&r.id))return!1;g(!0);try{const T=c.find(R=>R.id===I),{error:C}=await $.from("user_clinic_profiles").delete().eq("id",I).eq("user_id",r.id);if(C)throw C;const M=c.filter(R=>R.id!==I);if(n.setQueryData(["clinic-profiles",r.id],M),y===I){const R=M.find(L=>L.is_default)||M[0];Ue((R==null?void 0:R.id)||null,r.id)}return T!=null&&T.is_default&&M.length>0&&(await $.from("user_clinic_profiles").update({is_default:!0}).eq("id",M[0].id),n.setQueryData(["clinic-profiles",r.id],R=>(R??[]).map((L,j)=>j===0?{...L,is_default:!0}:L))),n.invalidateQueries({queryKey:["clinic-profiles",r.id]}),N.success("ClÃnica removida"),!0}catch(T){return console.error("Error deleting clinic profile:",T),N.error("Erro ao remover clÃnica"),!1}finally{g(!1)}},[r==null?void 0:r.id,c,y]),h=S.useCallback(async I=>A(I,{is_default:!0}),[A]),v=S.useCallback(I=>{c.find(C=>C.id===I)&&Ue(I,r==null?void 0:r.id)},[c,r==null?void 0:r.id]),_=S.useCallback(async(I,T,C="logo_url")=>{if(!(r!=null&&r.id))return null;try{if(!T.type.startsWith("image/"))return N.error("Formato de arquivo não suportado"),null;if(T.size>5*1024*1024)return N.error("Arquivo muito grande. Máximo: 5MB"),null;const M=C==="stationery_image_url"?1920:800;let R=T;T.type!=="image/svg+xml"&&(R=await ar(T,{mode:"diagnostic",maxWidth:M}));const L=R.name.split(".").pop(),j=C==="stationery_image_url"?"stationery":"clinic",ne=`${r.id}/${j}_${I}_${Date.now()}.${L}`,{error:Z}=await $.storage.from("user-branding").upload(ne,R,{upsert:!0});if(Z)throw Z;const V=ne,le={[C]:V};return C==="logo_url"&&(le.logo_storage_path=ne),await A(I,le),V}catch(M){return console.error(`Error uploading ${C}:`,M),N.error("Erro ao enviar imagem"),null}},[r==null?void 0:r.id,A]),x=S.useCallback(async(I,T="clinic")=>{if(!(r!=null&&r.id))return null;try{if(!I.type.startsWith("image/"))return N.error("Formato de arquivo não suportado"),null;if(I.size>5*1024*1024)return N.error("Arquivo muito grande. Máximo: 5MB"),null;const C=T==="stationery"?1920:800;let M=I;I.type!=="image/svg+xml"&&(M=await ar(I,{mode:"diagnostic",maxWidth:C}));const R=M.name.split(".").pop(),L=`${r.id}/${T}_new_${Date.now()}.${R}`,{error:j}=await $.storage.from("user-branding").upload(L,M,{upsert:!0});if(j)throw j;return L}catch(C){return console.error("Error uploading image:",C),N.error("Erro ao enviar imagem"),null}},[r==null?void 0:r.id]),F=S.useCallback(async(I,T)=>_(I,T,"logo_url"),[_]),P=c.find(I=>I.id===y)||null,X=c.find(I=>I.is_default)||null;return{profiles:c,activeProfile:P,activeProfileId:y,defaultProfile:X,isLoading:t?o:!1,isSaving:m,createProfile:b,updateProfile:A,deleteProfile:p,setDefaultProfile:h,selectProfile:v,uploadLogo:F,uploadImage:_,uploadImageDirect:x,refetch:s,DEFAULT_PROFILE:Pa}},Gr="fixed-document-logo",Da="fixed-document-signature",Le={retangular:{maxWidth:600,maxHeight:120},quadrado:{width:150,height:150}},sr={maxWidth:500,maxHeight:200},Yr=e=>e.getHTML().includes(Gr),Vr=e=>{let t=!1;return e.state.doc.descendants(n=>{if(n.type.name==="signatureBlock")return t=!0,!1}),t?!0:e.getHTML().includes(Da)},al=(e,t)=>{if(!(t!=null&&t.header_enabled)||!(t!=null&&t.logo_url))return console.warn("[DocumentFixedPositions] Logo não configurado ou header desabilitado"),!1;if(Yr(e))return!1;const r=t.logo_format||"retangular";let n="display: block; margin: 0 auto 1.5rem auto; object-fit: contain;";if(r==="quadrado"){const i=Le.quadrado;n+=` width: ${i.width}px; height: ${i.height}px;`}else{const i=Le.retangular;n+=` max-width: ${i.maxWidth}px; max-height: ${i.maxHeight}px; width: auto; height: auto;`}t.invert_logo&&(n+=" filter: invert(1);");const a=`<p style="text-align: center;"><img src="${t.logo_url}" alt="${t.clinic_name||"Logo"}" class="${Gr}" style="${n}" /></p>`;return e.chain().focus().setTextSelection(0).insertContent(a).run(),!0},il=(e,t)=>{if(!(t!=null&&t.signature_enabled))return console.warn("[DocumentFixedPositions] Assinatura desabilitada"),!1;if(Vr(e))return!1;const r=t.signature_type||"manual";if(r==="digital"){if(!t.signature_url)return console.warn("[DocumentFixedPositions] Assinatura digital sem imagem configurada"),!1}else if(!t.signature_name&&!t.signature_crm)return console.warn("[DocumentFixedPositions] Assinatura manual sem nome ou CRM configurado"),!1;return typeof e.commands.insertSignatureBlock!="function"?(console.error("[DocumentFixedPositions] SignatureBlock extension não registrada"),!1):e.commands.insertSignatureBlock({type:r,signatureUrl:t.signature_url||void 0,name:t.signature_name||void 0,crm:t.signature_crm||void 0,title:t.signature_title||void 0,size:t.signature_size||"medio",alignment:t.signature_alignment||"right"})},ol=e=>{if(!Yr(e))return!1;const r=e.getHTML().replace(/<p[^>]*>[\s]*<img[^>]*class="[^"]*fixed-document-logo[^"]*"[^>]*\/>[\s]*<\/p>/gi,"");return e.commands.setContent(r,{emitUpdate:!0}),!0},sl=e=>{if(!Vr(e))return!1;if(typeof e.commands.removeSignatureBlock=="function"&&e.commands.removeSignatureBlock())return!0;let r=e.getHTML().replace(/<p[^>]*class="[^"]*fixed-document-signature[^"]*"[^>]*>[\s\S]*?<\/p>/gi,"").replace(/<div[^>]*class="[^"]*fixed-document-signature[^"]*"[^>]*>[\s\S]*?<\/div>/gi,"");return e.commands.setContent(r,{emitUpdate:!0}),!0},Jr={A4:{widthMm:210,heightMm:297},Letter:{widthMm:215.9,heightMm:279.4}},Be={pageSize:"A4",marginTopMm:18,marginRightMm:10,marginBottomMm:15,marginLeftMm:10},cl={padrao:{label:"Padrão do RadReport",margins:{marginTopMm:18,marginRightMm:10,marginBottomMm:15,marginLeftMm:10}},normal:{label:"Normal (2,5 cm)",margins:{marginTopMm:25,marginRightMm:25,marginBottomMm:25,marginLeftMm:25}},estreita:{label:"Estreita (1,27 cm)",margins:{marginTopMm:13,marginRightMm:13,marginBottomMm:13,marginLeftMm:13}},larga:{label:"Larga (2,5 à 5 cm)",margins:{marginTopMm:25,marginRightMm:50,marginBottomMm:25,marginLeftMm:50}}},Ua=0,Ba=60,Ft=60;function et(e,t){const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?Math.min(Ba,Math.max(Ua,Math.round(r*10)/10)):t}function Oa(e){const t=e!=null&&e.metadata&&typeof e.metadata=="object"?e.metadata:{},r=t.page_layout&&typeof t.page_layout=="object"?t.page_layout:{},n=r.pageSize==="Letter"?"Letter":"A4",a={pageSize:n,marginTopMm:et(r.marginTopMm,Be.marginTopMm),marginRightMm:et(r.marginRightMm,Be.marginRightMm),marginBottomMm:et(r.marginBottomMm,Be.marginBottomMm),marginLeftMm:et(r.marginLeftMm,Be.marginLeftMm)},i=wt(a);return i.widthMm<Ft||i.heightMm<Ft?{...Be,pageSize:n}:a}function wt(e){const t=Jr[e.pageSize];return{widthMm:t.widthMm-e.marginLeftMm-e.marginRightMm,heightMm:t.heightMm-e.marginTopMm-e.marginBottomMm}}const vt={enabled:!0,format:"pagina_de",position:"right"},za=8,qa={left:"@bottom-left",center:"@bottom-center",right:"@bottom-right"};function ll(e){const t=e!=null&&e.metadata&&typeof e.metadata=="object"?e.metadata:{},r=t.page_numbering&&typeof t.page_numbering=="object"?t.page_numbering:{},n=r.position==="left"||r.position==="center"?r.position:vt.position,a=r.format==="numero"?"numero":vt.format;return{enabled:typeof r.enabled=="boolean"?r.enabled:vt.enabled,format:a,position:n}}function ul(e,t){const r=`${e.marginTopMm}mm ${e.marginRightMm}mm ${e.marginBottomMm}mm ${e.marginLeftMm}mm`;if(!(!!(t!=null&&t.enabled)&&e.marginBottomMm>=za))return`@page { size: ${e.pageSize}; margin: ${r}; }`;const a=qa[t.position]??"@bottom-right",i=t.format==="numero"?"counter(page)":'"Página " counter(page) " de " counter(pages)';return["@page {",` size: ${e.pageSize};`,` margin: ${r};`,` ${a} {`,` content: ${i};`," font-family: Arial, Helvetica, sans-serif;"," font-size: 8pt;"," color: #555555;"," }","}"].join(` 3`)}const ut=2,Kr=80;function Ha(e){return e/96*25.4}function dl(e){if(!e)return 0;const t=e.getBoundingClientRect();if(!t||!Number.isFinite(t.height)||t.height<=0)return 0;const r=Ha(t.height);return Math.min(Kr,Math.ceil(r*10)/10)}function yt(e){const t=r=>{const n=typeof r=="number"?r:Number(r);return!Number.isFinite(n)||n<=0?0:Math.min(Kr,Math.round(n*10)/10)};return{headerMm:t(e==null?void 0:e.headerMm),footerMm:t(e==null?void 0:e.footerMm),signatureMm:t(e==null?void 0:e.signatureMm)}}function Qr(e){const t=yt(e);return t.headerMm>0?t.headerMm+ut:0}function Zr(e){const t=yt(e),r=t.footerMm>0?t.footerMm+ut:0,n=t.signatureMm>0?t.signatureMm+ut:0;return r+n}function fl(e){const t=yt(e);return t.footerMm>0?t.footerMm+ut:0}function ml(e){return wt(e).widthMm}function ja(e,t){const r=wt(e).heightMm-Qr(t)-Zr(t);return Math.max(Ft,Math.round(r*10)/10)}function hl(e,t){const r=2.834645669291339,n=Jr[e.pageSize],a=wt(e),i=Qr(t),o=Zr(t),s=ja(e,t),c={paperWidth:n.widthMm,paperHeight:n.heightMm,marginTop:e.marginTopMm,marginRight:e.marginRightMm,marginBottom:e.marginBottomMm,marginLeft:e.marginLeftMm,contentWidth:a.widthMm,contentHeight:a.heightMm,topReserve:i,bottomReserve:o,usableWidth:a.widthMm,usableHeight:s,textTop:e.marginTopMm+i,textBottom:e.marginTopMm+i+s}
3,m=Object.fromEntries(Object.entries(c).map(([g,d])=>[g,Math.round(d*r*100)/100]));return{mm:c,pt:m,bands:yt(t),geometry:e}}const en="user-branding",cr=60*60*8,Wa=30*60*1e3,dt=new Map,Et=new Map;function ft(e){if(!e)return null;const t=String(e).trim();if(!t||t.startsWith("data:")||t.startsWith("blob:"))return null;if(!/^https?:\/\//i.test(t))return t.replace(/^\/+/,"");const r=`/${en}/`,n=t.indexOf(r);if(n===-1)return null;const a=t.slice(n+r.length).split("?")[0];if(!a)return null;try{return decodeURIComponent(a)}catch{return a}}async function Xa(e){const t=ft(e);if(!t)return e??null;const r=Date.now(),n=dt.get(t);if(n&&n.expiraEm-r>Wa)return n.url;const a=Et.get(t);if(a)return a;const i=(async()=>{const{data:o,error:s}=await $.storage.from(en).createSignedUrl(t,cr);return s||!(o!=null&&o.signedUrl)?(console.warn("[branding] não consegui assinar",t,s),null):(dt.set(t,{url:o.signedUrl,expiraEm:Date.now()+cr*1e3}),o.signedUrl)})();return Et.set(t,i),i.finally(()=>{Et.delete(t)}),i}function Ga(e){const t=ft(e);t?dt.delete(t):dt.clear()}const lr={signature_url:null,signature_name:"",signature_crm:"",signature_title:"Médico(a) Radiologista",signature_enabled:!1,signature_size:"medio",signature_type:"manual",signature_alignment:"right"},gl=e=>{const t=(e==null?void 0:e.eager)??!0,{user:r}=Ge();pt();const{settings:n,updateSettings:a,updateMetadata:i,isLoading:o}=Ia(),{profiles:s,activeProfile:c,defaultProfile:m,activeProfileId:g,selectProfile:d,isLoading:f}=Ra({enabled:t}),[y,b]=S.useState(lr),[A,p]=S.useState({enabled:!1,text:"LAUDO PROVISÃRIO"}),[h,v]=S.useState({headerFontSize:14,headerAlignment:"center",footerFontSize:11,footerAlignment:"center"}),[_,x]=S.useState(!1),[F,P]=S.useState({});S.useEffect(()=>{if(n!=null&&n.metadata&&typeof n.metadata=="object"){const u=n.metadata;if(u.doctor_signature&&b({...lr,...u.doctor_signature}),u.watermark_config){const k=u.watermark_config;p({enabled:k.enabled??!1,text:k.text??"LAUDO PROVISÃRIO"})}if(u.pagination_config){const k=u.pagination_config;v({headerFontSize:k.headerFontSize??14,headerAlignment:k.headerAlignment??"center",footerFontSize:k.footerFontSize??11,footerAlignment:k.footerAlignment??"center"})}if(u.print_config&&!u.doctor_signature){const k=u.print_config,D=k,B={signature_url:k.signature_url||null,signature_name:k.signature_name||"",signature_crm:k.signature_crm||"",signature_title:k.signature_title||"Médico(a) Radiologista",signature_enabled:D.footer_enabled??k.signature_enabled??!1,signature_size:"medio",signature_type:"manual",signature_alignment:"right"};b(B),a({metadata:{...u,doctor_signature:B,watermark_config:{enabled:k.watermark_enabled??!1,text:k.watermark_text??"LAUDO PROVISÃRIO"}}})}}},[n]);const X=c||m,I=(X==null?void 0:X.logo_storage_path)||(X==null?void 0:X.logo_url)||null,T=(X==null?void 0:X.stationery_image_url)||null,C=y.signature_url||null;S.useEffect(()=>{let u=!0;const k=[I,T,C].filter(Boolean);if(k.length!==0)return Promise.all(k.map(async D=>{const B=ft(D);if(!B)return null;const W=await Xa(D);return W?[B,W]:null})).then(D=>{u&&P(B=>{let W=!1;const G={...B};for(const Y of D)Y&&G[Y[0]]!==Y[1]&&(G[Y[0]]=Y[1],W=!0);return W?G:B})}),()=>{u=!1}},[I,T,C]);const M=S.useCallback(u=>{if(!u)return null;const k=ft(u);return k?F[k]??null:u},[F]),R=S.useMemo(()=>{const u=c||m,k=!!(u&&(u.logo_url||u.clinic_name)),D=!!(u&&(u.clinic_address||u.clinic_phone||u.clinic_email||u.clinic_website||u.clinic_cnpj||u.clinic_hours||u.footer_message));return{active_clinic_profile_id:(u==null?void 0:u.id)||g,header_enabled:k,use_physical_stationery:(u==null?void 0:u.use_physical_stationery)??!1,stationery_image_url:M((u==null?void 0:u.stationery_image_url)??null),stationery_opacity:(u==null?void 0:u.stationery_opacity)??.15,stationery_fit:(u==null?void 0:u.stationery_fit)??"cover",logo_url:M((u==null?void 0:u.logo_storage_path)??(u==null?void 0:u.logo_url)??null),logo_storage_path:(u==null?void 0:u.logo_storage_path)??null,logo_format:(u==null?void 0:u.logo_format)??"retangular",invert_logo:(u==null?void 0:u.invert_logo)??!1,clinic_name:(u==null?void 0:u.clinic_name)??"",clinic_address:(u
3==null?void 0:u.clinic_address)??"",clinic_phone:(u==null?void 0:u.clinic_phone)??"",clinic_email:(u==null?void 0:u.clinic_email)??"",clinic_website:(u==null?void 0:u.clinic_website)??"",clinic_cnpj:(u==null?void 0:u.clinic_cnpj)??"",clinic_hours:(u==null?void 0:u.clinic_hours)??"",footer_message:(u==null?void 0:u.footer_message)??"",footer_alignment:(u==null?void 0:u.footer_alignment)??"center",footer_enabled:D,signature_enabled:y.signature_enabled,signature_url:M(y.signature_url),signature_name:y.signature_name,signature_crm:y.signature_crm,signature_title:y.signature_title,signature_size:y.signature_size||"medio",signature_type:y.signature_type||"manual",signature_alignment:y.signature_alignment||"right",watermark_enabled:A.enabled,watermark_text:A.text,pagination_header_font_size:h.headerFontSize,pagination_header_alignment:h.headerAlignment,pagination_footer_font_size:h.footerFontSize,pagination_footer_alignment:h.footerAlignment}},[c,m,g,y,A,h,M]),L=S.useCallback(async u=>{const k={...y,...u};b(k);try{await i({doctor_signature:k})}catch(D){console.error("Error saving doctor signature:",D),N.error("Erro ao salvar dados do médico")}},[y,i]),j=S.useCallback(async u=>{const k={...A,...u};p(k);try{await i({watermark_config:k})}catch(D){console.error("Error saving watermark config:",D)}},[A,i]),ne=S.useCallback(async u=>{const k={...h,...u};v(k);try{await i({pagination_config:k})}catch(D){console.error("Error saving pagination config:",D)}},[h,i]),Z=S.useCallback(async u=>{try{await i({page_layout:u})}catch(k){console.error("Error saving page geometry:",k),N.error("Erro ao salvar as margens da página")}},[i]),V=S.useCallback(async u=>{("signature_enabled"in u||"signature_url"in u||"signature_name"in u||"signature_crm"in u||"signature_title"in u||"signature_type"in u||"signature_size"in u||"signature_alignment"in u)&&await L({signature_enabled:u.signature_enabled??y.signature_enabled,signature_url:u.signature_url??y.signature_url,signature_name:u.signature_name??y.signature_name,signature_crm:u.signature_crm??y.signature_crm,signature_title:u.signature_title??y.signature_title,signature_type:u.signature_type??y.signature_type,signature_size:u.signature_size??y.signature_size,signature_alignment:u.signature_alignment??y.signature_alignment}),("watermark_enabled"in u||"watermark_text"in u)&&await j({enabled:u.watermark_enabled??A.enabled,text:u.watermark_text??A.text}),("pagination_header_font_size"in u||"pagination_header_alignment"in u||"pagination_footer_font_size"in u||"pagination_footer_alignment"in u)&&await ne({headerFontSize:u.pagination_header_font_size??h.headerFontSize,headerAlignment:u.pagination_header_alignment??h.headerAlignment,footerFontSize:u.pagination_footer_font_size??h.footerFontSize,footerAlignment:u.pagination_footer_alignment??h.footerAlignment})},[y,A,h,L,j,ne]),le=S.useCallback(async(u,k,D)=>new Promise((B,W)=>{const G=new Image,Y=document.createElement("canvas"),J=Y.getContext("2d");if(!J){W(new Error("Canvas context not available"));return}G.onload=()=>{let{width:ue,height:de}=G;const ye=Math.min(k/ue,D/de);ye<1&&(ue=Math.round(ue*ye),de=Math.round(de*ye)),Y.width=ue,Y.height=de,J.imageSmoothingEnabled=!0,J.imageSmoothingQuality="high",J.drawImage(G,0,0,ue,de),Y.toBlob(Je=>{Je?B(new File([Je],u.name.replace(/\.[^/.]+$/,".png"),{type:"image/png"})):W(new Error("Failed to create blob"))},"image/png")},G.onerror=()=>W(new Error("Failed to load image")),G.src=URL.createObjectURL(u)}),[]),ee=S.useCallback(async(u,k,D)=>
3{if(!(r!=null&&r.id))return null;x(!0);try{let B,W;k==="logo"?D==="quadrado"?(B=Le.quadrado.width,W=Le.quadrado.height):(B=Le.retangular.maxWidth,W=Le.retangular.maxHeight):(B=sr.maxWidth,W=sr.maxHeight);const G=await le(u,B,W),Y=`${r.id}/${k}_${Date.now()}.png`,{error:J}=await $.storage.from("user-branding").upload(Y,G,{upsert:!0});if(J)throw J;return Ga(Y),Y}catch(B){return console.error("Error uploading file:",B),N.error("Erro ao fazer upload do arquivo"),null}finally{x(!1)}},[r==null?void 0:r.id,le]),Re=S.useCallback(async u=>{const k=await ee(u,"signature");k&&(await L({signature_url:k}),ir(),N.success("Assinatura salva com sucesso!"))},[ee,L]),De=S.useCallback(async()=>{await L({signature_url:null}),ir(),N.success("Assinatura removida")},[L]),Se=S.useMemo(()=>Oa(n),[n]);return{printConfig:R,updatePrintConfig:V,doctorSignature:y,updateDoctorSignature:L,watermarkConfig:A,updateWatermarkConfig:j,pageGeometry:Se,updatePageGeometry:Z,clinicProfiles:s,activeClinicProfile:c,activeProfileId:g,selectClinicProfile:d,uploadSignature:Re,removeSignature:De,isLoading:o||f,isUploading:_}},Ya=/<div\b[^>]*\bdata-patient-info-block\b[^>]*>/i;function Va(e){const t=Ya.exec(e);if(!t)return null;const r=t.index;let n=1,a=r+t[0].length;const i=e.length;for(;a<i&&n>0;){const o=e.indexOf("<div",a),s=e.indexOf("</div>",a);if(s===-1)return e.slice(0,r);o!==-1&&o<s?(n+=1,a=o+4):(n-=1,a=s+6)}return e.slice(0,r)+e.slice(a)}function Ja(e){if(e==null)return e??null;if(typeof e!="string"||e.length===0||!e.includes("data-patient-info-block"))return e;let t=e;for(let r=0;r<8;r+=1){const n=Va(t);if(n===null)break;t=n}return t}function tn(e){const t=["texto","conteudo_template","achados","impressao","tecnica","indicacao_clinica","adicionais","conclusao"],r={...e};for(const n of t)typeof r[n]=="string"&&r[n].includes("data-patient-info-block")&&(r[n]=Ja(r[n])??"");return r}function ur(e,t){const r=tn(e);return{user_id:t,titulo:(r.titulo||"").trim().slice(0,200),texto:r.texto??null,modalidade_codigo:r.modalidade_codigo,indicacao_clinica:r.indicacao_clinica??null,tecnica:r.tecnica??null,achados:r.achados??null,impressao:r.impressao??null,adicionais:r.adicionais??null,regiao_codigo:r.regiao_codigo||null,categoria:r.categoria||"normal",tags:Array.isArray(r.tags)?r.tags:[],conteudo_template:r.conteudo_template??null,modo:r.modo||"simples",atalho:r.atalho?r.atalho.toLowerCase().trim():null}}function dr(e,t){const r=tn(e);return{user_id:t,titulo:(r.titulo||"").trim().slice(0,200),texto:r.texto,conclusao:r.conclusao||null,modalidade_codigo:r.modalidade_codigo,categoria:r.categoria||"normal",regiao_codigo:r.regiao_codigo||null,tags:Array.isArray(r.tags)?r.tags:[],indicacao_clinica:r.indicacao_clinica??null,tecnica:r.tecnica??null,atalho:r.atalho?r.atalho.toLowerCase().trim():null}}const fr="recent-user-templates",mr="recent-user-frases",hr="fav-user-templates",gr="fav-user-frases",pr=10;function pl(){var Vt,Jt;const{user:e,authReady:t}=Ge(),{subscription:r}=Ca(),n=pt(),a=S.useCallback(()=>{n.invalidateQueries({queryKey:["user-content-active",e==null?void 0:e.id],refetchType:"none"}),n.invalidateQueries({queryKey:["user-content-mapping",e==null?void 0:e.id],refetchType:"none"})},[n,e==null?void 0:e.id]),i=S.useCallback(()=>{n.invalidateQueries({queryKey:["user-content-active",e==null?void 0:e.id]}),n.invalidateQueries({queryKey:["user-content-inactive",e==null?void 0:e.id]})},[n,e==null?void 0:e.id]),o=S.useCallback(()=>{n.invalidateQueries({queryKey:["user-content-inactive",e==null?void 0:e.id]})},[n,e==null?void 0:e.id]),s=S.useCallback(()=>{n.invalidateQueries({queryKey:["user-content-active",e==null?void 0:e.id]}),n.invalidateQueries({queryKey:["user-content-frozen",e==null?void 0:e.id]})},[n,e==null?void 0:e.id]),[c,m]=S.useState(()=>{try{return JSON.parse(localStorage.getItem(fr)||"[]")}catch{return[]}}),[g,d]=S.useState(()=>{try{return JSON.parse(localStorage.getItem(mr)||"[]")}catch{return[]}}),[f,y]=S.useState(()=>{try{return JSON.parse(localStorage.getItem(hr)||"[]")}catch{return[]}}),[b,A]=S.useState(()=>{try{return JSON.parse(localStorage.getItem(gr)||"[]")}catch{return[]}});S.useEffect(()=>{localStorage.setItem(fr,JSON.stringify(c))},[c]),S.useEffect(()=>{localStorage.setItem(mr,JSON.stringify(g))},[g]),S.useEffect(()=>{localStorage.setItem(hr,JSON.stringify(f))},[f]),S.useEffect(()=>{localStorage.setItem(gr,JSON.stringify(b))},[b]);const p=S.useCallback(l=>{m(E=>[l,...E.filter(q=>q!==l)].slice(0,pr))},[]),h=S.useCallback(l=>{d(E=>[l,...E.filter(q=>q!==l)].slice(0,pr))},[]),v=S.useCallback(l=>{y(E=>E.includes(l)?E.filter(q=>q!==l):[...E,l])},[]),_=S.useCallback(l=>{A(E=>E.includes(l)?E.filter(q=>q!==l):[...E,l])},[]),x=S.useCallback(l=>f.includes(l),[f]),F=S.useCallback(l=>b.includes(l),[b]),{data:P,isLoading:X,refetch:I}=ke({queryKey:["user-content-active",e==null?void 0:e.id],queryFn:async()=>
3{if(!e)return{templates:[],frases:[]};const[l,E]=await Promise.all([$.from("user_templates").select("*").eq("user_id",e.id).eq("ativo",!0).order("created_at",{ascending:!1}),$.from("user_frases").select("*").eq("user_id",e.id).eq("ativo",!0).order("created_at",{ascending:!1})]);return l.error&&console.error("Error fetching user templates:",l.error),E.error&&console.error("Error fetching user frases:",E.error),{templates:l.data||[],frases:E.data||[]}},enabled:!!t&&!!e,...Ze.USER_MUTABLE,gcTime:24*60*60*1e3,placeholderData:()=>{if(!(e!=null&&e.id))return;const l=n.getQueryData(["user-boot-data",e.id]);if(l)return{templates:l.user_templates||[],frases:l.user_frases||[]}}}),T=(P==null?void 0:P.templates)||[],C=(P==null?void 0:P.frases)||[],M=X,R=X,L=I,j=I,[ne,Z]=S.useState(!1),{data:V,isLoading:le,refetch:ee}=ke({queryKey:["user-content-inactive",e==null?void 0:e.id],queryFn:async()=>{if(!e)return{templates:[],frases:[]};const[l,E]=await Promise.all([$.from("user_templates").select("*").eq("user_id",e.id).eq("ativo",!1).order("updated_at",{ascending:!1}),$.from("user_frases").select("*").eq("user_id",e.id).eq("ativo",!1).order("updated_at",{ascending:!1})]);return{templates:l.data||[],frases:E.data||[]}},enabled:!!e&&ne,...Ze.USER_MUTABLE}),Re=(V==null?void 0:V.templates)||[],De=(V==null?void 0:V.frases)||[],Se=ne?le:!1,u=ne?le:!1,k=()=>(Z(!0),ee()),D=()=>(Z(!0),ee()),[B,W]=S.useState(!1);S.useEffect(()=>{if(!e||B)return;const l=window.requestIdleCallback,E=l?l(()=>W(!0),{timeout:5e3}):window.setTimeout(()=>W(!0),4e3);return()=>{l&&window.cancelIdleCallback?window.cancelIdleCallback(E):window.clearTimeout(E)}},[e,B]);const{data:G,refetch:Y}=ke({queryKey:["user-grace-period",e==null?void 0:e.id],queryFn:async()=>{if(!e)return null;const{data:l,error:E}=await $.from("user_downgrade_grace_periods").select("*").eq("user_id",e.id).eq("action_taken","pending").maybeSingle();return E||!l?null:l},enabled:!!e&&B,...Ze.STABLE}),{data:J,refetch:ue}=ke({queryKey:["user-content-frozen",e==null?void 0:e.id],queryFn:async()=>{if(!e)return{templates:[],frases:[]};const[l,E]=await Promise.all([$.from("user_templates").select("*").eq("user_id",e.id).eq("ativo",!1).eq("frozen_by_downgrade",!0).order("frozen_at",{ascending:!1}),$.from("user_frases").select("*").eq("user_id",e.id).eq("ativo",!1).eq("frozen_by_downgrade",!0).order("frozen_at",{ascending:!1})]);return{templates:l.data||[],frases:E.data||[]}},enabled:!!e&&!!G,...Ze.STABLE}),de=(J==null?void 0:J.templates)||[],ye=(J==null?void 0:J.frases)||[],Je=ue,ia=ue,oa=G?Math.max(0,Math.ceil((new Date(G.grace_period_end).getTime()-Date.now())/(1e3*60*60*24))):null,fe={templates:((Vt=r==null?void 0:r.features)==null?void 0:Vt.max_user_templates)||10,frases:((Jt=r==null?void 0:r.features)==null?void 0:Jt.max_user_frases)||20},bt=T.length<fe.templates,_t=C.length<fe.frases,sa=T.length>fe.templates,ca=C.length>fe.frases,la=Math.max(0,T.length-fe.templates),ua=Math.max(0,C.length-fe.frases),Xt=me({mutationFn:async()=>{if(!e)throw new Error("Usuário não autenticado");const{error:l}=await $.from("user_templates").update({ativo:!0,frozen_at:null,frozen_by_downgrade:!1}).eq("user_id",e.id).eq("frozen_by_downgrade",!0);if(l)throw l;const{error:E}=await $.from("user_frases").update({ativo:!0,frozen_at:null,frozen_by_downgrade:!1}).eq("user_id",e.id).eq("frozen_by_downgrade",!0);if(E)throw E},onSuccess:()=>{s(),N.success("Conteúdo reativado com sucesso!")},onError:l=>{N.error(Ie(l,"Erro ao reativar conteúdo"))}}),Ke=S.useCallback((l,E,q)=>{if(!e)return;const ae=["user-content-active",e.id];n.setQueryData(ae,be=>{const K=be||{templates:[],frases:[]},_e=K[l]||[];return q==="insert"?_e.some(Qe=>Qe.id===E.id)?K:{...K,[l]:[E,..._e]}:{...K,[l]:_e.map(Qe=>Qe.id===E.id?E:Qe)}})},[n,e]),da=me({mutationFn:async l=>{if(!e)throw new Error("Usuário não autenticado");if(!bt)throw new Error(`Limite de ${fe.templates} templates atingido`);const E=ur(l,e.id),{data:q,error:ae}=await $.from("user_templates").insert(E).select("*").single();if(ae)throw ae;if(!q)throw new Error("Resposta vazia do banco ao criar template.");return q},onSuccess:l=>{Ke("templates",l,"insert"),a()},onError:l=>{Ae.error("[useUserContent] addTemplate failed",{message:l==null?void 0:l.message,code:l==null?void 0:l.code,details:l==null?void 0:l.details,hint:l==null?void 0:l.hint})}}),fa=me({mutationFn:async l=>{if(!e)throw new Error("Usuário não autenticado");if(!_t)throw new Error(`Limite de ${fe.frases} frases atingido`);const E=dr(l,e.id),{data:q,error:ae}=await $.from("user_frases").insert(E).select("*").single();if(ae)throw ae;if(!q)throw new Error("Resposta vazia do banco ao criar frase.");return q},onSuccess:l=>{Ke("frases",l,"insert"),a()},onError:l=>{Ae.error("[useUserContent] addFrase failed",{message:l==null?void 0:l.message,code:l==null?void 0:l.code,details:l==null?void 0:l.details,hint:l==null?void 0:l.hint})}}),ma=me({mutationFn:async({id:l,...E})=>{if(!e)throw new Error("Usuário não autenticado");const q=ur(E,e.id),{user_id:ae,...be}=q,{data:K,error:_e}=await $.from("user_templates").update(be).eq("id",l).eq("user_id",e.id).select("*").single();if(_e)throw _e;if(!K)throw new Error("Não foi possÃvel atualizar (sem permissão ou linha inexistente).");return K},onSuccess:l=>{Ke("templates",l,"update"),a()},onError:l=>{Ae.error("[useUserContent] updateTemplate failed",{message:l==null?void 0:l.message,code:l==null?void 0:l.code,details:l==null?void 0:l.details,hint:l==null?void 0:l.hint})}}),ha=me({mutationFn:async({id:l,...E})=>{if(!e)throw new Error("Usuário não autenticado");const q=dr(E,e.id),{user_id:ae,...be}=q,{data:K,error:_e}=await $.from("user_frases").update(be).eq("id",l).eq("user_id",e.id).select("*").single();if(_e)throw _e;if(!K)throw new Error("Não foi possÃvel atualizar (sem permissão ou linha inexistente).");return K},onSuccess:l=>{Ke("frases",l,"update"),a()},onError:l=>{Ae.error("[useUserContent] updateFrase failed",{message:l==null?void 0:l.message,code:l==null?void 0:l.code,details:l==null?void 0:l.details,hint:l==null?void 0:l.hint})}}),ga=me({mutationFn:async l=>{if(!e)throw new Error("Usuário não autenticado");const{error:E}=await $.from("user_templates").update({ativo:!1}).eq("id",l).eq("user_id",e.id);if(E)throw E},onSuccess:()=>{i(),N.success("Template movido para lixeira")},onError:l=>{N.error(Ie(l,"Erro ao remover template"))}}),pa=me({mutationFn:async l=>{if(!e)throw new Error("Usuário não autenticado");const{error:E}=await $.from("user_frases").update({ativo:!1}).eq("id",l).eq("user_id",e.id);if(E)throw E},onSuccess:()=>{i(),N.success("Frase movida para lixeira")},onError:l=>{N.error(Ie(l,"Erro ao remover frase"))}}),Gt=me({mutationFn:async l=>{if(!e)throw new Error("Usuário não autenticado");if(!bt)throw new Error(`Limite de ${fe.templates} templates atingido. Exclua um template antes de restaurar.`);const{error:E}=await $.from("user_templates").update({ativo:!0}).eq("id",l).eq("user_id",e.id);if(E)throw E},onSuccess:()=>{i(),N.success("Template restaurado!")},onError:l=>{N.error(Ie(l,"Erro ao restaurar template"))}}),Yt=me({mutationFn:async l=>{if(!e)throw new Error("Usuário não autenticado");if(!_t)throw new Error(`Limite de ${fe.frases} frases atingido. Exclua uma frase antes de restaurar.`);const{error:E}=await $.from("user_frases").update({ativo:!0}).eq("id",l).eq("user_id",e.id);if(E)throw E},onSuccess:()=>{i(),N.success("Frase restaurada!")},onError:l=>{N.error(Ie(l,"Erro ao restaurar frase"))}}),wa=me({mutationFn:async l=>{if(!e)throw new Error("Usuário não autenticado");const{error:E}=await $.from("user_templates").delete().eq("id",l).eq("user_id",e.id);if(E)throw E},onSuccess:()=>{o(),N.success("Template excluÃdo permanentemente")},onError:l=>{N.error(Ie(l,"Erro ao excluir template"))}}),ya=me({mutationFn:async l=>{if(!e)throw new Error("Usuário não autenticado");const{error:E}=await $.from("user_frases").delete().eq("id",l).eq("user_id",e.id);if(E)throw E},onSuccess:()=>{o(),N.success("Frase excluÃda permanentemente")},onError:l=>{N.error(Ie(l,"Erro ao excluir frase"))}}),ba=T.filter(l=>c.includes(l.id)),_a=C.filter(l=>g.includes(l.id)),va=T.filter(l=>f.includes(l.id)),Ea=C.filter(l=>b.includes(l.id)),xa=S.useCallback(l=>{const E=l.toLowerCase().trim(),q=T.find(be=>{var K;return((K=be.atalho)==null?void 0:K.toLowerCase())===E});if(q)return Ae.debug("[findByShortcut] Found user template:",q.titulo),{type:"template",item:q};const ae=C.find(be=>{var K;return((K=be.atalho)==null?void 0:K.toLowerCase())===E});return ae?(Ae.debug("[findByShortcut] Found user frase:",ae.titulo),{type:"frase",item:ae}):null},[T,C]);return{userTemplates:T,userFrases:C,deletedTemplates:Re,deletedFrases:De,recentUserTemplates:ba,recentUserFrases:_a,favoriteUserTemplates:va,favoriteUserFrases:Ea,limits:fe,gracePeriod:G,gracePeriodDaysRemaining:oa,frozenTemplates:de,frozenFrases:ye,hasFrozenContent:de.length>0||ye.length>0,loadingTemplates:M,loadingFrases:R,loadingDeletedTemplates:Se,loadingDeletedFrases:u,canAddTemplate:bt,canAddFrase:_t,isTemplatesOverLimit:sa,isFrasesOverLimit:ca,templatesOverCount:la,frasesOverCount:ua,addTemplateAsync:da.mutateAsync,addFraseAsync:fa.mutateAsync,updateTemplateAsync:ma.mutateAsync,updateFraseAsync:ha.mutateAsync,deleteTemplate:ga.mutate,deleteFrase:pa.mutate,restoreTemplate:Gt.mutate,restoreFrase:Yt.mutate,permanentDeleteTemplate:wa.mutate,permanentDeleteFrase:ya.mutate,reactivateAllFrozen:Xt.mutate,findByShortcut:xa,trackUserTemplateUsage:p,trackUserFraseUsage:h,toggleFavoriteUserTemplate:v,toggleFavoriteUserFrase:_,isUserTemplateFavorite:x,isUserFraseFavorite:F,isRestoringTemplate:Gt.isPending,isRestoringFrase:Yt.isPending,isReactivatingFrozen:Xt.
3isPending,refetchTemplates:L,refetchFrases:j,refetchDeletedTemplates:k,refetchDeletedFrases:D,refetchGracePeriod:Y,refetchFrozenTemplates:Je,refetchFrozenFrases:ia}}const Me=e=>e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/\s+/g," ").trim(),Ka=[{kind:"impressao",canonical:"IMPRESSÃO",re:/^(impressao( diagnostica)?|conclus(ao|oes)( diagnostica)?|opiniao|diagnostico|hipotese(s)? diagnostica(s)?|parecer)$/},{kind:"tecnica",canonical:"TÃCNICA",re:/^(tecnica( do exame| utilizada)?|metodo(logia)?|protocolo|aquisicao|procedimento|exame realizado)$/},{kind:"achados",canonical:"ANÃLISE",re:/^(analise|achados?|relatorio|descricao|resultado(s)?|estudo|avaliacao|laudo|exame)$/},{kind:"indicacao",canonical:"INDICAÃÃO CLÃNICA",re:/^(indicacao( clinica)?|historia clinica|dados clinicos|informacoes clinicas|motivo do exame)$/},{kind:"comparacao",canonical:"COMPARAÃÃO",re:/^(comparacao|exames? previos?|estudo comparativo)$/},{kind:"complementar",canonical:"",re:/^(observac(ao|oes)|obs|recomendac(ao|oes)|nota(s)?|comentarios?|sugest(ao|oes)|adicionais|correlacao clinica)$/}];function Ce(e){const t=e.replace(/\u00a0/g," ").trim();if(!t||t.length>45)return null;const r=Me(t).replace(/[:.\-ââ]+$/,"").trim();for(const n of Ka)if(n.re.test(r))return{kind:n.kind,canonical:n.canonical||t.replace(/[:.]+$/,"").toUpperCase()};return null}function Qa(e){const t=e.match(/^([^:]{3,40}):\s*(.+)$/);if(!t)return null;const r=Ce(t[1]);return r?{...r,rest:t[2].trim()}:null}const Za=/\b(ultrassonografia|ultrassom|ultra-som|ecografia|ecodoppler|doppler|usg?|tomografia|angiotomografia|angio-?tc|tc|ressonancia|angiorressonancia|angio-?rm|rm|rnm|colangiorressonancia|radiografia|raio-?x|rx|mamografia|densitometria|cintilografia|elastografia|urografia|enterografia|artrografia|tomossintese|telerradiografia)\b/,rn=/^(paciente|nome|data|idade|sexo|dn|nascimento|medic[oa]|solicitante|convenio|crm|prontuario|atendimento|registro|pedido|exame n|codigo|clinica|hospital|unidade|origem|leito|setor)\b/;function nn(e){const t=Me(e).replace(/[:.]+$/,"");return t.length<4||t.length>140||rn.test(t)||/[.;]\s*\S/.test(t)&&t.split(" ").length>14?!1:Za.test(t)}const wr=/(\bdr\.?a?\s|\bdra?\.\s|cremeb?|\bcrm\b|\brqe\b|medic[oa] radiologista|titulo de especialista|radiologia e diagnostico por imagem|assinado digitalmente|assinatura|responsavel tecnico)/,ei=/^[\s_\-ââ=.]{4,}$/;function ie(e){return(e.textContent||"").replace(/\u00a0/g," ").replace(/\s+/g," ").trim()}const ti=/\b(figado|hepatic|vesicula|vias biliares|pancreas|baco|rins?|renal|bexiga|aorta|utero|ovario|prostata|tireoide|mama|pulm|mediastin|coracao|encefalo|ventriculo|parenquima|linfonodo|figado|alcas|estomago|intestin|coluna|vertebr|articula|tendao|musculo|liquido livre|cavidade)\b/,Oe=(e,t)=>{const r=e.createElement("h3");return r.textContent=t,r};function Nt(e,t){const r={html:e,titleText:"",sections:{tecnica:!1,achados:!1,conclusao:!1},inferredAchados:!1,removedHeader:!1,removedSignature:!1,warnings:[]};if(typeof DOMParser>"u"||!e)return r;const n=new DOMParser().parseFromString(`<div id="root">${e}</div>`,"text/html"),a=n.getElementById("root");let i=Array.from(a.children);i.forEach(p=>{if(!/^(P|H\d)$/.test(p.tagName))return;const h=ie(p);if(Ce(h))return;const v=Qa(h);if(v&&(v.kind!=="complementar"||/^[A-ZÃ-Ã\s]+$/.test(h.split(":")[0]))){const _=n.createElement("p");_.textContent=v.rest,p.replaceWith(Oe(n,v.canonical),_)}}),i=Array.from(a.children);let o=i.findIndex((p,h)=>h<15&&/^(P|H\d)$/.test(p.tagName)&&nn(ie(p))&&!Ce(ie(p)));o<0&&(o=i.findIndex((p,h)=>{if(h>=8||!/^(P|H\d)$/.test(p.tagName))return!1;const v=ie(p);return!v||v.length>120||rn.test(Me(v))||Ce(v)?!1:/center/.test(p.getAttribute("style")||"")||/^H[12]$/.test(p.tagName)||v===v.toUpperCase()&&/[A-ZÃ-Ã]{3}/.test(v)&&v.split(" ").length>=2}));let s="";if(o>=0){const p=i[o];s=ie(p).replace(/[:]+$/,"");const h=n.createElement("h2");h.setAttribute("style","text-align: center"),h.textContent=s.toUpperCase(),p.replaceWith(h),i[o]=h}let c=-1;const m={tecnica:!1,achados:!1,conclusao:!1};i.forEach((p,h)=>{if(h===o||!/^(P|H\d)$/.test(p.tagName))return;
3const v=Ce(ie(p));if(!v)return;const _=Oe(n,v.canonical);p.replaceWith(_),i[h]=_,v.kind==="impressao"&&(c<0&&(c=h),m.conclusao=!0),v.kind==="tecnica"&&(m.tecnica=!0),v.kind==="achados"&&(m.achados=!0)});let g=i.length;for(let p=i.length-1;p>Math.max(o,c);p--){const h=i[p],v=Me(ie(h));if(!v||ei.test(ie(h))||h.tagName==="HR"||wr.test(v)||/^[a-z .]{3,50}$/.test(v)&&(h.querySelector("em,i")||/center/.test(h.getAttribute("style")||""))&&p>i.length-5)g=p;else break}i.slice(g).some(p=>wr.test(Me(ie(p))))||(g=i.length);let f=!1;if(o>=0&&!m.achados){const p=c>=0?c:g;let h=o+1;for(let _=o+1;_<p;_++){if(i[_].tagName!=="H3")continue;h=_+1;let x=h+(i[_].textContent==="TÃCNICA"&&i[h]&&i[h].tagName!=="H3"?1:0);for(;x<p&&i[x].tagName!=="H3"&&!ti.test(Me(ie(i[x])));)x++;h=x<p&&i[x].tagName!=="H3"?x:Math.min(_+2,p)}const v=i.slice(h,p).filter(_=>_.tagName!=="H3"&&ie(_));if(v.length){const _=v[0];!m.tecnica&&/\b(cortes|aquisicao|aquisicoes|sequencias?|ponderad\w*|contraste|protocolo|transdutor|exame realizado|foram obtid\w*|reformata\w*|incidencias?)\b/.test(Me(ie(_)))&&v.length>1?(_.before(Oe(n,"TÃCNICA")),m.tecnica=!0,v[1].before(Oe(n,"ANÃLISE"))):_.before(Oe(n,"ANÃLISE")),m.achados=!0,f=!0}}const y=[];o<0&&y.push("TÃtulo do exame não encontrado"),m.conclusao||y.push("Impressão não encontrada");let b=!1,A=!1;if(t==="template"){const h=Array.from(a.children).find(_=>_.tagName==="H2");if(h&&o>=0){let _=h.previousElementSibling;for(;_;){const x=_.previousElementSibling;_.remove(),b=!0,_=x}}m.conclusao&&g<i.length&&i.slice(g).forEach(_=>{_.isConnected&&(_.remove(),A=!0)});let v=a.lastElementChild;for(;v&&(v.tagName==="HR"||!ie(v));){const _=v.previousElementSibling;v.remove(),v=_}}return{html:a.innerHTML,titleText:s,sections:m,inferredAchados:f,removedHeader:b,removedSignature:A,warnings:y}}const ri=/^(t[ée]cnica|m[ée]todo|relat[óo]rio|an[áa]lise|achados?|descri[çc][ãa]o|impress[ãa]o( diagn[óo]stica)?|conclus[ãa]o|opini[ãa]o|indica[çc][ãa]o( cl[Ãi]nica)?|hist[óo]ria cl[Ãi]nica|dados cl[Ãi]nicos|observa[çc](ão|ões|ao|oes)|obs|coment[áa]rios?|nota|recomenda[çc](ão|ões|ao|oes)|compara[çc][ãa]o|resultado)\s*:?$/i;function qe(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function yr(e){const t=e.replace(/\s+/g," ").trim();return!t||t.length>45?!1:ri.test(t)||!!Ce(t)}function an(e){if(typeof DOMParser>"u")return e.replace(/<(br|\/p|\/h\d|\/li|\/div|\/tr)[^>]*>/gi,` 4`).replace(/<[^>]+>/g,"").replace(/ /g," ").split(` 5`).map(a=>a.trim()).filter(Boolean);const t=new DOMParser().parseFromString(`<div>${e}</div>`,"text/html"),r=t.body.querySelectorAll("h1,h2,h3,h4,h5,h6,p,li,td"),n=[];if(r.forEach(a=>{const i=(a.textContent||"").replace(/\s+/g," ").trim();i&&n.push(i)}),n.length===0){const a=(t.body.textContent||"").trim();a&&n.push(...a.split(` 6`).map(i=>i.trim()).filter(Boolean))}return n}const ni=/^(paciente|nome|data|idade|sexo|m[ée]dico|solicitante|conv[êe]nio|crm|dr\.?|dra\.?|p[áa]gina|exame n)/i;function ai(e){const t=an(e),r=t.slice(0,15).find(n=>nn(n)&&!yr(n));if(r)return br(r.replace(/[:\s]+$/,"").trim());for(const n of t.slice(0,12)){const a=n.replace(/[:\s]+$/,"").trim();if(!(a.length<4||a.length>120)&&!yr(a)&&!ni.test(a)&&!/^\d+[\d/.\s-]*$/.test(a))return br(a)}return""}const ii=new Set(["de","do","da","dos","das","e","com","sem","em","a","o","para","por"]),oi=new Set(["us","tc","rm","rx","pet","ct","atm","tvp","bi-rads","ti-rads"]);function br(e){return e!==e.toUpperCase()?e:e.toLowerCase().split(/\s+/).map((t,r)=>oi.has(t)?t.toUpperCase():r>0&&ii.has(t)?t:t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const si=[{code:"MM",re:/\b(mamografia|mamograf|mmg|tomossintese)\b/},{code:"RM",re:/\b(ressonancia|rm|rnm|angio-?rm|colangio-?rm|entero-?rm)\b/},{code:"TC",re:/\b(tomografia|tc|angio-?tc|tcmd|uro-?tc|entero-?tc)\b/},{code:"US",re:/\b(ultrassonografia|ultrassom|ultra-som|ecografia|ultrassonografico|us|usg|doppler|ecodoppler|elastografia)\b/},{code:"RX",re:/\b(radiografia|raio-?x|rx|radiologico simples|telerradiografia|escanometria)\b/}];function ci(e,t=""){for(const r of[e,t.slice(0,1500)]){const n=qe(r);if(n){for(const a of si)if(a.re.test(n))return a.code}}return null}const li=[[/ coluna cervical /,"COL_CERVICAL"],[/ (gestacional|obstetric[ao]|gestacao|fetal|morfologic[ao]|translucencia) /,"OBSTETRICO"],[/ (carotid|vertebra(is|l) |cervica(l|is) |tireoide|tireoid|pescoco|cervical )/,"CERVICAL"],[/ (testicul|escrot|bolsa testicular|bolsa escrotal)/,"ESCROTO"],[/ (aparelho urinario|vias urinarias|rins|renal|renais|urinari)/,"ABDOME"],[/ doppler .*(membros?|mmii|mmss) |(membros?|mmii|mmss) .*doppler /,"VASCULAR"],[/ (membros? inferior(es)?|mmii) /,"EXT_INFERIOR"],[/ (membros? superior(es)?|mmss) /,"EXT_SUPERIOR"],[/ (abdome|abdominal|abdomen) /,"ABDOME"]];function ui(e,t,r){if(!(r!=null&&r.length))return null;const n=[...r].sort((o,s)=>s.nome.length-o.nome.length),a=o=>r.some(s=>s.codigo===o),i=` ${qe(e).replace(/[^a-z0-9]+/g," ")} `;for(const[o,s]of li)if(o.test(i)&&a(s))return s;for(const o of[e]){const s=` ${qe(o).replace(/[^a-z0-9]+/g," ")} `;if(s.trim().length!==0)for(const c of n){const m=qe(c.nome).replace(/[^a-z0-9]+/g," ").trim();if(m.length>=3&&s.includes(` ${m} `))return c.codigo}}return null}function di(e,t){if(!e)return"";const n=qe(e).replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(i=>i.length>2&&!["com","sem","para","das","dos","uma","uns"].includes(i)).map(i=>i[0]).join("").slice(0,5),a=(t||"").toLowerCase().slice(0,2);return`${a==="ge"?"":a}${n}`.slice(0,15)}function wl(e,t=[],r=""){const n=ai(e)||r,a=an(e).join(` 7`),i=ci(n,a),o=ui(n,a,t);return{titulo:n,modalidade:i,regiao:o,atalho:di(n,i||"GERAL")}}function yl(e){return e.replace(/\.[^.]+$/,"").replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}/*! @rgrove/parse-xml v4.2.0 | ISC License | Copyright Ryan Grove */var Bt=Object.defineProperty,fi=Object.getOwnPropertyDescriptor,mi=Object.getOwnPropertyNames,hi=Object.prototype.hasOwnProperty,gi=(e,t)=>{for(var r in t)Bt(e,r,{get:t[r],enumerable:!0})},pi=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of mi(t))!hi.call(e,a)&&a!==r&&Bt(e,a,{get:()=>t[a],enumerable:!(n=fi(t,a))||n.enumerable});return e},wi=e=>pi(Bt({},"__esModule",{value:!0}),e),on={};gi(on,{XmlCdata:()=>un,XmlComment:()=>dn,XmlDeclaration:()=>fn,XmlDocument:()=>hn,XmlDocumentType:()=>gn,XmlElement:()=>zt,XmlError:()=>pn,XmlNode:()=>z,XmlProcessingInstruction:()=>$t,XmlText:()=>Ot,parseXml:()=>ki});var yi=wi(on),xt="",bi=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,_i=class{constructor(e){if(this.k=this.u(e,!0),this.d=0,this.length=e.length,this.l=this.k!==this.length,this.h=e,this.l){let t=[];for(let r=0,n=0;n<this.k;++n)t[n]=r,r+=e.codePointAt(r)>65535?2:1;this.A=t}}get B(){return this.d>=this.k}u(e,t=this.l){return t?e.replace(bi,"_").length:e.length}p(e=1){this.d=Math.min(this.k,this.d+e)}f(e=this.d){var t;return this.l?(t=this.A[e])!=null?t:1/0:e}G(e=1){let t=this.m(e);return this.p(e),t}v(e){let t=this.f(),r=this.h.slice(t,t+e);return this.p(this.u(r)),r}w(e){let{length:t,l:r,h:n}=this,a=this.f(),i=a;if(r)for(;i<t;){let o=n[i],s=o>="\uD800"&&o<="\uDBFF";if(s&&(o+=n[i+1]),!e(o))break;i+=s?2:1}else for(;i<t&&e(n[i]);)++i;return this.v(i-a)}b(e){let{length:t}=e,r=this.f();return e===this.h.slice(r,r+t)?(this.p(t===1?1:this.u(e)),e):xt}x(e){let t=this.h.slice(this.f()).search(e);return t>0?this.v(t):xt}s(e){let t=this.f(),r=this.h.indexOf(e,t);return r>0?this.v(r-t):xt}m(e=1){let{d:t,h:r}=this;return this.l?r.slice(this.f(t),this.f(t+e)):r.slice(t,t+e)}n(e=0){this.d=e>=0?Math.min(this.k,e):Math.max(0,this.d+e)}},vi=/["&<]/,Ei=/['&<]/,xi=/\r\n|[\n\r\t]/g,Ti=/<|&|]]>/,Si=Object.freeze(Object.assign(Object.create(null),{amp:"&",apos:"'",gt:">",lt:"<",quot:'"'}));function sn(e){let t=e.codePointAt(0);return t>=97&&t<=122||t>=65&&t<=90||t>=48&&t<=57||t===45||t===46||t===183||t>=768&&t<=879||t===8255||t===8256||cn(e,t)}function cn(e,t=e.codePointAt(0)){return t>=97&&t<=122||t>=65&&t<=90||t===58||t===95||t>=192&&t<=214||t>=216&&t<=246||t>=248&&t<=767||t>=880&&t<=893||t>=895&&t<=8191||t===8204||t===8205||t>=8304&&t<=8591||t>=11264&&t<=12271||t>=12289&&t<=55295||t>=63744&&t<=64975||t>=65008&&t<=65533||t>=65536&&t<=983039}function Ii(e){return e==="#"||sn(e)}function Ai(e){let t=e.codePointAt(0);return t===32||t===9||t===10||t===13}function _r(e){return e>=32&&e<=55295||e===10||e===9||e===13||e>=57344&&e<=65533||e>=65536&&e<=1114111}var Ee=class ln{constructor(){this.parent=null,this.start=-1,this.end=-1}get document(){var t,r;return(r=(t=this.parent)==null?void 0:t.document)!=null?r:null}get isRootNode(){return this.parent!==null&&this.parent===this.document&&this.type===ln.TYPE_ELEMENT}get preserveWhitespace(){var t;return!!((t=this.parent)!=null&&t.preserveWhitespace)}get type(){return""}
7toJSON(){let t={type:this.type};return this.isRootNode&&(t.isRootNode=!0),this.preserveWhitespace&&(t.preserveWhitespace=!0),this.start!==-1&&(t.start=this.start,t.end=this.end),t}};Ee.TYPE_CDATA="cdata";Ee.TYPE_COMMENT="comment";Ee.TYPE_DOCUMENT="document";Ee.TYPE_DOCUMENT_TYPE="doctype";Ee.TYPE_ELEMENT="element";Ee.TYPE_PROCESSING_INSTRUCTION="pi";Ee.TYPE_TEXT="text";Ee.TYPE_XML_DECLARATION="xmldecl";var z=Ee,Ot=class extends z{constructor(e=""){super(),this.text=e}get type(){return z.TYPE_TEXT}toJSON(){return Object.assign(z.prototype.toJSON.call(this),{text:this.text})}},un=class extends Ot{get type(){return z.TYPE_CDATA}},dn=class extends z{constructor(e=""){super(),this.content=e}get type(){return z.TYPE_COMMENT}toJSON(){return Object.assign(z.prototype.toJSON.call(this),{content:this.content})}},fn=class extends z{constructor(e,t,r){super(),this.version=e,this.encoding=t??null,this.standalone=r??null}get type(){return z.TYPE_XML_DECLARATION}toJSON(){let e=z.prototype.toJSON.call(this);e.version=this.version;for(let t of["encoding","standalone"])this[t]!==null&&(e[t]=this[t]);return e}},zt=class mn extends z{constructor(t,r=Object.create(null),n=[]){super(),this.name=t,this.attributes=r,this.children=n}get isEmpty(){return this.children.length===0}get preserveWhitespace(){let t=this;for(;t instanceof mn;){if("xml:space"in t.attributes)return t.attributes["xml:space"]==="preserve";t=t.parent}return!1}get text(){return this.children.map(t=>"text"in t?t.text:"").join("")}get type(){return z.TYPE_ELEMENT}toJSON(){return Object.assign(z.prototype.toJSON.call(this),{name:this.name,attributes:this.attributes,children:this.children.map(t=>t.toJSON())})}},hn=class extends z{constructor(e=[]){super(),this.children=e}get document(){return this}get root(){for(let e of this.children)if(e instanceof zt)return e;return null}get text(){return this.children.map(e=>"text"in e?e.text:"").join("")}get type(){return z.TYPE_DOCUMENT}toJSON(){return Object.assign(z.prototype.toJSON.call(this),{children:this.children.map(e=>e.toJSON())})}},gn=class extends z{constructor(e,t,r,n){super(),this.name=e,this.publicId=t??null,this.systemId=r??null,this.internalSubset=n??null}get type(){return z.TYPE_DOCUMENT_TYPE}toJSON(){let e=z.prototype.toJSON.call(this);e.name=this.name;for(let t of["publicId","systemId","internalSubset"])this[t]!==null&&(e[t]=this[t]);return e}},pn=class extends Error{constructor(e,t,r){let n=1,a="",i=1;for(let c=0;c<t;++c){let m=r[c];m===` 8`?(n=1,a="",i+=1):(n+=1,a+=m)}let o=r.indexOf(` 9`,t);a+=o===-1?r.slice(t):r.slice(t,o);let s=0;a.length>50&&(n<40?a=a.slice(0,50):(s=n-20,a=a.slice(s,n+30))),super(`${e} (line ${i}, column ${n}) 10 ${a} 11`+" ".repeat(n-s+1)+`^ 12`),this.column=n,this.excerpt=a,this.line=i,this.name="XmlError",this.pos=t}},$t=class extends z{constructor(e,t=""){super(),this.name=e,this.content=t}get type(){return z.TYPE_PROCESSING_INSTRUCTION}toJSON(){return Object.assign(z.prototype.toJSON.call(this),{name:this.name,content:this.content})}},vr="",Mi=class{constructor(e,t={}){let r=this.document=new hn;this.j=r,this.g=t,this.c=new _i(e),this.g.includeOffsets&&(r.start=0,r.end=e.length),this.parse()}i(e,t){return e.parent=this.j,this.g.includeOffsets&&(e.start=this.c.f(t),e.end=this.c.f()),this.j.children.push(e),!0}y(e,t){let{children:r}=this.j,{length:n}=r;if(e=tt(e),n>0){let a=r[n-1];if((a==null?void 0:a.type)===z.TYPE_TEXT){let i=a;return i.text+=e,this.g.includeOffsets&&(i.end=this.c.f()),!0}}return this.i(new Ot(e),t)}H(){let e=Object.create(null);for(;this.e();){let t=this.q();if(!t)break;let r=this.t()&&this.I();if(r===!1)throw this.a("Attribute value expected");if(t in e)throw this.a(`Duplicate attribute: ${t}`);if(t==="xml:space"&&r!=="default"&&r!=="preserve")throw this.a('Value of the `xml:space` attribute must be "default" or "preserve"');e[t]=r}if(this.g.sortAttributes){let t=Object.keys(e).sort(),r=Object.create(null);for(let n=0;n<t.length;++n){let a=t[n];r[a]=e[a]}e=r}return e}I(){let{c:e}=this,t=e.m();if(t!=='"'&&t!=="'")return!1;e.p();let r,n=!1,a=vr,i=t==='"'?vi:Ei;e:for(;!e.B;)switch(r=e.x(i),r&&(this.o(r),a+=r.replace(xi," ")),e.m()){case t:n=!0;break e;case"&":a+=this.C();continue;case"<":throw this.a("Unescaped `<` is not allowed in an attribute value");default:break e}if(!n)throw this.a("Unclosed attribute");return e.p(),a}J(){let{c:e}=this,t=e.d;if(!e.b("<![CDATA["))return!1;let r=e.s("]]>");if(this.o(r),!e.b("]]>"))throw this.a("Unclosed CDATA section");return this.g.preserveCdata?this.i(new un(tt(r)),t):this.y(r,t)}K(){let{c:e}=this,t=e.d,r=e.x(Ti);if(!r)return!1;if(this.o(r),e.m(3)==="]]>")throw this.a("Element content may not contain the CDATA section close delimiter `]]>`");return this.y(r,t)}D(){let{c:e}=this,t=e.d;if(!e.b("<!--"))return!1;let r=e.s("--");if(this.o(r),!e.b("-->"))throw e.m(2)==="--"?this.a("The string `--` isn't allowed inside a comment"):this.a("Unclosed comment");return this.g.preserveComments?this.i(new dn(tt(r)),t):!0}L(){let e=this.c.d,t=this.C();return t?this.y(t,e):!1}M(){let{c:e}=this,t=e.d;if(!e.b("<!DOCTYPE"))return!1;
12let r=this.e()&&this.q();if(!r)throw this.a("Expected a name");let n,a;if(this.e()){if(e.b("PUBLIC")){if(n=this.e()&&this.N(),n===!1)throw this.a("Expected a public identifier");this.e()}if(n!==void 0||e.b("SYSTEM")){if(this.e(),a=this.r(),a===!1)throw this.a("Expected a system identifier");this.e()}}let i;if(e.b("[")){if(i=e.x(/\][\x20\t\r\n]*>/),!e.b("]"))throw this.a("Unclosed internal subset");this.e()}if(!e.b(">"))throw this.a("Unclosed doctype declaration");return this.g.preserveDocumentType?this.i(new gn(r,n,a,i),t):!0}E(){let{c:e}=this,t=e.d;if(!e.b("<"))return!1;let r=this.q();if(!r)return e.n(t),!1;let n=this.H(),a=!!e.b("/>"),i=new zt(r,n);if(i.parent=this.j,!a){if(!e.b(">"))throw this.a(`Unclosed start tag for element \`${r}\``);this.j=i;do this.K();while(this.E()||this.L()||this.J()||this.F()||this.D());let o=e.d,s;if(!e.b("</")||!(s=this.q())||s!==r)throw e.n(o),this.a(`Missing end tag for element ${r}`);if(this.e(),!e.b(">"))throw this.a(`Unclosed end tag for element ${r}`);this.j=i.parent}return this.i(i,t)}t(){return this.e(),this.c.b("=")?(this.e(),!0):!1}z(){return this.D()||this.F()||this.e()}q(){return cn(this.c.m())?this.c.w(sn):vr}F(){let{c:e}=this,t=e.d;if(!e.b("<?"))return!1;let r=this.q();if(r){if(r.toLowerCase()==="xml")throw e.n(t),this.a("XML declaration isn't allowed here")}else throw this.a("Invalid processing instruction");if(!this.e()){if(e.b("?>"))return this.i(new $t(r),t);throw this.a("Whitespace is required after a processing instruction name")}let n=e.s("?>");if(this.o(n),!e.b("?>"))throw this.a("Unterminated processing instruction");return this.i(new $t(r,tt(n)),t)}O(){let{c:e}=this,t=e.d;for(this.P();this.z(););if(this.M())for(;this.z(););return t<e.d}N(){let e=this.c.d,t=this.r();if(t!==!1&&!/^[-\x20\r\na-zA-Z0-9'()+,./:=?;!*#@$_%]*$/.test(t))throw this.c.n(e),this.a("Invalid character in public identifier");return t}C(){let{c:e}=this;if(!e.b("&"))return!1;let t=e.w(Ii);if(e.G()!==";")throw this.a("Unterminated reference (a reference must end with `;`)");let r;if(t[0]==="#"){let n=t[1]==="x"?parseInt(t.slice(2),16):parseInt(t.slice(1),10);if(isNaN(n))throw this.a("Invalid character reference");if(!_r(n))throw this.a("Character reference resolves to an invalid character");r=String.fromCodePoint(n)}else if(r=Si[t],r===void 0){let{ignoreUndefinedEntities:n,resolveUndefinedEntity:a}=this.g,i=`&${t};`;if(a){let o=a(i);if(o!=null){let s=typeof o;if(s!=="string")throw new TypeError(`\`resolveUndefinedEntity()\` must return a string, \`null\`, or \`undefined\`, but returned a value of type ${s}`);return o}}if(n)return i;throw e.n(-i.length),this.a(`Named entity isn't defined: ${i}`)}return r}r(){let{c:e}=this,t=e.b('"')||e.b("'");if(!t)return!1;let r=e.s(t);if(this.o(r),!e.b(t))throw this.a("Missing end quote");return r}e(){return!!this.c.w(Ai)}P(){let{c:e}=this,t=e.d;if(!e.b("<?xml"))return!1;if(!this.e())throw this.a("Invalid XML declaration");let r=!!e.b("version")&&this.t()&&this.r();if(r===!1)throw this.a("XML version is missing or invalid");if(!/^1\.[0-9]+$/.test(r))throw this.a("Invalid character in version number");let n,a;if(this.e()){if(n=!!e.b("encoding")&&this.t()&&this.r(),n){if(!/^[A-Za-z][\w.-]*$/.test(n))throw this.a("Invalid character in encoding name");this.e()}if(a=!!e.b("standalone")&&this.t()&&this.r(),a){if(a!=="yes"&&a!=="no")throw this.a('Only "yes" and "no" are permitted as values of `standalone`');this.e()}}if(!e.b("?>"))throw this.a("Invalid or unclosed XML declaration");return this.g.preserveXmlDeclaration?this.i(new fn(r,n||void 0,a||void 0),t):!0}a(e){let{c:t}=this;return new pn(e,t.d,t.h)}parse(){if(this.c.b("\uFEFF"),this.O(),!this.E())throw this.a("Root element is missing or invalid");for(;this.z(););if(!this.c.B)throw this.a("Extra content at the end of the document")}o(e){let{length:t}=e;for(let r=0;r<t;++r){let n=e.codePointAt(r);if(!_r(n))throw this.c.n(-([...e].length-r)),this.a("Invalid character");n>65535&&(r+=1)}}};function tt(e){let t=0;for(;(t=e.indexOf("\r",t))!==-1;)e=e[t+1]===` 13`?e.slice(0,t)+e.slice(t+1):e.slice(0,t)+` 14`+e.slice(t+1);return e}function ki(e,t){return new Mi(e,t).document}function Ci(e){const t=String(e),r=[];return{toOffset:a,toPoint:n};function n(i){if(typeof i=="number"&&i>-1&&i<=t.length){let o=0;for(;;){let s=r[o];if(s===void 0){const c=Er(t,r[o-1]);s=c===-1?t.length+1:c+1,r[o]=s}if(s>i)return{line:o+1,column:i-(o>0?r[o-1]:0)+1,offset:i};o++}}}function a(i){if(i&&typeof i.line=="number"&&typeof i.column=="number"&&!Number.isNaN(i.line)&&!Number.isNaN(i.column)){for(;r.length<i.line;){const s=r[r.length-1],c=Er(t,s),m=c===-1?t.length+1:c+1;if(s===m)break;r.push(m)}const o=(i.line>1?r[i.line-2]:0)+i.column-1;if(o<r[i.line-1])return o}}}function Er(e,t){const r=e.indexOf("\r",t),n=e.indexOf(` 15`,t);return n===-1?r:r===-1||r+1===n?n:r<n?r:n}function Fi(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?xr(e.position):"start"in e||"end"in e?xr(e):"line"in e||"column"in e?Lt(e):""}function Lt(e){return Tr(e&&e.line)+":"+Tr(e&&e.column)}function xr(e){return Lt(e&&e.start)+"-"+Lt(e&&e.end)}function Tr(e){return e&&typeof e=="number"?e:1}
15class re extends Error{constructor(t,r,n){super(),typeof r=="string"&&(n=r,r=void 0);let a="",i={},o=!1;if(r&&("line"in r&&"column"in r?i={place:r}:"start"in r&&"end"in r?i={place:r}:"type"in r?i={ancestors:[r],place:r.position}:i={...r}),typeof t=="string"?a=t:!i.cause&&t&&(o=!0,a=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof n=="string"){const c=n.indexOf(":");c===-1?i.ruleId=n:(i.source=n.slice(0,c),i.ruleId=n.slice(c+1))}if(!i.place&&i.ancestors&&i.ancestors){const c=i.ancestors[i.ancestors.length-1];c&&(i.place=c.position)}const s=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=s?s.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=s?s.line:void 0,this.name=Fi(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=o&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}re.prototype.file="";re.prototype.name="";re.prototype.reason="";re.prototype.message="";re.prototype.stack="";re.prototype.column=void 0;re.prototype.line=void 0;re.prototype.ancestors=void 0;re.prototype.cause=void 0;re.prototype.fatal=void 0;re.prototype.place=void 0;re.prototype.ruleId=void 0;re.prototype.source=void 0;function Ye(e){const t=Ci(e);let r;try{r=yi.parseXml(String(e),{includeOffsets:!0,preserveCdata:!0,preserveComments:!0,preserveDocumentType:!0,preserveXmlDeclaration:!0})}catch(i){const o=i,s=t.toPoint(o.pos),c=new re("Could not parse XML with `@rgrove/parse-xml`",{cause:o,place:s,ruleId:"error",source:"xast-util-from-xml"});throw c.fatal=!0,c.url="https://github.com/syntax-tree/xast-util-from-xml#throws",c}const n={location:t},a=Li(r,n);return yn(r,a,n),a}function Ni(e){return{type:"cdata",value:e.text}}function $i(e){return{type:"comment",value:e.content}}function Li(e,t){return{type:"root",children:wn(e.children,t)}}function Pi(e){return{type:"doctype",name:e.name,public:e.publicId||void 0,system:e.systemId||void 0}}function Ri(e,t){const r=wn(e.children,t);return{type:"element",name:e.name,attributes:{...e.attributes},children:r}}function Di(e){return{type:"instruction",name:e.name,value:e.content}}function Ui(e){return{type:"text",value:e.text}}function Bi(e){const t=[];return e.version&&t.push('version="'+e.version+'"'),e.encoding&&t.push('encoding="'+e.encoding+'"'),e.standalone&&t.push('standalone="'+e.standalone+'"'),{type:"instruction",name:"xml",value:t.join(" ")}}function wn(e,t){const r=[];let n=-1;for(;++n<e.length;){const a=e[n];let i;a.type==="cdata"?i=Ni(a):a.type==="comment"?i=$i(a):a.type==="doctype"?i=Pi(a):a.type==="element"?i=Ri(a,t):a.type==="pi"?i=Di(a):a.type==="text"?i=Ui(a):a.type==="xmldecl"&&(i=Bi(a)),i&&(yn(a,i,t),r.push(i))}return r}function yn(e,t,r){const n=e.start===-1?void 0:r.location.toPoint(e.start),a=e.end===-1?void 0:r.location.toPoint(e.end);n&&a&&(t.position={start:n,end:a})}var oe=Uint8Array,Pe=Uint16Array,Oi=Int32Array,bn=new oe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),_n=new oe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),zi=new oe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),vn=function(e,t){for(var r=new Pe(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];for(var a=new Oi(r[30]),n=1;n<30;++n)for(var i=r[n];i<r[n+1];++i)a[i]=i-r[n]<<5|n;return{b:r,r:a}},En=vn(bn,2),xn=En.b,qi=En.r;xn[28]=258,qi[258]=28;var Hi=vn(_n,0),ji=Hi.b,Pt=new Pe(32768);for(var O=0;O<32768;++O){var Te=(O&43690)>>1|(O&21845)<<1;Te=(Te&52428)>>2|(Te&13107)<<2,Te=(Te&61680)>>4|(Te&3855)<<4,Pt[O]=((Te&65280)>>8|(Te&255)<<8)>>1}var He=function(e,t,r){for(var n=e.length,a=0,i=new Pe(t);a<n;++a)e[a]&&++i[e[a]-1];var o=new Pe(t);for(a=1;a<t;++a)o[a]=o[a-1]+i[a-1]<<1;var s;if(r){s=new Pe(1<<t);var c=15-t;for(a=0;a<n;++a)if(e[a])for(var m=a<<4|e[a],g=t-e[a],d=o[e[a]-1]++<<g,f=d|(1<<g)-1;d<=f;++d)s[Pt[d]>>c]=m}else for(s=new Pe(n),a=0;a<n;++a)e[a]&&(s[a]=Pt[o[e[a]-1]++]>>15-e[a]);return s},Ve=new oe(288);for(var O=0;O<144;++O)Ve[O]=8;for(var O=144;O<256;++O)Ve[O]=9;for(var O=256;O<280;++O)Ve[O]=7;for(var O=280;O<288;++O)Ve[O]=8;var Tn=new oe(32);for(var O=0;O<32;++O)Tn[O]=5;var Wi=He(Ve,9,1),Xi=He(Tn,5,1),Tt=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},he=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(t&7)&r},St=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(t&7)},Gi=function(e){return(e+7)/8|0},qt=function(e,t,r){return(t==null||t<0)&&(t=0),(r==null||r>e.length)&&(r=e.length),new oe(e.subarray(t,r))}
15,Yi=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],se=function(e,t,r){var n=new Error(t||Yi[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,se),!r)throw n;return n},Vi=function(e,t,r,n){var a=e.length,i=n?n.length:0;if(!a||t.f&&!t.l)return r||new oe(0);var o=!r,s=o||t.i!=2,c=t.i;o&&(r=new oe(a*3));var m=function(ue){var de=r.length;if(ue>de){var ye=new oe(Math.max(de*2,ue));ye.set(r),r=ye}},g=t.f||0,d=t.p||0,f=t.b||0,y=t.l,b=t.d,A=t.m,p=t.n,h=a*8;do{if(!y){g=he(e,d,1);var v=he(e,d+1,3);if(d+=3,v)if(v==1)y=Wi,b=Xi,A=9,p=5;else if(v==2){var P=he(e,d,31)+257,X=he(e,d+10,15)+4,I=P+he(e,d+5,31)+1;d+=14;for(var T=new oe(I),C=new oe(19),M=0;M<X;++M)C[zi[M]]=he(e,d+M*3,7);d+=X*3;for(var R=Tt(C),L=(1<<R)-1,j=He(C,R,1),M=0;M<I;){var ne=j[he(e,d,L)];d+=ne&15;var _=ne>>4;if(_<16)T[M++]=_;else{var Z=0,V=0;for(_==16?(V=3+he(e,d,3),d+=2,Z=T[M-1]):_==17?(V=3+he(e,d,7),d+=3):_==18&&(V=11+he(e,d,127),d+=7);V--;)T[M++]=Z}}var le=T.subarray(0,P),ee=T.subarray(P);A=Tt(le),p=Tt(ee),y=He(le,A,1),b=He(ee,p,1)}else se(1);else{var _=Gi(d)+4,x=e[_-4]|e[_-3]<<8,F=_+x;if(F>a){c&&se(0);break}s&&m(f+x),r.set(e.subarray(_,F),f),t.b=f+=x,t.p=d=F*8,t.f=g;continue}if(d>h){c&&se(0);break}}s&&m(f+131072);for(var Re=(1<<A)-1,De=(1<<p)-1,Se=d;;Se=d){var Z=y[St(e,d)&Re],u=Z>>4;if(d+=Z&15,d>h){c&&se(0);break}if(Z||se(2),u<256)r[f++]=u;else if(u==256){Se=d,y=null;break}else{var k=u-254;if(u>264){var M=u-257,D=bn[M];k=he(e,d,(1<<D)-1)+xn[M],d+=D}var B=b[St(e,d)&De],W=B>>4;B||se(3),d+=B&15;var ee=ji[W];if(W>3){var D=_n[W];ee+=St(e,d)&(1<<D)-1,d+=D}if(d>h){c&&se(0);break}s&&m(f+131072);var G=f+k;if(f<ee){var Y=i-ee,J=Math.min(ee,G);for(Y+f<0&&se(3);f<J;++f)r[f]=n[Y+f]}for(;f<G;++f)r[f]=r[f-ee]}}t.l=y,t.p=Se,t.b=f,t.f=g,y&&(g=1,t.m=A,t.d=b,t.n=p)}while(!g);return f!=r.length&&o?qt(r,0,f):r.subarray(0,f)},Ji=new oe(0),we=function(e,t){return e[t]|e[t+1]<<8},ge=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},It=function(e,t){return ge(e,t)+ge(e,t+4)*4294967296};function Ki(e,t){return Vi(e,{i:2},t&&t.out,t&&t.dictionary)}var Rt=typeof TextDecoder<"u"&&new TextDecoder,Qi=0;try{Rt.decode(Ji,{stream:!0}),Qi=1}catch{}var Zi=function(e){for(var t="",r=0;;){var n=e[r++],a=(n>127)+(n>223)+(n>239);if(r+a>e.length)return{s:t,r:qt(e,r-1)};a?a==3?(n=((n&15)<<18|(e[r++]&63)<<12|(e[r++]&63)<<6|e[r++]&63)-65536,t+=String.fromCharCode(55296|n>>10,56320|n&1023)):a&1?t+=String.fromCharCode((n&31)<<6|e[r++]&63):t+=String.fromCharCode((n&15)<<12|(e[r++]&63)<<6|e[r++]&63):t+=String.fromCharCode(n)}};function eo(e,t){if(t){for(var r="",n=0;n<e.length;n+=16384)r+=String.fromCharCode.apply(null,e.subarray(n,n+16384));return r}else{if(Rt)return Rt.decode(e);var a=Zi(e),i=a.s,r=a.r;return r.length&&se(8),i}}var to=function(e,t){return t+30+we(e,t+26)+we(e,t+28)},ro=function(e,t,r){var n=we(e,t+28),a=eo(e.subarray(t+46,t+46+n),!(we(e,t+8)&2048)),i=t+46+n,o=ge(e,t+20),s=r&&o==4294967295?no(e,i):[o,ge(e,t+24),ge(e,t+42)],c=s[0],m=s[1],g=s[2];return[we(e,t+10),c,m,a,i+we(e,t+30)+we(e,t+32),g]},no=function(e,t){for(;we(e,t)!=1;t+=4+we(e,t+2));return[It(e,t+12),It(e,t+4),It(e,t+20)]};function ao(e,t){for(var r={},n=e.length-22;ge(e,n)!=101010256;--n)(!n||e.length-n>65558)&&se(13);var a=we(e,n+8);if(!a)return{};var i=ge(e,n+16),o=i==4294967295||a==65535;if(o){var s=ge(e,n-12);o=ge(e,s)==101075792,o&&(a=ge(e,s+32),i=ge(e,s+48))}for(var c=0;c<a;++c){var m=ro(e,i,o),g=m[0],d=m[1],f=m[2],y=m[3],b=m[4],A=m[5],p=to(e,A);i=b,g?g==8?r[y]=Ki(e.subarray(p,p+d),{out:new oe(f)}):se(14,"unknown compression type "+g):r[y]=qt(e,p,p+d)}return r}function xe(e,t,r){if(!r(t))throw new TypeError(`Expected ${e} type but got ${typeof r}.`)}function Sn(e){return e instanceof ArrayBuffer}const io=e=>xe("ArrayBuffer",e,Sn);function oo(e){return io(e),new Uint8Array(e)}const In=/^data:([\w-]+\/[\w-]+)?;base64,/;function so(e){return typeof e=="string"&&In.test(e)}function co(e,t){return lo(e,t).bytes}function lo(e,t){if(typeof e!="string")throw new TypeError("base64 input must be a string");let r=t!=null&&t.urlSafe?uo(e):e,n;const a=r.match(In);return a&&(n=a[1],r=r.slice(a[0].length)),{bytes:Uint8Array.from(globalThis.atob(r),o=>o.codePointAt(0)),type:n}}function uo(e){return e.replace(/-/g,"+").replace(/_/g,"/").padEnd(e.length+(4-e.length%4)%4,"=")}function An(e){return e instanceof Blob}const fo=e=>xe("Blob",e,An);function mo(e){return fo(e),e.arrayBuffer().then(t=>new Uint8Array(t))}function Mn(e){return e instanceof DataView}const ho=e=>xe("DataView",e,Mn);function go(e){return ho(e),new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function kn(e){try{return"pipe"in e&&typeof e.pipe=="function"}catch{return!1}}const Cn=e=>xe("NodeStream",e,kn);async function po(e){Cn(e);const t=await wo(e);let r=0;for(const i of t)r+=i.length;const n=new Uint8Array(r);let a=0;for(const i of t)n.set(i,a),a+=i.length;return n}function wo(e){return Cn(e),new Promise((t,r)=>{const n=[];e.on("data",a=>{n.push(a)}),e.once("error",r),e.once("end",()=>{t(n)})})}function Fn(e){return Array.isArray(e)&&(e.length===0||typeof e[0]=="number")}const yo=e=>xe("NumberArray",e,Fn);function bo(e){return yo(e),new Uint8Array(e)}function Nn(e){return e instanceof ReadableStream}const $n=e=>xe("ReadableStream",e,Nn);async function _o(e){var r;
15return(r=globalThis.Bun)!=null&&r.readableStreamToArrayBuffer?($n(e),globalThis.Bun.readableStreamToArrayBuffer(e)):(await vo(e)).arrayBuffer()}async function vo(e,t){var a;if((a=globalThis.Bun)!=null&&a.readableStreamToBlob)return $n(e),globalThis.Bun.readableStreamToBlob(e);const r=e.getReader(),n=[];for(;;){const{done:i,value:o}=await r.read();if(i)break;n.push(o)}return new Blob(n,t)}async function Eo(e){const t=await _o(e);return new Uint8Array(t)}function Ln(e){return e instanceof Response}const xo=e=>xe("Response",e,Ln);async function To(e){return xo(e),new Uint8Array(await e.arrayBuffer())}function Pn(e){return typeof e=="string"}const So=e=>xe("Text",e,Pn);function Io(e){return So(e),new Uint8Array(new TextEncoder().encode(e))}function Rn(e){return e instanceof Uint8Array}const Ao=e=>xe("Uint8Array",e,Rn),Mo=[["Uint8Array",Rn],["ArrayBuffer",Sn],["Blob",An],["DataView",Mn],["ReadableStream",Nn],["Response",Ln],["NodeStream",kn],["NumberArray",Fn],["Base64",so],["Text",Pn]];function ko(e){for(const[t,r]of Mo)if(r(e))return t;throw new TypeError(`Unknown data type: ${typeof e}.`)}const Co={ArrayBuffer:oo,Base64:co,Blob:mo,DataView:go,NodeStream
15:po,NumberArray:bo,ReadableStream:Eo,Response:To,Text:Io,Uint8Array:e=>(Ao(e),e)},Fo=e=>No(e,Co);function No(e,t,r){const n=r||ko(e),a=t[n];if(a===void 0)throw new Error(`Conversion from ${n} is not supported.`);return a(e)}const $o=new TextDecoder,U=(e,t=0,r=e.length)=>$o.decode(e.slice(t,r)),ve=(e,t=0,r=e.length)=>e.slice(t,r).reduce((n,a)=>n+("0"+a.toString(16)).slice(-2),""),Sr=(e,t=0)=>{const r=e[t]+e[t+1]*256;return r|(r&2**15)*131070},Ne=(e,t=0)=>e[t]*2**8+e[t+1],te=(e,t=0)=>e[t]+e[t+1]*2**8,Ir=(e,t=0)=>e[t]+e[t+1]*2**8+e[t+2]*2**16,Lo=(e,t=0)=>e[t]+e[t+1]*2**8+e[t+2]*2**16+(e[t+3]<<24),H=(e,t=0)=>e[t]*2**24+e[t+1]*2**16+e[t+2]*2**8+e[t+3],Fe=(e,t=0)=>e[t]+e[t+1]*2**8+e[t+2]*2**16+e[t+3]*2**24,Po={readUInt16BE:Ne,readUInt16LE:te,readUInt32BE:H,readUInt32LE:Fe};function pe(e,t,r,n){r=r||0;const a=n?"BE":"LE",i="readUInt"+t+a;return Po[i](e,r)}const Ro={validate:e=>U(e,0,2)==="BM",calculate:e=>({height:Math.abs(Lo(e,22)),width:Fe(e,18)})},Do=1,Uo=6,Bo=16;function Ar(e,t){const r=e[t];return r===0?256:r}function Mr(e,t){const r=Uo+t*Bo;return{height:Ar(e,r+1),width:Ar(e,r)}}const Dn={validate(e){const t=te(e,0),r=te(e,4);return t!==0||r===0?!1:te(e,2)===Do},calculate(e){const t=te(e,4),r=Mr(e,0);if(t===1)return r;const n=[r];for(let a=1;a<t;a+=1)n.push(Mr(e,a));return{height:r.height,images:n,width:r.width}}},Oo=2,zo={validate(e){const t=te(e,0),r=te(e,4);return t!==0||r===0?!1:te(e,2)===Oo},calculate:e=>Dn.calculate(e)},qo={validate:e=>Fe(e,0)===542327876,calculate:e=>({height:Fe(e,12),width:Fe(e,16)})},Ho=/^GIF8[79]a/,jo={validate:e=>Ho.test(U(e,0,6)),calculate:e=>({height:te(e,8),width:te(e,6)})},Wo={validate:e=>{const t=rt(e,"ftyp");if(!t)return!1;const r=U(e,t.offset+8,t.offset+12);return["heic","heix","hevc","hevx","mif1","msf1"].includes(r)},calculate:e=>{const t=rt(e,"meta");if(!t)throw new TypeError("heic: meta box not found");const r=rt(e,"iprp",t.offset+12,t.offset+t.size);if(!r)throw new TypeError("heic: iprp box not found");const n=rt(e,"ipco",r.offset+8,r.offset+r.size);if(!n)throw new TypeError("heic: ipco box not found");const a=Xo(e,"ispe",n.offset+8,n.offset+n.size).map(o=>({width:H(e,o.offset+12),height:H(e,o.offset+16)}));if(a.length===0)throw new TypeError("heic: ispe box not found");let i=a[0];for(let o=1;o<a.length;o++){const s=a[o];s.width*s.height>i.width*i.height&&(i=s)}return i}};function rt(e,t,r=0,n=e.length){let a=r;for(;a<n;){const i=H(e,a);if(U(e,a+4,a+8)===t)return{offset:a,size:i};if(i<=0||a+i>n)break;a+=i}}function Xo(e,t,r=0,n=e.length){let a=r;const i=[];for(;a<n;){const o=H(e,a);if(U(e,a+4,a+8)===t&&i.push({offset:a,size:o}),o<=0||a+o>n)break;a+=o}return i}const Go=8,Yo=4,Vo=4,Jo={ICON:32,"ICN#":32,"icm#":16,icm4:16,icm8:16,"ics#":16,ics4:16,ics8:16,is32:16,s8mk:16,icp4:16,icl4:32,icl8:32,il32:32,l8mk:32,icp5:32,ic11:32,ich4:48,ich8:48,ih32:48,h8mk:48,icp6:64,ic12:32,it32:128,t8mk:128,ic07:128,ic08:256,ic13:256,ic09:512,ic14:512,ic10:1024};function kr(e,t){const r=t+Vo;return[U(e,t,r),H(e,r)]}function Cr(e){const t=Jo[e];return{width:t,height:t,type:e}}const Ko={validate:e=>U(e,0,4)==="icns",calculate(e){const t=e.length,r=H(e,Yo);let n=Go,a=kr(e,n),i=Cr(a[0]);if(n+=a[1],n===r)return i;const o={height:i.height,images:[i],width:i.width};for(;n<r&&n<t;)a=kr(e,n),i=Cr(a[0]),n+=a[1],o.images.push(i);return o}},Qo={validate:e=>ve(e,0,4)==="ff4fff51",calculate:e=>({height:H(e,12),width:H(e,8)})},nt={ftyp:"66747970",jp2h:"6a703268",jp__:"6a502020",rreq:"72726571"},Zo=e=>{const t=e[0];let r=1+2*t;const a=Ne(e,r)*(2+t);r=r+2+a;const o=Ne(e,r)*(16+t);return r+2+o},Fr=e=>({height:H(e,4),width:H(e,8)}),es={validate(e){const t=ve(e,4,8),r=H(e,0);if(t!==nt.jp__||r<1)return!1;const n=r+4,a=H(e,r),i=e.slice(n,n+a);return ve(i,0,4)===nt.ftyp},calculate(e){const t=H(e,0),r=Ne(e,t+2);let n=t+4+r;switch(ve(e,n,n+4)){case nt.rreq:return n=n+4+4+Zo(e.slice(n+4)),Fr(e.slice(n+8,n+24));case nt.jp2h:return Fr(e.slice(n+8,n+24));default:throw new TypeError("Unsupported header found: "+U(e,n,n+4))}}},ts="45786966",rs=2,Dt=6,ns=2,as="4d4d",is="4949",Nr=12,os=2;function ss(e){return ve(e,2,6)===ts}function cs(e,t){return{height:Ne(e,t),width:Ne(e,t+2)}}function ls(e,t){const n=Dt+8,a=pe(e,16,n,t);for(let i=0;i<a;i++){const o=n+os+i*Nr,s=o+Nr;if(o>e.length)return;const c=e.slice(o,s);if(pe(c,16,0,t)===274)return pe(c,16,2,t)!==3||pe(c,32,4,t)!==1?void 0:pe(c,16,8,t)}}function us(e,t){const r=e.slice(rs,t),n=ve(r,Dt,Dt+ns),a=n===as;if(a||n===is)return ls(r,a)}function ds(e,t){if(t>e.length)throw new TypeError("Corrupt JPG, exceeded buffer limits");if(e[t]!==255)throw new TypeError("Invalid JPG, marker table corrupted")}const fs={validate:e=>ve(e,0,2)==="ffd8",calculate(e){e=e.slice(4);let t,r;for(;e.length>0;){const n=Ne(e,0);if(ss(e)&&(t=us(e,n)),ds(e,n),r=e[n+1],r===192||r===193||r===194){const a=cs(e,n+5);return t?{height:a.height,orientation:t,width:a.width}:a}e=e.slice(n+2)}throw new TypeError("Invalid JPG, no size found")}},ms={validate:e=>U(e,1,7)==="KTX 11",calculate:e=>({height:Fe(e,40),width:Fe(e,36)})},hs=`PNG\r 16� 17`,gs="IHDR",$r="CgBI",ps={validate(e){if(hs===U(e,1,8)){let t=U(e,12,16);if(t===$r&&(t=U(e,28,32)),t!==gs)throw new TypeError("Invalid PNG");return!0}return!1},calculate(e){return U(e,12,16)===$r?{height:H(e,36),width:H(e,32)}:{height:H(e,20),width:H(e,16)}}},Lr={P1:"pbm/ascii",P2:"pgm/ascii",P3:"ppm/ascii",P4:"pbm",P5:"pgm",P6:"ppm",P7:"pam",PF:"pfm"},Pr={default:e=>{let t=[];for(;e.length>0;){const r=e.shift();if(r[0]!=="#"){t=r.split(" ");break}}if(t.length===2)return{height:Number.parseInt(t[1],10),width:Number.parseInt(t[0],10)};throw new TypeError("Invalid PNM")},pam:e=>{const t={};for(;e.length>0;){const r=e.shift();if(r.length>16||(r.codePointAt(0)||0)>128)continue;const[n,a]=r.split(" ");if(n&&a&&(t[n.toLowerCase()]=Number.parseInt(a,10)),t.height&&t.width)break}if(t.height&&t.width)return{height:t.height,width:t.width};throw new TypeError("Invalid PAM")}},ws={validate:e=>U(e,0,2)in Lr,calculate(e){const t=U(e,0,2),r=Lr[t],n=U(e,3).split(/[\n\r]+/);return(Pr[r]||Pr.default)(n)}},ys={validate:e=>U(e,0,4)==="8BPS",calculate:e=>({height:H(e,14),width:H(e,18)})},Un=/<svg\s([^"'>]|"[^"]*"|'[^']*')*>/,ct={height:/\sheight=(["'])([^%]+?)\1/,root:Un,viewbox:/\sviewbox=(["'])(.+?)\1/i,width:/\swidth=(["'])([^%]+?)\1/},At=2.54,Bn={in:96,cm:96/At,em:16,ex:8,m:96/At*100,mm:96/At/10,pc:96/72/12,pt:96/72,px:1},bs=new RegExp(`^([0-9.]+(?:e\\d+)?)(${Object.keys(Bn).join("|")})?$`);function mt(e){const t=bs.exec(e);if(t)return Math.round(Number(t[1])*(Bn[t[2]]||1))}function _s(e){const t=e.split(" ");return{height:mt(t[3]),width:mt(t[2])}}function vs(e){const t=e.match(ct.width),r=e.match(ct.height),n=e.match(ct.viewbox);return{height:r&&mt(r[2]),viewbox:n&&_s(n[2]),width:t&&mt(t[2])}}function Es(e){return{height:e.height,width:e.width}}function xs(e,t){const r=t.width/t.height;return e.width?{height:Math.floor(e.width/r),width:e.width}:e.height?{height:e.height,width:Math.floor(e.height*r)}
17:{height:t.height,width:t.width}}const Ts={validate:e=>Un.test(U(e,0,1e3)),calculate(e){const t=U(e).match(ct.root);if(t){const r=vs(t[0]);if(r.width&&r.height)return Es(r);if(r.viewbox)return xs(r,r.viewbox)}throw new TypeError("Invalid SVG")}},Ss={validate(e){return te(e,0)===0&&te(e,4)===0},calculate(e){return{height:te(e,14),width:te(e,12)}}};function Is(e,t){const r=pe(e,32,4,t);let n=1024;const a=e.length;return r+n>a&&(n=a-r-10),e.slice(r+2,r+2+n)}function As(e,t){const r=pe(e,16,8,t);return(pe(e,16,10,t)<<16)+r}function Ms(e){if(e.length>24)return e.slice(12)}function ks(e,t){const r={};let n=e;for(;n&&n.length>0;){const a=pe(n,16,0,t),i=pe(n,16,2,t),o=pe(n,32,4,t);if(a===0)break;o===1&&(i===3||i===4)&&(r[a]=As(n,t)),n=Ms(n)}return r}function Cs(e){const t=U(e,0,2);if(t==="II")return"LE";if(t==="MM")return"BE"}const Fs=new Set(["49492a00","4d4d002a"]),Ns={validate:e=>Fs.has(ve(e,0,4)),calculate(e){const t=Cs(e)==="BE",r=Is(e,t),n=ks(r,t),a=n[256],i=n[257];if(!a||!i)throw new TypeError("Invalid Tiff. Missing tags");return{height:i,width:a}}};function $s(e){return{height:1+Ir(e,7),width:1+Ir(e,4)}}function Ls(e){return{height:1+((e[4]&15)<<10|e[3]<<2|(e[2]&192)>>6),width:1+((e[2]&63)<<8|e[1])}}function Ps(e){return{height:Sr(e,8)&16383,width:Sr(e,6)&16383}}const Rs={validate(e){const t=U(e,0,4)==="RIFF",r=U(e,8,12)==="WEBP",n=U(e,12,15)==="VP8";return t&&r&&n},calculate(e){const t=U(e,12,16);if(e=e.slice(20,30),t==="VP8X"){const n=e[0],a=(n&192)===0,i=(n&1)===0;if(a&&i)return $s(e);throw new TypeError("Invalid WebP")}if(t==="VP8 "&&e[0]!==47)return Ps(e);const r=ve(e,3,6);if(t==="VP8L"&&r!=="9d012a")return Ls(e);throw new TypeError("Invalid WebP")}},Ds={validate:e=>U(e,8,12)==="avif",calculate:e=>{const t=at(e,"meta"),r=at(e,"iprp",t.offset+12,t.offset+t.size),n=at(e,"ipco",r.offset+8,r.offset+r.size),a=at(e,"ispe",n.offset+8,n.offset+n.size),i=H(e,a.offset+12),o=H(e,a.offset+16);return{width:i,height:o}}};function at(e,t,r=0,n=e.length){for(let a=r;a<n;){const i=H(e,a);if(U(e,a+4,a+8)===t)return{offset:a,size:i};if(i<=0||a+i>n)break;a+=i}throw new Error(`${t} box not found`)}const je={bmp:Ro,cur:zo,dds:qo,gif:jo,heic:Wo,icns:Ko,ico:Dn,j2c:Qo,jp2:es,jpg:fs,ktx:ms,png:ps,pnm:ws,psd:ys,svg:Ts,tga:Ss,tiff:Ns,webp:Rs,avif:Ds},Us=Object.keys(je),Rr={56:"psd",66:"bmp",68:"dds",71:"gif",73:"tiff",77:"tiff",82:"webp",105:"icns",137:"png",255:"jpg"};function Bs(e){const t=e[0];if(t in Rr){const r=Rr[t];if(r&&je[r].validate(e))return r}return Us.find(r=>je[r].validate(e))}function Os(e){if(!(e instanceof Uint8Array))throw new TypeError("Input should be a Uint8Array");const t=Bs(e);if(t!==void 0&&t in je){const r=je[t].calculate(e);if(r!==void 0)return r.type=t,r}throw new TypeError(`Unsupported file type: ${t}`)}function On(e){return Math.round(e*96/1440)}function zs(e){return Math.round(e/(914400/96))}function ht(e){const t=parseInt(e,10);if(!isNaN(t))return zs(t)}function w(e,t){if(!e.children)return null;for(const r of e.children)if(r.type==="element"&&r.name===t)return r;return null}function Q(e,t){if(!e.children)return null;for(const r of e.children)if(r.type==="element"){if(r.name===t)return r;const n=Q(r,t);if(n)return n}return null}function ce(e,t){const r=[];if(!e.children)return r;for(const n of e.children)n.type==="element"&&(n.name===t&&r.push(n),r.push(...ce(n,t)));return r}function $e(e,t){const r=e[t];if(!r)return;const n=parseInt(r,10);if(!isNaN(n))return r}const it="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function zn(e){const t=e.length,r=Math.ceil(t/3)*4,n=Array.from({length:r});let a=0;for(let i=0;i<t;i+=3){const o=e[i],s=i+1<t?e[i+1]:0,c=i+2<t?e[i+2]:0,m=o>>2,g=(o&3)<<4|s>>4,d=(s&15)<<2|c>>6,f=c&63;n[a++]=it[m],n[a++]=it[g],n[a++]=i+1<t?it[d]:"=",n[a++]=i+2<t?it[f]:"="}return n.join("")}function qs(e){const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}var jr,Wr;const Hs=((Wr=(jr=globalThis.process)==null?void 0:jr.release)==null?void 0:Wr.name)==="node",qn=typeof window<"u";async function js(e){const t=await e;return t.default||t}let We;var Xe,Xr;let Hn=(Xr=class{constructor({enableHWA:e=!1}={}){tr(this,Xe,!1);rr(this,Xe,e)}create(e,t){const r=this._createCanvas(e,t);return{canvas:r,context:r.getContext("2d",{willReadFrequently:!er(this,Xe)})}}reset({canvas:e},t,r){if(!e)throw new Error("Canvas is not specified");e.width=t,e.height=r}destroy(e){if(!e.canvas)throw new Error("Canvas is not specified");e.canvas.width=0,e.canvas.height=0,e.canvas=void 0,e.context=void 0}_createCanvas(e,t){throw new Error("Not implemented")}},Xe=new WeakMap,Xr);class Ws extends Hn{constructor({ownerDocument:r=globalThis.document,enableHWA:n=!1}={}){super({enableHWA:n});Qt(this,"_document");this._document=r}_createCanvas(r,n){const a=this._document.createElement("canvas");return a.width=r,a.height=n,a}}class Xs extends Hn{constructor({enableHWA:t=!1}={}){super({enableHWA:t})}_createCanvas(t,r){if(!We)throw new Error("@napi-rs/canvas module is not resolved");return We.createCanvas(t,r)}}async function Gs(e){We??(We=await js(e()))}async function Ys(e){if(qn)return Ws;if(Hs){if(!e)throw new Error("In Node.js environment, @napi-rs/canvas is required for image cropping. Please provide canvasImport parameter or install it: pnpm add @napi-rs/canvas");return await Gs(e),Xs}throw new Error("Unsupported environment for canvas operations")}async function Vs(e,t,r={}){if(!t||!t.left&&!t.top&&!t.right&&!t.bottom||r.enabled===!1)return e;
17try{const n=await Ys(r.canvasImport),a=await Js(e,n),i=(t.left||0)/1e5*a.width,o=(t.top||0)/1e5*a.height,s=(t.right||0)/1e5*a.width,c=(t.bottom||0)/1e5*a.height,m=Math.round(a.width-i-s),g=Math.round(a.height-o-c);if(m<=0||g<=0)return console.warn("Invalid crop dimensions, returning original image"),e;const d=new n().create(m,g);if(!d.context)throw new Error("Failed to get 2D context from canvas");d.context.drawImage(a,i,o,m,g,0,0,m,g);const f=d.canvas.toDataURL(),y=await(await fetch(f)).arrayBuffer();return new Uint8Array(y)}catch(n){return console.warn("Image cropping failed, returning original image:",n),e}}async function Js(e,t){if(qn){const r=new Blob([e.buffer]),n=URL.createObjectURL(r);try{const a=new Image;return new Promise((i,o)=>{a.onload=()=>{URL.revokeObjectURL(n),i(a)},a.onerror=()=>{URL.revokeObjectURL(n),o(new Error("Failed to load image"))},a.src=n})}catch(a){throw URL.revokeObjectURL(n),a}}else{if(!We)throw new Error("@napi-rs/canvas module is not resolved");return await We.loadImage(Fa.from(e))}}const Ks="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";function Qs(e){const t=e.attributes.l,r=e.attributes.t,n=e.attributes.r,a=e.attributes.b;if(!(!t&&!r&&!n&&!a))return{left:t?parseInt(t,10):void 0,top:r?parseInt(r,10):void 0,right:n?parseInt(n,10):void 0,bottom:a?parseInt(a,10):void 0}}function Dr(e){var i,o;const t=w(e,"wp:align"),r=w(e,"wp:posOffset"),n=((i=t==null?void 0:t.children[0])==null?void 0:i.type)==="text"?t.children[0].value:void 0,a=((o=r==null?void 0:r.children[0])==null?void 0:o.type)==="text"?parseInt(r.children[0].value,10):void 0;if(!(!n&&a===void 0))return{...n&&{align:n},...a!==void 0&&{offset:a}}}function Ur(e){let t=w(e,"w:drawing");if(t)return t;const r=w(e,"mc:AlternateContent"),n=r&&w(r,"mc:Choice");return n?w(n,"w:drawing"):null}function jn(e,t,r,n){const a=r/n,i=e/t;return Math.abs(a-i)>.1?a>i?{width:e,height:Math.round(e/a)}:{width:Math.round(t*a),height:t}:{width:e,height:t}}function Zs(e){const t=new Map,r=e["word/_rels/document.xml.rels"];if(!r)return t;const n=Ye(new TextDecoder().decode(r)),a=w(n,"Relationships");if(!a)return t;const i=ce(a,"Relationship");for(const o of i)if(o.attributes.Type===Ks&&o.attributes.Id&&o.attributes.Target){const s="word/"+o.attributes.Target,c=e[s];if(!c)continue;let m,g,d="png";try{const b=Os(c);m=b.width,g=b.height,b.type&&(d=b.type)}catch{}const f=zn(c),y=`data:image/${d};base64,${f}`;t.set(o.attributes.Id,{src:y,width:m,height:g})}return t}async function Ut(e,t){var _;const{context:r}=t,n=Q(e,"a:blip");if(!(n!=null&&n.attributes["r:embed"]))return null;const a=n.attributes["r:embed"],i=r.images.get(a);if(!i)return null;let o=i.src;const s=Q(e,"a:srcRect");if(s){const x=Qs(s);if(x&&o.startsWith("data:")){const[F,P]=o.split(",");if(P){const X=qs(P);try{const I=await Vs(X,x,{canvasImport:r.canvasImport,enabled:r.enableImageCrop}),T=zn(I);o=`${F},${T}`}catch(I){console.warn("Image cropping failed, using original image:",I)}}}}const c=Q(e,"wp:extent");let m,g;if(c){const x=c.attributes.cx,F=c.attributes.cy;typeof x=="string"&&(m=ht(x)),typeof F=="string"&&(g=ht(F))}const d=Q(e,"a:xfrm");let f;if(d!=null&&d.attributes.rot){const x=parseInt(d.attributes.rot,10);isNaN(x)||(f=x/6e4)}const y=(_=Q(e,"wp:docPr"))==null?void 0:_.attributes.title,b=Q(e,"wp:positionH"),A=Q(e,"wp:positionV");let p;if(b||A){const x=b?Dr(b):void 0,F=A?Dr(A):void 0;p={horizontalPosition:{relative:(b==null?void 0:b.attributes.relativeFrom)||"page",...(x==null?void 0:x.align)&&{align:x.align},...(x==null?void 0:x.offset)!==void 0&&{offset:x.offset}},verticalPosition:{relative:(A==null?void 0:A.attributes.relativeFrom)||"page",...(F==null?void 0:F.align)&&{align:F.align},...(F==null?void 0:F.offset)!==void 0&&{offset:F.offset}}}}const h=Q(e,"pic:spPr");let v;if(h){const x=Q(h,"a:ln"),F=x&&Q(x,"a:solidFill"),P=F&&Q(F,"a:srgbClr");P!=null&&P.attributes.val&&(v={type:"solidFill",solidFillType:"rgb",value:P.attributes.val})}return{type:"image",attrs:{src:o,alt:"",...m!==void 0&&{width:m},...g!==void 0&&{height:g},...f!==void 0&&{rotation:f},...y&&{title:y},...p&&{floating:p},...v&&{outline:v}}}}function ec(e,t,r){if(t&&r&&e.width&&e.height){const n=jn(t,r,e.width,e.height);return{type:"image",attrs:{src:e.src,alt:"",width:n.width,height:n.height}}}return{type:"image",attrs:{src:e.src,alt:"",...t!==void 0&&{width:t},...r!==void 0&&{height:r}}}}async function Br(e,t){var g,d;const r=[],n=w(e,"wp:inline")||w(e,"wp:anchor");if(!n)return r;const a=w(n,"wp:extent");let i,o;if(a){const f=a.attributes.cx,y=a.attributes.cy;typeof f=="string"&&(i=ht(f)),typeof y=="string"&&(o=ht(y))}const s=w(n,"a:graphic");if(!s)return r;const c=w(s,"a:graphicData");if(!c)return r;const m=w(c,"wpg:wgp");if(m){const f=w(m,"wpg:grpSp"),y=f?[...ce(f,"pic:pic"),...ce(f,"pic")]:[...ce(m,"pic:pic"),...ce(m,"pic")];for(const b of y){const A=w(b,"a:graphic");if(!A){const _=w(b,"pic:blipFill")||Q(b,"a:blipFill");
17if(!_)continue;const x=w(_,"a:blip")||Q(_,"a:blip");if(!(x!=null&&x.attributes["r:embed"]))continue;const F=x.attributes["r:embed"],P=t.context.images.get(F);if(!P)continue;r.push(ec(P,i,o));continue}const p={children:[A]},h=await Ut(p,t);if(!h)continue;const v=((g=p.children[0])==null?void 0:g.type)==="element"?(d=Q(p.children[0],"a:blip"))==null?void 0:d.attributes["r:embed"]:void 0;if(i&&o&&v){const _=t.context.images.get(v);if(_!=null&&_.width&&(_!=null&&_.height)){const x=jn(i,o,_.width,_.height);h.attrs.width=x.width,h.attrs.height=x.height}else h.attrs.width=i,h.attrs.height=o}r.push(h)}}else{const f=await Ut(e,t);f&&r.push(f)}return r}const tc="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink";function rc(e){const t=new Map,r=e["word/_rels/document.xml.rels"];if(!r)return t;const n=Ye(new TextDecoder().decode(r)),a=w(n,"Relationships");if(!a)return t;const i=ce(a,"Relationship");for(const o of i)o.attributes.Type===tc&&o.attributes.Id&&o.attributes.Target&&t.set(o.attributes.Id,o.attributes.Target);return t}function nc(e){const t=new Map,r=new Map,n=e["word/numbering.xml"];if(!n)return t;const a=Ye(new TextDecoder().decode(n)),i=new Map,o=w(a,"w:numbering");if(!o)return t;const s=ce(o,"w:abstractNum");for(const m of s){const g=m.attributes["w:abstractNumId"],d=w(m,"w:lvl");if(!d)continue;const f=w(d,"w:numFmt");f!=null&&f.attributes["w:val"]&&i.set(g,f.attributes["w:val"]);const y=w(d,"w:start");y!=null&&y.attributes["w:val"]&&r.set(g,parseInt(y.attributes["w:val"],10))}const c=ce(o,"w:num");for(const m of c){const g=m.attributes["w:numId"],d=w(m,"w:abstractNumId");if(!(d!=null&&d.attributes["w:val"]))continue;const f=d.attributes["w:val"],y=i.get(f);if(!y)continue;const b=r.get(f);y==="bullet"?t.set(g,{type:"bullet"}):t.set(g,{type:"ordered",...b!==void 0&&{start:b}})}return t}function ac(e){const t=new Map,r=e["word/styles.xml"];if(!r)return t;const n=Ye(new TextDecoder().decode(r)),a=w(n,"w:styles");if(!a)return t;const i=ce(a,"w:style").filter(o=>o.attributes["w:type"]==="paragraph");for(const o of i){const s=o.attributes["w:styleId"];if(!s)continue;const c={styleId:s},m=w(o,"w:name");m!=null&&m.attributes["w:val"]&&(c.name=m.attributes["w:val"]);const g=w(o,"w:pPr");if(g){const f=w(g,"w:outlineLvl");(f==null?void 0:f.attributes["w:val"])!==void 0&&(c.outlineLvl=parseInt(f.attributes["w:val"],10))}const d=w(o,"w:rPr");if(d){const f={},y=w(d,"w:color");if(y!=null&&y.attributes["w:val"]&&y.attributes["w:val"]!=="auto"){const p=y.attributes["w:val"];f.color=p.startsWith("#")?p:`#${p}`}w(d,"w:b")&&(f.bold=!0),w(d,"w:i")&&(f.italic=!0),w(d,"w:u")&&(f.underline=!0),w(d,"w:strike")&&(f.strike=!0);const b=w(d,"w:sz");if(b!=null&&b.attributes["w:val"]){const p=b.attributes["w:val"],h=parseInt(p,10);isNaN(h)||(f.fontSize=h)}const A=w(d,"w:rFonts");A!=null&&A.attributes["w:ascii"]&&(f.fontFamily=A.attributes["w:ascii"]),Object.keys(f).length>0&&(c.charFormat=f)}t.set(s,c)}return t}function Or(e,t){const r=w(e,"w:t");if(!r)return null;const n=r.children.find(i=>i.type==="text");if(!(n!=null&&n.value))return null;const a=Wn(e,t);return{type:"text",text:n.value,...a.length&&{marks:a}}}async function Ht(e,t){const{context:r,styleInfo:n}=t,a=[];for(const i of e.children)if(i.type==="element"){if(i.name==="w:hyperlink"){const o=i,s=o.attributes["r:id"],c=r.hyperlinks.get(s);if(!c)continue;for(const m of o.children){if(m.type!=="element"||m.name!=="w:r")continue;const g=m,d=Ur(g);if(d){const y=await Ut(d,{context:r});if(y){a.push(y);continue}const b=await Br(d,{context:r});if(b.length){a.push(...b);continue}}const f=Or(g,n);f&&(f.marks=f.marks||[],f.marks.push({type:"link",attrs:{href:c}}),a.push(f))}}else if(i.name==="w:r"){const o=i,s=Ur(o);if(s){const m=await Br(s,{context:r});if(m.length){a.push(...m);continue}}if(w(o,"w:br")){const m=Wn(o,n);a.push({type:"hardBreak",...m.length&&{marks:m}})}const c=Or(o,n);c&&a.push(c)}}return a}function Wn(e,t){const r=[],n=w(e,"w:rPr");let a={};if(t!=null&&t.charFormat&&(a={...t.charFormat}),n){const i=w(n,"w:b");i&&(i.attributes["w:val"]==="false"?a.bold=!1:a.bold=!0);const o=w(n,"w:i");o&&(o.attributes["w:val"]==="false"?a.italic=!1:a.italic=!0),w(n,"w:u")&&(a.underline=!0),w(n,"w:strike")&&(a.strike=!0);const s=w(n,"w:color");
17if(s!=null&&s.attributes["w:val"]&&s.attributes["w:val"]!=="auto"){const f=s.attributes["w:val"];a.color=f.startsWith("#")?f:`#${f}`}const c=w(n,"w:sz");if(c!=null&&c.attributes["w:val"]){const f=c.attributes["w:val"],y=parseInt(f,10);isNaN(y)||(a.fontSize=y)}const m=w(n,"w:rFonts");m!=null&&m.attributes["w:ascii"]&&(a.fontFamily=m.attributes["w:ascii"]);const g=w(n,"w:shd");if(g!=null&&g.attributes["w:fill"]&&g.attributes["w:fill"]!=="auto"){const f=g.attributes["w:fill"];a.backgroundColor=f.startsWith("#")?f:`#${f}`}w(n,"w:highlight")&&r.push({type:"highlight"});const d=w(n,"w:vertAlign");if(d){const f=d.attributes["w:val"];f==="subscript"?r.push({type:"subscript"}):f==="superscript"&&r.push({type:"superscript"})}}if(a.bold&&r.push({type:"bold"}),a.italic&&r.push({type:"italic"}),a.underline&&r.push({type:"underline"}),a.strike&&r.push({type:"strike"}),a.color||a.backgroundColor||a.fontSize||a.fontFamily){const i={color:a.color||"",backgroundColor:a.backgroundColor||"",fontSize:"",fontFamily:"",lineHeight:""};if(a.fontSize){const o=Math.round(a.fontSize/1.5*10)/10;i.fontSize=`${o}px`}a.fontFamily&&(i.fontFamily=a.fontFamily),r.push({type:"textStyle",attrs:i})}return r}function Xn(e){const t=w(e,"w:pPr");if(!t)return;const r=w(t,"w:jc");if(!(r!=null&&r.attributes["w:val"]))return;const n=r.attributes["w:val"],a={left:"left",right:"right",center:"center",both:"justify"}[n];return a?{textAlign:a}:void 0}function Gn(e){const t=w(e,"w:pPr");if(!t)return null;const r={},n=w(t,"w:ind");if(n){const i=$e(n.attributes,"w:left");i&&(r.indentLeft=i);const o=$e(n.attributes,"w:right");o&&(r.indentRight=o);const s=$e(n.attributes,"w:firstLine");if(s)r.indentFirstLine=s;else{const c=$e(n.attributes,"w:hanging");c&&(r.indentFirstLine=`-${c}`)}}const a=w(t,"w:spacing");if(a){const i=$e(a.attributes,"w:before");i&&(r.spacingBefore=i);const o=$e(a.attributes,"w:after");o&&(r.spacingAfter=o)}return Object.keys(r).length?r:null}async function gt(e,t){var m,g;const{context:r,styleInfo:n}=t,a=w(e,"w:pPr"),i=(m=a&&w(a,"w:pStyle"))==null?void 0:m.attributes["w:val"];if(i&&r.styleMap){const d=r.styleMap.get(i);if((d==null?void 0:d.outlineLvl)!==void 0&&d.outlineLvl>=0&&d.outlineLvl<=5){const y=d.outlineLvl+1;return zr(e,t,d,y)}const f=i.match(/^Heading(\d+)$/);if(f){const y=parseInt(f[1],10);return zr(e,t,d,y)}}const o=i&&r.styleMap?r.styleMap.get(i):void 0,s=await Ht(e,{context:r,styleInfo:n||o}),c={...Xn(e),...Gn(e)};if(ic(e)){const d=s.filter(f=>f.type!=="hardBreak");return[{type:"paragraph",...Object.keys(c).length&&{attrs:c},content:d.length?d:void 0},{type:"horizontalRule"}]}if(s.length===1&&s[0].type==="hardBreak"){const d=w(e,"w:r");if(((g=d&&w(d,"w:br"))==null?void 0:g.attributes["w:type"])==="page")return{type:"horizontalRule"}}return s.length===1&&s[0].type==="image"?s[0]:{type:"paragraph",...Object.keys(c).length&&{attrs:c},content:s}}function ic(e){const t=[],r=n=>{if(n.name==="w:r")t.push(n);else for(const a of n.children)a.type==="element"&&r(a)};return r(e),t.some(n=>{var a;return((a=w(n,"w:br"))==null?void 0:a.attributes["w:type"])==="page"})}async function zr(e,t,r,n){return{type:"heading",attrs:{level:n,...Gn(e)},content:await Ht(e,{context:t.context,styleInfo:r})}}function ot(e){if(!e)return null;const t=e.attributes["w:val"],r=e.attributes["w:sz"],n=e.attributes["w:color"],a={single:"solid",dashed:"dashed",dotted:"dotted",double:"double",none:"none",nil:"none"},i={};if(n&&n!=="auto"&&(i.color=`#${n}`),r){const o=parseInt(r);isNaN(o)||(i.width=Math.round(o/6))}return t&&a[t]&&(i.style=a[t]),Object.keys(i).length>0?i:null}function oc(e){const t={marginTop:void 0,marginBottom:void 0,marginLeft:void 0,marginRight:void 0},r=w(e,"w:tblPr");if(!r)return null;const n=w(r,"w:tblCellMar");if(!n)return null;const a=w(n,"w:top");if(a!=null&&a.attributes["w:w"]){const c=parseInt(a.attributes["w:w"]);isNaN(c)||(t.marginTop=c)}const i=w(n,"w:bottom");if(i!=null&&i.attributes["w:w"]){const c=parseInt(i.attributes["w:w"]);isNaN(c)||(t.marginBottom=c)}const o=w(n,"w:left");if(o!=null&&o.attributes["w:w"]){const c=parseInt(o.attributes["w:w"]);isNaN(c)||(t.marginLeft=c)}const s=w(n,"w:right");if(s!=null&&s.attributes["w:w"]){const c=parseInt(s.attributes["w:w"]);isNaN(c)||(t.marginRight=c)}return t.marginTop===void 0&&t.marginBottom===void 0&&t.marginLeft===void 0&&t.marginRight===void 0?null:t}function sc(e){const t={rowHeight:null},r=w(e,"w:trPr");if(!r)return t;const n=w(r,"w:trHeight");if(n!=null&&n.attributes["w:val"]){const a=parseInt(n.attributes["w:val"]),i=On(a);t.rowHeight=`${i}px`}return t}function Yn(e){var c;const t={colspan:1,rowspan:1,colwidth:null},r=w(e,"w:tcPr");if(!r)return t;const n=w(r,"w:gridSpan");n!=null&&n.attributes["w:val"]&&(t.colspan=parseInt(n.attributes["w:val"])),((c=w(r,"w:vMerge"))==null?void 0:c.attributes["w:val"])==="continue"&&(t.rowspan=0);const a=w(r,"w:tcW");
17if(a!=null&&a.attributes["w:w"]){const m=parseInt(a.attributes["w:w"]),g=On(m);t.colwidth=[g]}const i=w(r,"w:shd");i!=null&&i.attributes["w:fill"]&&(t.backgroundColor=`#${i.attributes["w:fill"]}`);const o=w(r,"w:vAlign");o!=null&&o.attributes["w:val"]&&(t.verticalAlign=o.attributes["w:val"]);const s=w(r,"w:tcBorders");if(s){const m=ot(w(s,"w:top"));m&&(t.borderTop=m);const g=ot(w(s,"w:bottom"));g&&(t.borderBottom=g);const d=ot(w(s,"w:left"));d&&(t.borderLeft=d);const f=ot(w(s,"w:right"));f&&(t.borderRight=f)}return t}async function cc(e,t){const r=[];for(const o of e.children)o.type==="element"&&o.name==="w:tr"&&r.push(o);const n=new Map,a=await Promise.all(r.map((o,s)=>lc(o,{context:t.context,activeRowspans:n,rows:r,rowIndex:s}))),i=oc(e);return{type:"table",...i&&{attrs:i},content:a}}async function lc(e,t){const r=[];let n=0;const a=sc(e);for(const i of e.children){if(i.type!=="element"||i.name!=="w:tc")continue;const o=t.activeRowspans.get(n);if(o&&o>0){t.activeRowspans.set(n,o-1),n++;continue}let s=Yn(i);if((s==null?void 0:s.rowspan)===1){const m=uc({rows:t.rows,rowIndex:t.rowIndex,colIndex:n});m>1&&(s={...s,rowspan:m})}if(s!=null&&s.rowspan&&s.rowspan>1&&t.activeRowspans.set(n,s.rowspan-1),(s==null?void 0:s.rowspan)===0){n++;continue}const c=await dc(i,t);r.push({type:"tableCell",...s&&{attrs:s},content:c}),n+=(s==null?void 0:s.colspan)||1}return{type:"tableRow",...a&&{attrs:a},content:r}}function uc(e){let t=1,r=e.colIndex;for(let n=e.rowIndex+1;n<e.rows.length;n++){const a=e.rows[n];let i=!1;for(const o of a.children){if(o.type!=="element"||o.name!=="w:tc")continue;const s=Yn(o),c=(s==null?void 0:s.colspan)||1;if(r>=0&&r<c){if((s==null?void 0:s.rowspan)===0)t++,i=!0;else return t;break}r-=c}if(!i)break}return t}async function dc(e,t){const r=[];for(const n of e.children)if(n.type==="element"&&n.name==="w:p"){const a=await gt(n,t);Array.isArray(a)?r.push(...a):r.push(a)}return r.length?r:[{type:"paragraph",content:[]}]}const Vn="â",jt="â";function Jn(e){const t=w(e,"w:r");if(!t)return null;const r=w(t,"w:t");if(!r)return null;const n=r.children.find(a=>a.type==="text");return(n==null?void 0:n.value)&&n||null}function Kn(e){const t=Jn(e);if(!t)return!1;const r=t.value;return r.startsWith(Vn)||r.startsWith(jt)}function fc(e){var t;return((t=Jn(e))==null?void 0:t.value.startsWith(jt))||!1}async function mc(e,t){return{type:"taskItem",attrs:{checked:fc(e)},content:[await gc(e,t)]}}async function hc(e,t){const{siblings:r,index:n,processedIndices:a}=t,i=[];let o=n;for(;o<r.length;){const s=r[o];if(s.name!=="w:p"||!Kn(s))break;a.add(o);const c=await mc(s,{context:t.context,styleInfo:t.styleInfo});i.push(c),o++}return{type:"taskList",content:i}}async function gc(e,t){const{context:r,styleInfo:n}=t,a=await Ht(e,{context:r,styleInfo:n});if(a.length>0&&a[0].type==="text"){const o=a[0],s=o.text;if(s.startsWith(Vn)||s.startsWith(jt)){const c=s.substring(2).trimStart();c?o.text=c:a.shift()}}const i=Xn(e);return{type:"paragraph",...i&&{attrs:i},content:a.length?a:void 0}}function pc(e){var n;const t=w(e,"w:pPr"),r=(n=t&&w(t,"w:pStyle"))==null?void 0:n.attributes["w:val"];return r==="CodeBlock"||(r==null?void 0:r.startsWith("Code"))||!1}function wc(e){var n;const t=w(e,"w:pPr"),r=(n=t&&w(t,"w:pStyle"))==null?void 0:n.attributes["w:val"];return(r==null?void 0:r.startsWith("CodeBlock"))&&r.replace("CodeBlock","").toLowerCase()||void 0}function Qn(e){const t=w(e,"w:pPr");return!!t&&w(t,"w:numPr")!==void 0}function qr(e){const t=w(e,"w:pPr"),r=t&&w(t,"w:numPr");if(!r)return null;const n=w(r,"w:ilvl"),a=w(r,"w:numId");return!n||!a?null:{numId:a.attributes["w:val"],level:parseInt(n.attributes["w:val"]||"0",10)}}function yc(e){var a,i;const t=w(e,"w:r");if(!t)return!1;let r=!1,n=!1;for(const o of t.children)o.type==="element"&&(o.name==="w:br"&&o.attributes["w:type"]==="page"?r=!0:o.name==="w:t"?(i=(a=o.children.find(s=>s.type==="text"))==null?void 0:a.value)!=null&&i.trim().length&&(n=!0):o.name!=="w:rPr"&&(n=!0));return r&&!n}async function bc(e,t={}){const r=await Fo(e),n=ao(r),a=rc(n),i=Zs(n),o=n["word/document.xml"];if(!o)throw new Error("Invalid DOCX file: missing word/document.xml");const s=Ye(new TextDecoder().decode(o)),c=nc(n),m=ac(n),g={enableImageCrop:!1,ignoreEmptyParagraphs:!1,...t,hyperlinks:a,images:i,listTypeMap:c,styleMap:m};return await _c(s,{context:g})}async function _c(e,t){if(e.type!=="root")return{type:"doc",content:[]};const r=w(e,"w:document");
17if(!r)return{type:"doc",content:[]};const n=w(r,"w:body");return n?{type:"doc",content:await vc(n.children.filter(a=>a.type==="element"),t)}:{type:"doc",content:[]}}async function vc(e,t){const r=[],n=new Set;for(let a=0;a<e.length;a++){if(n.has(a))continue;const i=e[a];if(t.context.ignoreEmptyParagraphs&&i.name==="w:p"&&Ic(i))continue;const o=await Ec(i,e,a,t,n);Array.isArray(o)?r.push(...o):o&&r.push(o)}return r}async function Ec(e,t,r,n,a){switch(e.name){case"w:tbl":return await cc(e,n);case"w:p":return pc(e)?await xc(e):Kn(e)?await hc(e,{...n,siblings:t,index:r,processedIndices:a}):Qn(e)?await Tc(e,t,r,n,a):yc(e)?{type:"horizontalRule"}:await gt(e,n);default:return null}}async function xc(e){const t=wc(e),r=Sc(e);return{type:"codeBlock",...t&&{attrs:{language:t}},content:r}}async function Tc(e,t,r,n,a){const i=qr(e);if(!i)return await gt(e,n);const o=n.context.listTypeMap.get(i.numId),s=(o==null?void 0:o.type)||"bullet",c=[];let m=r;for(;m<t.length;){const d=t[m];if(d.name!=="w:p"||!Qn(d))break;const f=qr(d);if(!f||f.numId!==i.numId)break;a.add(m);const y=await gt(d,n),b=Array.isArray(y)?y[0]:y;c.push({type:"listItem",content:[b]}),m++}const g={type:s==="bullet"?"bulletList":"orderedList",content:c};return s==="ordered"&&(g.attrs={type:null,...(o==null?void 0:o.start)!==void 0&&{start:o.start}}),g}function Sc(e){const t=[],r=ce(e,"w:r");for(const n of r){const a=w(n,"w:t");if(!a)continue;const i=a.children.find(o=>o.type==="text");i&&"value"in i&&i.value&&t.push({type:"text",text:i.value})}return t}function Ic(e){const t=ce(e,"w:r");for(const r of t){const n=w(r,"w:t");if(n){const i=n.children.find(o=>o.type==="text");if(i&&"value"in i&&i.value&&i.value.trim().length>0)return!1}if(w(r,"w:drawing")||w(r,"mc:AlternateContent")||w(r,"w:pict"))return!1;const a=w(r,"w:br");if(a&&a.attributes["w:type"]==="page")return!1}return!0}function Zn(e){var a,i,o,s,c,m,g,d,f,y,b,A,p;if(!e)return"";if(e.type==="text"){let h=Ac(e.text||"");const v=e.marks||[];for(const _ of v)switch(_.type){case"bold":h=`<strong>${h}</strong>`;break;case"italic":h=`<em>${h}</em>`;break;case"underline":h=`<u>${h}</u>`;break;case"strike":h=`<s>${h}</s>`;break;case"code":h=`<code>${h}</code>`;break;case"subscript":h=`<sub>${h}</sub>`;break;case"superscript":h=`<sup>${h}</sup>`;break;case"link":h=`<a href="${Mt(((a=_.attrs)==null?void 0:a.href)||"")}">${h}</a>`;break}return h}const t=(e.content||[]).map(h=>Zn(h)).join(""),r=(i=e.attrs)==null?void 0:i.textAlign,n=r&&r!=="left"?` style="text-align: ${r}"`:"";switch(e.type){case"doc":return t;case"paragraph":return`<p${n}>${t||"<br>"}</p>`;case"heading":{const h=((o=e.attrs)==null?void 0:o.level)||1;return`<h${h}${n}>${t}</h${h}>`}case"bulletList":return`<ul>${t}</ul>`;case"orderedList":{const h=(s=e.attrs)==null?void 0:s.start;return`<ol${h&&h!==1?` start="${h}"`:""}>${t}</ol>`}case"listItem":return`<li>${t}</li>`;case"taskList":return`<ul data-type="taskList">${t}</ul>`;case"taskItem":return`<li data-type="taskItem"${(c=e.attrs)!=null&&c.checked?' data-checked="true"':""}>${t}</li>`;case"blockquote":return`<blockquote>${t}</blockquote>`;case"codeBlock":return`<pre><code${(m=e.attrs)!=null&&m.language?` class="language-${e.attrs.language}"`:""}>${t}</code></pre>`;case"hardBreak":return"<br>";case"horizontalRule":return"<hr>";case"image":{const h=((g=e.attrs)==null?void 0:g.src)||"",v=((d=e.attrs)==null?void 0:d.alt)||"",_=(f=e.attrs)!=null&&f.width?` width="${e.attrs.width}"`:"";return`<img src="${Mt(h)}" alt="${Mt(v)}"${_}>`}case"table":return`<table>${t}</table>`;case"tableRow":return`<tr>${t}</tr>`;case"tableHeader":{const h=((y=e.attrs)==null?void 0:y.colspan)>1?` colspan="${e.attrs.colspan}"`:"",v=((b=e.attrs)==null?void 0:b.rowspan)>1?` rowspan="${e.attrs.rowspan}"`:"";return`<th${h}${v}>${t}</th>`}case"tableCell":{const h=((A=e.attrs)==null?void 0:A.colspan)>1?` colspan="${e.attrs.colspan}"`:"",v=((p=e.attrs)==null?void 0:p.rowspan)>1?` rowspan="${e.attrs.rowspan}"`:"";return`<td${h}${v}>${t}</td>`}default:return t?`<p>${t}</p>`:""}}function Ac(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Mt(e){return e.replace(/"/g,""").replace(/&/g,"&")}async function Mc(e){const t=await e.arrayBuffer(),r=await bc(t,{ignoreEmptyParagraphs:!1,enableImageCrop:!1});return!r||!r.content||r.content.length===0?"":Zn(r)}function kc(e,t,r){if(r==="replace")e.commands.setContent(t,{emitUpdate:!0});else{const{from:n}=e.state.selection;e.chain().focus().insertContentAt(n,t,{parseOptions:{preserveWhitespace:!1}}).run()}}const Cc=/text-align\s*:\s*(center|right|justify)/i,Fc=/^\s*[â¢*·âªââ¦]\s+/,Nc=/^\s*\d{1,2}[.)]\s+/;function $c(e){e.querySelectorAll("[style]").forEach(t=>{const r=(t.getAttribute("style")||"").match(Cc);r&&/^(P|H\d|DIV|LI|TD|TH)$/.test(t.tagName)?t.setAttribute("style",`text-align: ${r[1].toLowerCase()}`):t.removeAttribute("style")}),e.querySelectorAll("[class]").forEach(t=>t.removeAttribute("class")),e.querySelectorAll("font, mark").forEach(t=>t.replaceWith(...Array.from(t.childNodes))),e.querySelectorAll("span").forEach(t=>{t.attributes.length||t.replaceWith(...Array.from(t.childNodes))}),e.querySelectorAll("div").forEach(t=>{if(t.parentElement===e&&!t.querySelector("p,h1,h2,h3,table,ul,ol")){const r=t.ownerDocument.createElement("p");r.innerHTML=t.innerHTML,t.getAttribute("style")&&r.setAttribute("style",t.getAttribute("style")),t.replaceWith(r)}})}function Lc(e){return e.querySelector("img,table,hr")?!1:(e.textContent||"").replace(/\u00a0/g," ").trim()===""}function Pc(e){return(e.textContent||"").replace(/\u00a0/g," ").replace(/\s+/g," ").trim()}function Rc(e){Array.from(e.querySelectorAll(":scope >
17 p")).forEach(t=>{if(!t.querySelector("br"))return;const r=t.innerHTML.split(/<br\s*\/?>/i);if(r.length<2)return;const n=t.getAttribute("style"),a=t.ownerDocument.createDocumentFragment();r.forEach(i=>{const o=t.ownerDocument.createElement("p");o.innerHTML=i,n&&o.setAttribute("style",n),a.appendChild(o)}),t.replaceWith(a)})}function Dc(e){const t=new DOMParser().parseFromString(`<div id="root">${e}</div>`,"text/html"),r=t.getElementById("root");return $c(r),Rc(r),Array.from(r.children).forEach(n=>{/^(P|H\d|DIV)$/.test(n.tagName)&&Lc(n)&&n.remove()}),Array.from(r.children).forEach(n=>{if(/^H[1-6]$/.test(n.tagName)){const a=t.createElement("p");a.innerHTML=n.innerHTML;const i=n.getAttribute("style");i&&a.setAttribute("style",i),n.tagName==="H1"&&!i&&a.setAttribute("style","text-align: center"),n.replaceWith(a)}}),r.innerHTML}function Uc(e){const t=new DOMParser().parseFromString(`<div id="root">${e}</div>`,"text/html"),r=t.getElementById("root");let n=null,a=null;return Array.from(r.children).forEach(i=>{const o=i.tagName==="P"?Pc(i):"",s=Fc.test(o)?"ul":Nc.test(o)?"ol":null;if(!s){n=null,a=null;return}(!n||a!==s)&&(n=t.createElement(s),a=s,i.before(n));const c=t.createElement("li"),m=t.createElement("p");m.innerHTML=i.innerHTML.replace(s==="ul"?/^(\s|<[^>]+>)*[â¢*·âªââ¦]\s+/:/^(\s|<[^>]+>)*\d{1,2}[.)]\s+/,g=>g.replace(/[â¢*·âªââ¦]|\d{1,2}[.)]/,"").replace(/\s+$/,"")),c.appendChild(m),n.appendChild(c),i.remove()}),r.innerHTML}function ea(e,t="editor"){if(typeof DOMParser>"u"||!e)return Nt(e,t);const r=Nt(Dc(e),t);return{...r,html:Uc(r.html)}}function ta(e,t="editor"){return ea(e,t).html}function bl(e){return ea(e,"template")}function _l(e){const t={tecnica:!1,achados:!1,conclusao:!1};if(!e)return t;const r=/<h[1-4][^>]*>([\s\S]*?)<\/h[1-4]>/gi;let n;for(;n=r.exec(e);){const a=Ce(n[1].replace(/<[^>]+>/g,""));(a==null?void 0:a.kind)==="tecnica"&&(t.tecnica=!0),(a==null?void 0:a.kind)==="achados"&&(t.achados=!0),(a==null?void 0:a.kind)==="impressao"&&(t.conclusao=!0)}if(!t.achados||!t.conclusao){const a=Nt(e,"editor").sections;t.tecnica||(t.tecnica=a.tecnica),t.achados||(t.achados=a.achados),t.conclusao||(t.conclusao=a.conclusao)}return t}function Bc(e){const t=e.lastIndexOf(".");return t===-1?"":e.slice(t).toLowerCase()}function ra(){return"DOCX, DOC, PDF, RTF, TXT, HTML, MD"}function Oc(){return".docx,.doc,.pdf,.odt,.txt,.html,.htm,.rtf,.md,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/plain,text/html,text/rtf,text/markdown"}function st(e){return new Promise((t,r)=>{const n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>r(new Error("Falha ao ler o arquivo")),n.readAsText(e,"UTF-8")})}function na(e){const t=/^(fonttbl|colortbl|stylesheet|info|pict|header|headerl|headerr|headerf|footer|footerl|footerr|footerf|footnote|listtable|listoverridetable|rsidtbl|generator|xmlnstbl|themedata|colorschememapping|latentstyles|datastore|mmathPr|filetbl|revtbl)$/,r=[];let n={b:!1,i:!1,u:!1,skip:!1,uc:1};const a=[];let i="",o="",s=0,c={b:!1,i:!1,u:!1};const m=p=>p==="&"?"&":p==="<"?"<":p===">"?">":p,g=()=>{c.u&&!n.u&&(i+="</u>",c.u=!1),c.i&&!n.i&&(i+="</em>",c.i=!1),c.b&&!n.b&&(i+="</strong>",c.b=!1),!c.b&&n.b&&(i+="<strong>",c.b=!0),!c.i&&n.i&&(i+="<em>",c.i=!0),!c.u&&n.u&&(i+="<u>",c.u=!0)},d=()=>{c.u&&(i+="</u>"),c.i&&(i+="</em>"),c.b&&(i+="</strong>"),c={b:!1,i:!1,u:!1}},f=p=>{if(!n.skip){if(s>0){s--;return}g(),i+=m(p)}},y=()=>{d();const p=i.trim(),h=o?` style="text-align: ${o}"`:"";a.push(p?`<p${h}>${p}</p>`:"<p><br></p>"),i=""};let b=0,A=!0;for(;b<e.length;){const p=e[b];if(p==="{"){if(r.push({...n}),b++,e[b]==="\\"&&e[b+1]==="*"){n.skip=!0,b+=2;continue}const h=/^\\([a-zA-Z]+)/.exec(e.slice(b,b+40));h&&t.test(h[1])&&!A&&(n.skip=!0),A=!1;continue}if(p==="}"){n=r.pop()??n,b++;continue}if(p==="\\"){const h=e[b+1];if(h==="\\"||h==="{"||h==="}"){f(h),b+=2;continue}if(h==="'"){const F=e.slice(b+2,b+4),P=parseInt(F,16);isNaN(P)||f(new TextDecoder("windows-1252").decode(new Uint8Array([P]))),b+=4;continue}if(h==="~"){f(" "),b+=2;continue}if(h===` 18`||h==="\r"){n.skip||y(),b+=2;continue}const v=/^\\([a-zA-Z]+)(-?\d+)? ?/.exec(e.slice(b,b+40));if(!v){b++;continue}b+=v[0].length;const _=v[1],x=v[2]!==void 0?parseInt(v[2],10):void 0;if(n.skip)continue;switch(_){case"par":y();break;case"line":g(),i+="<br>";break;case"tab":f(" ");break;case"pard":o="";break;case"qc":o="center";break;case"qj":o="justify";break;case"qr":o="right";break;case"ql":o="";break;case"b":n.b=x!==0;break;case"i":n.i=x!==0;break;case"ul":n.u=x!==0;break;case"ulnone":n.u=!1;break;case"plain":n.b=n.i=n.u=!1;break;case"uc":n.uc=x??1;break;case"u":{let F=x??0;F<0&&(F+=65536),g(),i+=m(String.fromCharCode(F)),s=n.uc;break}}continue}if(p==="\r"||p===` 19`){b++;continue}f(p),b++}for(i.trim()&&y();a.length&&a[0]==="<p><br></p>";)a.shift();for(;a.length&&a[a.length-1]==="<p><br></p>";)a.pop();return a.join("")}function zc(e){const t=e.split(` 20`),r=[];let n=!1,a=null;for(let i=0;i<t.length;i++){let o=t[i];if(!o.trim()){n&&(r.push(a==="ol"?"</ol>":"</ul>"),n=!1,a=null);continue}const s=o.match(/^(#{1,6})\s+(.+)$/);if(s){n&&(r.push(a==="ol"?"</ol>":"</ul>"),n=!1);const d=s[1].length;r.push(`<h${d}>${ze(s[2])}</h${d}>`);continue}if(/^(-{3,}|\*{3,}|_{3,})$/.test(o.trim())){n&&(r.push(a==="ol"?"</ol>":"</ul>"),n=!1),r.push("<hr>");continue}const c=o.match(/^[\s]*[-*+]\s+(.+)$/);if(c){(!n||a!=="ul")&&(n&&r.push(a==="ol"?"</ol>":"</ul>"),r.push("<ul>"),n=!0,a="ul"),r.push(`<li>${ze(c[1])}</li>`);continue}const m=o.match(/^[\s]*\d+\.\s+(.+)$/);if(m){(!n||a!=="ol")&&(n&&r.push(a==="ul"?"</ul>":"</ol>"),r.push("<ol>"),n=!0,a="ol"),r.push(`<li>${ze(m[1])}</li>`);continue}const g=o.match(/^>\s*(.*)$/);if(g){n&&(r.push(a==="ol"?"</ol>":"</ul>"),n=!1),r.push(`<blockquote><p>${ze(g[1])}</p></blockquote>`);continue}n&&(r.push(a==="ol"?"</ol>":"</ul>"),n=!1,a=null),r.push(`<p>${ze(o)}</p>`)}return n&&r.push(a==="ol"?"</ol>":"</ul>"),r.join("")}function ze(e){let t=Wt(e);return t=t.replace(/!\[([^\]]*)\]\(([^)]+)\)/g,'<img src="$2" alt="$1">'),t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2">$1</a>'),t=t.replace(/\*{3}(.+?)\*{3}/g,"<strong><em>$1</em></strong>"),t=t.replace(/\*{2}(.+?)\*{2}/g,"<strong>$1</strong>"),t=t.replace(/\*(.+?)\*/g,"<em>$1</em>"),t=t.replace(/`([^`]+)`/g,"<code>$1</code>"),t=t.replace(/~~(.+?)~~/g,"<s>$1</s>"),t}function Wt(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function qc(e){return e.split(/\n\n+/).map(t=>`<p>${t.split(` 21`).map(r=>Wt(r)).join("<br>")}</p>`).join("")}function Hc(e){return e.split(` 22`).map(t=>t.trim()).filter((t,r,n)=>t||(n[r-1]??"")!=="").map(t=>t?`<p>${Wt(t)}</p>`:"").join("")}const Hr="Negrito e tabelas podem não vir deste formato. Para manter toda a formatação, salve como .docx no Word.";async function aa(e){var a;const t=Bc(e.name);let r="",n;switch(t){case".docx":r=await Mc(e);break;case".doc":{const{extractHtmlFromDoc:i}=await nr(async()=>{const{extractHtmlFromDoc:s}=await import("./docBinaryImporter-DYZkN9Fd.js");return{extractHtmlFromDoc:s}},__vite__mapDeps([0,1,2])),o=await i(e);r=o.html,o.formatted||(n=Hr);break}case".pdf":{const{extractFullTextFromPdf:i}=await nr(async()=>{const{extractFullTextFromPdf:s}=await import("./pdfTextExtractor-ezac6Ghx.js");return{extractFullTextFromPdf:s}},__vite__mapDeps([3,1])),o=await i(e);if(!o.trim())throw new Error("Este PDF parece ser uma imagem escaneada (sem texto). Copie o texto do laudo original ou salve como .docx.");r=Hc(o),n=Hr;break}case".txt":r=qc(await st(e));break;case".html":case".htm":{const i=await st(e),o=((a=i.match(/<body[^>]*>([\s\S]*)<\/body>/i))==null?void 0:a[1])??i;r=Aa.sanitize(o,{ALLOWED_TAGS:["p","br","strong","b","em","i","u","s","h1","h2","h3","h4","ul","ol","li","table","thead","tbody","tr","th","td","span","sub","sup","hr","blockquote"],ALLOWED_ATTR:["style","colspan","rowspan"]});break}case".rtf":r=na(await st(e));break;case".md":r=zc(await st(e));break;case".odt":case".pages":throw new Error('Formato não suportado. No programa de texto, use "Salvar como" > Word (.docx).');default:throw new Error(`Formato não suportado. Aceitos: ${ra()}`)}if(!r.replace(/<[^>]+>/g,"").trim())throw new Error("Documento vazio ou sem texto reconhecÃvel");return{html:ta(r),warning:n}}async function jc(e,t,r="replace"){if(!e){N.error("Editor não disponÃvel");return}Ae.debug(`[Document Import] Starting import: ${t.name} mode=${r}`);const n=N.loading(`Importando ${t.name}...`);try{const{html:a,warning:i}=await aa(t);kc(e,a,r),N.dismiss(n),N.success("Documento importado!",{description:i?`${t.name}. ${i}`:t.name,duration:i?8e3:4e3})}catch(a){console.error("[Document Import] Error:",a),N.dismiss(n),N.error("Não foi possÃvel importar",{description:a instanceof Error?a.message:"Erro desconhecido",duration:9e3})}}const vl=Object.freeze(Object.defineProperty({__proto__:null,convertFileToHtml:aa,convertRtfToHtml:na,getAcceptString:Oc,getSupportedFormatsLabel:ra,importFile:jc,promoteSectionHeadings:ta},Symbol.toStringTag,{value:"Module"}));function El(){var g;const{user:e}=Ge(),t=pt(),{data:r,isLoading:n,error:a}=ke({queryKey:["user-writing-style",e==null?void 0:e.id],queryFn:async()=>
22{if(!(e!=null&&e.id))return null;const{data:d,error:f}=await $.rpc("get_user_writing_style",{p_user_id:e.id,p_section:null,p_modality:null,p_force_refresh:!1});if(f)throw console.error("Erro ao buscar perfil de estilo:",f),f;return d},enabled:!!(e!=null&&e.id),staleTime:1e3*60*30,gcTime:1e3*60*60,refetchOnWindowFocus:!1,refetchOnMount:!1}),{data:i}=ke({queryKey:["user-style-statistics",e==null?void 0:e.id],queryFn:async()=>{if(!(e!=null&&e.id))return null;const{data:d,error:f}=await $.rpc("get_style_statistics",{p_user_id:e.id});return f?(console.error("Erro ao buscar estatÃsticas de estilo:",f),null):d},enabled:!!(e!=null&&e.id),staleTime:1e3*60*15,gcTime:1e3*60*60,refetchOnWindowFocus:!1,refetchOnMount:!1}),o=S.useCallback(async()=>{e!=null&&e.id&&(await $.rpc("get_user_writing_style",{p_user_id:e.id,p_section:null,p_modality:null,p_force_refresh:!0}),t.invalidateQueries({queryKey:["user-writing-style",e.id]}))},[e==null?void 0:e.id,t]),s=S.useCallback(()=>{var h,v,_,x;if(!r)return"Ainda aprendendo seu estilo...";const{preferences:d,vocabulary:f,learning_status:y,usage_data:b,is_new_user:A}=r,p=[];if(A&&p.push("ð Usuário novo - usando estilo padrão"),p.push(`ð Confiança: ${y.confidence}`),p.push(`ð Laudos analisados: ${y.reports_analyzed}`),d.verbosity){const F={concise:"Conciso (< 100 caracteres)",moderate:"Moderado (100-300 caracteres)",detailed:"Detalhado (> 300 caracteres)"};p.push(`âï¸ Estilo de conclusão: ${F[d.verbosity]}`)}if(((h=f.favorite_phrases)==null?void 0:h.length)>0&&p.push(`ð¬ Frases favoritas: "${f.favorite_phrases.slice(0,2).join('", "')}"`),((v=f.opening_patterns)==null?void 0:v.length)>0&&p.push(`Padrões de abertura: "${f.opening_patterns.slice(0,2).join('", "')}"`),((_=b==null?void 0:b.most_used_frases)==null?void 0:_.length)>0&&p.push(`Frases mais usadas: ${b.most_used_frases.length}`),y.dictionary_terms&&y.dictionary_terms>0&&p.push(`Termos no dicionário: ${y.dictionary_terms}`),i&&i.total_feedbacks>0&&(p.push(` 23Feedback de IA:`),p.push(` Taxa de aceitação: ${i.acceptance_rate}%`),p.push(` Feedbacks: ${i.total_feedbacks} (${i.accepted_count} aceitos)`),((x=i.top_rejection_reasons)==null?void 0:x.length)>0)){const F=i.top_rejection_reasons.slice(0,2).map(P=>`${P.reason} (${P.count}x)`).join(", ");p.push(` Motivos de rejeição: ${F}`)}return p.join(` 24`)},[r,i]),c=((g=r==null?void 0:r.learning_status)==null?void 0:g.confidence)||"learning";return{styleProfile:r,styleStatistics:i,isLoading:n,error:a,confidence:c,isLearning:c==="learning"||c==="low",refreshStyle:o,getStyleContextPreview:s}}function xl(){const{user:e}=Ge();return{recordFeedback:S.useCallback(async r=>{if(!(e!=null&&e.id))return null;try{return(await Na("enrich-feedback",{user_id:e.id,function_name:r.functionName,ai_output:r.aiOutput,user_final_text:r.userFinalText||null,accepted:r.accepted,rejection_reason:r.rejectionReason||null,section:r.section||null,modality:r.modality||null,processing_time_ms:r.processingTimeMs||null})).feedback_id}catch(n){console.error("[StyleFeedback] Edge Function error, falling back to RPC:",n);try{const{data:a,error:i}=await $.rpc("record_ai_style_feedback",{p_user_id:e.id,p_function_name:r.functionName,p_ai_output:r.aiOutput,p_user_final_text:r.userFinalText||null,p_accepted:r.accepted,p_rejection_reason:r.rejectionReason||null,p_section:r.section||null,p_modality:r.modality||null,p_processing_time_ms:r.processingTimeMs||null});return i?(console.error("[StyleFeedback] RPC fallback error:",i),null):a}catch(a){return console.error("[StyleFeedback] RPC fallback exception:",a),null}}},[e==null?void 0:e.id])}}function Tl(e,t){if(!e||!t)return 0;const r=s=>s.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(c=>c.length>2),n=new Set(r(e)),a=new Set(r(t));if(n.size===0||a.size===0)return 0;const i=new Set([...n].filter(s=>a.has(s))),o=new Set([...n,...a]);return i.size/o.size}const Wc=Ma()(ka(e=>({enabled:!1,showBadges:!0,showCriticalAlerts:!0,showPearls:!0,flashCommandEnabled:!0,setEnabled:t=>e({enabled:t}),toggleMode:()=>e(t=>({enabled:!t.enabled})),updateSettings:t=>e(t)}),{name:"radreport-education-mode"}));function Sl(){const e=Wc();return{isEnabled:e.enabled,showBadges:e.enabled&&e.showBadges,showCriticalAlerts:e.enabled&&e.showCriticalAlerts,showPearls:e.enabled&&e.showPearls,flashCommandEnabled:e.enabled&&e.flashCommandEnabled,settings:{enabled:e.enabled,showBadges:e.showBadges,showCriticalAlerts:e.showCriticalAlerts,showPearls:e.showPearls,flashCommandEnabled:e.flashCommandEnabled},setEnabled:e.setEnabled,toggleMode:e.toggleMode,updateSettings:e.updateSettings}}export{di as A,xl as B,Tl as C,ml as D,dl as E,Qr as F,Zr as G,fl as H,ut as I,hl as J,ul as K,Oa as L,cl as M,ll as N,Fi as O,vl as P,re as V,wl as a,yl as b,aa as c,_l as d,gl as e,ra as f,Oc as g,kc as h,Os as i,jc as
24j,El as k,Ra as l,wt as m,Ua as n,Ba as o,Sl as p,Ce as q,al as r,Ja as s,bl as t,pl as u,il as v,ol as w,sl as x,Yr as y,Vr 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.