var content=(function(){"use strict";function $F(r){return r}const I=globalThis.browser?.runtime?.id?globalThis.browser:globalThis.chrome,$a="paperlens_onboarding_completed";class an{static instance;constructor(){}static getInstance(){return an.instance||(an.instance=new an),an.instance}async shouldShow(){try{return!(await I.storage.local.get($a))[$a]}catch(e){return console.warn("[PaperLens Onboarding] Failed to read onboarding state:",e),!0}}async markComplete(){try{await I.storage.local.set({[$a]:!0}),console.log("[PaperLens Onboarding] Marked as completed")}catch(e){console.error("[PaperLens Onboarding] Failed to mark onboarding complete:",e)}}async reset(){try{await I.storage.local.remove($a),console.log("[PaperLens Onboarding] State reset")}catch(e){console.error("[PaperLens Onboarding] Failed to reset onboarding state:",e)}}}const Sb=`/**
 * Onboarding Overlay Styles
 *
 * \u9996\u6B21\u5B89\u88C5\u5F15\u5BFC\u906E\u7F69\u5C42 + \u63D0\u793A\u5361\u7247\u6837\u5F0F\u3002
 * \u76F4\u63A5\u6CE8\u5165\u5230\u9875\u9762 DOM\uFF08\u975E Shadow DOM\uFF09\uFF0C\u56E0\u4E3A\u9700\u8981\u8986\u76D6\u6574\u4E2A\u9875\u9762\u3002
 */

.pl-onboarding-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 2147483647;
  pointer-events: auto;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans CJK SC', 'Noto Sans SC', 'Source Han Sans SC', 'Helvetica Neue', Arial, sans-serif;
}

/* \u2500\u2500 \u9AD8\u4EAE\u533A\u57DF \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-onboarding-highlight {
  position: fixed;
  display: none;
  border-radius: 6px;
  box-shadow:
    0 0 0 4px #2563eb,
    0 0 0 9999px rgba(0, 0, 0, 0.6);
  z-index: 1;
  transition: all 0.3s ease;
}

/* \u2500\u2500 \u63D0\u793A\u5361\u7247 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-onboarding-card {
  position: fixed;
  display: none;
  background: #ffffff;
  border-radius: 12px;
  padding: 20px;
  z-index: 2;
  box-shadow:
    0 0 0 1px rgba(0, 0, 0, 0.05),
    0 20px 25px -5px rgba(0, 0, 0, 0.1),
    0 8px 10px -6px rgba(0, 0, 0, 0.1);
  font-size: 14px;
  color: #1f2937;
  opacity: 0;
  transform: translateY(8px);
  transition: opacity 0.3s ease, transform 0.3s ease;
}

.pl-onboarding-card--visible {
  opacity: 1;
  transform: translateY(0);
}

/* \u2500\u2500 \u5361\u7247\u6807\u9898 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-onboarding-card-title {
  font-size: 16px;
  font-weight: 700;
  margin-bottom: 8px;
  color: #111827;
  line-height: 1.4;
}

/* \u2500\u2500 \u5361\u7247\u8BF4\u660E \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-onboarding-card-desc {
  font-size: 13px;
  line-height: 1.6;
  color: #6b7280;
  margin-bottom: 16px;
}

/* \u2500\u2500 \u5361\u7247\u5E95\u90E8 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-onboarding-card-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* \u2500\u2500 \u6B65\u9AA4\u6307\u793A\u5668 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-onboarding-card-step {
  font-size: 12px;
  color: #9ca3af;
  font-weight: 500;
}

/* \u2500\u2500 \u6309\u94AE\u7EC4 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-onboarding-card-btns {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* \u2500\u2500 \u6309\u94AE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-onboarding-btn {
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.15s ease;
  font-family: inherit;
}

.pl-onboarding-btn--skip {
  background: transparent;
  color: #9ca3af;
}

.pl-onboarding-btn--skip:hover {
  color: #6b7280;
  background: #f3f4f6;
}

.pl-onboarding-btn--next {
  background: #2563eb;
  color: #ffffff;
}

.pl-onboarding-btn--next:hover {
  background: #1d4ed8;
}

/* \u2500\u2500 \u6DF1\u8272\u6A21\u5F0F\u9002\u914D \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
@media (prefers-color-scheme: dark) {
  .pl-onboarding-highlight {
    box-shadow:
      0 0 0 4px #60a5fa,
      0 0 0 9999px rgba(0, 0, 0, 0.75);
  }

  .pl-onboarding-card {
    background: #1f2937;
    box-shadow:
      0 0 0 1px rgba(255, 255, 255, 0.1),
      0 20px 25px -5px rgba(0, 0, 0, 0.4),
      0 8px 10px -6px rgba(0, 0, 0, 0.3);
    color: #e5e7eb;
  }

  .pl-onboarding-card-title {
    color: #f3f4f6;
  }

  .pl-onboarding-card-desc {
    color: #9ca3af;
  }

  .pl-onboarding-card-step {
    color: #6b7280;
  }

  .pl-onboarding-btn--skip {
    color: #6b7280;
  }

  .pl-onboarding-btn--skip:hover {
    color: #9ca3af;
    background: #374151;
  }

  .pl-onboarding-btn--next {
    background: #3b82f6;
  }

  .pl-onboarding-btn--next:hover {
    background: #60a5fa;
  }
}
`,_t=".paperlens-metric-host",kt=".paperlens-citation-host",Pn=".paperlens-save-host",Bn=".paperlens-export-host",wb=".paperlens-abstract-host",In=".pl-translate-wrapper",Tb=".paperlens-checkbox-host",Xc=".paperlens-filter-toolbar-host",Eb=".pl-toolbar-progress",Fb=".pl-toolbar-cancel-btn",Db=".paperlens-article-type-host",eu=".paperlens-extra-download-host",xo=".paperlens-zotero-host",on=[{selector:Xc,title:"\u{1F680} \u7B5B\u9009\u4E0E\u6392\u5E8F",description:"\u6309\u5F71\u54CD\u56E0\u5B50\u3001\u88AB\u5F15\u6B21\u6570\u3001\u5E74\u4EFD\u3001\u5206\u533A\u548C\u5F00\u653E\u83B7\u53D6\u72B6\u6001\u7B5B\u9009\u7ED3\u679C\uFF0C\u4E5F\u53EF\u4EE5\u6279\u91CF\u5BFC\u51FA\u6216\u4FDD\u5B58\u5230 Zotero\u3002",preferredPosition:"bottom"},{selector:_t,title:"\u{1F4CA} \u671F\u520A\u6307\u6807",description:"\u5728\u8BBA\u6587\u65C1\u663E\u793A IF\u3001JCR \u5206\u533A\u548C\u4E2D\u79D1\u9662\u5206\u533A\uFF0C\u5E2E\u52A9\u4F60\u5FEB\u901F\u5224\u65AD\u671F\u520A\u4FE1\u606F\u3002",preferredPosition:"top"},{selector:Pn,title:"\u2B50 \u4FDD\u5B58\u5230\u6587\u732E\u5E93",description:"\u70B9\u51FB\u201C\u6536\u85CF\u201D\u5373\u53EF\u4FDD\u5B58\u8BBA\u6587\u3002\u767B\u5F55\u540E\u53EF\u540C\u6B65\u5230\u4F60\u7684\u5728\u7EBF\u6587\u732E\u5E93\u3002",preferredPosition:"right"},{selector:Bn,title:"\u{1F4E5} \u5BFC\u51FA\u5F15\u7528",description:"\u652F\u6301 RIS\u3001BibTeX\u3001MEDLINE\u3001CSV\uFF0C\u53EF\u7528\u4E8E Zotero\u3001EndNote \u548C LaTeX\u3002",preferredPosition:"right"},{selector:In,title:"AI \u89E3\u8BFB",description:"\u5728\u8BBA\u6587\u9875\u9762\u67E5\u770B\u9898\u76EE\u3001\u6458\u8981\u3001\u5173\u952E\u8BCD\u548C\u7ED3\u6784\u5316\u89E3\u8BFB\uFF0C\u9002\u5408\u5FEB\u901F\u4E86\u89E3\u6587\u7AE0\u8981\u70B9\u3002",preferredPosition:"right"}],tu=3,_b=500,kb=300;let Er=0,Ce=null,Me=null,K=null,Oa=null,Fr=null,Dr=null,Mn=null,_r=null,Ua=!1;function Nb(r){if(!r||!r.offsetParent)return!1;const e=r.getBoundingClientRect();return e.width>0&&e.height>0}function nu(r){Er=0,Ua=!1,Oa=r,Rb(),Ha(Er)}function Lb(){Ao(),Co(),ru(),au(),Er=0,Mn=null,Ua=!1,Oa=null}function Ao(){Fr!==null&&(clearTimeout(Fr),Fr=null)}function ru(){Dr&&(window.removeEventListener("resize",Dr),Dr=null)}function Co(){_r&&(_r(),_r=null)}function Rb(){if(Ce)return;Ce=document.createElement("div"),Ce.className="pl-onboarding-overlay",Ce.setAttribute("data-paperlens-onboarding","");const r=document.createElement("style");r.textContent=Sb,Ce.appendChild(r),Me=document.createElement("div"),Me.className="pl-onboarding-highlight",Ce.appendChild(Me),K=document.createElement("div"),K.className="pl-onboarding-card",Ce.appendChild(K),Ce.addEventListener("click",e=>{e.target===Ce||e.target}),document.body.appendChild(Ce),Dr=()=>Bb(),window.addEventListener("resize",Dr)}function au(){Ce&&(Ce.remove(),Ce=null),Me=null,K=null}function Ha(r,e=0){if(r>=on.length){su(Ua);return}Er=r;const t=Pb(r);if(t){Ib(r,t);return}e<tu?Fr=setTimeout(()=>{Fr=null,Ha(r,e+1)},_b):(console.warn(`[PaperLens Onboarding] Step ${r+1} target not found after ${tu} retries, skipping`),Ha(r+1))}function Pb(r){const e=on[r];if(!e)return null;const t=document.querySelectorAll(e.selector);for(const n of t)if(n instanceof HTMLElement&&Nb(n))return n;return null}function Bb(){!Mn||!Ce||(iu(Mn),ou(Mn,on[Er].preferredPosition))}function Ib(r,e){Mn=e,Ua=!0,Mb(r),K&&K.classList.remove("pl-onboarding-card--visible"),e.scrollIntoView({behavior:"smooth",block:"center"});let t=!1;const n=()=>{t||(t=!0,iu(e),ou(e,on[r].preferredPosition),K&&(K.classList.remove("pl-onboarding-card--visible"),K.offsetHeight,K.classList.add("pl-onboarding-card--visible")))},a=()=>{n()};if("onscrollend"in window){window.addEventListener("scrollend",a,{once:!0});const i=setTimeout(()=>{window.removeEventListener("scrollend",a),n()},kb);_r=()=>{window.removeEventListener("scrollend",a),clearTimeout(i)}}else{const i=setTimeout(n,500);_r=()=>{clearTimeout(i)}}}function iu(r){if(!Me)return;const e=r.getBoundingClientRect();Me.style.position="fixed",Me.style.top=`${e.top-4}px`,Me.style.left=`${e.left-4}px`,Me.style.width=`${e.width+8}px`,Me.style.height=`${e.height+8}px`,Me.style.display="block"}function ou(r,e){if(!K)return;const t=r.getBoundingClientRect(),n=360,a=16,i=window.innerWidth,o=window.innerHeight;K.style.visibility="hidden",K.style.display="block";const s=K.offsetHeight;K.style.visibility="";let l,c,u=e;switch(e){case"top":t.top-s-a<10&&(u="bottom");break;case"bottom":t.bottom+s+a>o-10&&(u="top");break;case"left":t.left-n-a<10&&(u="right");break;case"right":t.right+n+a>i-10&&(u="left");break}switch(u){case"top":l=t.top-s-a,c=t.left+t.width/2-n/2;break;case"bottom":l=t.bottom+a,c=t.left+t.width/2-n/2;break;case"left":l=t.top+t.height/2-s/2,c=t.left-n-a;break;case"right":l=t.top+t.height/2-s/2,c=t.right+a;break}c=Math.max(16,Math.min(c,i-n-16)),l=Math.max(16,Math.min(l,o-s-16)),K.style.top=`${l}px`,K.style.left=`${c}px`,K.style.width=`${n}px`}function Mb(r){if(!K)return;const e=on[r],t=r===on.length-1;K.innerHTML="";const n=document.createElement("div");n.className="pl-onboarding-card-title",n.textContent=e.title,K.appendChild(n);const a=document.createElement("div");a.className="pl-onboarding-card-desc",a.textContent=e.description,K.appendChild(a);const i=document.createElement("div");i.className="pl-onboarding-card-footer";const o=document.createElement("span");o.className="pl-onboarding-card-step",o.textContent=`${r+1}/${on.length}`,i.appendChild(o);const s=document.createElement("div");s.className="pl-onboarding-card-btns";const l=document.createElement("button");l.className="pl-onboarding-btn pl-onboarding-btn--skip",l.textContent="\u8DF3\u8FC7",l.addEventListener("click",()=>su(!0)),s.appendChild(l);const c=document.createElement("button");c.className="pl-onboarding-btn pl-onboarding-btn--next",c.textContent=t?"\u5F00\u59CB\u4F7F\u7528 \u2728":"\u4E0B\u4E00\u6B65 \u2192",c.addEventListener("click",()=>{Ao(),Co(),Ha(r+1)}),s.appendChild(c),i.appendChild(s),K.appendChild(i)}async function su(r){Ao(),Co(),ru(),au(),Mn=null,r&&Oa?await Oa():r||console.log("[PaperLens Onboarding] No steps could be shown \u2014 not marking complete, will retry next visit")}const za=[];function qb(r,e){const t=r.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/^\*:\/\//,"(https?|ftp):\\/\\/").replace(/\*/g,".*");return new RegExp("^"+t+"$").test(e)}function q(r){if(!r)throw new Error("[AdapterRegistry] Cannot register null or undefined adapter");const e=za.findIndex(t=>t.id===r.id);e>=0&&(console.warn(`[AdapterRegistry] Adapter with id "${r.id}" already registered, replacing...`),za.splice(e,1)),za.push(r),console.log(`[AdapterRegistry] Registered adapter: ${r.id} (${r.name})`)}function jb(r){const e=location.href;for(const t of za)for(const n of t.matches)if(qb(n,e))return console.log(`[AdapterRegistry] Detected adapter: ${t.id} (${t.name}) for URL: ${e}`),t;return console.debug(`[AdapterRegistry] No adapter found for URL: ${e}`),null}class j{isSearchPage(){return!1}isArticlePage(){return!1}parseSearchResults(){return[]}parseArticlePage(){return null}getMetricBarAnchor(e){return{element:e,position:"after"}}getResultsContainer(){return document.body}getPageInfo(){return{pageNum:1,totalPages:1,url:location.href}}}const $b=".top-wrapper",Ob="section.search-results-list",lu="section.search-results-list",Ja="div.search-results-chunks",ke="div.search-results-chunk",ie="article.full-docsum",vo="div.docsum-content",So="div.docsum-snippet",cu="span.docsum-pmid",Nt="a.docsum-title",sn="data-article-id",Ub="a.docsum-title",uu="span.docsum-authors.full-authors",kr="span.docsum-journal-citation.full-journal-citation",wo="span.docsum-journal-citation.short-journal-citation",Va="span.publication-type",Wa="div.docsum-citation.full-citation",Hb="main#article-details",zb="h1.heading-title, h1.title",Jb="div.article-source, span.citation, div.citation",du='span#doi a, span#doi, a[href*="doi.org"]',Vb="span#pmid, strong.current-id",Wb="span#pmc",Gb="div.article-meta, div.abstract-content",Zb=/doi:\s*(10\.\d{4,}\/[^\s.]+(?:\.[^\s]+)*?)(?:\.\s|$)/i,Yb=/\b(\d{4})\b/,Kb=/^((?:18|19|20)\d{2}(?:\s+[A-Za-z]{3,9})?(?:\s+\d{1,2})?)/;function pu(r){return r.match(Zb)?.[1]??null}function To(r){const e=r.match(Yb);if(e?.[1]){const t=parseInt(e[1],10);if(t>=1800&&t<=2100)return t}return null}function Qb(r){const e=r.indexOf(".");return e<0?null:r.slice(e+1).trim().match(Kb)?.[1]??null}function Xb(r){const e=r.indexOf(".");return e>0?r.substring(0,e).trim():r.trim()}function Eo(r){const e=r.indexOf(".");return e>0?r.substring(0,e).trim():r.trim()}function hu(r){return r.textContent?.trim()??""}function fu(r){if(!r)return[];const e=r.replace(/\.\s*$/,"").trim();return e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}function Ga(r){return r&&r.replace(/\.\s*$/,"").trim()||null}function Za(r){let t=r.querySelector(Nt)?.getAttribute(sn)??"";t||(t=r.querySelector(cu)?.textContent?.trim()??"");const n=r.querySelector(Ub),a=n?hu(n):"",o=r.querySelector(kr)?.textContent?.trim()??"",l=r.querySelector(wo)?.textContent?.trim()??"",c=pu(o),u=To(o),d=Qb(o),p=Eo(o),h=Xb(l),y=r.querySelector(uu)?.textContent?.trim()??"",x=fu(y),T=r.querySelector(So)?.textContent?.replace(/\s+/g," ").trim(),E=r.querySelector(Va),w=Ga(E?.textContent?.trim()??null),v={PMID:t,title:a,journal:p,fetchedAt:Date.now()};return c&&(v.DOI=c),h&&h!==p&&(v.journalAbbr=h),x.length>0&&(v.authors=x),T&&(v.abstractSnippet=T),u!==null&&(v.year=u),d&&(v.publicationDate=d),w&&(v.articleType=w),v}class eg extends j{id="pubmed";name="PubMed";matches=["*://pubmed.ncbi.nlm.nih.gov/*"];isSearchPage(){return new URLSearchParams(location.search).has("term")}isArticlePage(){const e=location.pathname;return/^\/\d+\/?$/.test(e)}parseSearchResults(){const e=[],t=document.querySelectorAll(ie);for(const n of t)try{const a=this.parseArticleElement(n);a&&e.push(a)}catch(a){console.error("[PubMedAdapter] Failed to parse article:",a)}return e}parseArticlePage(){const e=document.querySelector(Hb);if(!e)return console.warn("[PubMedAdapter] Article page main content not found"),null;try{const n=e.querySelector(Vb)?.textContent?.trim()??"",i=e.querySelector(zb)?.textContent?.trim()??"",s=e.querySelector(Jb)?.textContent?.trim()??"",c=e.querySelector(du)?.getAttribute("href")??"",u=/10\.\d{4,}\/[^\s?]+/i,d=c.match(u)?.[0]??null,p=Eo(s),h=To(s),y=e.querySelector(Gb)?.querySelector(Va)?.textContent?.trim()??null,x=y?Ga(y):null;return{title:i,journalName:p,pmid:n||void 0,doi:d||void 0,year:h||void 0,articleTypes:x?[x]:void 0,url:location.href,hostElement:e,source:this.id}}catch(t){return console.error("[PubMedAdapter] Failed to parse article page:",t),null}}getMetricBarAnchor(e){const t=e.querySelector(Wa);if(t)return{element:t,position:"before"};const n=e.querySelector(vo);return n&&n.firstElementChild?{element:n.firstElementChild,position:"before"}:super.getMetricBarAnchor(e)}getResultsContainer(){return document.querySelector(lu)}getPageInfo(){const e={pageNum:1,totalPages:1,url:location.href};try{const t=new URLSearchParams(location.search),n=t.get("page");if(n){const o=parseInt(n,10);!isNaN(o)&&o>0&&(e.pageNum=o)}const a=document.querySelector(".page-numbers, .pagination");if(a){const o=a.querySelector("a:last-child");if(o){const l=o.getAttribute("href");if(l){const c=l.match(/page=(\d+)/);c&&(e.totalPages=parseInt(c[1],10))}}const s=a.querySelectorAll('a[href*="page="]');if(s.length>0&&e.totalPages===1)for(const l of s){const c=l.getAttribute("href");if(c){const u=c.match(/page=(\d+)/);if(u){const d=parseInt(u[1],10);d>e.totalPages&&(e.totalPages=d)}}}}const i=t.get("size");if(i){const o=parseInt(i,10);!isNaN(o)&&o>0&&(e.itemsPerPage=o)}}catch(t){console.warn("[PubMedAdapter] Failed to extract page info:",t)}return e}parseArticleElement(e){const t=e.querySelector(Nt);let n=t?.getAttribute(sn)??"";n||(n=e.querySelector(cu)?.textContent?.trim()??"");const a=t?hu(t):"";if(!a)return console.warn("[PubMedAdapter] Article without title, skipping"),null;const o=e.querySelector(kr)?.textContent?.trim()??"",s=Eo(o);if(!s)return console.warn("[PubMedAdapter] Article without journal name, skipping"),null;const l=pu(o),c=To(o),d=e.querySelector(uu)?.textContent?.trim()??"",p=fu(d),f=e.querySelector(So)?.textContent?.replace(/\s+/g," ").trim(),y=e.querySelector(Va),x=Ga(y?.textContent?.trim()??null),T=x?[x]:void 0,E=t?.getAttribute("href");return{title:a,journalName:s,pmid:n||void 0,doi:l||void 0,year:c||void 0,authors:p.length>0?p:void 0,abstractSnippet:f,articleTypes:T,url:E||void 0,hostElement:e,source:this.id}}}const mu=/[-–—]\s*([^,\-–—\d][^,\-–—]*?),\s*((?:19|20)\d{2})\b/,bu=/\b((?:19|20)\d{2})\b/,tg=/\s[-–—]\s/,ng=/^\/scholar\/?$/,gu=/^\/scholar_lookup\/?$/,rg=["title","doi","journal","author","pmid","publication_year","pages"],yu=/(?:^|\s)(?:books\.google|scholar\.google|researchgate|academia\.edu|semanticscholar|pubmed|ncbi|nih\.gov|arxiv|biorxiv|medrxiv|ssrn|repository|proquest|springer\.com|wiley\.com|sciencedirect|tandfonline|jstor|ieeexplore|dl\.acm|nature\.com|nejm\.org|thelancet\.com)(?:\s|$)/i,ag=[{pattern:/:\/\/(?:www\.)?nejm\.org\//i,journal:"New England Journal of Medicine"},{pattern:/:\/\/academic\.oup\.com\/jnci(?:\/|$)/i,journal:"JNCI-Journal of the National Cancer Institute"},{pattern:/:\/\/jamanetwork\.com\/journals\/jama(?:\/|$)/i,journal:"JAMA-JOURNAL OF THE AMERICAN MEDICAL ASSOCIATION"},{pattern:/10\.3322\/caac/i,journal:"CA-A Cancer Journal for Clinicians"},{pattern:/:\/\/ascopubs\.org\/doi\/(?:abs|full|pdf)\/10\.1200\/jco/i,journal:"Journal of Clinical Oncology"},{pattern:/:\/\/(?:www\.)?thelancet\.com\/journals\/lanonc(?:\/|$)/i,journal:"Lancet Oncology"}];class ig extends j{id="google-scholar";name="Google Scholar";matches=["*://scholar.google.com/*","*://scholar.google.com.hk/*","*://scholar.google.co.jp/*","*://scholar.google.com.tw/*"];isSearchPage(){const e=new URLSearchParams(location.search);return ng.test(location.pathname)?e.has("q")||document.querySelector("div.gs_ri")!==null:gu.test(location.pathname)?rg.some(t=>e.has(t))||document.querySelector("div.gs_ri")!==null:!1}isArticlePage(){return!1}parseSearchResults(){const e=[],t=document.querySelectorAll("div.gs_ri");for(const n of t)try{const a=this.parseResultElement(n);a&&e.push(a)}catch(a){console.error("[GoogleScholarAdapter] Failed to parse result:",a)}return e}parseArticlePage(){return null}getMetricBarAnchor(e){const t=e.querySelector("div.gs_a");return t?{element:t,position:"after"}:super.getMetricBarAnchor(e)}getResultsContainer(){return document.getElementById("gs_res_ccl_mid")??document.getElementById("gs_res_ccl_top")??document.querySelector("#gs_res_ccl")}getPageInfo(){const e={pageNum:1,totalPages:1,url:location.href};try{const n=new URLSearchParams(location.search).get("start");if(n){const i=parseInt(n,10);!isNaN(i)&&i>=0&&(e.pageNum=Math.floor(i/10)+1,e.itemsPerPage=10)}const a=document.getElementById("gs_ab_md");if(a){const o=(a.textContent??"").match(/[\d,]+/);if(o){const s=parseInt(o[0].replace(/,/g,""),10);!isNaN(s)&&s>0&&(e.totalItems=s,e.totalPages=Math.ceil(s/(e.itemsPerPage??10)))}}}catch(t){console.warn("[GoogleScholarAdapter] Failed to extract page info:",t)}return e}parseResultElement(e){const t=e.querySelector("h3.gs_rt a"),n=e.querySelector("h3.gs_rt"),a=this.cleanTitle(t?.textContent??n?.textContent??"");if(!a)return console.warn("[GoogleScholarAdapter] Result without title, skipping"),null;const o=e.querySelector("div.gs_a")?.textContent?.trim()??"",s=e.closest("div.gs_r")??e,l=t?.href??t?.getAttribute("href")??"",c=this.collectArticleUrls(s,l),u=this.parseMetaText(o),d=this.inferJournalFromUrls(c),p=d.journalCandidates[0]??"",h=this.shouldPreferInferredJournal(u.journalName)?p||u.journalName:u.journalName||p,f=this.uniqueStrings([h,u.journalName,...d.journalCandidates]),y=u.year,x=this.parseAuthors(o),T=e.querySelector("div.gs_rs"),E=T?.textContent?.replace(/\s+/g," ").trim()??void 0;return{title:a,journalName:h,journalCandidates:f,authors:x,year:y,url:t?.getAttribute("href")??void 0,doi:this.extractDOI(l,T?.textContent??"")??this.extractLookupDOI(),issn:d.issn,abstractSnippet:E||void 0,hostElement:s,source:this.id}}parseMetaText(e){let t="",n;const a=e.split(tg).map(c=>c.trim()).filter(Boolean),i=a.length>=2?a[1]:"";if(i){t=this.extractJournalFromPublicationSection(i);const c=i.match(bu);if(c&&(n=parseInt(c[1],10)),t)return{journalName:t,year:n}}const o=e.match(mu);if(o)return t=o[1].trim(),n=parseInt(o[2],10),{journalName:t,year:n};const s=e.match(/[-–—]\s*([^,\-–—]*?)\s+((?:19|20)\d{2})\b/);if(s){const c=s[1].trim();if(c.length>1)return t=c,n=parseInt(s[2],10),{journalName:t,year:n}}const l=e.match(bu);return l&&(n=parseInt(l[1],10)),{journalName:t,year:n}}cleanTitle(e){return e.replace(/^\s*(?:\[[^\]]+\]\s*)+/,"").replace(/\s+/g," ").trim()}shouldPreferInferredJournal(e){return!e||/…|\.\.\./.test(e)}uniqueStrings(e){const t=new Set,n=[];for(const a of e){const i=a?.replace(/\s+/g," ").trim();!i||t.has(i.toLowerCase())||(t.add(i.toLowerCase()),n.push(i))}return n}collectArticleUrls(e,t){const n=[];t&&n.push(t);for(const a of e.querySelectorAll("a[href]")){const i=a.href||a.getAttribute("href")||"";!i||/^javascript:/i.test(i)||n.push(i)}return this.uniqueStrings(n)}inferJournalFromUrls(e){const t=[];let n;for(const a of e){const i=this.safeDecodeUrl(a);for(const s of ag)s.pattern.test(i)&&t.push(s.journal);const o=this.extractIssnFromScienceDirectPii(i);o&&!n&&(n=o)}return{journalCandidates:this.uniqueStrings(t),issn:n}}safeDecodeUrl(e){try{return decodeURIComponent(e)}catch{return e}}extractIssnFromScienceDirectPii(e){const t=e.match(/\/pii\/S(\d{4})(\d{3}[\dX])/i);if(!(!t?.[1]||!t?.[2]))return`${t[1]}-${t[2].toUpperCase()}`}extractJournalFromPublicationSection(e){const t=e.replace(/\s+/g," ").trim();if(/\.[a-z]{2,}(?:\/|$)/i.test(t)||!t||yu.test(t))return"";let n=t.replace(/\b((?:19|20)\d{2})\b.*$/,"").trim();return!n||(n=n.replace(/[,.;:\s]+$/,"").replace(/\b(?:vol(?:ume)?|issue|no\.?|number|pages?|pp\.?)\b[\s\S]*$/i,"").replace(/\s+\d+[\s\S]*$/,"").replace(/[,.;:\s]+$/,"").trim(),!n||/^\d/.test(n))||yu.test(n)?"":n}isCitationLibraryPage(){return location.pathname!=="/citations"?!1:new URLSearchParams(location.search).has("user")}extractDOI(e,t){const n=this.safeDecodeUrl(e),a=n.match(/doi\.org\/(10\.\d{4,}\/[^\s?&#]+)/i);if(a?.[1])return a[1];const i=n.match(/\/(10\.\d{4,9}\/[^\s?&#]+)/i);if(i?.[1])return i[1];const o=t.match(/(10\.\d{4,9}\/[\w.\-]+[\w])/);if(o?.[1])return o[1]}extractLookupDOI(){return gu.test(location.pathname)&&new URLSearchParams(location.search).get("doi")?.replace(/^https?:\/\/(?:dx\.)?doi\.org\//i,"").replace(/^doi:\s*/i,"").trim()||void 0}parseAuthors(e){const t=e.search(/[\u2013\u2014]/),n=e.indexOf(" - "),a=t>0?t:n>0?n:-1;if(a<=0)return;const i=e.slice(0,a).trim();if(!i||i.length<2)return;const o=i.split(/,\s*|\s*&\s*|\s+and\s+/i).map(s=>s.trim().replace(/^\s*\[?\d+\]?\s*/,"")).filter(s=>s.length>0&&s.length<100);if(!(o.length===0||o.length>20))return o}parseCitationLibrary(){const e=[],t=document.querySelectorAll("tr.gsc_a_tr");for(const n of t)try{const a=n.querySelector("a.gsc_a_at"),i=a?.textContent?.trim()??"";if(!i)continue;const o=n.querySelectorAll("div.gs_gray");let s="",l;const c=n.querySelector("span.gsc_a_h.gsc_a_hc");if(c){const d=parseInt(c.textContent?.trim()??"",10);isNaN(d)||(l=d)}for(let d=0;d<o.length;d++){const h=o[d].textContent?.trim()??"";if(!h)continue;const f=h.match(mu);if(f&&!s){s=f[1].trim(),l||(l=parseInt(f[2],10));continue}if(d===0)continue;const y=h.match(/^([A-Za-z][A-Za-z\s\.\&\-\/\:]+?),?\s*((?:19|20)\d{2})\b/);if(y&&!s){s=y[1].trim(),l||(l=parseInt(y[2],10));continue}const x=h.match(/^([A-Za-z][A-Za-z\s\.\&\-\/\:]+?)\s+\d+/);if(x&&!s){s=x[1].trim();continue}const T=h.match(/^([A-Za-z][A-Za-z\s\.\&\-\/\:]+)$/);if(T&&!s){const E=T[1].trim(),w=E.split(/\s+/),v=E.length>=8||w.length>=2,g=/^(Elsevier|Springer|Springer Nature|Wiley|Wiley\-Blackwell|IEEE|ACM|PLOS|MDPI|Frontiers|Taylor & Francis|SAGE Publications|SAGE|Oxford University Press|Cambridge University Press|Nature Publishing Group|BMC|IOP Publishing|APS|ACS|RSC|AAAS)$/i.test(E),C=/^(Nature|Science|Cell|eLife|Lancet|BMJ|JAMA|NEJM|PNAS|PRL|Angew)$/i.test(E);(v||C)&&!g&&!/\d/.test(E)&&(s=E)}}const u=a?.getAttribute("href")??void 0;e.push({title:i,journalName:s,year:l,url:u,hostElement:n,source:this.id})}catch(a){console.error("[GoogleScholarAdapter] Failed to parse citation row:",a)}return e}getCitationLibraryAnchor(e){const t=e.querySelector("td.gsc_a_t");if(t){const n=t.querySelector("a.gsc_a_at");return n?{element:n,position:"after"}:{element:t,position:"append"}}return super.getMetricBarAnchor(e)}}const Fo=/\b((?:19|20)\d{2})\b/,og=/\b10\.\d{4,9}\/[-._;()/:A-Z0-9]+/i,Do=['a[href*="/kcms2/article/abstract"]','a[href*="/kcms2/article/"]','a[href*="/kcms/detail/"]','a[href*="/KCMS/detail/"]'].join(","),Ya="paperlens-cnki-enhancement-line",xu="data-paperlens-cnki-detail";class sg extends j{id="cnki";name="\u4E2D\u56FD\u77E5\u7F51";matches=["*://kns.cnki.net/*","*://www.cnki.net/*","*://navi.cnki.net/*"];isSearchPage(){const e=location.pathname;return e.includes("/kns8s/defaultresult")||e.includes("/kns/brief/")||e.includes("/kns8s/search")}isArticlePage(){const e=location.pathname;return/\/kcms2\/article\//.test(e)||/\/detail\//.test(e)}parseSearchResults(){const e=[],t=this.parseTableView();if(t.length>0)return t;const n=this.parseSummaryView();return n.length>0?n:e}parseArticlePage(){try{const e=document.querySelector(".detail")??document.querySelector("main")??document.body,n=(e.querySelector("h1")??e.querySelector(".title"))?.textContent?.trim()??"";if(!n)return console.warn("[CnkiAdapter] Article page without title"),null;const a=this.extractDetailPageJournal(e),i=this.extractDetailPageYear(e),o=e.querySelectorAll(".author a"),s=o.length>0?Array.from(o).map(h=>h.textContent?.trim()).filter(h=>h.length>0):void 0,c=(e.querySelector('[name="DOI"]')??e.querySelector('a[href*="doi.org/"]'))?.textContent?.trim()??void 0,d=(e.querySelector(".abstract")??e.querySelector("#ChDivSummary"))?.textContent?.replace(/\s+/g," ").trim()??void 0,p=this.extractDetailPageFullTextUrl(e);return{title:n,journalName:a,year:i,authors:s,doi:c,url:location.href,nativeFullTextUrl:p,abstractSnippet:d||void 0,hostElement:e,source:this.id}}catch(e){return console.error("[CnkiAdapter] Failed to parse article page:",e),null}}getMetricBarAnchor(e){if(this.isArticlePage()){const a=this.getOrCreateDetailEnhancementLine(e);if(a)return{element:a,position:"append"}}const t=e.querySelector("td.name");if(t)return{element:this.getOrCreateEnhancementLine(e,t)??t,position:"append"};const n=this.getDirectCells(e)[1];return n?{element:this.getOrCreateEnhancementLine(e,n)??n,position:"append"}:{element:e,position:"prepend"}}getResultsContainer(){const e=document.querySelector("table.result-table-list")??document.querySelector(".result-table-list")??document.querySelector(".result-table")??document.querySelector("#gridTable")??document.querySelector(".s-single")?.parentElement;return e||this.findArticleTable()}getPageInfo(){const e={pageNum:1,totalPages:1,url:location.href};try{const t=new URLSearchParams(location.search),n=t.get("curpage");if(n){const o=parseInt(n,10);!isNaN(o)&&o>0&&(e.pageNum=o)}const a=document.querySelector("#pc_1")??document.querySelector(".pager-title-cell em");if(a){const s=(a.textContent?.trim()??"").match(/\d+/);if(s){const l=parseInt(s[0],10);!isNaN(l)&&l>0&&(e.totalPages=l)}}const i=t.get("pageSize");if(i){const o=parseInt(i,10);!isNaN(o)&&o>0&&(e.itemsPerPage=o)}}catch(t){console.warn("[CnkiAdapter] Failed to extract page info:",t)}return e}parseTableView(){const e=[],t=this.findTableRows();for(const n of t)if(!n.classList.contains("header"))try{const a=this.parseTableRow(n);a&&e.push(a)}catch(a){console.error("[CnkiAdapter] Failed to parse table row:",a)}return e}parseSummaryView(){const e=[],t=document.querySelectorAll(".s-single");for(const n of t)try{const a=n.querySelector("a.fz14"),i=a?.textContent?.trim()??"";if(!i)continue;const o=n.querySelector(".source")?.textContent?.trim()??"";e.push({title:i,journalName:o,url:a?.getAttribute("href")??void 0,hostElement:n,source:this.id})}catch(a){console.error("[CnkiAdapter] Failed to parse summary item:",a)}return e}parseTableRow(e){const t=this.findTitleElement(e),n=this.cleanText(t?.textContent??"");if(!n)return console.warn("[CnkiAdapter] Table row without title, skipping"),null;const a=this.extractJournalFromRow(e),i=this.getDirectCells(e),s=this.cleanText(e.querySelector("td.date")?.textContent??i[4]?.textContent??"").match(Fo),l=s?parseInt(s[1],10):void 0,c=this.cleanText(e.querySelector("td.author")?.textContent??i[2]?.textContent??"").replace(/显示全部作者/g,""),u=c?c.split(/[;；,，]/).map(f=>f.trim()).filter(Boolean):void 0,d=this.extractDoi(e),p=this.cleanText(i[5]?.textContent??""),h=p?[p]:void 0;return{title:n,journalName:a,year:l,authors:u,doi:d,url:this.toAbsoluteUrl(t?.getAttribute("href")),hostElement:e,articleTypes:h,source:this.id}}extractJournalFromRow(e){const t=e.querySelector("td.name .source");if(t){const o=t.getAttribute("data-source");if(o)return o.trim();const s=t.textContent?.trim()??"";if(s)return s}const n=e.querySelector("td.source");if(n){const o=this.cleanText(n.textContent??"");if(o)return o}const i=this.getDirectCells(e)[3];if(i){const o=i.querySelector("a"),s=this.cleanText(o?.textContent??i.textContent??"");if(s)return s}return""}findTableRows(){const e=[],t=new Set,n=["table.result-table-list tbody tr",".result-table-list tbody tr","#gridTable tbody tr",".result-table tbody tr","table tbody tr"];for(const a of n)document.querySelectorAll(a).forEach(i=>{t.has(i)||this.findTitleElement(i)&&(t.add(i),e.push(i))});return e}findArticleTable(){for(const e of Array.from(document.querySelectorAll("table")))if(e.querySelector(Do)||e.querySelector("td.name a.fz14"))return e;return null}findTitleElement(e){const t=e.querySelector("td.name a.fz14");if(t)return t;const i=this.getDirectCells(e)[1]?.querySelector(Do);return i||e.querySelector(Do)}getOrCreateEnhancementLine(e,t){const n=t.querySelector(`.${Ya}`);if(n)return n;const a=t.ownerDocument.createElement("div");a.className=Ya,a.style.cssText=["display:flex","flex-wrap:wrap","align-items:center","gap:6px","margin-top:6px","line-height:1.4"].join(";");const i=this.findTitleElement(e);return i?.parentElement===t?i.insertAdjacentElement("afterend",a):t.appendChild(a),a}getOrCreateDetailEnhancementLine(e){const t=e.querySelector(".top-tip"),n=t?.querySelector("a")??t?.querySelector(".source a")??t?.querySelector(".source")??e.querySelector(".source a")??e.querySelector(".source"),a=n?.parentElement??t;if(!a)return null;const i=a.querySelector(`.${Ya}[${xu}="true"]`);if(i)return i;const o=a.ownerDocument.createElement("span");return o.className=Ya,o.setAttribute(xu,"true"),o.style.cssText=["display:inline-flex","flex-wrap:wrap","align-items:center","gap:6px","margin-left:8px","vertical-align:middle","max-width:100%"].join(";"),n?n.insertAdjacentElement("afterend",o):a.appendChild(o),o}getDirectCells(e){return Array.from(e.children).filter(t=>t.tagName.toLowerCase()==="td")}cleanText(e){return e.replace(/\s+/g," ").trim()}toAbsoluteUrl(e){if(e)try{return new URL(e,location.href).href}catch{return e}}extractDoi(e){const t=e.querySelector('a[href*="doi.org/"]');return[t?.getAttribute("href"),t?.textContent,e.textContent].filter(Boolean).join(" ").match(og)?.[0]}extractDetailPageJournal(e){const t=e.querySelector(".top-tip a");if(t){const a=t.textContent?.trim()??"";if(a)return a}const n=e.querySelector(".source");if(n){const a=n.textContent?.trim()??"";if(a)return a}return""}extractDetailPageFullTextUrl(e){const t=['a[href*="download.aspx"]','a[href*="/kcms/download/"]','a[href*="/KCMS/download/"]','a[href*="download?filename="]',".doc-operate a[href]",".download a[href]","a.btn-download[href]"].join(","),n=Array.from(e.querySelectorAll(t));for(const a of n){const i=a.getAttribute("href");if(!i)continue;const o=this.cleanText(a.textContent??""),s=i.toLowerCase();if(/下载|原文|pdf|caj|整本/.test(o)||/download|pdf|caj/.test(s))return this.toAbsoluteUrl(i)}}extractDetailPageYear(e){const n=(e.querySelector(".top-tip")?.textContent?.trim()??"").match(Fo);if(n)return parseInt(n[1],10);const a=e.querySelector(".date")??e.querySelector('[name="publishdate"]');if(a){const o=(a.textContent?.trim()??"").match(Fo);if(o)return parseInt(o[1],10)}}}const Au=/\b((?:19|20)\d{2})\b/,Cu=/\b10\.\d{4,9}\/[-._;()/:A-Z0-9]+/i,vu=/\b\d{4}-\d{3}[\dX]\b/i;class lg extends j{id="wos";name="Web of Science";matches=["*://www.webofscience.com/*"];isSearchPage(){return/\/(search|results)/.test(location.pathname)}isArticlePage(){const e=location.pathname;return/\/full-record\//.test(e)||e.includes("/wos/woscc/full-record")}parseSearchResults(){const e=[],t=document.querySelectorAll("app-record");for(const a of t)try{const i=this.parseRecordElement(a);i&&e.push(i)}catch(i){console.error("[WoSAdapter] Failed to parse app-record:",i)}if(e.length>0)return e;const n=document.querySelectorAll(".search-results-item");for(const a of n)try{const i=this.parseLegacyItem(a);i&&e.push(i)}catch(i){console.error("[WoSAdapter] Failed to parse legacy item:",i)}return e}parseArticlePage(){try{const e=this.getDetailHostElement(),t=["h1",".title",'[data-name="title"]','[data-ta*="title"]','[data-test*="title"]'],n=this.queryFirst(e,t)??this.queryFirst(document,t),a=this.getMetaContent("citation_title")??this.cleanText(n?.textContent);if(!a)return console.warn("[WoSAdapter] Article page without title"),null;const i=this.getMetaContent("citation_journal_title")??this.extractDetailPageJournal(e),o=this.extractDetailPageYear(e),s=this.cleanDoi(this.getMetaContent("citation_doi"))??this.extractDetailPageDoi(e),l=this.getMetaContents("citation_author"),c=l.length>0?l:this.extractAuthorsFromRoot(e),u=this.queryFirst(e,[".abstract",'[data-name="abstract"]','[data-ta*="abstract"]','[data-test*="abstract"]']),d=this.getMetaContent("citation_abstract")??this.cleanText(u?.textContent)??void 0;return{title:a,journalName:i,year:o,authors:c,doi:s,articleTypes:this.extractArticleTypesFromRoot(e),issn:this.getMetaContent("citation_issn")??this.getMetaContent("citation_eissn")??this.extractIssnFromRoot(e,!1),url:location.href,abstractSnippet:d,hostElement:e,source:this.id}}catch(e){return console.error("[WoSAdapter] Failed to parse article page:",e),null}}getMetricBarAnchor(e){const t=e.shadowRoot??e,n=t.querySelector("h3.title")??t.querySelector('[data-ta*="title"]')??t.querySelector('[data-test*="title"]')??t.querySelector("h3");if(n)return{element:n,position:"after"};const i=(e.matches("app-record")?e:e.querySelector("app-record"))?.shadowRoot,o=i?.querySelector("h3.title")??i?.querySelector('[data-ta*="title"]')??i?.querySelector('[data-test*="title"]')??i?.querySelector("h3");return o?{element:o,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector(".search-results-list")??document.querySelector('[class*="search-results"]')??document.querySelector("app-search-results")??document.querySelector("app-record-list")??null}getPageInfo(){const e={pageNum:1,totalPages:1,url:location.href};try{const n=new URLSearchParams(location.search).get("page");if(n){const o=parseInt(n,10);!isNaN(o)&&o>0&&(e.pageNum=o)}const a=document.querySelector(".pagination")??document.querySelector('[class*="pager"]');if(a){const o=a.querySelector("li:last-child a")??a.querySelector(".last a");if(o){const s=o.textContent?.trim()??"",l=parseInt(s,10);!isNaN(l)&&l>0&&(e.totalPages=l)}}const i=document.querySelector(".search-results-count")??document.querySelector('[class*="result-count"]');if(i){const s=(i.textContent?.trim()??"").match(/[\d,]+/);if(s){const l=parseInt(s[0].replace(/,/g,""),10);!isNaN(l)&&l>0&&(e.totalItems=l)}}}catch(t){console.warn("[WoSAdapter] Failed to extract page info:",t)}return e}parseRecordElement(e){const t=e.shadowRoot??e,n=this.queryFirst(t,["h3.title a","h3 a",".title a",'[data-ta="summary-record-title"] a','[data-ta*="title"] a','[data-test*="title"] a','a[aria-label*="title"]',"a[title]"]),a=this.cleanText(n?.textContent)??this.cleanText(n?.getAttribute("title"))??"";if(!a)return console.warn("[WoSAdapter] app-record without title, skipping"),null;const i=this.extractJournalFromRoot(t),o=this.extractYearFromRoot(t),s=this.extractDoiFromRoot(t),l=this.extractAuthorsFromRoot(t),c=e.closest(".search-results-item")??e;return{title:a,journalName:i,year:o,authors:l,doi:s,articleTypes:this.extractArticleTypesFromRoot(t),issn:this.extractIssnFromRoot(t),url:this.toAbsoluteUrl(n?.getAttribute("href")),hostElement:c,source:this.id}}parseLegacyItem(e){const t=this.queryFirst(e,["a[title]","h3 a",".title a",'[data-ta*="title"] a','[data-test*="title"] a']),n=this.cleanText(t?.getAttribute("title"))??this.cleanText(t?.textContent)??"";if(!n)return console.warn("[WoSAdapter] Legacy item without title, skipping"),null;const a=this.extractJournalFromRoot(e),i=this.extractYearFromRoot(e);return{title:n,journalName:a,year:i,authors:this.extractAuthorsFromRoot(e),doi:this.extractDoiFromRoot(e),articleTypes:this.extractArticleTypesFromRoot(e),issn:this.extractIssnFromRoot(e),url:this.toAbsoluteUrl(t?.getAttribute("href")),hostElement:e,source:this.id}}extractJournalFromRoot(e){const t=[".source-title span",".source-title",'[data-name="sourceTitle"]','[data-name="source"]','[data-ta*="source"]','[data-test*="source"]','[data-ta*="journal"]','[data-test*="journal"]',"p.source"];for(const a of t){const i=this.cleanJournalName(this.queryFirst(e,[a])?.textContent);if(i)return i}const n=this.cleanText(this.queryFirst(e,[".summary",'[data-name="summary"]'])?.textContent);return this.extractJournalFromSummary(n)??""}extractYearFromRoot(e){const t=this.queryFirst(e,[".pub-year",'[data-name="publicationDate"]','[data-name="published"]','[data-ta*="date"]','[data-test*="date"]',".summary",'[data-name="summary"]']);return this.extractYear(t?.textContent)}extractDoiFromRoot(e,t=!0){const n=e.querySelector("[data-doi]"),a=this.cleanDoi(n?.getAttribute("data-doi"));if(a)return a;const i=e.querySelector('a[href*="doi.org/"]'),o=this.cleanDoi(i?.getAttribute("href"));if(o)return o;const s=this.queryFirst(e,['[data-name="doi"]','[data-ta*="doi"]','[data-test*="doi"]']);return this.cleanDoi(s?.textContent)??(t?this.cleanDoi(e.textContent):void 0)}extractDetailPageJournal(e){return this.extractJournalFromRoot(e)}extractDetailPageYear(e){const t=this.getMetaContent("citation_publication_date")??this.getMetaContent("citation_online_date")??this.getMetaContent("citation_year");return this.extractYear(t)??this.extractYearFromRoot(e)}extractDetailPageDoi(e){return this.extractDoiFromRoot(e,!1)}getDetailHostElement(){return document.querySelector(".full-record")??document.querySelector('[data-name="full-record"]')??document.querySelector('[data-ta*="full-record"]')??document.querySelector('[data-test*="full-record"]')??document.querySelector("main")??document.body}extractAuthorsFromRoot(e){const t=e.querySelectorAll([".authors a",'[data-name="authors"] a','[data-ta*="author"] a','[data-test*="author"] a',".authors span",'[data-name="authors"] span'].join(", ")),n=Array.from(t).map(c=>this.cleanAuthorName(c.textContent)).filter(c=>!!c);if(n.length>0)return[...new Set(n)];const a=this.queryFirst(e,[".authors",'[data-name="authors"]','[data-ta*="author"]','[data-test*="author"]']),i=this.cleanText(a?.textContent);if(!i)return;const o=i.replace(/^By\s*[:：]\s*/i,""),l=(o.includes(";")?o.split(";"):o.split(/\s{2,}/)).map(c=>this.cleanAuthorName(c)).filter(c=>!!c);return l.length>0?[...new Set(l)]:void 0}extractArticleTypesFromRoot(e){const t=['[data-name="documentType"]','[data-name="document-type"]','[data-ta*="document-type"]','[data-test*="document-type"]',".document-type",".doctype"],a=this.firstTextFromSelectors(e,t)??this.extractLabeledValue(e.textContent,["Document Type","Publication Type","Article Type"]);if(!a)return;const i=a.replace(/^(?:Document Type|Publication Type|Article Type)\s*[:：]\s*/i,"").split(/[;|]/).flatMap(o=>o.split(/\s{2,}/)).map(o=>this.cleanText(o)).filter(o=>!!o).filter(o=>!Au.test(o)&&!Cu.test(o)&&!vu.test(o));return i.length>0?[...new Set(i)]:void 0}extractIssnFromRoot(e,t=!0){const n=['[data-name="issn"]','[data-name="eissn"]','[data-ta*="issn"]','[data-test*="issn"]',".issn"],a=this.firstTextFromSelectors(e,n);return this.cleanIssn(a)??(t?this.cleanIssn(e.textContent):void 0)}cleanAuthorName(e){return this.cleanText(e)?.replace(/^By\s*[:：]\s*/i,"").replace(/\s*\([^)]*\)\s*$/,"")||void 0}extractJournalFromSummary(e){if(!e)return;const t=e.match(/\b(?:Source|Source Title|Publication Name|Journal|Published in)\s*[:：]\s*([^.;|]+)/i);if(t)return this.cleanJournalName(t[1])}firstTextFromSelectors(e,t){for(const n of t){const a=this.cleanText(this.queryFirst(e,[n])?.textContent);if(a)return a}}extractLabeledValue(e,t){const n=this.cleanText(e);if(n)for(const a of t){const i=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o="(?:Published|Publication Date|Publication Year|DOI|ISSN|eISSN|Source|Source Title|Authors|Times Cited|Accession Number|Volume|Issue|Pages?)",s=n.match(new RegExp(`${i}\\s*[:\uFF1A]\\s*([\\s\\S]*?)(?=\\s+${o}\\s*[:\uFF1A]|$)`,"i"));if(s)return this.cleanText(s[1])}}cleanJournalName(e){return this.cleanText(e)?.replace(/^(?:Source|Source Title|Publication Name|Journal|Published in)\s*[:：]\s*/i,"").replace(/\b(?:Volume|Vol\.?|Issue|Pages?)\b.*$/i,"").replace(/\s*[,;|]\s*$/,"").trim()||void 0}extractYear(e){const t=this.cleanText(e)?.match(Au);return t?parseInt(t[1],10):void 0}cleanDoi(e){const t=this.cleanText(e);if(!t)return;let n=t;try{n=decodeURIComponent(t)}catch{n=t}const a=n.match(Cu);if(a)return a[0].replace(/[.,;]+$/,"")}cleanIssn(e){return this.cleanText(e)?.match(vu)?.[0].toUpperCase()}queryFirst(e,t){for(const n of t)try{const a=e.querySelector(n);if(a)return a}catch{}return null}cleanText(e){return e?.replace(/\s+/g," ").trim()||void 0}getMetaContent(e){return this.cleanText(document.querySelector(`meta[name="${e}"]`)?.getAttribute("content")??document.querySelector(`meta[property="${e}"]`)?.getAttribute("content"))}getMetaContents(e){return Array.from(document.querySelectorAll(`meta[name="${e}"], meta[property="${e}"]`)).map(t=>this.cleanText(t.getAttribute("content"))).filter(t=>!!t)}toAbsoluteUrl(e){if(e)try{return new URL(e,location.href).href}catch{return e}}}const cg=/\b((?:19|20)\d{2})\b/,ug=/\b10\.\d{4,9}\/[-._;()/:A-Z0-9]+/i,dg=/\b(?:arxiv|bioRxiv|medRxiv|SSRN)\b/i,pg=[{pattern:/^Proceedings of the National Academy of Sciences$/i,canonical:"Proceedings of the National Academy of Sciences of the United States of America"}],Su=[{pattern:/\b(?:NeurIPS|NIPS|Neural Information Processing Systems)\b/i,canonical:"NeurIPS"},{pattern:/\bCVPR\b|Computer Vision and Pattern Recognition/i,canonical:"CVPR"},{pattern:/\bICCV\b|International Conference on Computer Vision/i,canonical:"ICCV"},{pattern:/\bECCV\b|European Conference on Computer Vision/i,canonical:"ECCV"},{pattern:/\bICML\b|International Conference on Machine Learning/i,canonical:"ICML"},{pattern:/\bICLR\b|International Conference on Learning Representations/i,canonical:"ICLR"},{pattern:/\bKDD\b|Knowledge Discovery and Data Mining/i,canonical:"KDD"},{pattern:/\bSIGIR\b/i,canonical:"SIGIR"},{pattern:/\bSIGMOD\b/i,canonical:"SIGMOD"},{pattern:/\bVLDB\b/i,canonical:"VLDB"},{pattern:/\bACL\b|Association for Computational Linguistics/i,canonical:"ACL"},{pattern:/\bEMNLP\b/i,canonical:"EMNLP"},{pattern:/\bAAAI\b/i,canonical:"AAAI"},{pattern:/\bIJCAI\b/i,canonical:"IJCAI"},{pattern:/\bCHI\b|Human Factors in Computing Systems/i,canonical:"CHI"},{pattern:/\bWWW\b|World Wide Web Conference/i,canonical:"WWW"},{pattern:/\bSOSP\b/i,canonical:"SOSP"},{pattern:/\bOSDI\b/i,canonical:"OSDI"},{pattern:/\bUSENIX\b/i,canonical:"USENIX"}],hg=/\b(?:conference|symposium|workshop|congress)\b/i;class fg extends j{id="semantic-scholar";name="Semantic Scholar";matches=["*://www.semanticscholar.org/*"];isSearchPage(){return location.pathname!=="/search"?!1:new URLSearchParams(location.search).has("q")}isArticlePage(){const e=location.pathname.split("/").filter(Boolean);return e[0]==="paper"&&e.length>=2}parseSearchResults(){const e=[],t=new Set,n=new Set;for(const a of this.getSearchResultHosts())if(!t.has(a)){t.add(a);try{const i=this.parseSearchResultHost(a);if(!i)continue;const o=this.articleKey(i);if(n.has(o))continue;n.add(o),e.push(i)}catch(i){console.error("[SemanticScholarAdapter] Failed to parse result:",i)}}return e}parseArticlePage(){try{if(/page not found/i.test(document.title))return null;const e=this.getDetailHostElement();if(!e)return null;const t=this.getJsonLdArticle(),n=this.getMetaContent("citation_title")??this.cleanTitle(t?.headline??t?.name??"")??this.cleanTitle(this.queryText(e,['h1[data-test-id*="title"]','h1[data-testid*="title"]',"h1",'[data-test-id*="paper-title"]','[data-testid*="paper-title"]',".paper-detail-title"]));if(!n)return console.warn("[SemanticScholarAdapter] Article page without title"),null;const a=this.getMetaContent("citation_journal_title")||this.extractJsonLdVenue(t)||this.extractVenue(e),i=this.normalizeVenue(a),o=this.unique([a,i.canonical,i.displayName,this.getMetaContent("citation_conference_title")]),s=this.cleanDoi(this.getMetaContent("citation_doi"))??this.extractDoi(e),l=this.extractYear(this.getMetaContent("citation_publication_date"))??this.extractYear(t?.datePublished)??this.extractYear(this.queryText(e,[".cl-paper-pubdates",'[data-test-id*="pubdate"]','[data-testid*="pubdate"]','[data-test-id*="publication-date"]','[data-testid*="publication-date"]',"time"]))??this.extractYear(this.extractDetailHeaderText(e)),c=this.unique([...this.getMetaContents("citation_author"),...this.extractJsonLdAuthors(t),...this.extractAuthors(e)]),u=this.cleanAbstract(this.getMetaContent("citation_abstract"))??this.cleanAbstract(t?.description)??this.extractAbstract(e);return{title:n,journalName:i.canonical||i.displayName||a||"",journalCandidates:o,authors:c,year:l,doi:s,pmid:this.extractPmid(e),url:location.href,abstractSnippet:u,articleTypes:this.inferArticleTypes(a,this.extractPublicationTypeText(e),t),issn:this.getMetaContent("citation_issn")??this.getMetaContent("citation_eissn")??void 0,hostElement:e,source:this.id}}catch(e){return console.error("[SemanticScholarAdapter] Failed to parse article page:",e),null}}getMetricBarAnchor(e){const t=this.queryFirst(e,[".cl-paper__bulleted-row",".cl-paper-pubdates",'[data-test-id="paper-meta"]','[data-testid="paper-meta"]','[data-test-id*="venue"]','[data-testid*="venue"]']);if(t)return{element:t,position:"after"};const n=this.queryFirst(e,['[data-test-id="title-link"]','[data-testid="title-link"]',".cl-paper-title","h1","h2","h3"]);return n?{element:n,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector('[data-test-id="result-page"]')??document.querySelector('[data-testid="result-page"]')??document.querySelector(".result-page")??document.querySelector("main")}getPageInfo(){const e={pageNum:1,totalPages:1,url:location.href,itemsPerPage:10},t=new URLSearchParams(location.search).get("page");if(t){const n=Number.parseInt(t,10);Number.isFinite(n)&&n>0&&(e.pageNum=n)}return e}parseSearchResultHost(e){const t=this.getTitleLink(e),n=this.cleanTitle(t?.textContent??this.queryText(e,[".cl-paper-title","h2","h3"]));if(!n)return null;const a=this.extractVenue(e),i=this.normalizeVenue(a),o=this.extractDoi(e);return{title:n,journalName:i.canonical||i.displayName||a||"",journalCandidates:this.unique([a,i.canonical,i.displayName]),authors:this.extractAuthors(e),year:this.extractYear(this.queryText(e,[".cl-paper-pubdates",'[data-test-id*="pubdate"]','[data-testid*="pubdate"]','[data-test-id*="publication-date"]','[data-testid*="publication-date"]']))??this.extractYear(e.textContent??""),doi:o,pmid:this.extractPmid(e),url:this.absoluteUrl(t?.getAttribute("href"))??void 0,abstractSnippet:this.extractAbstract(e),articleTypes:this.inferArticleTypes(a,e.textContent??""),hostElement:e,source:this.id}}getSearchResultHosts(){const e=new Set,t=[".cl-paper-row[data-paper-id]",".cl-paper-row",".paper-row","[data-paper-id]",'[data-test-id*="paper-row"]','[data-testid*="paper-row"]',"article"];for(const n of document.querySelectorAll(t.join(",")))(this.getTitleLink(n)||n.querySelector(".cl-paper-title"))&&e.add(n);if(e.size===0){const n=document.querySelectorAll('a[data-test-id="title-link"][href*="/paper/"],a[data-testid="title-link"][href*="/paper/"],a[href^="/paper/"],a[href*="semanticscholar.org/paper/"]');for(const a of n)e.add(this.closestResultHost(a))}return[...e]}getTitleLink(e){const t=this.queryFirst(e,['a[data-test-id="title-link"][href*="/paper/"]','a[data-testid="title-link"][href*="/paper/"]','a[href^="/paper/"]','a[href*="semanticscholar.org/paper/"]']);if(t instanceof HTMLAnchorElement)return t;const a=this.queryFirst(e,[".cl-paper-title","h2","h3"])?.closest('a[href*="/paper/"]');return a instanceof HTMLAnchorElement?a:null}closestResultHost(e){return e.closest(".cl-paper-row")??e.closest(".paper-row")??e.closest("[data-paper-id]")??e.closest('[data-test-id*="paper"]')??e.closest('[data-testid*="paper"]')??e.closest("article")??e.closest("li")??e.parentElement??e}getDetailHostElement(){const e=document.querySelector('[data-test-id*="paper-detail"]')??document.querySelector('[data-testid*="paper-detail"]')??document.querySelector(".paper-detail")??document.querySelector(".paper-detail-page")??document.querySelector("#paper-header")??document.querySelector(".paper-header")??document.querySelector("main")??document.querySelector("article");if(e)return e;const t=this.queryFirst(document,['h1[data-test-id*="title"]','h1[data-testid*="title"]','[data-test-id*="paper-title"]','[data-testid*="paper-title"]',".paper-detail-title","h1"]);return t?t.closest('[data-test-id*="paper-detail"]')??t.closest('[data-testid*="paper-detail"]')??t.closest('[class*="paper-detail"]')??t.closest('[class*="paper-header"]')??t.closest('[class*="paper__header"]')??t.closest("section")??t.closest("div")??null:null}extractVenue(e){const t=this.queryText(e,['[data-test-id="normalized-venue-link"] [data-test-id="venue-metadata"]','[data-testid="normalized-venue-link"] [data-testid="venue-metadata"]','[data-test-id="venue-metadata"]','[data-testid="venue-metadata"]','[data-test-id*="venue"]','[data-testid*="venue"]','a[href^="/venue?name="]','a[href*="/venue?name="]',".cl-paper-venue",'[class*="venue"]']);return this.cleanVenue(t)}normalizeVenue(e){const t=this.cleanVenue(e);if(!t)return{displayName:"",canonical:""};for(const n of pg)if(n.pattern.test(t))return{displayName:t,canonical:n.canonical};for(const n of Su)if(n.pattern.test(t))return{displayName:t,canonical:n.canonical};return{displayName:t,canonical:t}}inferArticleTypes(e,t,n){const a=e??"",i=`${a} ${t}`.replace(/\s+/g," ");if(dg.test(i))return["Preprint"];if(Su.some(s=>s.pattern.test(i))||hg.test(a))return["Conference"];const o=Array.isArray(n?.["@type"])?n?.["@type"]?.join(" "):n?.["@type"];return o&&/preprint/i.test(o)?["Preprint"]:e?["JournalArticle"]:[]}extractPublicationTypeText(e){return this.queryText(e,['[data-test-id*="publication-type"]','[data-testid*="publication-type"]','[data-test-id*="paper-type"]','[data-testid*="paper-type"]','[class*="publication-type"]','[class*="paper-type"]'])}extractDetailHeaderText(e){return[this.queryText(e,[".cl-paper-pubdates",'[data-test-id*="pubdate"]','[data-testid*="pubdate"]','[data-test-id*="publication-date"]','[data-testid*="publication-date"]',"time"]),this.extractVenue(e),this.extractPublicationTypeText(e)].filter(Boolean).join(" ")}extractAuthors(e){const t=new Set,n=['[data-test-id="author-list"] a','[data-testid="author-list"] a','[data-test-id*="author"] a[href*="/author/"]','[data-testid*="author"] a[href*="/author/"]','.cl-paper-authors a[href*="/author/"]','a[href^="/author/"]'];for(const a of e.querySelectorAll(n.join(","))){const i=this.cleanText(a.textContent);i&&(/show|authors?|more|expand|\.\.\./i.test(i)||t.add(i))}return[...t]}extractAbstract(e){return this.cleanAbstract(this.queryText(e,[".tldr-abstract-replacement",'[data-test-id*="tldr"]','[data-testid*="tldr"]','[data-test-id*="abstract"]','[data-testid*="abstract"]',".abstract"]))??void 0}extractDoi(e){const t=e.querySelector('a[href*="doi.org/"]'),n=t instanceof HTMLAnchorElement?this.cleanDoi(t.href):void 0;return n||(this.cleanDoi(e.textContent??"")??void 0)}extractPmid(e){const t=e.querySelector('a[href*="pubmed.ncbi.nlm.nih.gov/"]');if(t instanceof HTMLAnchorElement){const a=t.href.match(/pubmed\.ncbi\.nlm\.nih\.gov\/(\d+)/);if(a?.[1])return a[1]}return(e.textContent??"").match(/\bPMID[:\s]+(\d{5,12})\b/i)?.[1]}getJsonLdArticle(){for(const e of document.querySelectorAll('script[type="application/ld+json"]'))try{const t=JSON.parse(e.textContent??""),a=(Array.isArray(t)?t:[t]).find(i=>{const o=Array.isArray(i["@type"])?i["@type"].join(" "):i["@type"]??"";return/article|scholarly|creativework/i.test(o)||!!i.headline});if(a)return a}catch{}return null}extractJsonLdVenue(e){if(!e)return"";const t=e.isPartOf;if(typeof t=="string")return t;if(t?.name)return t.name;const n=e.publisher;return typeof n=="string"?n:n?.name??""}extractJsonLdAuthors(e){return e?.author?(Array.isArray(e.author)?e.author:[e.author]).map(n=>typeof n=="string"?n:n.name??"").map(n=>this.cleanText(n)).filter(n=>!!n):[]}queryFirst(e,t){for(const n of t){const a=e.querySelector(n);if(a)return a}return null}queryText(e,t){const n=this.queryFirst(e,t);return this.cleanText(n?.textContent)??""}getMetaContent(e){const t=`meta[name="${e}"], meta[property="${e}"]`,a=document.querySelector(t)?.getAttribute("content");return this.cleanText(a)??void 0}getMetaContents(e){return[...document.querySelectorAll(`meta[name="${e}"], meta[property="${e}"]`)].map(t=>this.cleanText(t.getAttribute("content"))).filter(t=>!!t)}extractYear(e){const t=e?.match(cg);return t?.[1]?Number.parseInt(t[1],10):void 0}cleanTitle(e){return this.cleanText(e)?.replace(/^\[[^\]]+\]\s*/,"").replace(/\s*\|\s*Semantic Scholar$/i,"").trim()||null}cleanVenue(e){return this.cleanText(e)?.replace(/^Published\s+in\s+/i,"").replace(/^Venue[:\s]+/i,"").replace(/^Journal[:\s]+/i,"").replace(/^Conference[:\s]+/i,"").replace(/\s*\|\s*Semantic Scholar$/i,"").trim()??""}cleanAbstract(e){return this.cleanText(e)?.replace(/^TLDR\s*:?\s*/i,"").replace(/\s*Expand\s*$/i,"").trim()||null}cleanDoi(e){if(!e)return;let t=e;try{t=decodeURIComponent(e)}catch{t=e}const n=t.match(ug);if(n?.[0])return n[0].replace(/^https?:\/\/(?:dx\.)?doi\.org\//i,"").replace(/[)\].,;:]+$/g,"")}cleanText(e){return e?.replace(/\u00a0/g," ").replace(/\s+/g," ").trim()||null}absoluteUrl(e){if(!e)return null;try{return new URL(e,location.origin).href}catch{return null}}unique(e){const t=new Set,n=[];for(const a of e){const i=this.cleanText(a);if(!i)continue;const o=i.toLowerCase();t.has(o)||(t.add(o),n.push(i))}return n}articleKey(e){return e.doi??e.url??`${e.title}|${e.journalName}|${e.year??""}`}}const wu=/\b((?:19|20)\d{2})\b/,mg=/\b10\.\d{4,9}\/[-._;()/:A-Z0-9]+/i,Tu="paperlens-wanfang-enhancement-line",Nr=/(?:期刊论文|学位论文|会议论文|专利|科技报告|成果|标准|地方志|图书|视频)/,bg=['a[href*="/Paper/Detail"]','a[href*="/paper/detail"]','a[href^="/periodical/"]','a[href^="/thesis/"]','a[href^="/conference/"]','a[href*="d.wanfangdata.com.cn/periodical/"]','a[href*="d.wanfangdata.com.cn/thesis/"]','a[href*="d.wanfangdata.com.cn/conference/"]'].join(","),Lr={WF_QK:"\u4E2D\u6587\u671F\u520A",WF_XW:"\u5B66\u4F4D\u8BBA\u6587",WF_HY:"\u4F1A\u8BAE\u8BBA\u6587",WF_ZL:"\u4E13\u5229",WF_BZ:"\u6807\u51C6",WF_TS:"\u56FE\u4E66"};class gg extends j{id="wanfang";name="\u4E07\u65B9\u6570\u636E";matches=["*://www.wanfangdata.com.cn/*","*://med.wanfangdata.com.cn/*","*://s.wanfangdata.com.cn/*","*://d.wanfangdata.com.cn/*"];isSearchPage(){if(location.hostname==="s.wanfangdata.com.cn")return/^\/(?:paper|periodical|thesis|conference|patent|nstr|cstad|standard|law|localchronicleitem|localchronicle|video|book)\b/i.test(location.pathname);const e=location.pathname.toLowerCase();return e.includes("/paper/search")||e==="/search"||e.includes("/search")}isArticlePage(){const e=location.pathname.toLowerCase();return e.includes("/paper/detail")||location.hostname==="d.wanfangdata.com.cn"&&/^\/(?:periodical|thesis|conference)\//.test(e)}parseSearchResults(){const e=[],t=new Set,n=this.getResultsContainer()??document.body;for(const a of n.querySelectorAll(bg)){const i=this.findResultHost(a);if(!(!i||t.has(i))){t.add(i);try{const o=this.parseResultHost(i,a);o&&e.push(o)}catch(o){console.error("[WanfangAdapter] Failed to parse result:",o)}}}if(location.hostname==="s.wanfangdata.com.cn"){const a=this.parseCurrentSearchResults(n);if(a.length>0)return this.uniqueArticlesByIdentity([...a,...e])}return e}parseArticlePage(){try{const e=this.getDetailHostElement();if(!e)return null;const t=this.cleanTitle(e.querySelector(".headline h2")?.textContent??e.querySelector("h2")?.textContent??"");if(!t)return null;const n=this.getDbid(location.href),a=Lr[n??""]??this.extractDetailType(),o=this.isJournalType(a)?this.extractDetailJournal(e):"",s=this.extractSourceId(location.href,e);return{title:t,journalName:o,journalCandidates:o?[o]:void 0,authors:this.extractDetailAuthors(e),year:this.extractDetailYear(e,a),doi:this.extractDetailDoi(e),sourceId:s,url:this.toCanonicalArticleUrl(location.href)??location.href,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.extractDetailAbstract(e),hostElement:e,articleTypes:a?[a]:void 0,source:this.id}}catch(e){return console.error("[WanfangAdapter] Failed to parse article page:",e),null}}getMetricBarAnchor(e){const t=e.querySelector(".item-title")??e.querySelector(".reference")??e.querySelector(".content")??this.findCurrentSearchTitleBlock(e)??e.querySelector(".headline")??e.querySelector("h2")?.parentElement;return t?{element:this.getOrCreateEnhancementLine(t),position:"append"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector("#resultsList")??document.querySelector("#paper-content-wrap")??document.querySelector(".result-list-container")??document.querySelector(".mod-results-list")??document.querySelector(".result-list")??document.querySelector(".table-list")??document.querySelector(".detail-list")??document.querySelector("main")??document.querySelector("[data-paperlens-results]")}getPageInfo(){const e=new URLSearchParams(location.search),t=Number.parseInt(e.get("p")??e.get("page")??"1",10),n=document.body.textContent?.match(/共\s*(\d+)\s*页/)?.[1],a=n?Number.parseInt(n,10):1;return{pageNum:Number.isFinite(t)&&t>0?t:1,totalPages:Number.isFinite(a)&&a>0?a:1,url:location.href,itemsPerPage:10}}parseResultHost(e,t){const n=this.cleanTitle(t.textContent??"");if(!n)return null;const a=this.getMetaParagraph(e),i=this.cleanText(a?.textContent??""),o=this.extractBracketType(i)||this.typeFromUrl(t.getAttribute("href")),l=this.isJournalType(o)?this.extractJournalFromMeta(a):"",c=this.extractSourceId(t.getAttribute("href"),e);return{title:n,journalName:l,journalCandidates:l?[l]:void 0,authors:this.extractAuthorsFromMeta(a,o,t),year:this.extractYear(i),doi:this.extractSearchDoi(e),sourceId:c,url:this.toAbsoluteUrl(t.getAttribute("href")),nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.extractSearchAbstract(e),hostElement:e,articleTypes:o?[o]:void 0,source:this.id}}parseCurrentSearchResults(e){const t=this.findCurrentSearchResultHosts(e),n=[],a=new Set;for(const i of t)try{const o=this.parseCurrentSearchHost(i);if(!o)continue;const s=[o.sourceId,o.url,o.title,o.year].filter(Boolean).join("|");if(s&&a.has(s))continue;s&&a.add(s),n.push(o)}catch(o){console.error("[WanfangAdapter] Failed to parse current search host:",o)}return n}findCurrentSearchResultHosts(e){const t=Array.from(e.querySelectorAll(".new-list .list-item, .list-item .content")).map(a=>a.matches(".list-item")?a:a.closest(".list-item")).filter(a=>!!a).map(a=>this.findCurrentSearchMetadataHost(a)).filter(a=>this.isCurrentSearchResultHost(a));if(t.length>0)return t.filter((a,i,o)=>o.findIndex(s=>s===a)===i);const n=Array.from(e.querySelectorAll("div, article, li, section")).map(a=>this.findCurrentSearchMetadataHost(a)).filter(a=>this.isCurrentSearchResultHost(a));return n.filter(a=>!n.some(i=>i!==a&&a.contains(i)))}isCurrentSearchResultHost(e){const t=this.cleanText(e.textContent??"");if(!t)return!1;const n=!!e.querySelector(".reference"),a=!!e.querySelector(".essay-type")||Nr.test(t)||/\[\s*(?:期刊论文|学位论文|会议论文|专利|科技报告|成果|标准)\s*\]/.test(t),i=!!e.querySelector(".abstract")||/摘要[:：]/.test(t),o=!!e.querySelector(".wf-list-button, .online-read, .list-button-quote")||/(?:在线阅读|下载|引用|收藏)/.test(t),s=this.findCurrentSearchTitleLink(e),l=!!this.extractCurrentSearchTitleFromHost(e),c=/(?:被引|下载)[:：]\s*\d+/.test(t);return!(!s&&!n&&!l||!a||!i&&!o&&!c)}parseCurrentSearchHost(e){const t=this.cleanText(e.textContent??"");if(!t)return null;const n=this.findCurrentSearchMetadataHost(e),a=this.findCurrentSearchTitleLink(e),i=this.cleanTitle(e.querySelector(".reference a")?.textContent??a?.textContent??this.extractCurrentSearchTitleFromHost(e)??this.extractCurrentSearchTitle(t)??"");if(!i)return null;const o=this.cleanText(e.querySelector(".essay-type")?.textContent??t.match(Nr)?.[0]??t.match(/\[\s*([^\]]+)\s*\]/)?.[1]??""),l=this.isJournalType(o)?this.cleanJournalName(t.match(/《([^》]+)》/)?.[1]??""):"",c=Array.from(e.querySelectorAll(".reference a[href], .content a[href], .wf-search-card__meta a[href], .meta-row a[href]")).map(h=>this.cleanText(h.textContent??"")).filter(h=>h&&h!==i&&!/^(?:在线阅读|下载|引用|收藏|登录|注册)$/.test(h)&&!/《[^》]+》/.test(h)).slice(0,8),u=c.length>0?c:this.extractCurrentSearchAuthors(t),d=a?.getAttribute("href")??n.querySelector('a[href*="/periodical/"], a[href*="/thesis/"], a[href*="/conference/"], a[href*="/Paper/Detail"], a[href*="d.wanfangdata.com.cn/"]')?.getAttribute("href")??this.modernDetailUrlFromItemMetadata(n),p=this.cleanText(e.querySelector(".abstract")?.textContent?.replace(/^摘要[:：]?\s*/,"")??t.match(/摘要[:：]\s*(.+?)(?=\s*(?:在线阅读|下载|引用|收藏|评审材料|被引[:：]|下载[:：]|$))/)?.[1]??"")||void 0;return{title:i,journalName:l,journalCandidates:l?[l]:void 0,authors:u?.length?u:void 0,year:this.extractYear(t),sourceId:this.extractSourceId(d,n),url:this.toCanonicalArticleUrl(d)??this.toAbsoluteUrl(d),nativeFullTextUrl:this.extractNativeFullTextUrl(n),abstractSnippet:p,hostElement:e,articleTypes:o?[o]:void 0,source:this.id}}findResultHost(e){return e.closest(".item-content")??e.closest("tr")??e.closest(".result-list-item")??e.closest(".paper-list-item")??e.closest(".detail-list")??e.closest(".item")??e.closest("li")??e.closest("article")??e.closest("[data-paperlens-result]")}findCurrentSearchTitleLink(e){const t=e.querySelector(".reference a[href]")??e.querySelector("h1 a, h2 a, h3 a")??e.querySelector('a[href*="/periodical/"], a[href*="/thesis/"], a[href*="/conference/"], a[href*="/Paper/Detail"], a[href*="d.wanfangdata.com.cn/"]');if(!t)return null;const n=this.cleanTitle(t.textContent??"");return!n||/^(?:在线阅读|下载|引用|收藏|登录|注册)$/.test(n)?null:t}findCurrentSearchTitleBlock(e){const t=this.findCurrentSearchTitleLink(e)?.closest("h1, h2, h3, .title, .record-title");return t||(Array.from(e.querySelectorAll("h1, h2, h3, div, p, span")).filter(a=>{const i=this.cleanText(a.textContent??"");return!i||i.length>180||/(?:在线阅读|下载|引用|收藏|摘要[:：]|被引[:：]|下载[:：])/.test(i)?!1:/^\[?\d+\]?[.．、]?\s*\S/.test(i)}).sort((a,i)=>this.cleanText(a.textContent??"").length-this.cleanText(i.textContent??"").length)[0]??null)}findCurrentSearchMetadataHost(e){let t=e;for(;t&&t!==document.body;){if(t.matches(".item-checkbox[data-itemid], [data-content], [data-id]")||t.querySelector(".item-checkbox[data-itemid], [data-content], [data-id]"))return t;t=t.parentElement}return e}extractCurrentSearchTitle(e){const t=e.match(new RegExp(String.raw`^\[?\d+\]?[.．、]?\s*(.+?)(?=\s*\[\s*${Nr.source}\s*\]|\s+${Nr.source}\b)`));return this.cleanTitle(t?.[1]??"")||void 0}extractCurrentSearchTitleFromHost(e){const t=this.findCurrentSearchTitleBlock(e);if(t){const n=t.cloneNode(!0);n.querySelectorAll('[class^="paperlens-"], [class*=" paperlens-"]').forEach(o=>o.remove());const a=this.cleanText(n.textContent??""),i=this.cleanTitle(a.replace(/^\[?\d+\]?[.．、]?\s*/,""));if(i)return i}return this.extractCurrentSearchTitle(this.cleanText(e.textContent??""))}extractCurrentSearchAuthors(e){const t=e.match(new RegExp(String.raw`\[\s*${Nr.source}\s*\]\s*(.+?)\s*-\s*《`)),n=this.cleanText(t?.[1]??"");if(!n)return;const a=n.split(/[\s,，;；/]+/).map(i=>i.trim()).filter(i=>i&&!/[0-9]/.test(i)&&!/^(?:北大核心|CSTPCD|CSCD|CSSCI|SCI|EI|在线阅读|下载|引用|收藏|评审材料)$/.test(i)).slice(0,8);return a.length>0?a:void 0}getMetaParagraph(e){for(const t of Array.from(e.querySelectorAll("p"))){const n=t.textContent??"";if(!/【摘要】|^摘要/.test(n)&&this.extractBracketType(n))return t}if(e.matches("tr, .detail-list"))return e;for(const t of Array.from(e.querySelectorAll([".item-intro p",".item-intro",".paper-info",".detail-info",".result-info",".item-meta",".meta",".source",".periodical","td:not(.paperTitleTd)","p"].join(",")))){if(t.closest(".item-title, .paperTitleTd"))continue;const n=t.textContent??"";if(!/【摘要】|^摘要/.test(n)&&(t.querySelector("a")||wu.test(n)||/《[^》]+》/.test(n)))return t}return null}extractBracketType(e){const t=e.match(/【([^】]+)】/),n=this.cleanText(t?.[1]??"");return this.isKnownResourceType(n)?n:""}isKnownResourceType(e){return/期刊|学位|会议|专利|标准|图书|报纸|成果/i.test(e)}typeFromUrl(e){const t=this.getDbid(e??"");if(t&&Lr[t])return Lr[t];try{const n=new URL(e??"",location.href).pathname.toLowerCase();if(n.includes("/periodical/"))return"\u4E2D\u6587\u671F\u520A";if(n.includes("/thesis/"))return"\u5B66\u4F4D\u8BBA\u6587";if(n.includes("/conference/"))return"\u4F1A\u8BAE\u8BBA\u6587"}catch{}return""}isJournalType(e){return!!(e&&/期刊/i.test(e))}extractJournalFromMeta(e){if(!e)return"";const t=e.querySelector('a[href*="/Periodical/Jump"]'),n=this.cleanJournalName(t?.textContent??"");if(n)return n;const a=this.cleanJournalName(e.textContent?.match(/《([^》]+)》/)?.[1]??"");if(a)return a;const i=Array.from(e.querySelectorAll('a[href*="d.wanfangdata.com.cn/periodical/"], a[href*="/periodical/"]')).find(o=>!o.closest(".item-title, .paperTitleTd"));return this.cleanJournalName(i?.textContent??"")}extractAuthorsFromMeta(e,t,n){if(!e)return;const a=Array.from(e.querySelectorAll("a")),i=[];if(this.isJournalType(t))for(const o of a){const s=o.getAttribute("href")??"";if(o===n||this.isDetailLink(o))continue;if(s.includes("/Periodical/Jump"))break;const l=this.cleanText(o.textContent??"");l&&i.push(l)}else if(/学位/.test(t)){const o=this.cleanText(a.find(s=>this.isAuthorSearchLink(s))?.textContent??"");o&&i.push(this.cleanText(o))}else{const o=this.cleanText(a.find(s=>this.isAuthorSearchLink(s))?.textContent??"");o&&i.push(o)}return i.length>0?i:void 0}isAuthorSearchLink(e){const t=decodeURIComponent(e.getAttribute("href")??"");return/(?:^|[?&])q=.*作者[:=：]/.test(t)||/\/Author\//i.test(t)}isDetailLink(e){const t=e.getAttribute("href")??"";return/\/Paper\/Detail|\/paper\/detail|d\.wanfangdata\.com\.cn\/(?:periodical|thesis|conference)\//i.test(t)}extractSearchAbstract(e){for(const t of Array.from(e.querySelectorAll("p")))if(/【摘要】/.test(t.textContent??""))return this.cleanText(t.textContent??"").replace(/^【摘要】\s*/,"")||void 0}getDetailHostElement(){return document.querySelector(".newContext .content")??document.querySelector(".content")??document.querySelector(".newContext")??null}extractDetailType(){const e=this.getDbid(location.href);if(e&&Lr[e])return Lr[e];const t=location.pathname.toLowerCase();if(location.hostname==="d.wanfangdata.com.cn"){if(t.includes("/periodical/"))return"\u4E2D\u6587\u671F\u520A";if(t.includes("/thesis/"))return"\u5B66\u4F4D\u8BBA\u6587";if(t.includes("/conference/"))return"\u4F1A\u8BAE\u8BBA\u6587"}const n=this.cleanText(document.querySelector(".breadcrumbs")?.textContent??"");return/学位/.test(n)?"\u5B66\u4F4D\u8BBA\u6587":/会议/.test(n)?"\u4F1A\u8BAE\u8BBA\u6587":""}extractDetailJournal(e){const t=[...Array.from(document.querySelectorAll('.breadcrumbs a[href*="/Periodical/Jump"]')),...Array.from(e.querySelectorAll('a[href*="/Periodical/Jump"]')),...Array.from(document.querySelectorAll('.side a[href*="/Periodical/Jump"], .aside a[href*="/Periodical/Jump"]'))];for(const n of t){const a=this.cleanJournalName(n.textContent??"");if(a&&!/首页/.test(a))return a}return""}extractDetailAuthors(e){const t=e.querySelector(".details");if(!t)return;const n=[],a=this.findDetailRowByLabel(t,/^作者$/),i=a?.querySelector(".table-td")??a;if(i)for(const o of Array.from(i?.querySelectorAll("a")??[])){const s=this.cleanText(o.textContent??"");s&&n.push(s)}return n.length>0?n:void 0}extractDetailYear(e,t){if(this.isJournalType(t)){const a=document.querySelector('a[href*="/Periodical/Jump"][href*="year="]'),i=this.extractYearFromUrlParam(a?.getAttribute("href"),"year")??this.extractYear(a?.textContent??"");if(i)return i;const s=this.cleanText(document.querySelector(".sourceTitle")?.textContent??document.querySelector(".side, .aside")?.textContent??"").match(/((?:19|20)\d{2})年\s*\d+\s*卷/);return s?.[1]?Number.parseInt(s[1],10):void 0}const n=e.querySelector(".details");if(n)for(const a of Array.from(n.querySelectorAll(".table-tr"))){const i=this.cleanText(a.querySelector(".table-th")?.textContent??"").replace(/[：:]$/,"");if(/发布时间|首次上网|DOI|作者|导师/.test(i))continue;const o=this.extractYear(a.textContent??"");if(o)return o}}extractYearFromUrlParam(e,t){if(e)try{const n=new URL(e,location.href).searchParams.get(t);return n?this.extractYear(n):void 0}catch{return}}findDetailRowByLabel(e,t){for(const n of Array.from(e.querySelectorAll(".table-tr"))){const a=this.cleanText(n.querySelector(".table-th")?.textContent??"").replace(/[：:]$/,"");if(t.test(a))return n}return null}extractDetailAbstract(e){const t=e.querySelector(".abstracts p")?.textContent??e.querySelector(".abstracts")?.textContent??"";return this.cleanText(t.replace(/^摘要/,"").replace(/\s*更多\s*$/,""))||void 0}extractDetailDoi(e){const t=e.querySelector(".details"),n=t?this.findDetailRowByLabel(t,/^DOI$/i):null;return n?this.extractDoi(n):void 0}extractSearchDoi(e){for(const t of Array.from(e.querySelectorAll('a[href*="doi.org/"]'))){if(this.isRelatedContext(t))continue;const n=this.extractDoi(t);if(n)return n}for(const t of Array.from(e.querySelectorAll("p, .item-meta, .meta, .source, .doi"))){if(this.isRelatedContext(t))continue;const n=this.cleanText(this.textWithoutRelatedContexts(t));if(!/(?:^|\s)DOI\s*[:：]?/i.test(n))continue;const a=this.extractDoiFromText(n);if(a)return a}}extractDoi(e){const t=e.querySelector('a[href*="doi.org/"]'),n=[t?.getAttribute("href"),t?.textContent,e.textContent].filter(Boolean).join(" ");return this.extractDoiFromText(n)}extractDoiFromText(e){return e.match(mg)?.[0]?.replace(/[)\].,;:]+$/g,"")}isRelatedContext(e){return!!e.closest(["#similarLiterature",".similar",".related",".relatePaper",".relateScholar",".recommend",".reference",".references",".citation"].join(","))}textWithoutRelatedContexts(e){const t=e.cloneNode(!0);for(const n of Array.from(t.querySelectorAll(["#similarLiterature",".similar",".related",".relatePaper",".relateScholar",".recommend",".reference",".references",".citation"].join(","))))n.remove();return t.textContent??""}extractNativeFullTextUrl(e){const t=e.querySelector('a[href*="MedFulltext"], a.btn-download[href], a.lnk-download[href]')??Array.from(e.querySelectorAll("a[href]")).find(n=>/下载/.test(this.cleanText(n.textContent??"")));return this.toSafeHttpUrl(t?.getAttribute("href"))}extractYear(e){const t=e.match(wu);return t?.[1]?Number.parseInt(t[1],10):void 0}getDbid(e){try{const n=new URL(e,location.href).searchParams.get("dbid");if(n)return n}catch{}return/DegreePaper_/i.test(e)?"WF_XW":/ConferencePaper_/i.test(e)?"WF_HY":/PeriodicalPaper_/i.test(e)?"WF_QK":null}extractSourceId(e,t){const n=this.extractRawSourceId(e)??this.extractRawSourceId(t?.querySelector("[data-content]")?.getAttribute("data-content"))??this.extractRawSourceId(t?.querySelector("[data-id]")?.getAttribute("data-id"))??this.sourceIdFromItemMetadata(t);return n?`wanfang:${n}`:void 0}extractRawSourceId(e){if(!e)return;try{const a=new URL(e,location.href),i=a.searchParams.get("id");if(i)return i;const o=a.pathname.match(/\/(periodical|thesis|conference)\/([A-Za-z0-9_-]+)/i);if(o?.[1]&&o[2])return`${{periodical:"PeriodicalPaper",thesis:"DegreePaper",conference:"ConferencePaper"}[o[1].toLowerCase()]}_${o[2]}`}catch{}const t=e.match(/\b(?:PeriodicalPaper|DegreePaper|ConferencePaper|Patent|Standard|Book)_[A-Za-z0-9_-]+\b/i)?.[0];if(t)return t;const n=e.match(/\/(periodical|thesis|conference)\/([A-Za-z0-9_-]+)/i);if(n?.[1]&&n[2])return`${{periodical:"PeriodicalPaper",thesis:"DegreePaper",conference:"ConferencePaper"}[n[1].toLowerCase()]}_${n[2]}`}sourceIdFromItemMetadata(e){const t=e?.querySelector(".item-checkbox"),n=t?.getAttribute("data-itemid"),a=t?.getAttribute("data-dbid")??"";if(!n)return;const o={WF_QK:"PeriodicalPaper",WF_XW:"DegreePaper",WF_HY:"ConferencePaper"}[a];return o?`${o}_${n}`:n}modernDetailUrlFromItemMetadata(e){const t=e?.querySelector(".item-checkbox"),n=t?.getAttribute("data-itemid"),a=t?.getAttribute("data-dbid")??"";if(!n)return;const o={WF_QK:"periodical",WF_XW:"thesis",WF_HY:"conference"}[a];return o?`https://d.wanfangdata.com.cn/${o}/${n}`:void 0}toCanonicalArticleUrl(e){const t=this.toAbsoluteUrl(e);if(t)try{const i=new URL(t,location.href).pathname.match(/^\/(periodical|thesis|conference)\/([A-Za-z0-9_-]+)$/i);if(i?.[1]&&i[2])return`https://d.wanfangdata.com.cn/${i[1].toLowerCase()}/${i[2]}`}catch{}const n=this.extractRawSourceId(e);if(!n)return t;try{const a=new URL(e??"",location.href);return a.hostname==="d.wanfangdata.com.cn"?a.href:new URL(`/Paper/Detail/${n}`,a.origin).href}catch{return t}}uniqueArticlesByIdentity(e){const t=new Set;return e.filter(n=>{const a=[n.sourceId,n.url,n.title,n.year].filter(Boolean).join("|");return a?t.has(a)?!1:(t.add(a),!0):!0})}getOrCreateEnhancementLine(e){const t=e.querySelector(`.${Tu}`);if(t)return t;const n=e.ownerDocument.createElement("div");return n.className=Tu,n.style.cssText=["display:flex","flex-wrap:wrap","align-items:center","gap:6px","margin-top:6px","line-height:1.4"].join(";"),e.appendChild(n),n}cleanTitle(e){return this.cleanText(e).replace(/^\d+\.\s*/,"").replace(/^目录[:：]?\s*/i,"").replace(/[《》]/g,"")}cleanJournalName(e){return this.cleanText(e).replace(/[《》]/g,"")}cleanText(e){return e.replace(/\u00a0/g," ").replace(/\s+/g," ").trim()}toAbsoluteUrl(e){if(e)try{return new URL(e,location.href).href}catch{return e}}toSafeHttpUrl(e){if(e)try{const t=new URL(e,location.href);return t.protocol==="http:"||t.protocol==="https:"?t.href:void 0}catch{return}}}const yg=/\b((?:19|20)\d{2})\b/,Ka=/\b10\.\d{4,9}\/[-._;()/:<>+\[\]A-Z0-9]+/i,xg=/(?:https?:\/\/(?:dx\.)?doi\.org\/)?10\.\d{4,9}\/[-._;()/:<>+\[\]A-Z0-9]+/gi,_o="paperlens-baidu-scholar-enhancement-line",qn=[".sc_content",".result",".result-item","[data-paperlens-baidu-result]"].join(","),Rr=[".sc_title a","h3 a",".result-title a",'a[data-click*="title"]'].join(","),Ag=/(?:资源类型|类型|文献类型)\s*[:：]\s*([^；;，,\s]+)/,Pr=/学位|硕士|博士|专利|图书|书籍|会议|标准|报纸|网页|资讯|百科|课程|视频|conference|proceedings?|preprint|thesis|dissertation|patent|book|chapter|newspaper|web/i,ko=/[-–—]\s*《?([^《》,，;；\-–—]+?)》?\s*(?:[,，]\s*|\s+)((?:19|20)\d{2})(?:年)?(?:\b|(?=\s|[-–—,，.。;；]|来源|DOI|被引|引用|$))(?:\s*(?:(?:[-–—]|[,，.。;；]|来源\s*[:：]?)\s*)?([^；;\n]+))?/,No=/中国知网|知网|百度文库|百度百科|万方数据|维普|豆瓣|百科|文库|Wanfang|CNKI|CQVIP|xueshu|example\.|www\.|https?:\/\/|\.(?:com|cn|org|net|edu)\b/i,Cg=/百度文库|百度百科|文库|百科|微信公众号|公众号|微信|搜狐网?|丁香园|医学界|医脉通|medlive|豆瓣|知乎|百度经验|百家号|博客|新闻|资讯|转载|课程|视频|学报网|期刊网|杂志网|example\.|wikipedia|blog|news|portal|wenku/i,vg=/(?:万方|wanfang|中国知网|知网|cnki|维普|cqvip|pubmed|ncbi|doi\.org|crossref|springer|wiley|sciencedirect|tandfonline|oup|cambridge|sagepub|nature\.com|science\.org|ieee|acm|jstor|biorxiv|medrxiv|arxiv|scholar|xueshu)/i,Sg=["CA: A Cancer Journal for Clinicians","CA-A Cancer Journal for Clinicians","New England Journal of Medicine","The Lancet","The Lancet Oncology","Journal of Clinical Oncology","JAMA","Nature","Science"];class wg extends j{id="baidu-scholar";name="\u767E\u5EA6\u5B66\u672F";matches=["*://xueshu.baidu.com/*"];isSearchPage(){return new URLSearchParams(location.search).has("wd")&&(location.pathname==="/s"||location.pathname==="/ndscholar/browse/search")}isArticlePage(){return!1}parseSearchResults(){const e=[];if(this.isSecurityVerificationPage())return this.clearStaleEnhancementsInContainer(),e;const t=this.getResultsContainer()??document.body;if(!t)return e;for(const n of this.getResultHosts(t))try{const a=this.parseResultHost(n);a?e.push(a):this.clearStaleEnhancements(n)}catch(a){console.error("[BaiduScholarAdapter] Failed to parse result:",a),this.clearStaleEnhancements(n)}return e}parseArticlePage(){return null}getMetricBarAnchor(e){const t=e.querySelector(".sc_title")??e.querySelector("h3")??e.querySelector(".result-title");if(t)return{element:this.getOrCreateEnhancementLine(t),position:"append"};const n=e.querySelector(".sc_info")??e.querySelector(".result-meta");return n?{element:n,position:"after"}:{element:e,position:"append"}}getResultsContainer(){return document.querySelector("#bdxs_result_lists")??document.querySelector("#bdxs_result_list")??document.querySelector("main")??document.querySelector("#container")??document.querySelector("[data-paperlens-baidu-results]")}getPageInfo(){const e=new URLSearchParams(location.search),t=Number.parseInt(e.get("page")??"",10),n=Number.parseInt(e.get("pn")??"0",10);return{pageNum:Number.isFinite(t)&&t>0?t:Math.floor(Math.max(0,Number.isFinite(n)?n:0)/10)+1,totalPages:1,url:location.href,itemsPerPage:10}}parseResultHost(e){const t=e.querySelector(Rr),n=this.cleanTitle(t?.textContent??"");if(!n)return null;const a=this.cleanText(this.collectMetaText(e));if(this.isVerificationResult(n,a))return null;const i=this.extractExplicitType(e,a),o=this.extractArticleTypes(i),s=this.toAbsoluteUrl(t?.getAttribute("href")),l=this.extractAuthors(e,a),c=this.extractDoi(s,a),u=this.extractJournalName(e,a,o,!!c),d=this.extractSourceId(t?.getAttribute("href"),n,this.sourceIdDisambiguator(a,o,u,l,c));return{title:n,journalName:u,journalCandidates:u?[u]:void 0,authors:l,year:this.extractYearFromMeta(a),doi:c,sourceId:d,url:s,abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:o,source:this.id}}collectMetaText(e){const t=Array.from(e.querySelectorAll([".sc_info",".sc_author",".sc_source",".sc_time",".sc_journal",".result-meta",".c_author",".c_source","[data-paperlens-meta]"].join(",")));return t.length===0?this.cleanText(this.textWithoutTitle(e)):t.map(n=>n.textContent??"").filter(Boolean).join(" ")}extractExplicitType(e,t){return this.cleanText(e.querySelector("[data-paperlens-type], .sc_type, .c_type, .result-type")?.textContent??"")||this.cleanText(t.match(Ag)?.[1]??"")}extractArticleTypes(e){if(/学位|硕士|博士/.test(e))return["\u5B66\u4F4D\u8BBA\u6587"];if(/专利|patent/i.test(e))return["\u4E13\u5229"];if(/会议|conference|proceeding/i.test(e))return["\u4F1A\u8BAE\u8BBA\u6587"];if(/图书|书籍|book|chapter/i.test(e))return["\u56FE\u4E66"];if(/网页|百科|资讯|web/i.test(e))return["\u7F51\u9875"];if(/preprint/i.test(e))return["\u9884\u5370\u672C"];if(/期刊|journal article/i.test(e))return["\u671F\u520A"]}extractJournalName(e,t,n,a){const i=n?.join(" ")??"";if(Pr.test(i))return"";const o=a||/期刊|journal/i.test(i)||/(?:类型|文献类型)\s*[:：]\s*(?:期刊|Journal Article)/i.test(t),s=this.cleanText((e.querySelector("[data-paperlens-journal], .sc_source, .c_source")?.textContent??"").replace(/^(?:来源|Source)\s*[:：]\s*/i,"")),l=this.extractCitationSource(s);if(l)return l;const c=this.extractLabeledJournal(s,o);if(c)return c;const u=this.cleanJournalName(this.stripCurrentArticleSourceTail(s));if(u&&!No.test(u)&&!this.hasCitationDoiContext(u)&&!this.isNonScholarlySourceText(s)&&(this.hasCjk(u)||o))return u;const d=this.extractCitationSource(t);if(d)return d;const p=this.extractLabeledJournal(t,o);if(p)return p;const h=this.cleanJournalName(t.match(/《([^》]+)》/)?.[1]??"");if(h&&!ko.test(t)&&!Pr.test(i)&&!this.hasUntrustedQuotedTail(t))return h;const f=o?this.extractKnownEnglishJournal(t):"";return f||""}extractLabeledJournal(e,t){if(this.isNonScholarlySourceText(e))return"";const n=[/(?:期刊|刊名|发表于)\s*[:：]\s*《?([^《》；;,，]+?)》?(?=\s*(?:(?:19|20)\d{2}年?\b|(?:DOI|被引|引用|年份|时间|Year|类型|文献类型)\s*[:：]?|[；;,，]|$))/i,/(?:来源期刊|期刊来源)\s*[:：]\s*《?([^《》；;,，]+?)》?(?=\s*(?:(?:19|20)\d{2}年?\b|(?:DOI|被引|引用|年份|时间|Year|类型|文献类型)\s*[:：]?|[；;,，]|$))/i];for(const a of n){const i=this.cleanJournalName(e.match(a)?.[1]??"");if(i&&!Pr.test(i)&&i.length>1)return i}if(t){const a=this.cleanJournalName(e.match(/(?:Source|来源)\s*[:：]\s*([^；;,，]+?)(?:\s+(?:类型|文献类型|时间|年份|被引|DOI)\s*[:：]|$)/i)?.[1]??""),i=this.stripCurrentArticleSourceTail(a);if(i&&!Pr.test(i)&&!No.test(i)&&!this.hasCitationDoiContext(i)&&i.length>1)return i}return""}extractKnownEnglishJournal(e){const t=this.cleanText(e).toLowerCase();if(!t)return"";for(const n of Sg)if(t.includes(n.toLowerCase()))return n;return""}extractAuthors(e,t){const n=this.cleanText(e.querySelector("[data-paperlens-authors], .sc_author, .c_author")?.textContent??""),a=this.cleanText(t.match(/(?:作者|Author)\s*[:：]\s*([\s\S]+?)(?:\s+(?:来源|Source|类型|期刊|刊名|发表于|授予单位|时间|年份|被引|DOI)\s*[:：]|$)/i)?.[1]??""),i=n||a||this.extractBareCitationAuthors(t),o=this.cleanText(i).replace(/^(?:作者|Author)\s*[:：]\s*/i,"").split(/[;,，；]/).map(s=>this.cleanText(s)).filter(s=>s&&!/^(?:作者|等)$/.test(s)&&!/摘要|来源|类型|网页|资讯|AI\b/i.test(s)).slice(0,12);return o.length>0?o:void 0}extractSourceId(e,t,n){const a=e??"",i=this.normalizeTrackingUrl(a);try{const o=new URL(i,location.href),l=this.isBaiduHost(o.hostname)&&/\/(?:usercenter\/paper\/show|paper|detail)/.test(o.pathname)?o.searchParams.get("paperid")??o.searchParams.get("id")??o.searchParams.get("pid"):null;if(l)return`baidu-scholar:${l}`}catch{}return`baidu-scholar:${this.stableHash(`${i}|${t}|${n}`)}`}extractDoi(e,t){return this.extractDoiFromUrlPath(e)??this.extractLabeledDoi(t)}extractYearFromMeta(e){const t=this.stripDoiText(this.stripCurrentArticleCountFields(this.normalizeCjkSpacing(e))),n=t.match(/(?:年份|时间|Year)\s*[:：]?\s*((?:19|20)\d{2})/i);if(n?.[1])return Number.parseInt(n[1],10);const a=t.match(/[,，]\s*((?:19|20)\d{2})\b/);return a?.[1]?Number.parseInt(a[1],10):this.extractYear(t)}extractAbstract(e){const t=e.querySelector(".sc_abstract")?.textContent??e.querySelector(".sc_content_summary")?.textContent??e.querySelector(".c_abstract")?.textContent??this.extractFallbackAbstract(e)??"";return this.cleanText(t.replace(/^摘要\s*[:：]/,""))||void 0}extractYear(e){const t=e.match(yg);return t?.[1]?Number.parseInt(t[1],10):void 0}sourceIdDisambiguator(e,t,n,a,i){return this.cleanText([n,i,a?.join("|"),t?.join("|"),this.extractYearFromMeta(e),this.extractExplicitType(document.createElement("div"),e),this.cleanText(e.match(ko)?.[1]??""),this.extractDisambiguatingSource(e),this.extractGrantingUnit(e)].filter(Boolean).join("|"))}extractDisambiguatingSource(e){const t=this.cleanText(e.match(/(?:来源|Source)\s*[:：]\s*([^；;,，]+?)(?=\s*(?:(?:类型|文献类型|授予单位|时间|年份|被引|引用|参考文献|DOI)\s*[:：]|$))/i)?.[1]??"");return this.cleanText(this.stripCurrentArticleSourceTail(t))}extractGrantingUnit(e){return this.cleanText(e.match(/授予单位\s*[:：]\s*([^；;,，]+?)(?=\s*(?:(?:类型|文献类型|时间|年份|被引|引用|参考文献|DOI)\s*[:：]|$))/i)?.[1]??"")}getOrCreateEnhancementLine(e){const t=e.querySelector(`.${_o}`);if(t)return t;const n=e.ownerDocument.createElement("div");return n.className=_o,n.style.cssText=["display:flex","flex-wrap:wrap","align-items:center","gap:6px","margin-top:6px","line-height:1.4"].join(";"),e.appendChild(n),n}cleanTitle(e){return this.cleanText(e).replace(/^\s*(?:\[[^\]]+\]\s*)+/,"").replace(/[《》]/g,"")}cleanJournalName(e){const t=this.cleanText(e).replace(/[《》]/g,"");return/^(?:AI|IF|CCF|JCR|CAS)$/i.test(t)?"":t}extractCitationSource(e){const t=e.match(ko),n=this.cleanJournalName(t?.[1]??""),a=this.cleanText(t?.[3]??"");return n&&this.hasCjk(n)&&!Pr.test(n)&&!this.isNonScholarlySourceText(e)&&this.isTrustedCitationTail(a)&&!No.test(n)?n:""}extractBareCitationAuthors(e){const t=this.cleanText(e.match(/^(.+?)\s*[-–—]\s*《?[^《》,，;；\-–—]+?》?\s*(?:[,，]\s*|\s+)(?:19|20)\d{2}(?:年)?(?:\b|(?=\s|[-–—,，.。;；]|来源|DOI|被引|引用|$))/)?.[1]??"");return!t||/摘要|来源|类型|网页|资讯|AI\b|https?:\/\/|www\.|\.(?:com|cn|org|net)\b/i.test(t)?"":t}extractDoiFromUrlPath(e){if(e)try{const t=new URL(e,location.href);if(this.isBaiduHost(t.hostname))return;const n=this.safeDecode(t.pathname),a=this.isDoiResolverHost(t.hostname)?n.replace(/^\/+/,""):this.extractPublisherDoiPath(n);if(!this.isDoiResolverHost(t.hostname)&&!this.isConservativePublisherDoiPath(a)||this.hasSuspiciousDoiPathSuffix(a))return;const i=a.match(Ka);return this.normalizeDoiCandidate(i?.[0])}catch{const t=e.split(/[?#]/)[0],n=this.safeDecode(t),a=n.match(/^https?:\/\/(?:dx\.)?doi\.org\/(.+)$/i),i=a?a[1]:this.extractPublisherDoiPath(n);return!i||!a&&!this.isConservativePublisherDoiPath(i)||this.hasSuspiciousDoiPathSuffix(i)?void 0:this.normalizeDoiCandidate(i.match(Ka)?.[0])}}extractLabeledDoi(e){const t=this.cleanText(e);for(const n of t.matchAll(/(?:^|[\s;；,，([{（【])(?:DOI\s*[:：]?\s*)?((?:https?:\/\/(?:dx\.)?doi\.org\/)?10\.\d{4,9}\/[-._;()/:<>+\[\]A-Z0-9]+)/gi)){const a=n.index??0,i=t.slice(0,a),o=Math.max(i.lastIndexOf(";"),i.lastIndexOf("\uFF1B"),i.lastIndexOf(" \u4F5C\u8005"),i.lastIndexOf(" Author"),i.lastIndexOf(" \u6765\u6E90"),i.lastIndexOf(" Source"),i.lastIndexOf(" \u7C7B\u578B"),i.lastIndexOf(" \u6587\u732E\u7C7B\u578B"),i.lastIndexOf(" \u671F\u520A"),i.lastIndexOf(" \u520A\u540D")),s=i.slice(Math.max(0,o));if(this.hasCitationDoiContext(s)||this.hasAdjacentCitationDoiContext(i,o))continue;const l=this.normalizeDoiCandidate(n[1]);if(l)return l}}normalizeDoiCandidate(e){const t=this.cleanDoi(e);if(t&&!this.hasSuspiciousDoiPathSuffix(t))return/^10\.\d{4,9}\/[-._;()/:<>+\[\]A-Z0-9]+$/i.test(t)?t:void 0}cleanDoi(e){let t=e;for(;t;){const n=t;for(t=t.replace(/^https?:\/\/(?:dx\.)?doi\.org\//i,"").replace(/[.,;:。；：，、]+$/g,"").replace(/\/+$/g,"");t.endsWith(")")&&this.countCharacters(t,")")>this.countCharacters(t,"(");)t=t.slice(0,-1);for(;t.endsWith("]")&&this.countCharacters(t,"]")>this.countCharacters(t,"[");)t=t.slice(0,-1);if(t===n)break}return t?.toLowerCase()}countCharacters(e,t){return e.split(t).length-1}hasCjk(e){return/[\u3400-\u9fff]/.test(e)}isBaiduHost(e){return e==="baidu.com"||e.endsWith(".baidu.com")}isTrustedCitationTail(e){return e?this.isNonScholarlySourceText(e)?!1:this.isCurrentArticleMetadataTail(e)?!0:vg.test(e):!0}isNonScholarlySourceText(e){const t=this.normalizeCjkSpacing(e);return Cg.test(t)}hasCitationDoiContext(e){const t=this.stripCurrentArticleCountFields(this.normalizeCjkSpacing(e));return/(?:参考文献|引用文献|被引文献|被引用文献)\s*(?:DOI\s*[:：]?|[:：;；,，.。-]|$)|\b(?:References?|Cites|Citing(?:\s+article)?|Cited(?:\s+article)?|Citation(?:\(s\)|s)?)(?:\s*\(\s*\d[\d,]*\s*\))?\s*(?:DOI\s*[:：]?|[:：;；,，.。-]|$)/i.test(t)}hasAdjacentCitationDoiContext(e,t){if(t<0)return!1;const n=e.slice(0,t),a=Math.max(n.lastIndexOf(";"),n.lastIndexOf("\uFF1B"),n.lastIndexOf(","),n.lastIndexOf("\uFF0C")),i=n.slice(Math.max(0,a));return this.hasCitationDoiContext(i)&&!Ka.test(i)}isCurrentArticleMetadataTail(e){return this.stripDoiText(this.stripCurrentArticleCountFields(this.normalizeCjkSpacing(e))).trim().length===0}stripCurrentArticleCountFields(e){return e.replace(/(?:被引(?:量|数|次数|频次)?|被?引用(?:量|数|次数|频次)?|参考文献(?:量|数|次数|频次)?)\s*[:：]?\s*(?:暂无|无|--|-|\d[\d,，]*(?:\.\d+)?(?:\s*万)?(?:\s*(?:次|篇|条))?\s*[+＋]?)/g,"").replace(/\b(?:cited by|citation count|citations?|citation\(s\)|references?\s+count|references?)\s*[:：]?\s*(?:N\/A|na|--|-|\d[\d,]*(?:\.\d+)?\s*[KMB]?\+?(?:\s*(?:times?|articles?|papers?))?)/gi,"")}stripCurrentArticleSourceTail(e){return this.stripDoiTail(this.stripCurrentArticleCountFields(e)).replace(/(?:参考文献|引用文献|被引文献|被引用文献)\s*(?:DOI\s*[:：]?|[:：;；,，.。-])[\s\S]*$/i,"").replace(/\b(?:References?|Cites|Citing(?:\s+article)?|Cited(?:\s+article)?|Citation(?:\(s\)|s)?)(?:\s*\(\s*\d[\d,]*\s*\))?\s*(?:DOI\s*[:：]?|[:：;；,，.。-])[\s\S]*$/i,"").replace(/\s+(?:19|20)\d{2}年?\b[\s\S]*$/,"").replace(/\s+Journal Article\b[\s\S]*$/i,"").replace(/[([{（【\s]+$/g,"").trim()}stripDoiText(e){return e.replace(/\bDOI\s*[:：]?\s*(?:https?:\/\/(?:dx\.)?doi\.org\/)?10\.\d{4,9}\/[-._;()/:<>+\[\]A-Z0-9]+/gi,"").replace(xg,"")}stripDoiTail(e){return e.replace(/\bDOI\s*[:：]?\s*(?:https?:\/\/(?:dx\.)?doi\.org\/)?10\.\d{4,9}\/[-._;()/:<>+\[\]A-Z0-9]+[\s\S]*$/i,"").replace(/https?:\/\/(?:dx\.)?doi\.org\/10\.\d{4,9}\/[-._;()/:<>+\[\]A-Z0-9]+[\s\S]*$/i,"").replace(/\b10\.\d{4,9}\/[-._;()/:<>+\[\]A-Z0-9]+[\s\S]*$/i,"")}normalizeCjkSpacing(e){let t=this.cleanText(e);for(;/[\u3400-\u9fff]\s+[\u3400-\u9fff]/.test(t);)t=t.replace(/([\u3400-\u9fff])\s+([\u3400-\u9fff])/g,"$1$2");return t}isSecurityVerificationPage(){const e=Array.from(document.querySelectorAll(['iframe[src*="verify"]','iframe[src*="captcha"]','iframe[src*="challenge"]','iframe[src*="access-check"]','iframe[src*="security-check"]','form[action*="verify"]','form[action*="captcha"]','form[action*="challenge"]','form[action*="access-check"]','form[action*="security-check"]','[id*="captcha" i]','[class*="captcha" i]','[id*="challenge" i]','[class*="challenge" i]','[id*="access-check" i]','[class*="access-check" i]','[id*="security-check" i]','[class*="security-check" i]','[id*="verify-code" i]','[class*="verify-code" i]'].join(","))),t=document.querySelector("#bdxs_result_lists, #bdxs_result_list, [data-paperlens-baidu-results]"),n=!!t,a=document.querySelector("#container"),i=t??a,o=n||!!a,s=this.hasScholarlyResultEvidence(i),l=this.hasVerificationResultRow(i),c=this.cleanText(`${document.title??""} ${document.body?.textContent??""}`),u=`${c.slice(0,2e3)} ${c.slice(-3e3)}`;return l||e.some(d=>this.isStrongVerificationElement(d))||e.length>0&&!s||this.hasChallengeCopy(this.getTextOutsideResultHosts())||!s&&this.hasChallengeCopy(u)||!o&&/百度安全验证|网络不给力，请稍后重试|请完成以下验证/i.test(u)?!0:!o&&/请输入验证码|系统检测到您的请求存在异常/i.test(u)}isStrongVerificationElement(e){if(e.matches(qn)&&this.hasScholarlyResultEvidence(e))return!1;if(`${e.id??""} ${e.getAttribute("class")??""}`.split(/\s+/).some(a=>/^(?:captcha|challenge|access-check|security-check|verify-code)$/i.test(a)))return!0;const n=e.getAttribute("src")??e.getAttribute("action")??"";if(!n)return!1;try{const a=new URL(n,location.href),i=a.hostname.toLowerCase();return i==="verify.baidu.com"||i.endsWith(".verify.baidu.com")||i==="wappass.baidu.com"||i==="passport.baidu.com"?!0:/(?:^|\/)(?:captcha|verify|security-check|challenge|access-check)(?:[/?#]|$)/i.test(`${a.pathname}${a.search}`)}catch{return/(?:^|\/)(?:captcha|verify|security-check|challenge|access-check)(?:[/?#]|$)/i.test(n)}}hasChallengeCopy(e){return/(?:百度安全验证|安全验证|安全校验|滑块验证|拖动滑块|请完成以下验证|请输入验证码|系统检测到您的请求存在异常|Access check|Continue after check)/i.test(e)}getTextOutsideResultHosts(){if(!document.body)return"";const e=document.body.cloneNode(!0);return e.querySelectorAll([qn,"script","style","noscript"].join(",")).forEach(t=>t.remove()),this.cleanText(e.textContent??"")}hasVerificationResultRow(e){return e?this.getResultHosts(e).some(t=>{const n=this.cleanText(t.querySelector(Rr)?.textContent??""),a=this.cleanText(this.collectMetaText(t));if(this.isVerificationResult(n,a))return!0;const i=this.cleanText(t.textContent??"");return this.hasChallengeCopy(i)&&!this.hasScholarlyResultEvidence(t)}):!1}hasScholarlyResultEvidence(e){return e?this.getResultHosts(e).some(t=>{const n=this.cleanText(t.querySelector(Rr)?.textContent??"");if(!n)return!1;const a=this.cleanText(this.collectMetaText(t));if(this.isVerificationResult(n,a))return!1;const i=this.cleanText(t.textContent??"");return Ka.test(i)||/(?:来源期刊|刊名|来源|Source|Journal Article|作者|Author|类型\s*[:：]\s*期刊|文献类型\s*[:：]\s*期刊)/i.test(i)}):!1}getResultHosts(e){const t=e.matches(qn)?[e]:Array.from(e.querySelectorAll(qn));if(t.length>0)return t;const n=Array.from(e.querySelectorAll(Rr)),a=[],i=new Set;for(const o of n){const s=this.findCurrentResultHost(o);!s||i.has(s)||(i.add(s),a.push(s))}return a}findCurrentResultHost(e){const t=this.cleanTitle(e.textContent??"");if(!t)return null;let n=e.closest("h1, h2, h3")?.parentElement??e.parentElement;for(;n&&n!==document.body;){const a=this.cleanText(n.textContent??"");if(a.includes(t)&&(/(?:来源|Source|被引|DOI|收藏|摘要|期刊)/i.test(a)||/(?:19|20)\d{2}年/.test(a)))return n;n=n.parentElement}return e.parentElement}textWithoutTitle(e){const t=e.cloneNode(!0);return t.querySelector(Rr)?.remove(),t.textContent??""}extractFallbackAbstract(e){return this.cleanText(this.textWithoutTitle(e)).match(/摘要[:：]\s*(.+?)(?=\s*(?:来源|Source|被引|DOI|收藏|$))/)?.[1]}isVerificationResult(e,t){const n=this.cleanText(e),a=this.cleanText(t);return/^百度学术$/i.test(n)&&/安全检测中|请稍候|稍后|验证|captcha|verify/i.test(a)||/^(?:安全验证|安全校验|滑块验证)$/i.test(n)&&/(?:拖动滑块|滑块验证|安全校验|继续访问|captcha|verify|验证码)/i.test(a)||/^(?:请完成以下验证|百度安全验证|网络不给力，请稍后重试|请输入验证码)$/i.test(n)||/^(?:Access check|请完成以下验证|百度安全验证|请输入验证码)$/i.test(n)&&/(?:验证后继续访问|Continue after check|captcha|verify|百度学术)/i.test(a)||/^(?:系统检测到您的请求存在异常|访问异常|请输入验证码完成验证)$/i.test(n)&&/(?:请输入验证码|滑块验证|验证后继续访问|Continue after check|captcha|verify)/i.test(a)||/(?:百度安全验证|请完成以下验证|访问异常|请输入验证码|系统检测到您的请求存在异常)/i.test(n)&&/(?:请输入验证码|滑块验证|验证后继续访问|Continue after check|captcha|verify|百度学术)/i.test(a)?!0:/^(?:验证后继续访问|Continue after check|请输入验证码|滑块验证)$/i.test(a)}isDoiResolverHost(e){const t=e.toLowerCase();return t==="doi.org"||t==="dx.doi.org"}hasSuspiciousDoiPathSuffix(e){const n=e.replace(/^\/+/,"").replace(/^10\.\d{4,9}\//i,"").split("/").filter(Boolean);return n.length>2&&/^\d{5,}$/.test(n.at(-1)??"")||/\/(?:supplementary|supplement|article-info|citations?|references?|metrics|figures?|full|abstract|epdf|pdf)$/i.test(e)}isConservativePublisherDoiPath(e){return/^10\.\d{4,9}\/[-._;()/:<>+\[\]A-Z0-9]+$/i.test(e)}extractPublisherDoiPath(e){return e.match(/\/doi\/(?:(?:full|abs|pdf|epdf|abstract)\/)?(10\.\d{4,9}\/[-._;()/:<>+\[\]A-Z0-9]+)$/i)?.[1]??""}stableHash(e){let t=3735928559,n=1103547991;for(let a=0;a<e.length;a++){const i=e.charCodeAt(a);t=Math.imul(t^i,2654435761),n=Math.imul(n^i,1597334677)}return t=Math.imul(t^t>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),`${(t>>>0).toString(36)}${(n>>>0).toString(36)}`}hasUntrustedQuotedTail(e){const t=this.cleanText(e.match(/《[^》]+》\s*(?:[,，.。;；]?\s*(?:19|20)\d{2}(?:年)?)?\s*([^；;\n]*)/)?.[1]??"");return!!t&&!this.isTrustedCitationTail(t)}cleanText(e){return e.replace(/\u00a0/g," ").replace(/\s+/g," ").trim()}safeDecode(e){try{return decodeURIComponent(e)}catch{return e}}normalizeTrackingUrl(e){if(!e)return"";try{const t=new URL(e,location.href);if(!this.isBaiduHost(t.hostname))return this.normalizeExternalUrl(t);for(const n of Array.from(t.searchParams.keys()))this.isBaiduTrackingParam(n)&&t.searchParams.delete(n);return`${t.origin}${t.pathname}${t.search}${t.hash}`}catch{return e.replace(/([?&])(?:tn|sc_[^=&]*|wd|ie|rsv_[^=&]*|oq|bs|f|usm|rsp|inputT|pn|page)=[^&#]*/gi,"$1").replace(/[?&]+$/,"")}}isBaiduTrackingParam(e){return/^(?:tn|sc_|wd|ie|rsv_|oq|bs|usm|rsp|inputT)/i.test(e)||/^(?:f|pn|page)$/i.test(e)}normalizeExternalUrl(e){for(const n of Array.from(e.searchParams.keys()))(/^utm_/i.test(n)||/^(?:fbclid|gclid|yclid|mc_cid|mc_eid|spm)$/i.test(n))&&e.searchParams.delete(n);const t=Array.from(e.searchParams.entries()).sort(([n,a],[i,o])=>n.localeCompare(i)||a.localeCompare(o));e.search="";for(const[n,a]of t)e.searchParams.append(n,a);return this.normalizeDoiIdentityInUrl(e.href)}normalizeDoiIdentityInUrl(e){return e.replace(/\/doi\/(?:(?:full|abs|pdf|epdf|abstract)\/)?/gi,t=>t.toLowerCase()).replace(/10\.\d{4,9}(?:\/|%2f)[-._;()/:<>+\[\]A-Z0-9%]+/gi,t=>t.toLowerCase())}clearStaleEnhancements(e){e.querySelectorAll([".paperlens-metric-host",".paperlens-extra-tags",".paperlens-extra-download-host",".paperlens-zotero-host",".paperlens-action-row",".paperlens-save-host",".paperlens-export-host",`.${_o}`].join(",")).forEach(t=>t.remove()),e.removeAttribute("data-paperlens-article-id"),e.removeAttribute("data-paperlens-article-signature")}clearStaleEnhancementsInContainer(){const e=this.getResultsContainer();if(!e)return;const t=e.matches(qn)?[e]:Array.from(e.querySelectorAll(qn));if(t.length>0){t.forEach(n=>this.clearStaleEnhancements(n));return}this.clearStaleEnhancements(e)}toAbsoluteUrl(e){if(e)try{return new URL(e,location.href).href}catch{return e}}}const Tg=/\b10\.\d{4,9}\/[-._;()/:A-Z0-9]+/i,Eg=/\b((?:19|20)\d{2})\b/,Fg="#completesearch-publs ul.publ-list > li.entry",Dg="#publ-section ul.publ-list > li.entry",_g="ul.publ-list > li.entry",kg=[{pattern:/\b(?:NIPS|NeurIPS|Neural Information Processing Systems)\b/i,canonical:"NeurIPS"},{pattern:/\bCVPR\b|Computer Vision and Pattern Recognition/i,canonical:"CVPR"},{pattern:/\bICCV\b|International Conference on Computer Vision/i,canonical:"ICCV"},{pattern:/\bECCV\b|European Conference on Computer Vision/i,canonical:"ECCV"},{pattern:/\bICML\b|International Conference on Machine Learning/i,canonical:"ICML"},{pattern:/\bICLR\b|International Conference on Learning Representations/i,canonical:"ICLR"},{pattern:/\bKDD\b|Knowledge Discovery and Data Mining/i,canonical:"KDD"},{pattern:/\bSIGIR\b/i,canonical:"SIGIR"},{pattern:/\bSIGMOD\b/i,canonical:"SIGMOD"},{pattern:/\bVLDB\b/i,canonical:"VLDB"},{pattern:/\bACL\b|Association for Computational Linguistics/i,canonical:"ACL"},{pattern:/\bEMNLP\b/i,canonical:"EMNLP"},{pattern:/\bAAAI\b/i,canonical:"AAAI"},{pattern:/\bIJCAI\b/i,canonical:"IJCAI"},{pattern:/\bCHI\b|Human Factors in Computing Systems/i,canonical:"CHI"},{pattern:/\bWWW\b|World Wide Web Conference/i,canonical:"WWW"},{pattern:/\bSOSP\b/i,canonical:"SOSP"},{pattern:/\bOSDI\b/i,canonical:"OSDI"},{pattern:/\bUSENIX\b/i,canonical:"USENIX"}],Ng=[{pattern:/^Proc\.\s*ACM\s*Program\.\s*Lang\.$/i,journalName:"Proceedings of the ACM on Programming Languages-PACMPL",extraCandidates:["Proceedings of the ACM on Programming Languages","PACM PL"]},{pattern:/^Proc\.\s*ACM\s*Hum\.\s*Comput\.\s*Interact\.$/i,journalName:"Proceedings of the ACM on Human-Computer Interaction",extraCandidates:["PACMHCI"]},{pattern:/^Proc\.\s*VLDB\s*Endow\.$/i,journalName:"Proceedings of the VLDB Endowment"}];class Lg extends j{id="dblp";name="DBLP";matches=["*://dblp.org/*","*://dblp.uni-trier.de/*"];isSearchPage(){const e=location.pathname.replace(/\/+$/,"");return(e==="/search"||e==="/search/publ")&&new URLSearchParams(location.search).has("q")}isArticlePage(){return location.pathname.startsWith("/rec/")||document.body?.classList.contains("rec-page")}parseSearchResults(){const e=[],t=new Set;for(const n of this.getSearchResultHosts())try{const a=this.parseEntry(n);if(!a)continue;const i=a.sourceId??a.url??a.title;if(t.has(i))continue;t.add(i),e.push(a)}catch(a){console.error("[DblpAdapter] Failed to parse search result:",a)}return e}parseArticlePage(){const e=this.getDetailHostElement();if(!e)return null;try{return this.parseEntry(e)}catch(t){return console.error("[DblpAdapter] Failed to parse article page:",t),null}}getMetricBarAnchor(e){const t=e.querySelector("cite.data")??e.querySelector("cite");if(t)return{element:t,position:"after"};const n=e.querySelector(".title");return n?{element:n,position:"after"}:{element:e,position:"append"}}getResultsContainer(){return document.querySelector("#completesearch-publs .body")??document.querySelector("#publ-section")??document.querySelector("#main")??document.body}getPageInfo(){const t=document.querySelector("#completesearch-publs .metadata")?.getAttribute("data-matches")??"",n=Number.parseInt(t,10);return{pageNum:1,totalPages:Number.isFinite(n)&&n>0?Math.max(1,Math.ceil(n/30)):1,url:location.href,itemsPerPage:30,totalItems:Number.isFinite(n)?n:void 0}}getSearchResultHosts(){const e=Array.from(document.querySelectorAll(Fg));return e.length>0?e:Array.from(document.querySelectorAll(_g)).filter(t=>!t.closest("#publ-references-section, #publ-citations-section"))}getDetailHostElement(){return document.querySelector(Dg)??document.querySelector("body.rec-page li.entry")??null}parseEntry(e){const t=this.cleanText(e.querySelector('.title[itemprop="name"], .title')?.textContent??"");if(!t)return null;const n=this.extractDblpKey(e),a=this.extractVenue(e),i=this.inferRecordKind(e,a,n),o=this.normalizeVenue(a,i),s=this.extractNativeFullTextUrl(e),l=this.extractDoi(e),c=this.extractRecordUrl(e,n);return{title:t,journalName:o.journalName,journalCandidates:o.candidates,authors:this.extractAuthors(e),year:this.extractYear(e),doi:l,sourceId:n?`dblp:${n}`:void 0,url:c,nativeFullTextUrl:s,hostElement:e,articleTypes:i.articleTypes,source:this.id,citationType:i.citationType,nativeExportUrls:this.extractNativeExportUrls(e,n)}}extractAuthors(e){return this.unique(Array.from(e.querySelectorAll('[itemprop="author"] [itemprop="name"], cite [itemprop="name"][title]')).map(t=>this.cleanText(t.getAttribute("title")??t.textContent??"")).filter(Boolean))}extractVenue(e){const t=e.querySelector("cite.data")??e;return Array.from(t.querySelectorAll('[itemprop="isPartOf"] [itemprop="name"]')).map(a=>this.cleanText(a.textContent??"")).filter(Boolean)[0]??""}inferRecordKind(e,t,n){const a=e.className,i=this.cleanText(e.querySelector(".box img[title]")?.getAttribute("title")??""),o=`${a} ${i} ${t} ${n}`;return/\b(?:informal|CoRR|arXiv)\b/i.test(o)?{articleTypes:["Preprint"],citationType:"misc",journalMetricsAllowed:!1}:/\b(?:article|Journal Articles)\b/i.test(o)||n.startsWith("journals/")?{articleTypes:["JournalArticle"],citationType:"article",journalMetricsAllowed:!0}:/\b(?:inproceedings|proceedings|Conference and Workshop Papers)\b/i.test(o)||n.startsWith("conf/")?{articleTypes:["Conference"],citationType:"inproceedings",journalMetricsAllowed:!1}:/\b(?:incollection|book chapter|Parts in Books or Collections)\b/i.test(o)?{articleTypes:["BookChapter"],citationType:"incollection",journalMetricsAllowed:!1}:/\b(?:book|Books and Theses)\b/i.test(o)?{articleTypes:["Book"],citationType:"book",journalMetricsAllowed:!1}:{articleTypes:["Publication"],citationType:"misc",journalMetricsAllowed:!1}}normalizeVenue(e,t){if(!e)return{journalName:"",candidates:void 0};if(t.citationType==="inproceedings"){const a=this.canonicalConference(e)||e;return{journalName:a,candidates:this.unique([e,a])}}const n=this.canonicalJournal(e);return t.journalMetricsAllowed&&n?{journalName:n.journalName,candidates:this.unique([e,n.journalName,...n.extraCandidates??[]])}:t.journalMetricsAllowed?{journalName:e,candidates:this.unique([e])}:{journalName:e,candidates:this.unique([e])}}canonicalConference(e){for(const n of kg)if(n.pattern.test(e))return n.canonical;const t=e.trim().match(/^([A-Z][A-Z0-9]{1,})(?:\s*(?:\([^)]*\)|[-:,]\s*.*|\d{4}|$))/);return t?.[1]?t[1]:""}canonicalJournal(e){for(const t of Ng)if(t.pattern.test(e))return{journalName:t.journalName,extraCandidates:t.extraCandidates};return null}extractDblpKey(e){const t=this.cleanText(e.getAttribute("id")??"");if(t&&/^(?:conf|journals|books|series|reference|tr)\/.+/i.test(t))return t;const n=this.cleanText(e.querySelector(".select-on-click small")?.textContent??"");return n&&n.includes("/")?n:this.extractRecordUrl(e,"")?.match(/\/rec\/([^?#.]+(?:\/[^?#.]+)*)/)?.[1]??""}extractRecordUrl(e,t){const n=document.querySelector('link[rel="canonical"][href*="/rec/"]')?.href;if(n)return this.normalizeRecordUrl(n);const a=Array.from(e.querySelectorAll('a[href*="/rec/"]')).map(i=>this.absoluteUrl(i.getAttribute("href"))).find(i=>i&&/\/rec\//.test(i)&&!this.isExportRecordUrl(i));return a?this.normalizeRecordUrl(a):t?`https://dblp.org/rec/${t}`:void 0}extractNativeFullTextUrl(e){const t=Array.from(e.querySelectorAll('li.ee a[itemprop="url"]'));for(const n of t){const a=this.absoluteUrl(n.getAttribute("href"));if(a&&!/\/rec\/|dblp\.org\/db\//i.test(a))return a}}extractNativeExportUrls(e,t){const n=Array.from(e.querySelectorAll("a[href]")).map(o=>this.absoluteUrl(o.getAttribute("href"))).filter(o=>!!o),a=n.find(o=>/\.bib(?:$|[?#])/i.test(o))??(t?`https://dblp.org/rec/${t}.bib`:void 0),i=n.find(o=>/\.ris(?:$|[?#])/i.test(o))??(t?`https://dblp.org/rec/${t}.ris`:void 0);if(!(!a&&!i))return{bibtex:a,ris:i}}normalizeRecordUrl(e){const t=e.split("#")[0]??e;return(t.split("?")[0]??t).replace(/\.html$/i,"")}isExportRecordUrl(e){return/[?&]view=|\/rec\/.+\.(?:bib|ris|xml|rdf|nt|ttl|txt)(?:$|[?#])/i.test(e)}extractDoi(e){for(const t of Array.from(e.querySelectorAll('a[href*="doi.org/"]'))){const n=this.cleanDoi(t.getAttribute("href"));if(n)return n}return this.cleanDoi(e.textContent??"")}extractYear(e){const n=(e.querySelector('[itemprop="datePublished"]')?.textContent??e.textContent??"").match(Eg);if(!n?.[1])return;const a=Number.parseInt(n[1],10);return Number.isFinite(a)?a:void 0}cleanDoi(e){if(!e)return;let t=e;try{t=decodeURIComponent(e)}catch{t=e}const n=t.match(Tg);if(n?.[0])return n[0].replace(/^https?:\/\/(?:dx\.)?doi\.org\//i,"").replace(/[)\].,;:]+$/g,"")}absoluteUrl(e){const t=e?.trim();if(t)try{return new URL(t,location.href).href}catch{return}}unique(e){const t=[],n=new Set;for(const a of e){const i=this.cleanText(a??"");if(!i)continue;const o=i.toLowerCase();n.has(o)||(n.add(o),t.push(i))}return t}cleanText(e){return e.replace(/\s+/g," ").trim()}}const Rg=/\b10\.\d{4,9}\/[-._;()/:A-Z0-9]+/i,Pg=/\b((?:19|20)\d{2})\b/,Bg=[".List-results-items > *","xpl-document-card","[data-artnum]","[data-documentid]",".document-card",".result-item",".xpl-result",'[class*="ResultItem"]',"article"].join(","),Ig=["#xplMainContent","main",".document-main",".document-container","#LayoutWrapper","body"].join(","),Eu=['[id*="reference"]','[id*="Reference"]','[class*="reference"]','[class*="Reference"]','[id*="related"]','[id*="Related"]','[class*="related"]','[class*="Related"]','[id*="recommend"]','[id*="Recommend"]','[class*="recommend"]','[class*="Recommend"]','[data-test*="reference"]','[data-testid*="reference"]'].join(","),Mg=[{pattern:/\b(?:NIPS|NeurIPS|Neural Information Processing Systems)\b/i,canonical:"NeurIPS"},{pattern:/\bCVPR\b|Computer Vision and Pattern Recognition/i,canonical:"CVPR"},{pattern:/\bICCV\b|International Conference on Computer Vision/i,canonical:"ICCV"},{pattern:/\bECCV\b|European Conference on Computer Vision/i,canonical:"ECCV"},{pattern:/\bICML\b|International Conference on Machine Learning/i,canonical:"ICML"},{pattern:/\bICLR\b|International Conference on Learning Representations/i,canonical:"ICLR"},{pattern:/\bKDD\b|Knowledge Discovery and Data Mining/i,canonical:"KDD"},{pattern:/\bSIGIR\b/i,canonical:"SIGIR"},{pattern:/\bSIGMOD\b/i,canonical:"SIGMOD"},{pattern:/\bVLDB\b/i,canonical:"VLDB"},{pattern:/\bACL\b|Association for Computational Linguistics/i,canonical:"ACL"},{pattern:/\bEMNLP\b/i,canonical:"EMNLP"},{pattern:/\bAAAI\b/i,canonical:"AAAI"},{pattern:/\bIJCAI\b/i,canonical:"IJCAI"},{pattern:/\bCHI\b|Human Factors in Computing Systems/i,canonical:"CHI"},{pattern:/\bWWW\b|World Wide Web Conference/i,canonical:"WWW"},{pattern:/\bSOSP\b/i,canonical:"SOSP"},{pattern:/\bOSDI\b/i,canonical:"OSDI"},{pattern:/\bICSE\b|International Conference on Software Engineering/i,canonical:"ICSE"},{pattern:/\bINFOCOM\b|International Conference on Computer Communications/i,canonical:"INFOCOM"},{pattern:/\bICDE\b|International Conference on Data Engineering/i,canonical:"ICDE"},{pattern:/\bHPCA\b|High Performance Computer Architecture/i,canonical:"HPCA"},{pattern:/\bMICRO\b|International Symposium on Microarchitecture/i,canonical:"MICRO"},{pattern:/\bISCA\b|International Symposium on Computer Architecture/i,canonical:"ISCA"},{pattern:/\bRTSS\b|Real-Time Systems Symposium/i,canonical:"RTSS"}];class qg extends j{id="ieee-xplore";name="IEEE Xplore";matches=["*://ieeexplore.ieee.org/*"];isSearchPage(){return location.pathname.startsWith("/search/")||location.pathname==="/search/searchresult.jsp"||new URLSearchParams(location.search).has("queryText")}isArticlePage(){return/^\/(?:abstract\/)?document\/\d+\/?$/i.test(location.pathname)||!!this.getIeeeDocumentMetadata()}parseSearchResults(){const e=[],t=new Set;for(const n of this.getSearchResultHosts())try{const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;if(t.has(i))continue;t.add(i),e.push(a)}catch(a){console.error("[IeeeXploreAdapter] Failed to parse search result:",a)}return e}parseArticlePage(){const e=document.querySelector(Ig);if(!e)return null;try{const t=this.getIeeeDocumentMetadata();if(t){const n=this.metadataToArticle(t,e,location.href);if(n)return n}return this.parseDetailDom(e)}catch(t){return console.error("[IeeeXploreAdapter] Failed to parse article page:",t),null}}getMetricBarAnchor(e){const t=e.querySelector('h1, h2, .document-title, .result-item-title, [class*="title"]');if(t)return{element:t,position:"after"};const n=e.querySelector('.description, .document-meta, .publication-title, [class*="metadata"], [class*="meta"]');return n?{element:n,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector(".List-results-items")??document.querySelector("#xplMainContent")??document.querySelector("main")??document.body}getPageInfo(){const t=this.cleanText(document.querySelector('.results-display, .Showing, [class*="result"] [class*="count"]')?.textContent??"").match(/\b([\d,]+)\s+results?\b/i),n=t?Number.parseInt(t[1].replace(/,/g,""),10):void 0;return{pageNum:Number.parseInt(new URLSearchParams(location.search).get("pageNumber")??"1",10)||1,totalPages:n?Math.max(1,Math.ceil(n/25)):1,url:location.href,itemsPerPage:25,totalItems:n}}getSearchResultHosts(){const e=Array.from(document.querySelectorAll(Bg)).filter(t=>this.looksLikeSearchResult(t));return this.uniqueElements(e)}looksLikeSearchResult(e){return e.closest('[class^="paperlens-"], [class*=" paperlens-"]')?!1:e.querySelector('a[href*="/document/"], a[href*="/abstract/document/"]')||e.getAttribute("data-artnum")||e.getAttribute("data-documentid")?!0:/\b10\.\d{4,9}\//i.test(e.textContent??"")&&/IEEE|Conference|Transactions|Journal|Proceedings/i.test(e.textContent??"")}parseSearchHost(e){const t=this.findTitleLink(e),n=this.cleanText(t?.textContent??e.querySelector('.document-title, .result-item-title, h2, h3, [class*="title"]')?.textContent??"");if(!n)return null;const a=this.extractArticleNumber(e,t?.href),i=this.extractVenue(e),o=this.extractDoi(e),s=this.extractTypeText(e),l=this.inferRecordKind({isConference:/conference|proceedings|symposium|workshop/i.test(s),isJournal:/journal|transactions|letters|magazine/i.test(s),contentTypeDisplay:s,xploreDocumentType:s,publicationTitle:i}),c=this.normalizeVenue(i,l);return{title:n,journalName:c.journalName,journalCandidates:c.candidates,authors:this.extractAuthorsFromDom(e),year:this.extractYear(e),doi:o,sourceId:a?`ieee:${a}`:void 0,url:this.toAbsoluteUrl(t?.href??"")??void 0,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:l.articleTypes,source:this.id,citationType:l.citationType}}parseDetailDom(e){const t=this.cleanText(document.querySelector('meta[property="og:title"]')?.getAttribute("content")??e.querySelector("h1, .document-title")?.textContent??document.title.replace(/\s*\|\s*IEEE Xplore\s*$/i,""));if(!t)return null;const n=this.extractVenue(e),a=this.extractTypeText(e),i=this.inferRecordKind({isConference:/conference|proceedings|symposium|workshop/i.test(a),isJournal:/journal|transactions|letters|magazine/i.test(a),contentTypeDisplay:a,publicationTitle:n}),o=this.normalizeVenue(n,i),s=this.extractArticleNumber(e,location.href);return{title:t,journalName:o.journalName,journalCandidates:o.candidates,authors:this.extractAuthorsFromDom(e),year:this.extractYear(e),doi:this.extractDoi(e,{allowTextFallback:!1}),sourceId:s?`ieee:${s}`:void 0,url:this.toAbsoluteUrl(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:i.articleTypes,source:this.id,citationType:i.citationType}}metadataToArticle(e,t,n){const a=this.cleanText(e.title??e.displayDocTitle??e.formulaStrippedArticleTitle??"");if(!a)return null;const i=this.cleanText(e.publicationTitle??e.displayPublicationTitle??""),o=this.inferRecordKind(e),s=this.normalizeVenue(i,o),l=e.articleNumber?String(e.articleNumber):this.extractArticleNumber(t,n),c=this.toAbsoluteUrl(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??(l?`/document/${l}`:n));return{title:a,journalName:s.journalName,journalCandidates:s.candidates,authors:this.extractAuthorsFromMetadata(e),year:this.extractMetadataYear(e),doi:this.cleanDoi(e.doi??e.doiLink??""),sourceId:l?`ieee:${l}`:void 0,url:c,nativeFullTextUrl:this.toNativeFullTextUrl(e.pdfUrl??e.pdfPath??""),abstractSnippet:this.cleanText(e.abstract??""),hostElement:t,articleTypes:o.articleTypes,source:this.id,citationType:o.citationType}}inferRecordKind(e){const t=[e.contentType,e.contentTypeDisplay,e.xploreDocumentType].filter(Boolean).join(" "),n=[e.publicationTitle,e.displayPublicationTitle].filter(Boolean).join(" ");return this.truthyFlag(e.isJournal)||/journal|journals|transactions|letters|magazine/i.test(t)||this.isJournalVenue(n)?{articleTypes:["JournalArticle"],citationType:"article",metricsAllowed:!0}:this.truthyFlag(e.isConference)||/conference|proceedings|symposium|workshop/i.test(t)||this.isConferenceVenue(n)?{articleTypes:["Conference"],citationType:"inproceedings",metricsAllowed:!1}:this.truthyFlag(e.isBook)||this.truthyFlag(e.isChapter)||/book|chapter/i.test(`${t} ${n}`)?{articleTypes:["BookChapter"],citationType:"incollection",metricsAllowed:!1}:{articleTypes:["JournalArticle"],citationType:"article",metricsAllowed:!0}}normalizeVenue(e,t){const n=this.cleanText(e),a=n?[n]:[];if(!t.metricsAllowed){const i=this.normalizeConferenceVenue(n);return i&&i!==n&&a.unshift(i),{journalName:i??n,candidates:this.unique(a)}}return{journalName:n,candidates:this.unique(a)}}normalizeConferenceVenue(e){return this.matchConferenceAlias(e)??(e||void 0)}isJournalVenue(e){return/\b(?:IEEE\s+)?(?:Transactions|Journal|Letters|Magazine)\b/i.test(e)||/^Proceedings of the IEEE$/i.test(e.trim())}isConferenceVenue(e){const t=this.cleanText(e);return!t||this.isJournalVenue(t)?!1:this.matchConferenceAlias(t)?!0:/conference|symposium|workshop/i.test(t)||/\bproceedings\b/i.test(t)}matchConferenceAlias(e){for(const t of Mg)if(t.pattern.test(e))return t.canonical}extractTypeText(e){const t=['[data-field="contentType"]','[data-field="documentType"]',".content-type",".document-type",".xpl-type",'[class*="content-type"]','[class*="document-type"]','[data-test*="content-type"]','[data-testid*="content-type"]'].join(",");return Array.from(e.querySelectorAll(t)).map(n=>this.cleanText(n.textContent??"")).filter(Boolean).join(" ")}extractVenue(e){const t=['[data-field="publicationTitle"]',".publication-title",".published-in",".document-publication-title",".stats-document-abstract-publishedIn",'[class*="publication"]','[class*="published"]'].join(",");for(const i of Array.from(e.querySelectorAll(t))){const o=this.cleanText(i.textContent??"").replace(/^Published in:\s*/i,"");if(o&&!/^(PDF|HTML|View|Abstract)$/i.test(o))return o}const a=this.cleanText(e.textContent??"").match(/Published in:\s*([^|]+?)(?:\s+(?:Date|Year|DOI|Pages):|$)/i);return a?this.cleanText(a[1]):""}findTitleLink(e){return Array.from(e.querySelectorAll('h2 a[href*="/document/"], h3 a[href*="/document/"], .result-item-title a[href*="/document/"], a[href*="/document/"], a[href*="/abstract/document/"]')).find(n=>this.cleanText(n.textContent??"").length>0)??null}extractAuthorsFromMetadata(e){if(Array.isArray(e.authors))return this.unique(e.authors.map(n=>typeof n=="string"?n:n.name??n.fullName??n.preferredName??"").map(n=>this.cleanText(n)).filter(Boolean));const t=Array.isArray(e.authorNames)?e.authorNames:typeof e.authorNames=="string"?e.authorNames.split(/;|, and | and /i):[];return this.unique(t.map(n=>this.cleanText(n)).filter(Boolean))}extractAuthorsFromDom(e){const t=[".authors a",".authors span",'[class*="author"] a','[class*="author"] span',"[data-author-name]"].join(","),n=Array.from(e.querySelectorAll(t)).map(a=>this.cleanText(a.getAttribute("data-author-name")??a.textContent??"")).filter(a=>a&&!/^(Authors?|View|Show more)$/i.test(a));return this.unique(n)}extractYear(e){const t=['[data-field="publicationYear"]',".publication-year",".year",'[class*="year"]','[class*="date"]'].join(",");for(const n of Array.from(e.querySelectorAll(t))){const a=this.yearFromText(n.textContent??"");if(a)return a}return this.yearFromText(e.textContent??"")}extractMetadataYear(e){if(e.publicationYear){const t=Number.parseInt(String(e.publicationYear),10);if(Number.isFinite(t))return t}return this.yearFromText(e.publicationDate??"")}yearFromText(e){const t=e.match(Pg);return t?Number.parseInt(t[1],10):void 0}extractDoi(e,t={}){const n=t.allowTextFallback??!0;for(const a of Array.from(e.querySelectorAll('a[href*="doi.org/"], a[href*="doi.ieeecomputersociety.org/"]'))){if(this.isExcludedDoiContext(a))continue;const i=this.cleanDoi(a.href);if(i)return i}if(n)return this.cleanDoi(this.textWithoutExcludedDoiContexts(e))}cleanDoi(e){return e.match(Rg)?.[0].replace(/[),.;\s]+$/g,"")}extractArticleNumber(e,t){const n=e.getAttribute("data-artnum")??e.getAttribute("data-documentid")??e.getAttribute("data-article-number")??"";if(n)return n.trim();const a=t??"",i=a.match(/\/document\/(\d+)/i)??a.match(/[?&]arnumber=(\d+)/i);if(i)return i[1];const o=e.querySelector('a[href*="/document/"], a[href*="arnumber="]');return(o?.href.match(/\/document\/(\d+)/i)??o?.href.match(/[?&]arnumber=(\d+)/i))?.[1]}extractNativeFullTextUrl(e){const t=e.querySelector('a[href*="/stamp/stamp.jsp"], a[href*="arnumber="][href*="pdf"], a[href*="/ielx"]');return this.toNativeFullTextUrl(t?.getAttribute("href")??t?.href??"")??void 0}extractAbstract(e){return this.cleanText(e.querySelector('.abstract, [class*="abstract"], .description')?.textContent??"")||void 0}getIeeeDocumentMetadata(){const e=window.xplGlobal?.document?.metadata;return e?.title||e?.displayDocTitle?e:this.extractAssignedJson("xplGlobal.document.metadata=")??this.extractAssignedJson("window.xplGlobal.document.metadata=")}extractAssignedJson(e){for(const t of Array.from(document.scripts)){const n=t.textContent??"",a=n.indexOf(e);if(a<0)continue;const i=n.indexOf("{",a+e.length);if(i<0)continue;const o=this.readBalancedObject(n,i);if(o)try{return JSON.parse(o)}catch{continue}}return null}readBalancedObject(e,t){let n=0,a=!1,i="",o=!1;for(let s=t;s<e.length;s++){const l=e[s];if(a){o?o=!1:l==="\\"?o=!0:l===i&&(a=!1,i="");continue}if(l==='"'||l==="'"){a=!0,i=l;continue}if(l==="{"&&n++,l==="}"&&(n--,n===0))return e.slice(t,s+1)}return null}truthyFlag(e){return e===!0||e==="true"||e==="1"}isExcludedDoiContext(e){return!!e.closest(Eu)}textWithoutExcludedDoiContexts(e){const t=e.cloneNode(!0);return t.querySelectorAll(Eu).forEach(n=>n.remove()),t.textContent??""}toNativeFullTextUrl(e){const t=this.toAbsoluteUrl(e);if(t)try{const n=new URL(t).hostname.toLowerCase();return n==="ieeexplore.ieee.org"||n.endsWith(".ieeexplore.ieee.org")?t:void 0}catch{return}}toAbsoluteUrl(e){const t=e.trim();if(!(!t||/^javascript:/i.test(t)||/^data:/i.test(t)))try{const n=new URL(t,location.origin);return/^https?:$/.test(n.protocol)?n.href:void 0}catch{return}}cleanText(e){return e.replace(/\s+/g," ").trim()}unique(e){return Array.from(new Set(e.filter(Boolean)))}uniqueElements(e){return Array.from(new Set(e))}}const jg=/\b10\.\d{4,9}\/[-._;()/:A-Z0-9]+/i,$g=/\b((?:19|20)\d{2})\b/,Og=/\b\d{4}-?\d{3}[\dX]\b/i,Ug=/\/pii\/([^/?#]+)/i,Hg=["ol.search-results > li",".ResultItem","li.ResultItem",".result-item",'[data-testid*="result-item"]','[class*="ResultItem"]',"article"].join(","),zg=["article","#article","main","#main-content","body"].join(","),Fu=['[id*="reference"]','[id*="Reference"]','[class*="reference"]','[class*="Reference"]','[id*="related"]','[id*="Related"]','[class*="related"]','[class*="Related"]','[id*="recommend"]','[id*="Recommend"]','[class*="recommend"]','[class*="Recommend"]','[data-test*="reference"]','[data-testid*="reference"]'].join(",");class Jg extends j{id="sciencedirect";name="ScienceDirect";matches=["*://www.sciencedirect.com/*"];isSearchPage(){return location.pathname==="/search"||location.pathname.startsWith("/search/")}isArticlePage(){return/^\/science\/article\/(?:abs\/)?pii\//i.test(location.pathname)||!!this.firstMetaContent(["citation_title"])}parseSearchResults(){const e=[],t=new Set;for(const n of this.getSearchResultHosts())try{const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;if(t.has(i))continue;t.add(i),e.push(a)}catch(a){console.error("[ScienceDirectAdapter] Failed to parse search result:",a)}return e}parseArticlePage(){const e=document.querySelector(zg);if(!e)return null;try{return this.parseArticleMetadata(e)??this.parseArticleDom(e)}catch(t){return console.error("[ScienceDirectAdapter] Failed to parse article page:",t),null}}getMetricBarAnchor(e){if(this.isArticlePage()&&!this.isSearchPage()){const a=this.findDetailTitle(e)??this.findDetailTitle(document.body);if(a)return{element:a,position:"after"};const i=e.querySelector('.author-group, .Authors, [class*="author-group"], [class*="authors"]');return i?{element:i,position:"after"}:{element:e,position:"prepend"}}const t=e.querySelector('h2, h3, .result-list-title-link, .title-text, [class*="title"]');if(t)return{element:t,position:"after"};const n=e.querySelector('.publication-title, .srctitle, .publication-volume, [class*="source"], [class*="publication"]');return n?{element:n,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector("ol.search-results")??document.querySelector('[data-testid*="results"]')??document.querySelector("main")??document.body}getPageInfo(){const e=new URLSearchParams(location.search),t=Number.parseInt(e.get("offset")??"0",10)||0,n=Math.floor(t/25)+1,i=this.cleanText(document.querySelector('[data-testid*="results-count"], .search-body-results-text, .ResultCount')?.textContent??"").match(/\b([\d,]+)\s+results?\b/i),o=i?Number.parseInt(i[1].replace(/,/g,""),10):void 0;return{pageNum:n,totalPages:o?Math.max(1,Math.ceil(o/25)):1,url:location.href,itemsPerPage:25,totalItems:o}}getSearchResultHosts(){const e=Array.from(document.querySelectorAll(Hg)).filter(t=>this.looksLikeSearchResult(t));return Array.from(new Set(e))}looksLikeSearchResult(e){return e.closest('[class^="paperlens-"], [class*=" paperlens-"]')?!1:!!this.findArticleLink(e)||/Book chapter|ScienceDirect|DOI:|\/science\/article\/pii\//i.test(e.textContent??"")}parseSearchHost(e){const t=this.findArticleLink(e),n=this.cleanText(t?.textContent??e.querySelector('h2, h3, .result-list-title-link, .anchor, [class*="title"]')?.textContent??"");if(!n)return null;const a=this.toAbsoluteUrl(t?.getAttribute("href")??t?.href??""),i=this.extractNativeFullTextUrl(e),o=this.extractPii(a??"")??this.extractPii(i??"")??this.extractPiiFromAttributes(e)??this.extractPiiFromText(this.textWithoutExcludedDoiContexts(e)),s=this.extractIssnFromPii(o)??this.extractIssn(e),l=this.extractVenue(e),c=this.inferRecordKind(this.extractTypeText(e),l,o),u=this.normalizeVenue(l,s,c);return{title:n,journalName:u.journalName,journalCandidates:u.candidates,authors:this.extractAuthorsFromDom(e),year:this.extractYear(e),doi:this.extractDoi(e,{allowTextFallback:!1}),sourceId:o?`sciencedirect:${o}`:void 0,url:a,nativeFullTextUrl:i,abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:c.articleTypes,issn:s,source:this.id,citationType:c.citationType}}parseArticleMetadata(e){const t=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??this.firstJsonLdValue(p=>p.headline??p.name)??"").replace(/\s*\|\s*ScienceDirect\s*$/i,"");if(!t)return null;const n=this.toAbsoluteUrl(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??this.firstMetaContent(["citation_public_url","og:url"])??location.href),a=this.extractPii(n??location.href),i=this.extractIssnFromPii(a)??this.firstMetaContent(["citation_issn","prism.issn"])??this.firstJsonLdValue(p=>this.jsonLdIssn(p)),o=this.cleanVenue(this.firstMetaContent(["citation_journal_title","prism.publicationName"])??this.firstJsonLdValue(p=>p.isPartOf?.name)??""),s=[this.firstMetaContent(["citation_article_type","dc.type"]),this.firstJsonLdValue(p=>Array.isArray(p["@type"])?p["@type"].join(" "):p["@type"]),this.extractTypeText(e)].filter(Boolean).join(" "),l=this.inferRecordKind(s,o,a),c=this.normalizeVenue(o,i,l),u=this.extractMetadataPublicationDate(),d=this.extractAuthorsFromMetadata();return{title:t,journalName:c.journalName,journalCandidates:c.candidates,authors:d.length>0?d:this.extractAuthorsFromDom(e),year:this.yearFromText(u??"")??this.extractMetadataYear(),publicationDate:u,doi:this.extractMetadataDoi(),sourceId:a?`sciencedirect:${a}`:void 0,url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.firstMetaContent(["dc.description","description","citation_abstract"])??this.extractAbstract(e),hostElement:e,articleTypes:l.articleTypes,issn:i,volume:this.firstMetaContent(["citation_volume","prism.volume"])??void 0,issue:this.firstMetaContent(["citation_issue","prism.number"])??void 0,pages:this.extractMetadataPages(),source:this.id,citationType:l.citationType}}parseArticleDom(e){const t=this.cleanText(e.querySelector("h1, .title-text")?.textContent??document.title.replace(/\s*\|\s*ScienceDirect\s*$/i,""));if(!t)return null;const n=this.toAbsoluteUrl(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),a=this.extractPii(n??location.href),i=this.extractIssnFromPii(a)??this.extractIssn(e),o=this.extractVenue(e),s=this.inferRecordKind(this.extractTypeText(e),o,a),l=this.normalizeVenue(o,i,s);return{title:t,journalName:l.journalName,journalCandidates:l.candidates,authors:this.extractAuthorsFromDom(e),year:this.extractYear(e),doi:this.extractDoi(e),sourceId:a?`sciencedirect:${a}`:void 0,url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:s.articleTypes,issn:i,source:this.id,citationType:s.citationType}}inferRecordKind(e,t,n){const a=`${e} ${t} ${n??""}`;return/book chapter|chapter|book section|reference work|encyclopedia|\bB978/i.test(a)?{articleTypes:["BookChapter"],citationType:"incollection",metricsAllowed:!1}:/book\b/i.test(a)&&!/journal|article/i.test(a)?{articleTypes:["Book"],citationType:"book",metricsAllowed:!1}:{articleTypes:["JournalArticle"],citationType:"article",metricsAllowed:!0}}normalizeVenue(e,t,n){const a=this.cleanVenue(e),i=a?[a]:[];return/^the\s+lancet$/i.test(a)&&i.push("Lancet"),n.metricsAllowed?{journalName:a||(t?"":a),candidates:this.unique(i)}:{journalName:a,candidates:this.unique(i)}}findArticleLink(e){const t=Array.from(e.querySelectorAll('h2 a[href*="/science/article/"], h3 a[href*="/science/article/"], a.result-list-title-link[href], a.anchor[href]')),n=Array.from(e.querySelectorAll('a[href*="/science/article/"]'));return[...t,...n.filter(i=>!t.includes(i))].find(i=>/\/science\/article\//i.test(i.href)&&!/\/(?:pdfft|pdf)\b|\.pdf(?:[?#]|$)/i.test(i.getAttribute("href")??i.href??"")&&this.cleanText(i.textContent??"").length>0&&!/^(?:View article|Abstract|Summary|Recommended articles?)$/i.test(this.cleanText(i.textContent??"")))??null}extractVenue(e){const t=[".publication-title",".publication-volume",".srctitle",".source-title",".sourceTitle",".journal-title",".journalTitle",".result-list-source-title",'a[href*="/journal/"]','[data-aa-name*="publication"]','[data-aa-name*="source"]','[data-aa-name*="journal"]','[data-testid*="publication"]','[data-testid*="source"]','[data-testid*="journal"]','[class*="publication"]','[class*="source"]','[class*="journal"]'].join(",");for(const i of Array.from(e.querySelectorAll(t))){const o=this.cleanVenue(i.textContent??"");if(o&&!/^(Article|Book chapter|PDF|View|Download|Open access)$/i.test(o))return o}const a=this.cleanText(e.textContent??"").match(/(?:Journal|Published in|Source)\s*:?\s*([^|•]+?)(?:\s*[|•]\s*|\s+(?:Volume|Issue|Pages|Year|DOI)\b|$)/i);return a?this.cleanVenue(a[1]):""}extractTypeText(e){const t=[".subtype",".article-type",".content-type",'[data-testid*="subtype"]','[data-testid*="type"]','[class*="subtype"]','[class*="article-type"]','[class*="content-type"]'].join(",");return Array.from(e.querySelectorAll(t)).map(n=>this.cleanText(n.textContent??"")).filter(Boolean).join(" ")}cleanVenue(e){return this.cleanText(e).replace(/^In\s+/i,"").replace(/^Journal\s*:?\s*/i,"").replace(/^Source\s*:?\s*/i,"").replace(/^Published in\s*:?\s*/i,"").replace(/\b(?:Volume|Vol\.?|Issue|No\.?|Pages?|pp\.?)\b[\s\S]*$/i,"").replace(/\b((?:19|20)\d{2})\b[\s\S]*$/i,"").replace(/[,.;:\s]+$/g,"").trim()}extractAuthorsFromMetadata(){const e=this.allMetaContent(["citation_author"]);if(e.length>0)return this.unique(e.map(n=>this.cleanText(n)));const t=this.allMetaContent(["dc.creator"]);return t.length>0?this.unique(t.map(n=>this.cleanText(n))):this.unique(this.getJsonLdArticles().flatMap(n=>this.jsonLdAuthors(n)).map(n=>this.cleanText(n)).filter(Boolean))}extractAuthorsFromDom(e){const t=["[data-author-name]",".author-group .author",".Authors .author",'[class*="author-group"] .author','[class*="author-list"] .author','.author a[href*="/author/"]',".author span.author",'[class*="author-name"]',"[data-author-name]"].join(",");return this.unique(Array.from(e.querySelectorAll(t)).map(n=>this.cleanText(n.getAttribute("data-author-name")??n.textContent??"")).filter(n=>n&&!/^(?:Authors?|View|Show more|Corresponding author)$/i.test(n)&&!/^\d+$/.test(n)))}extractYear(e){const t=[".publication-year",".date",'[class*="year"]','[class*="date"]',"time"].join(",");for(const n of Array.from(e.querySelectorAll(t))){const a=this.yearFromText(n.textContent??"");if(a)return a}return this.yearFromText(e.textContent??"")}extractMetadataYear(){return this.yearFromText(this.firstMetaContent(["citation_publication_date","citation_online_date","prism.publicationDate","dc.date"])??this.firstJsonLdValue(e=>e.datePublished)??"")}extractMetadataDoi(){const e=this.allMetaContent(["citation_doi","prism.doi","dc.identifier","dc.identifier.doi"]);for(const t of e){const n=this.cleanDoi(t);if(n)return n}for(const t of this.getJsonLdArticles())for(const n of this.jsonLdIdentifiers(t)){const a=this.cleanDoi(n);if(a)return a}}extractMetadataPublicationDate(){return this.cleanText(this.firstMetaContent(["citation_publication_date","citation_online_date","prism.publicationDate","dc.date"])??this.firstJsonLdValue(t=>t.datePublished)??"")||void 0}extractMetadataPages(){const e=this.firstMetaContent(["citation_pages","prism.pageRange","citation_firstpage"])??"",t=this.firstMetaContent(["citation_lastpage"])??"";return e&&t&&e!==t&&!e.includes("-")?`${e}-${t}`:e||t||void 0}yearFromText(e){const t=e.match($g);return t?Number.parseInt(t[1],10):void 0}extractDoi(e,t={}){const n=t.allowTextFallback??!0;for(const i of Array.from(e.querySelectorAll('a[href*="doi.org/"]'))){if(this.isExcludedDoiContext(i))continue;const o=this.cleanDoi(i.href);if(o)return o}const a=this.extractLabeledDoi(this.textWithoutExcludedDoiContexts(e));if(a)return a;if(n)return this.cleanDoi(this.textWithoutExcludedDoiContexts(e))}cleanDoi(e){return e.match(jg)?.[0].replace(/[),.;\s]+$/g,"")}extractIssn(e){const t=this.firstMetaContent(["citation_issn","prism.issn"]);if(t)return this.normalizeIssn(t);const n=(e.textContent??"").match(Og);return n?this.normalizeIssn(n[0]):void 0}normalizeIssn(e){const t=e.trim().toUpperCase().replace(/[^0-9X]/g,"");if(/^\d{7}[\dX]$/.test(t))return`${t.slice(0,4)}-${t.slice(4)}`}extractNativeFullTextUrl(e){const t=this.firstMetaContent(["citation_pdf_url"]),n=this.toNativeFullTextUrl(t??"");if(n)return n;const a=this.unique(Array.from(e.querySelectorAll('a[href*="/pdfft"], a[href*="/science/article/pii/"][href*="pdf"], a[href$=".pdf"], a[href*="/pdf"]')).filter(o=>!this.isExcludedDoiContext(o)).map(o=>this.toNativeFullTextUrl(o.getAttribute("href")??o.href??"")??"").filter(Boolean));return a.length===0?void 0:a.length===1||this.unique(a.map(o=>this.nativeFullTextIdentity(o))).length===1?a[0]:void 0}extractAbstract(e){return this.cleanText(e.querySelector('.abstract, [class*="abstract"], .result-list-description')?.textContent??"")||void 0}findDetailTitle(e){const t=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??this.firstJsonLdValue(o=>o.headline??o.name)??document.title.replace(/\s*\|\s*ScienceDirect\s*$/i,"")),n=Array.from(e.querySelectorAll('h1, #screen-reader-main-title, .title-text, [data-testid*="title"]'));if(!t)return n[0]??null;const a=t.toLowerCase().replace(/[^a-z0-9]+/g,"");return n.find(o=>this.cleanText(o.textContent??"").toLowerCase().replace(/[^a-z0-9]+/g,"")===a)??n[0]??null}extractPii(e){return e.match(Ug)?.[1]?.replace(/[^\w-]/g,"")}extractPiiFromText(e){return e.match(/\b(?:PII|pii)\s*:?\s*([A-Z]\d{10,}[A-Z0-9]*)\b/)?.[1]}extractLabeledDoi(e){return e.match(/\bDOI\b\s*:?\s*(10\.\d{4,9}\/[-._;()/:A-Z0-9]+)/i)?.[1]?.replace(/[),.;\s]+$/g,"")}extractPiiFromAttributes(e){const t=[e,...Array.from(e.querySelectorAll("[data-pii], [data-article-pii], [data-source-id], [data-eid]"))];for(const n of t){const a=n.getAttribute("data-pii")??n.getAttribute("data-article-pii")??n.getAttribute("data-source-id")??n.getAttribute("data-eid")??"",i=this.extractPiiValue(a);if(i)return i}}extractPiiValue(e){return this.extractPii(e)??this.extractPiiFromText(e)??e.trim().match(/^[A-Z]\d{10,}[A-Z0-9]*$/i)?.[0]?.toUpperCase()}extractIssnFromPii(e){const t=e?.match(/^S(\d{4})(\d{3}[\dX])/i);if(!(!t?.[1]||!t?.[2]))return`${t[1]}-${t[2].toUpperCase()}`}firstMetaContent(e){return this.allMetaContent(e)[0]}allMetaContent(e){const t=[];for(const n of e){const a=[`meta[name="${n}"]`,`meta[property="${n}"]`,`meta[name="${n.toLowerCase()}"]`,`meta[property="${n.toLowerCase()}"]`].join(",");for(const i of Array.from(document.querySelectorAll(a))){const o=this.cleanText(i.getAttribute("content")??"");o&&t.push(o)}}return this.unique(t)}firstJsonLdValue(e){for(const t of this.getJsonLdArticles()){const n=this.cleanText(e(t)??"");if(n)return n}}getJsonLdArticles(){const e=[];for(const t of Array.from(document.querySelectorAll('script[type="application/ld+json"]')))try{const n=JSON.parse(t.textContent??""),a=Array.isArray(n)?n:[n,...n["@graph"]??[]];e.push(...a.filter(i=>this.isJsonLdArticle(i)))}catch{continue}return e}isJsonLdArticle(e){const t=Array.isArray(e["@type"])?e["@type"].join(" "):e["@type"]??"";return/Article|ScholarlyArticle|Chapter|CreativeWork/i.test(t)||!!e.headline}jsonLdAuthors(e){const t=e.author;return t?typeof t=="string"?[t]:Array.isArray(t)?t.map(n=>typeof n=="string"?n:n.name??"").filter(Boolean):t.name?[t.name]:[]:[]}jsonLdIssn(e){const t=e.isPartOf?.issn;return Array.isArray(t)?t[0]:t}jsonLdIdentifiers(e){const t=e.identifier;return t?typeof t=="string"?[t]:Array.isArray(t)?t.flatMap(n=>typeof n=="string"?[n]:[n.value??"",n.propertyID??""].filter(Boolean)):[]:[]}isExcludedDoiContext(e){return!!e.closest(Fu)}textWithoutExcludedDoiContexts(e){const t=e.cloneNode(!0);return t.querySelectorAll(Fu).forEach(n=>n.remove()),t.textContent??""}toNativeFullTextUrl(e){const t=this.toAbsoluteUrl(e);if(t)try{const n=new URL(t).hostname.toLowerCase();return n==="www.sciencedirect.com"||n==="sciencedirect.com"||n==="reader.elsevier.com"?t:void 0}catch{return}}nativeFullTextIdentity(e){const t=this.extractPii(e);if(t)return`pii:${t}`;try{const n=new URL(e);return`${n.origin}${n.pathname}`}catch{return e}}toAbsoluteUrl(e){const t=e.trim();if(!(!t||/^javascript:/i.test(t)||/^data:/i.test(t)))try{const n=new URL(t,location.origin);return/^https?:$/.test(n.protocol)?n.href:void 0}catch{return}}cleanText(e){return e.replace(/\s+/g," ").trim()}unique(e){return Array.from(new Set(e.filter(Boolean)))}}const Vg=/\b10\.\d{4,9}\/[-._;()/:A-Z0-9]+/i,Wg=/\b((?:19|20)\d{2})\b/,Lo=['li[data-test="search-result-item"]','article[data-test="search-result-item"]','[data-test="search-result-item"]',".app-card-open",".app-card-open[data-test]",".c-search-result-list__item"].join(","),Du=["article",".c-card"].join(","),Gg=["article","#main-content","main","body"].join(","),jn=['[id*="reference"]','[id*="Reference"]','[class*="reference"]','[class*="Reference"]','[id*="related"]','[id*="Related"]','[class*="related"]','[class*="Related"]','[id*="recommend"]','[id*="Recommend"]','[class*="recommend"]','[class*="Recommend"]','[data-test*="reference"]','[data-testid*="reference"]'].join(",");class Zg extends j{id="springerlink";name="SpringerLink";matches=["*://link.springer.com/*"];isSearchPage(){return location.pathname==="/search"||location.pathname.startsWith("/search/")}isArticlePage(){return/^\/(?:article|chapter|book|rwe|referenceworkentry)\//i.test(location.pathname)||!!this.firstMetaContent(["citation_title"])}parseSearchResults(){const e=[],t=new Set;for(const n of this.getSearchResultHosts())try{const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;if(t.has(i))continue;t.add(i),e.push(a)}catch(a){console.error("[SpringerLinkAdapter] Failed to parse search result:",a)}return e}parseArticlePage(){const e=document.querySelector(Gg);if(!e)return null;try{return this.parseMetadataArticle(e)??this.parseDetailDom(e)}catch(t){return console.error("[SpringerLinkAdapter] Failed to parse article page:",t),null}}getMetricBarAnchor(e){if(e.matches(Lo)||e.classList.contains("app-card-open")){const o=e.querySelector(".app-card-open__meta");if(o)return{element:o,position:"after"};const s=Array.from(e.querySelectorAll('[data-test="published"]')).find(c=>!c.closest('[data-test="title"]'));if(s)return{element:s,position:"after"};const l=e.querySelector('.app-card-open__authors, [data-test="authors-list"], [data-test="authors"]');if(l)return{element:l,position:"after"}}const n=this.findDetailCitationLine(e);if(n)return{element:n,position:"after"};const a=e.querySelector('[data-test="title"], h1, h2, h3, .app-card-open__heading, .c-article-title');if(a)return{element:a,position:"after"};const i=e.querySelector('[data-test="authors-list"], .app-card-open__authors, .app-article-masthead__journal-title');return i?{element:i,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector('[data-test="darwin-search"]')??document.querySelector('[data-test="results-data"]')??document.querySelector("main")??document.body}getPageInfo(){const e=new URLSearchParams(location.search),t=Number.parseInt(e.get("page")??"1",10)||1,n=this.cleanText(document.querySelector('[data-test="results-data-total"], .app-search-filter__result-count')?.textContent??""),a=n.match(/\b([\d,]+)\s*[-–]\s*([\d,]+)\s+of\s+([\d,]+)\s+results?\b/i),i=n.match(/\bof\s+([\d,]+)\s+results?\b/i),o=a?Number.parseInt(a[3].replace(/,/g,""),10):i?Number.parseInt(i[1].replace(/,/g,""),10):void 0,s=a?Math.max(1,Number.parseInt(a[2].replace(/,/g,""),10)-Number.parseInt(a[1].replace(/,/g,""),10)+1):20;return{pageNum:t,totalPages:o?Math.max(1,Math.ceil(o/s)):1,url:location.href,itemsPerPage:s,totalItems:o}}getSearchResultHosts(){const e=Array.from(document.querySelectorAll(Lo)).filter(t=>this.looksLikeSearchResult(t));return e.length>0?this.uniqueElements(e):this.uniqueElements(Array.from(document.querySelectorAll(Du)).filter(t=>this.looksLikeSearchResult(t)))}looksLikeSearchResult(e){return e.closest('[class^="paperlens-"], [class*=" paperlens-"]')||e.closest(jn)||e.matches(Du)&&e.parentElement?.closest(Lo)?!1:!!this.findTitleLink(e)}parseSearchHost(e){const t=this.findTitleLink(e),n=this.cleanText(t?.textContent??e.querySelector('[data-test="title"], h2, h3, [class*="heading"]')?.textContent??"");if(!n)return null;const a=this.toAbsoluteUrl(t?.getAttribute("href")??t?.href??""),i=this.cleanDoi(a??"")??this.extractDoi(e,{allowTextFallback:!1}),o=this.extractTypeText(e,t),s=this.extractVenue(e),l=this.inferRecordKind(o,a,s),c=this.extractPublicationDate(e);return{title:n,journalName:s,journalCandidates:s?[s]:[],authors:this.extractSearchAuthors(e),year:this.extractYear(e),publicationDate:c,doi:i,sourceId:i?`springer:${i}`:a?`springer:${new URL(a).pathname}`:void 0,url:a,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:l.articleTypes,source:this.id,citationType:l.citationType}}parseMetadataArticle(e){const t=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??"").replace(/\s*\|\s*Springer(?: Nature)? Link\s*$/i,"");if(!t)return null;const n=this.toAbsoluteUrl(this.firstMetaContent(["citation_fulltext_html_url","prism.url","og:url"])??document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),a=this.cleanDoi(this.firstMetaContent(["citation_doi","DOI","dc.identifier","prism.doi"])??n??""),i=this.firstMetaContent(["citation_article_type","dc.type"])??"",o=this.cleanVenue(this.firstMetaContent(["citation_journal_title","prism.publicationName","citation_inbook_title","citation_book_title"])??""),s=this.inferRecordKind(i,n,o),l=this.allMetaContent(["citation_author","dc.creator"]),c=this.firstMetaContent(["citation_publication_date","citation_online_date","prism.publicationDate","dc.date"]);return{title:t,journalName:o,journalCandidates:o?[o]:[],authors:l.length>0?l:this.extractDomAuthors(e),year:this.yearFromText(c??""),publicationDate:c??void 0,doi:a,sourceId:a?`springer:${a}`:n?`springer:${new URL(n).pathname}`:void 0,url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.firstMetaContent(["dc.description"])??this.extractAbstract(e),hostElement:e,articleTypes:s.articleTypes,issn:this.normalizeIssn(this.firstMetaContent(["citation_issn","prism.issn"])??""),volume:this.firstMetaContent(["citation_volume","prism.volume"])??void 0,issue:this.firstMetaContent(["citation_issue","prism.number"])??void 0,pages:this.extractMetaPages(),source:this.id,citationType:s.citationType}}parseDetailDom(e){const t=this.cleanText(e.querySelector('h1, [data-test="title"]')?.textContent??document.title.replace(/\s*\|\s*Springer(?: Nature)? Link\s*$/i,""));if(!t)return null;const n=this.toAbsoluteUrl(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),a=this.cleanDoi(n??"")??this.extractDoi(e,{allowTextFallback:!1}),i=this.extractTypeText(e),o=this.extractVenue(e),s=this.inferRecordKind(i,n,o),l=this.extractPublicationDate(e);return{title:t,journalName:o,journalCandidates:o?[o]:[],authors:this.extractDomAuthors(e),year:this.extractYear(e),publicationDate:l,doi:a,sourceId:a?`springer:${a}`:n?`springer:${new URL(n).pathname}`:void 0,url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:s.articleTypes,source:this.id,citationType:s.citationType}}inferRecordKind(e,t,n){const a=`${e} ${t??""} ${n}`;return/conference paper|conference proceedings/i.test(a)?{articleTypes:["Conference"],citationType:"inproceedings",metricsAllowed:!1}:/\/(?:chapter|rwe|referenceworkentry)\//i.test(a)||/chapter|reference work entry|referenceworkentry/i.test(a)?{articleTypes:["BookChapter"],citationType:"incollection",metricsAllowed:!1}:/\/book\//i.test(a)||/\bbook\b|textbook|reference work/i.test(a)?{articleTypes:["Book"],citationType:"book",metricsAllowed:!1}:{articleTypes:["JournalArticle"],citationType:"article",metricsAllowed:!0}}findDetailCitationLine(e){if(this.isSearchPage())return null;const t=e.querySelector(".c-article-identifiers.c-article-identifiers--cite-list, .c-article-identifiers--cite-list");if(t&&!t.closest(jn)&&this.cleanText(t.textContent??""))return t;const n=e.querySelector('[data-test="journal-volume"]');if(n){const a=n.closest("li, div, p, section, ul, ol")??n;if(!a.closest(jn))return a}for(const a of[".c-article-identifiers__item",".c-bibliographic-information__list-item",".app-article-masthead__meta li",".app-article-masthead__meta div"])for(const i of Array.from(e.querySelectorAll(a))){if(i.closest(jn))continue;const o=this.cleanText(i.textContent??"");if(o&&/\b(?:volume|vol\.?|issue|article\s+number|pages?|pp\.?)\b/i.test(o))return i}return null}findTitleLink(e){return Array.from(e.querySelectorAll('[data-test="title"] a[href], a.app-card-open__link[href], a[data-test="title-link"][href], h2 a[href], h3 a[href], a[href*="/article/"], a[href*="/chapter/"], a[href*="/book/"], a[href*="/rwe/"], a[href*="/referenceworkentry/"]')).find(n=>this.cleanText(n.textContent??"").length>0)??null}extractTypeText(e,t){return[...Array.from(e.querySelectorAll('[data-test="content-type"], .c-meta__type')).map(a=>this.cleanText(a.textContent??"")),t?.getAttribute("data-track-action")??""].filter(Boolean).join(" ")}extractVenue(e){const t=e.querySelector('[data-test="parent"]');if(t)return this.cleanVenue(t.textContent??"");const n=e.querySelector('.app-card-open__authors a[href*="/journal/"], .app-card-open__authors a[href*="/book/"], .app-card-open__authors a[href*="/referencework"], .app-card-open__context a[href*="/journal/"], .app-card-open__context a[href*="/book/"], .app-card-open__context a[href*="/referencework"]');if(n){const s=this.cleanVenue(n.textContent??"");if(this.looksLikeVenue(s))return s}const a=this.extractVenueFromInlineContext(e);if(a)return a;const i=e.querySelector('[data-test="journal-title"], [data-testid="journal-title"], .app-card-open__context a[href*="/journal/"], .app-card-open__context, .c-search-result-list__item-meta');if(i){const s=this.cleanVenue(i.textContent??"");if(this.looksLikeVenue(s))return s}const o=e.querySelector(".app-article-masthead__journal-title");return o?this.cleanVenue(o.textContent??""):this.cleanVenue(this.firstMetaContent(["citation_journal_title","prism.publicationName","citation_inbook_title","citation_book_title"])??"")}extractSearchAuthors(e){const t=this.cleanText(e.querySelector('[data-test="authors"]')?.textContent??"");return t?this.unique(t.replace(/\s+in\s+.*$/i,"").split(/,|;|\band\b/i).map(n=>this.cleanText(n)).filter(n=>n&&n!=="...")):[]}extractDomAuthors(e){return this.unique(Array.from(e.querySelectorAll('[data-test="author-name"], .c-article-author-list__item a[data-author-search]')).map(t=>this.cleanText(t.getAttribute("data-author-search")??t.textContent??"")).filter(Boolean))}extractYear(e){for(const t of Array.from(e.querySelectorAll('[data-test="published"], time, [class*="date"], [class*="year"]'))){const n=this.yearFromText(t.textContent??"");if(n)return n}return this.yearFromText(e.textContent??"")}extractPublicationDate(e){return this.cleanText(e.querySelector('[data-test="published"], time, [class*="date"], [class*="year"]')?.textContent??"").replace(/^Published:\s*/i,"")||void 0}extractDoi(e,t={}){const n=t.allowTextFallback??!0;for(const a of Array.from(e.querySelectorAll('a[href*="doi.org/"], a[href*="/article/10."], a[href*="/chapter/10."]'))){if(this.isExcludedDoiContext(a))continue;const i=this.cleanDoi(a.href);if(i)return i}for(const a of Array.from(e.querySelectorAll(this.getDoiTextSelector()))){if(this.isExcludedDoiContext(a))continue;const i=this.cleanDoi(a.textContent??"");if(i)return i}if(n)return this.cleanDoi(this.textWithoutExcludedDoiContexts(e))}extractNativeFullTextUrl(e){const t=this.toNativeFullTextUrl(this.firstMetaContent(["citation_pdf_url"])??"");if(t)return t;const n=e.querySelector('a[data-test="pdf-link"], a[data-article-pdf="true"], a[href*="/content/pdf/"], a[href$=".pdf"]');return this.toNativeFullTextUrl(n?.getAttribute("href")??n?.href??"")??void 0}extractAbstract(e){return this.cleanText(e.querySelector('[data-test="description"], .c-article-section__content, .c-article-body__content')?.textContent??"")||void 0}firstMetaContent(e){return this.allMetaContent(e)[0]}allMetaContent(e){const t=[];for(const n of e){const a=[`meta[name="${n}"]`,`meta[property="${n}"]`,`meta[name="${n.toLowerCase()}"]`,`meta[property="${n.toLowerCase()}"]`].join(",");for(const i of Array.from(document.querySelectorAll(a))){const o=this.cleanText(i.getAttribute("content")??"");o&&t.push(o)}}return this.unique(t)}cleanDoi(e){return e.match(Vg)?.[0].replace(/[),.;\s]+$/g,"")}yearFromText(e){const t=e.match(Wg);return t?Number.parseInt(t[1],10):void 0}normalizeIssn(e){const t=e.trim().toUpperCase().replace(/[^0-9X]/g,"");if(/^\d{7}[\dX]$/.test(t))return`${t.slice(0,4)}-${t.slice(4)}`}isExcludedDoiContext(e){return!!e.closest(jn)}getDoiTextSelector(){return['[data-test="doi"]','[data-testid="doi"]','[data-test*="doi"]','[data-testid*="doi"]','[id*="doi"]','[class*="doi"]',".c-bibliographic-information__list-item",".c-article-identifiers__item"].join(",")}textWithoutExcludedDoiContexts(e){const t=e.cloneNode(!0);return t.querySelectorAll(jn).forEach(n=>n.remove()),t.textContent??""}toNativeFullTextUrl(e){const t=this.toAbsoluteUrl(e);if(t)try{const n=new URL(t),a=n.hostname.toLowerCase();return n.protocol!=="https:"?void 0:a==="link.springer.com"||a.endsWith(".link.springer.com")||a==="media.springernature.com"?t:void 0}catch{return}}cleanVenue(e){return this.cleanText(e).replace(/^in\s+/i,"").replace(/\s*[•·|]\s*(?:Open Access|Published|Article|Chapter|PDF)\b[\s\S]*$/i,"").replace(/\b(?:Volume|Vol\.?|Issue|No\.?|Pages?|pp\.?)\b[\s\S]*$/i,"").replace(/\b((?:19|20)\d{2})\b[\s\S]*$/i,"").replace(/^Published:\s*/i,"").replace(/[,.;:\s]+$/g,"").trim()}extractMetaPages(){const e=this.firstMetaContent(["citation_pages","prism.pageRange","citation_firstpage"]),t=this.firstMetaContent(["citation_lastpage"]);if(e&&t&&e!==t&&!e.includes("-"))return`${e}-${t}`;if(e)return e;if(t)return t}extractVenueFromInlineContext(e){const t=Array.from(e.querySelectorAll(".app-card-open__authors, .app-card-open__context"));for(const n of t){const a=this.cleanText(n.textContent??"");if(!a)continue;const i=a.match(/\bin\s+(.+)$/i);if(!i?.[1])continue;const o=this.cleanVenue(i[1]);if(this.looksLikeVenue(o))return o}}looksLikeVenue(e){return!!(e&&!/^(?:Article|Chapter|Open Access|Published|PDF)$/i.test(e)&&!/^(?:Article|Chapter|Open Access|Published|PDF)\b/i.test(e)&&!/^(?:Authors?|By)\b/i.test(e))}toAbsoluteUrl(e){const t=e.trim();if(!(!t||/^javascript:/i.test(t)||/^data:/i.test(t)))try{const n=new URL(t,location.origin);return/^https?:$/.test(n.protocol)?n.href:void 0}catch{return}}cleanText(e){return e.replace(/\s+/g," ").trim()}unique(e){return Array.from(new Set(e.filter(Boolean)))}uniqueElements(e){return Array.from(new Set(e))}}const Yg=/\b10\.\d{4,9}\/[^\s"'<>?#]+/i,Kg=/\b((?:19|20)\d{2})\b/;function m(r){return(r??"").replace(/\s+/g," ").trim()}function F(r,e=document){for(const t of r){const n=_u(t),a=e.querySelector(`meta[name="${n}"], meta[property="${n}"]`)?.getAttribute("content"),i=m(a);if(i)return i}}function Je(r,e=document){const t=_u(r);return U(Array.from(e.querySelectorAll(`meta[name="${t}"], meta[property="${t}"]`)).map(n=>m(n.getAttribute("content"))).filter(Boolean))}function B(r){const e=m(r);if(e)try{return new URL(e,location.href).toString()}catch{return}}function Ne(r){const t=m(r).replace(/^doi:\s*/i,"").replace(/^https?:\/\/(?:dx\.)?doi\.org\//i,"").replace(/[),.;\]]+$/g,"").match(Yg);return t?t[0].replace(/[),.;\]]+$/g,""):void 0}function Z(r){return Ne(r)}function qe(r){const e=m(r).match(Kg);return e?Number.parseInt(e[1],10):void 0}function U(r){return Array.from(new Set(r.filter(Boolean)))}const Qg=['[data-test="article-description"]','[data-testid*="abstract"]','[data-test*="abstract"]',"[data-abstract-type]",".hlFld-Abstract",".abstract",".summary",".snippet",'[class*="abstract"]','[class*="Abstract"]','[class*="summary"]','[class*="Summary"]',".c-article-section__content",'[id*="abstract"]','[id*="Abstract"]','section[id*="abstract"]','div[id*="abstract"]',".search-result__body"].join(",");function je(r,e=Qg){const t=new WeakMap,n=Xg(r,t);if(n)return n;for(const a of Array.from(r.querySelectorAll(e))){if(!Bo(a,t))continue;const i=Ro(a.textContent);if(Po(i))return i}}function $n(){return B(document.querySelector('link[rel="canonical"]')?.getAttribute("href"))??B(F(["citation_public_url","citation_fulltext_html_url","og:url"]))??location.href}function le(){const r=m(document.title);return/just a moment|请稍候|请稍后|enable javascript and cookies|checking your browser|bot manager captcha|captcha/i.test(r)||!!document.querySelector(['script[src*="challenge-platform"]','script[src*="perfdrive.com"]','iframe[src*="challenges.cloudflare.com"]'].join(","))}function _u(r){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/["\\]/g,"\\$&")}function Xg(r,e){for(const t of Array.from(r.querySelectorAll('h2, h3, h4, [role="heading"]'))){if(!Bo(t,e)||!/^abstract\b/i.test(m(t.textContent)))continue;const n=ku(t.nextElementSibling,e);if(n)return n;const a=ku(t.parentElement?.nextElementSibling??null,e);if(a)return a;const i=t.closest("section, div");if(i&&i!==r){const o=Ro(i.textContent);if(Po(o))return o}}}function ku(r,e){const t=[];let n=r;for(;n&&!ey(n);){if(n instanceof HTMLElement&&!Bo(n,e)){n=n.nextElementSibling;continue}const a=Ro(n.textContent);Po(a)&&t.push(a),n=n.nextElementSibling}return t.length?m(t.join(" ")):void 0}function ey(r){const e=m(r.textContent),t=r.matches('h1, h2, h3, h4, [role="heading"]')?e:"",n=m(r.querySelector(':scope > h1, :scope > h2, :scope > h3, :scope > h4, :scope > [role="heading"]')?.textContent),a=t||n;if(a&&!/^abstract\b/i.test(a))return!0;const i=m([r.id,r.className,r.getAttribute("role"),r.getAttribute("aria-label"),r.getAttribute("data-test"),r.getAttribute("data-testid")].join(" "));return/\b(?:introduction|materials?|methods?|results?|discussion|references?|bibliography|acknowledg|supplement|figures?|tables?|metrics?|citations?|related)\b/i.test(i)}function Ro(r){return m(r).replace(/^abstract\s*/i,"").replace(/^summary\s*/i,"").trim()}function Po(r){return r.length>=12&&!/^(?:abstract|summary|figures?|tables?|references?|metrics?|citations?|related|authors?|article)(?:\s+(?:figures?|tables?|references?|metrics?|citations?|related|authors?|article))*$/i.test(r)}function Bo(r,e){const t=e.get(r);if(t!==void 0)return t;let n=r;for(;n&&n!==document.body;){if(n.hidden||n.getAttribute("aria-hidden")==="true")return e.set(r,!1),!1;const a=n.getAttribute("style")??"";if(/display\s*:\s*none|visibility\s*:\s*hidden|opacity\s*:\s*0(?:[;\s]|$)|clip\s*:\s*rect\(\s*0/i.test(a))return e.set(r,!1),!1;const i=typeof window<"u"&&typeof window.getComputedStyle=="function"?window.getComputedStyle(n):null;if(i&&(i.display==="none"||i.visibility==="hidden"||i.opacity==="0"))return e.set(r,!1),!1;n=n.parentElement}return e.set(r,!0),!0}const ty=/\b10\.\d{4,9}\/[^\s"'<>]+/i,ny=/\b((?:19|20)\d{2})\b/,Nu=["li.search__item",".search__item",".search-result",".search-result__item"].join(","),ry=["article","#main-content","main","body"].join(","),Io=['[id*="reference"]','[id*="Reference"]','[class*="reference"]','[class*="Reference"]','[role="doc-bibliography"]','section[aria-label*="Reference"]','section[aria-labelledby*="reference"]',".article-section__references",".references-section",'[id*="related"]','[id*="Related"]','[class*="related"]','[class*="Related"]','[id*="recommend"]','[id*="Recommend"]','[class*="recommend"]','[class*="Recommend"]','[data-test*="reference"]','[data-testid*="reference"]'].join(",");class ay extends j{id="wiley";name="Wiley Online Library";matches=["*://onlinelibrary.wiley.com/*","*://*.onlinelibrary.wiley.com/*"];isSearchPage(){return this.isChallengePage()?!1:location.pathname==="/action/doSearch"||location.pathname.startsWith("/action/doSearch")||new URLSearchParams(location.search).has("AllField")}isArticlePage(){return this.isChallengePage()?!1:/^\/doi\/(?:abs|full|pdf|epdf|book)?\/?10\./i.test(location.pathname)||!!this.firstMetaContent(["citation_title"])}parseSearchResults(){const e=[],t=new Set;for(const n of this.getSearchResultHosts())try{const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;if(t.has(i))continue;t.add(i),e.push(a)}catch(a){console.error("[WileyAdapter] Failed to parse search result:",a)}return e}parseArticlePage(){const e=document.querySelector(ry);if(!e)return null;try{return this.parseMetadataArticle(e)??this.parseDetailDom(e)}catch(t){return console.error("[WileyAdapter] Failed to parse article page:",t),null}}getMetricBarAnchor(e){if(e.matches(Nu)){const a=e.querySelector('.publication_meta, .search-result__meta, .search-result__info, .meta__citation, .meta__source, .journal-title, .source-title, .publication-year, time, [data-testid*="meta"], [data-testid*="citation"]');if(a)return{element:a,position:"after"};const i=e.querySelector('.authors, .citation__authors, .meta__authors, [class*="authors"]');if(i)return{element:i,position:"after"}}const t=e.querySelector('.citation__authors, .meta__authors, .publication_meta, [class*="authors"], [class*="meta"]');if(this.isArticlePage()&&t)return{element:t,position:"after"};const n=e.querySelector('h1, h2, h3, .citation__title, .hlFld-Title, .publication_title a, [class*="title"]');return n?{element:n,position:"after"}:t?{element:t,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector(".search-result__body")??document.querySelector(".search-results")??document.querySelector('[data-testid*="search"]')??document.querySelector("main")??document.body}getPageInfo(){const e=new URLSearchParams(location.search),t=Number.parseInt(e.get("startPage")??e.get("page")??"0",10),n=Number.isFinite(t)?t+1:1,i=this.cleanText(document.querySelector('.result__count, .search-result__count, [class*="result-count"], [data-testid*="result-count"]')?.textContent??"").match(/\b([\d,]+)\s+results?\b/i),o=i?Number.parseInt(i[1].replace(/,/g,""),10):void 0;return{pageNum:n,totalPages:o?Math.max(1,Math.ceil(o/20)):1,url:location.href,itemsPerPage:20,totalItems:o}}getSearchResultHosts(){return this.isChallengePage()?[]:this.uniqueElements(Array.from(document.querySelectorAll(Nu)).filter(e=>this.looksLikeSearchResult(e)))}looksLikeSearchResult(e){return e.closest('[class^="paperlens-"], [class*=" paperlens-"]')||e.closest(Io)?!1:!!this.findTitleLink(e)}parseSearchHost(e){const t=this.findTitleLink(e),n=this.cleanText(t?.textContent??e.querySelector('h2, h3, .publication_title, .search-result__title, [class*="title"]')?.textContent??"");if(!n)return null;const a=this.toArticleUrl(t?.getAttribute("href")??t?.href??""),i=this.cleanDoi(a??"")??this.extractDoi(e,{allowTextFallback:!1}),o=this.extractTypeText(e),s=this.extractVenue(e),l=this.inferRecordKind(o,a,"",i);return{title:n,journalName:s,journalCandidates:s?this.journalCandidates(s):[],authors:this.extractAuthorsFromDom(e),year:this.extractYear(e),doi:i,sourceId:i?`wiley:${i}`:a?`wiley:${new URL(a).pathname}`:void 0,url:a,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:l.articleTypes,source:this.id,citationType:l.citationType}}parseMetadataArticle(e){const t=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??"").replace(/\s*\|\s*Wiley Online Library\s*$/i,"");if(!t)return null;const n=this.toArticleUrl(this.firstMetaContent(["citation_public_url","citation_fulltext_html_url","prism.url","og:url"])??document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),a=this.firstDoi([...this.allMetaContent(["citation_doi","dc.identifier","prism.doi"]),n??""]),i=this.firstMetaContent(["citation_inbook_title","citation_book_title"])??"",o=this.cleanVenue(this.firstMetaContent(["citation_journal_title","prism.publicationName"])??i??""),s=this.firstMetaContent(["citation_article_type","dc.type"])??"",l=this.inferRecordKind(s,n,i,a);return{title:t,journalName:o,journalCandidates:o?this.journalCandidates(o):[],authors:this.allMetaContent(["citation_author","dc.creator"]),year:this.yearFromText(this.firstMetaContent(["citation_publication_date","citation_online_date","prism.publicationDate","dc.date"])??""),doi:a,sourceId:a?`wiley:${a}`:n?`wiley:${new URL(n).pathname}`:void 0,url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.firstMetaContent(["citation_abstract","dc.description","description","og:description"])??this.extractAbstract(e),hostElement:e,articleTypes:l.articleTypes,issn:this.normalizeIssn(this.firstMetaContent(["citation_issn","prism.issn"])??""),source:this.id,citationType:l.citationType}}parseDetailDom(e){const t=this.cleanText(e.querySelector("h1, .citation__title, .hlFld-Title")?.textContent??document.title.replace(/\s*\|\s*Wiley Online Library\s*$/i,""));if(!t)return null;const n=this.toArticleUrl(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),a=this.cleanDoi(n??"")??this.extractDoi(e,{allowTextFallback:!1}),i=this.extractVenue(e),o=this.inferRecordKind(this.extractTypeText(e),n,"",a);return{title:t,journalName:i,journalCandidates:i?this.journalCandidates(i):[],authors:this.extractAuthorsFromDom(e),year:this.extractYear(e),doi:a,sourceId:a?`wiley:${a}`:n?`wiley:${new URL(n).pathname}`:void 0,url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:o.articleTypes,source:this.id,citationType:o.citationType}}inferRecordKind(e,t,n="",a=""){const i=`${e} ${t??""} ${n}`;return/conference paper|conference proceeding/i.test(i)?{articleTypes:["Conference"],citationType:"inproceedings",metricsAllowed:!1}:/\/doi\/book\//i.test(t??"")&&!this.isChapterDoi(a)&&!/chapter|book section/i.test(e)?{articleTypes:["Book"],citationType:"book",metricsAllowed:!1}:/book chapter|chapter|book section|citation_inbook_title|citation_book_title/i.test(i)||this.cleanText(n).length>0?{articleTypes:["BookChapter"],citationType:"incollection",metricsAllowed:!1}:/\bbook\b/i.test(i)&&!/journal|article/i.test(i)?{articleTypes:["Book"],citationType:"book",metricsAllowed:!1}:{articleTypes:["JournalArticle"],citationType:"article",metricsAllowed:!0}}findTitleLink(e){return Array.from(e.querySelectorAll('h2 a[href], h3 a[href], .publication_title a[href], .search-result__title a[href], a[href*="/doi/10."], a[href*="/doi/abs/10."], a[href*="/doi/full/10."]')).find(n=>this.isArticleLink(n)&&this.cleanText(n.textContent??"").length>0)??null}extractVenue(e){const t=[".publication_meta .journal",".publication_meta a[href]",".journal-title",".meta__journal",".meta__source",".citation__journal-title",".publication_meta",".search-result__meta",".search-result__info",".meta__citation",'[data-testid*="journal"]','[data-testid*="citation"]','[data-testid*="meta"]',".source-title",".meta__source"].join(",");for(const n of Array.from(e.querySelectorAll(t))){if(n instanceof HTMLAnchorElement&&/\/doi\/|doi\.org\//i.test(n.getAttribute("href")??""))continue;const a=this.cleanVenue(n.textContent??"");if(this.isLikelyVenueText(a))return a}for(const n of Array.from(e.querySelectorAll('.publication_meta, .search-result__meta, .search-result__info, .meta__citation, .meta__source, [data-testid*="citation"], [data-testid*="meta"], [class*="citation"], [class*="meta"], [class*="source"]'))){const a=this.extractVenueFromMetadataText(n.textContent??"");if(a)return a}return this.cleanVenue(this.firstMetaContent(["citation_journal_title","prism.publicationName","citation_inbook_title","citation_book_title"])??"")}extractTypeText(e){const t=[".publication-type",".content-type",".issue-item__type",'[data-testid*="type"]','[class*="type"]'].join(",");return Array.from(e.querySelectorAll(t)).map(n=>this.cleanText(n.textContent??"")).filter(Boolean).join(" ")}extractAuthorsFromDom(e){const t=[".author-name",".loa__author-name",".citation__author",".authors a",".authors span",'[class*="author"] a','[class*="author"] span',"[data-author-name]"].join(",");return this.unique(Array.from(e.querySelectorAll(t)).map(n=>this.cleanText(n.getAttribute("data-author-name")??n.textContent??"")).filter(n=>n&&!/^(Authors?|View|Show more)$/i.test(n)))}extractYear(e){for(const t of Array.from(e.querySelectorAll('time, .publication-year, .date, [class*="year"], [class*="date"]'))){const n=this.yearFromText(t.textContent??"");if(n)return n}return this.yearFromText(e.textContent??"")}extractDoi(e,t={}){const n=t.allowTextFallback??!0;for(const a of Array.from(e.querySelectorAll('a[href*="doi.org/"], a[href*="/doi/10."]'))){if(this.isExcludedDoiContext(a))continue;const i=this.cleanDoi(a.href);if(i)return i}for(const a of Array.from(e.querySelectorAll('[data-test*="doi"], [data-testid*="doi"], [id*="doi"], [class*="doi"], .epub-doi'))){if(this.isExcludedDoiContext(a))continue;const i=this.cleanDoi(a.textContent??"");if(i)return i}if(n)return this.cleanDoi(this.textWithoutExcludedDoiContexts(e))}extractNativeFullTextUrl(e){const t=this.toNativeFullTextUrl(this.firstMetaContent(["citation_pdf_url"])??"");if(t)return t;const n=e.querySelector('a[href*="/doi/pdf/"], a[href*="/doi/epdf/"], a[href$=".pdf"], a[href*="/pdf"]');return this.toNativeFullTextUrl(n?.getAttribute("href")??n?.href??"")??void 0}extractAbstract(e){return je(e)}firstMetaContent(e){return this.allMetaContent(e)[0]}allMetaContent(e){const t=[];for(const n of e){const a=[`meta[name="${n}"]`,`meta[property="${n}"]`,`meta[name="${n.toLowerCase()}"]`,`meta[property="${n.toLowerCase()}"]`].join(",");for(const i of Array.from(document.querySelectorAll(a))){const o=this.cleanText(i.getAttribute("content")??"");o&&t.push(o)}}return this.unique(t)}journalCandidates(e){const t=[e];return/^CA:\s*A Cancer Journal for Clinicians$/i.test(e)&&t.push("CA-A Cancer Journal for Clinicians"),this.unique(t)}cleanDoi(e){return this.decodeDoiSource(e).match(ty)?.[0].replace(/[),.;\s]+$/g,"")}yearFromText(e){const t=e.match(ny);return t?Number.parseInt(t[1],10):void 0}normalizeIssn(e){const t=e.trim().toUpperCase().replace(/[^0-9X]/g,"");if(/^\d{7}[\dX]$/.test(t))return`${t.slice(0,4)}-${t.slice(4)}`}isExcludedDoiContext(e){return!!e.closest(Io)||!!Array.from(e.parentElement?.children??[]).some(t=>/^References?$/i.test(this.cleanText(t.textContent??"")))}isChallengePage(){const e=document.title;return/Just a moment|Enable JavaScript and cookies|Access denied/i.test(e)||document.querySelector('.cf-turnstile, iframe[src*="challenges.cloudflare.com"], script[src*="/cdn-cgi/challenge-platform/"]')?!0:/Enable JavaScript and cookies to continue|Checking if the site connection is secure/i.test(document.body?.textContent??"")}isChapterDoi(e){return/\b(?:\.ch\d+|_chap\d+|\.chapter\d+)$/i.test(e??"")}decodeDoiSource(e){try{return decodeURIComponent(e)}catch{return e}}textWithoutExcludedDoiContexts(e){const t=e.cloneNode(!0);return t.querySelectorAll(Io).forEach(n=>n.remove()),t.textContent??""}firstDoi(e){for(const t of e){const n=this.cleanDoi(t);if(n)return n}}isArticleLink(e){try{const t=new URL(e.getAttribute("href")??e.href,location.origin);return/^\/doi\/(?:abs\/|full\/|pdf\/|epdf\/|book\/)?10\./i.test(t.pathname)||/^\/doi\/(?:abs\/|full\/)?no-visible-doi$/i.test(t.pathname)}catch{return!1}}toNativeFullTextUrl(e){const t=this.toAbsoluteUrl(e);if(t)try{const n=new URL(t),a=n.hostname.toLowerCase();if(n.protocol!=="https:")return;const i=a==="onlinelibrary.wiley.com"||a.endsWith(".onlinelibrary.wiley.com"),o=/^\/doi\/(?:pdf|epdf)\//i.test(n.pathname);return i&&o?t:void 0}catch{return}}toArticleUrl(e){const t=this.toAbsoluteUrl(e);if(t)try{const n=new URL(t);return n.searchParams.delete("af"),n.searchParams.delete("campaign"),n.href}catch{return t}}cleanVenue(e){return this.cleanText(e).replace(/^In\s+/i,"").replace(/^(?:Published in|Publication|Source)\s*:?\s*/i,"").replace(/^Journal\s*:?\s*/i,"").replace(/\s*(?:[•·|]|,\s+)(?:Wiley Online Library|Published online|First published)\b[\s\S]*$/i,"").replace(/\s+[•·|]\s*doi:\s*10\.\S+[\s\S]*$/i,"").replace(/\s*\bdoi:\s*10\.\S+[\s\S]*$/i,"").replace(/\b(?:Volume|Vol\.?|Issue|No\.?|Pages?|pp\.?)\b[\s\S]*$/i,"").replace(/\b((?:19|20)\d{2})\b[\s\S]*$/i,"").replace(/[,.;:\s]+$/g,"").trim()}isLikelyVenueText(e){return!e||/^(?:Article|Chapter|PDF|Full text|Research Article)$/i.test(e)||/^(?:Wiley Online Library|Published online|First published)$/i.test(e)||/\b(?:published online|first published|volume|issue|research article)\b/i.test(e)?!1:!/^\d{4}$/.test(e)}extractVenueFromMetadataText(e){const t=this.cleanText(e);if(!t)return"";const n=t.replace(/\s*\bdoi:\s*10\.\S+[\s\S]*$/i,"").replace(/\s*\(?10\.\d{4,9}\/[^\s)]+[\s\S]*$/i,"").replace(/\s*[•·|]\s*/g," \u2022 ").trim(),a=[n,n.replace(/\s*[•·]\s*Wiley Online Library\b[\s\S]*$/i,"").trim(),n.replace(/,\s*(?:19|20)\d{2}\b[\s\S]*$/i,"").trim(),n.split("\u2022")[0]?.trim()??""];for(const i of a){const o=this.cleanVenue(i);if(this.isLikelyVenueText(o))return o}return""}toAbsoluteUrl(e){const t=e.trim();if(!(!t||/^javascript:/i.test(t)||/^data:/i.test(t)))try{const n=new URL(t,location.origin);return/^https?:$/.test(n.protocol)?n.href:void 0}catch{return}}cleanText(e){return e.replace(/\s+/g," ").trim()}unique(e){return Array.from(new Set(e.filter(Boolean)))}uniqueElements(e){return Array.from(new Set(e))}}const iy=/\b10\.\d{4,9}\/[^\s"'?#]+/i,oy=/\b((?:19|20)\d{2})\b/,ln=["li.search__item",".search__item",".search-result__item",".resultItem",".search-result-card",'[data-testid*="searchResultItem"]','[data-testid*="search-result"]'].join(","),sy=[ln,".art_title",".hlFld-Title",".publication_title"].join(","),Mo=[".search-results",".searchResultList",'[aria-label="Search results"]',".results-shell"].join(","),ly=[Mo,'[data-testid*="search"]','[data-test*="search"]'].join(","),cy=["#main-content article","main article","#main-content","main","article","body"],qo=['[id*="reference"]','[id*="Reference"]','[class*="reference"]','[class*="Reference"]','[class*="ref-list"]','[class*="refList"]','[class*="references-list"]','[role="doc-bibliography"]','section[aria-label*="Reference"]','section[aria-label*="reference"]','section[aria-labelledby*="Reference"]','section[aria-labelledby*="reference"]','[id*="related"]','[id*="Related"]','[class*="related"]','[class*="Related"]','[id*="recommend"]','[id*="Recommend"]','[class*="recommend"]','[class*="Recommend"]','[id*="cited"]','[class*="cited"]','[data-test*="reference"]','[data-testid*="reference"]'].join(",");class uy extends j{id="taylor-francis";name="Taylor & Francis Online";matches=["*://www.tandfonline.com/*"];isSearchPage(){return this.isChallengePage()?!1:location.pathname==="/action/doSearch"||location.pathname.startsWith("/action/doSearch")||new URLSearchParams(location.search).has("AllField")}isArticlePage(){return this.isChallengePage()?!1:/^\/doi\/(?:abs|full|pdf|epdf|book)?\/?10\./i.test(location.pathname)||!!this.firstMetaContent(["citation_title"])}parseSearchResults(){const e=[],t=new Set;for(const n of this.getSearchResultHosts())try{const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;if(t.has(i))continue;t.add(i),e.push(a)}catch(a){console.error("[TaylorFrancisAdapter] Failed to parse search result:",a)}return e}parseArticlePage(){if(this.isChallengePage())return null;const e=this.getDetailHostElement();if(!e)return null;try{return this.parseMetadataArticle(e)??this.parseDetailDom(e)}catch(t){return console.error("[TaylorFrancisAdapter] Failed to parse article page:",t),null}}getMetricBarAnchor(e){const t=e.querySelector('.citation__authors, .publication_meta, [class*="authors"], [class*="meta"]');if(this.isArticlePage()&&t)return{element:t,position:"after"};const n=e.querySelector('h1, h2, h3, .citation__title, .hlFld-Title, .art_title a, [class*="title"]');return n?{element:n,position:"after"}:t?{element:t,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return this.getSearchResultLists()[0]??document.querySelector('[data-testid*="search"]')??document.querySelector("main")??document.body}getPageInfo(){const e=new URLSearchParams(location.search),t=Number.parseInt(e.get("startPage")??e.get("page")??"0",10),n=Number.isFinite(t)?t+1:1,i=this.cleanText(document.querySelector('.result__count, .search-result__count, [class*="result-count"], [data-testid*="result-count"]')?.textContent??"").match(/\b([\d,]+)\s+results?\b/i),o=i?Number.parseInt(i[1].replace(/,/g,""),10):void 0;return{pageNum:n,totalPages:o?Math.max(1,Math.ceil(o/20)):1,url:location.href,itemsPerPage:20,totalItems:o}}getSearchResultHosts(){if(this.isChallengePage())return[];const e=this.getSearchResultLists(),t=e.length>0?e:[...Array.from(document.querySelectorAll(ly)),...Array.from(document.querySelectorAll("main"))],n=t.length>0?t:[document.querySelector("main")??document];return this.uniqueElements(n.flatMap(a=>Array.from(a.querySelectorAll(sy))).map(a=>this.toSearchResultHost(a)).filter(a=>!!a).filter(a=>this.looksLikeSearchResult(a)))}looksLikeSearchResult(e){return e.closest('[class^="paperlens-"], [class*=" paperlens-"]')||this.isExcludedSearchContext(e)||e.closest(qo)?!1:!!this.findTitleLink(e)}getSearchResultLists(){return Array.from(document.querySelectorAll(Mo)).filter(e=>!this.isExcludedSearchContext(e))}getDetailHostElement(){const e=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??"").replace(/\s*\|\s*Taylor\s*&\s*Francis Online\s*$/i,""),t=this.uniqueElements(cy.flatMap(s=>Array.from(document.querySelectorAll(s))));if(e){const s=e.toLowerCase(),l=t.find(c=>(c===document.body||!this.isExcludedSearchContext(c))&&this.cleanText(c.textContent??"").toLowerCase().includes(s));if(l)return l}const n=this.cleanDoi(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href);if(n){const s=t.find(l=>l!==document.body&&!this.isExcludedSearchContext(l)&&this.extractDoi(l,{allowTextFallback:!1})===n);if(s)return s}const a=t.filter(s=>s!==document.body&&!this.isExcludedSearchContext(s)&&!!s.querySelector("h1, .citation__title, .hlFld-Title")),i=this.leafHeadingCandidates(a),o=n?i.find(s=>this.candidateDoi(s)===n)??i.find(s=>!this.candidateDoi(s)&&this.hasDetailArticleEvidence(s))??this.lastNoDoiCandidate(i):i.find(s=>!this.candidateDoi(s)&&this.hasDetailArticleEvidence(s))??this.lastNoDoiCandidate(i)??i[i.length-1];return o||(t.find(s=>s===document.body||!this.isExcludedSearchContext(s))??null)}parseSearchHost(e){const t=this.findTitleLink(e),n=this.cleanText(t?.textContent??e.querySelector('h2, h3, .art_title, .search-result__title, [class*="title"]')?.textContent??"");if(!n)return null;const a=this.toArticleUrl(t?.getAttribute("href")??t?.href??""),i=this.cleanDoi(a??"")??this.extractDoi(e,{allowTextFallback:!1}),o=this.extractTypeText(e),s=this.extractVenue(e),l=this.inferRecordKind(o,a,"",i);return{title:n,journalName:s,journalCandidates:s?[s]:[],authors:this.extractAuthorsFromDom(e),year:this.extractYear(e),doi:i,sourceId:i?`taylor-francis:${i}`:a?`taylor-francis:${new URL(a).pathname}`:void 0,url:a,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:l.articleTypes,source:this.id,citationType:l.citationType}}parseMetadataArticle(e){const t=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??"").replace(/\s*\|\s*Taylor\s*&\s*Francis Online\s*$/i,"");if(!t)return null;const n=this.toArticleUrl(this.firstMetaContent(["citation_public_url","citation_fulltext_html_url","prism.url","og:url"])??document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),a=this.firstDoi([...this.allMetaContent(["citation_doi","dc.identifier","prism.doi"]),n??""]),i=this.firstMetaContent(["citation_inbook_title"])??"",o=this.firstMetaContent(["citation_book_title"])??"",s=i||(o&&this.cleanVenue(o).toLowerCase()!==this.cleanVenue(t).toLowerCase()?o:""),l=this.cleanVenue(this.firstMetaContent(["citation_journal_title","prism.publicationName"])||i||o||s||""),c=this.firstMetaContent(["citation_article_type","dc.type"])??"",u=this.inferRecordKind(c,n,s,a);return{title:t,journalName:l,journalCandidates:l?[l]:[],authors:this.allMetaContent(["citation_author","dc.creator"]),year:this.yearFromText(this.firstMetaContent(["citation_publication_date","citation_online_date","prism.publicationDate","dc.date"])??""),doi:a,sourceId:a?`taylor-francis:${a}`:n?`taylor-francis:${new URL(n).pathname}`:void 0,url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.firstMetaContent(["citation_abstract","dc.description","description","og:description"])??this.extractAbstract(e),hostElement:e,articleTypes:u.articleTypes,issn:this.normalizeIssn(this.firstMetaContent(["citation_issn","prism.issn"])??""),source:this.id,citationType:u.citationType}}parseDetailDom(e){const t=this.cleanText(e.querySelector("h1, .citation__title, .hlFld-Title")?.textContent??document.title.replace(/\s*\|\s*Taylor\s*&\s*Francis Online\s*$/i,""));if(!t)return null;const n=this.toArticleUrl(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),a=this.cleanDoi(n??"")??this.extractDoi(e,{allowTextFallback:!1}),i=this.extractVenue(e),o=this.inferRecordKind(this.extractTypeText(e),n,"",a);return{title:t,journalName:i,journalCandidates:i?[i]:[],authors:this.extractAuthorsFromDom(e),year:this.extractYear(e),doi:a,sourceId:a?`taylor-francis:${a}`:n?`taylor-francis:${new URL(n).pathname}`:void 0,url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:o.articleTypes,source:this.id,citationType:o.citationType}}inferRecordKind(e,t,n="",a=""){const i=`${e} ${t??""} ${n}`,o=/\/doi\/book\//i.test(t??""),s=e.match(/\b(?:book|chapter)\s+reviews?\b/i);if(s)return{articleTypes:[this.toTitleCase(s[0])],citationType:"article",metricsAllowed:!1};const l=/book chapter|chapter|book section/i.test(i)||this.cleanText(n).length>0||o&&this.isChapterDoi(a);return/conference paper|conference proceeding/i.test(i)?{articleTypes:["Conference"],citationType:"inproceedings",metricsAllowed:!1}:l?{articleTypes:["BookChapter"],citationType:"incollection",metricsAllowed:!1}:o?{articleTypes:["Book"],citationType:"book",metricsAllowed:!1}:/\bbook\b/i.test(i)&&!/journal|article/i.test(i)?{articleTypes:["Book"],citationType:"book",metricsAllowed:!1}:{articleTypes:["JournalArticle"],citationType:"article",metricsAllowed:!0}}findTitleLink(e){return Array.from(e.querySelectorAll('h2 a[href], h3 a[href], .art_title a[href], .art_title[href], .hlFld-Title a[href], .hlFld-Title[href], .publication_title a[href], .publication_title[href], .search-result__title a[href], .search-result__title[href], a[href*="/doi/10."], a[href*="/doi/abs/10."], a[href*="/doi/full/10."]')).find(n=>this.isArticleLink(n)&&this.cleanText(n.textContent??"").length>0)??null}extractVenue(e){const t=[".publication_meta .journal",".publication_meta a[href]",".journal-title",".meta__journal",".meta__source",".citation__journal-title",".publication_meta",".search-result__meta",".search-result__info",".meta__citation",'[data-testid*="journal"]','[data-testid*="citation"]','[data-testid*="meta"]',".source-title",".meta__source"].join(",");for(const n of Array.from(e.querySelectorAll(t))){if(n instanceof HTMLAnchorElement&&/\/doi\/|doi\.org\//i.test(n.getAttribute("href")??""))continue;const a=this.cleanVenue(n.textContent??"");if(this.isLikelyVenueText(a))return a}for(const n of Array.from(e.querySelectorAll('.publication_meta, .search-result__meta, .search-result__info, .meta__citation, [data-testid*="citation"], [data-testid*="meta"], [class*="citation"], [class*="meta"]'))){const a=this.cleanText(n.textContent??""),i=this.cleanVenue(a.replace(/\s*[·•|]\s*Taylor\s*&\s*Francis(?:\s+Online)?\b[\s\S]*$/i,"").trim());if(this.isLikelyVenueText(i))return i}return this.cleanVenue(this.firstMetaContent(["citation_journal_title","prism.publicationName","citation_inbook_title","citation_book_title"])??"")}extractTypeText(e){const t=[".publication-type",".content-type",".issue-item__type",'[data-testid*="type"]','[class*="type"]'].join(",");return Array.from(e.querySelectorAll(t)).map(n=>this.cleanText(n.textContent??"")).filter(Boolean).join(" ")}extractAuthorsFromDom(e){const t=[".author-name",".loa__author-name",".citation__author",".authors a",".authors span",'[class*="author"] a','[class*="author"] span',"[data-author-name]"].join(",");return this.unique(Array.from(e.querySelectorAll(t)).map(n=>this.cleanText(n.getAttribute("data-author-name")??n.textContent??"")).filter(n=>n&&!/^(Authors?|View|Show more)$/i.test(n)))}extractYear(e){for(const t of Array.from(e.querySelectorAll('time, .publication-year, .date, [class*="year"], [class*="date"]'))){const n=this.yearFromText(t.textContent??"");if(n)return n}return this.yearFromText(e.textContent??"")}extractDoi(e,t={}){const n=t.allowTextFallback??!0;for(const a of Array.from(e.querySelectorAll('a[href*="doi.org/"], a[href*="/doi/10."], a[href*="/doi/abs/10."], a[href*="/doi/full/10."], a[href*="/doi/pdf/10."], a[href*="/doi/epdf/10."], a[href*="/doi/book/10."]'))){if(this.isExcludedDoiContext(a)||this.isExcludedSearchContext(a))continue;const i=this.cleanDoi(a.href);if(i)return i}for(const a of Array.from(e.querySelectorAll('[data-test*="doi"], [data-testid*="doi"], [id*="doi"], [class*="doi"], .epub-doi'))){if(this.isExcludedDoiContext(a)||this.isExcludedSearchContext(a))continue;const i=this.cleanDoi(a.textContent??"");if(i)return i}if(n)return this.cleanDoi(this.textWithoutExcludedDoiContexts(e))}extractNativeFullTextUrl(e){const t=this.toNativeFullTextUrl(this.firstMetaContent(["citation_pdf_url"])??"");if(t)return t;for(const n of Array.from(e.querySelectorAll('a[href*="/doi/pdf/"], a[href*="/doi/epdf/"], a[href$=".pdf"], a[href*="/pdf"]'))){if(this.isExcludedDoiContext(n)||this.isExcludedSearchContext(n))continue;const a=this.toNativeFullTextUrl(n.getAttribute("href")??n.href??"");if(a)return a}}extractAbstract(e){return je(e)}firstMetaContent(e){return this.allMetaContent(e)[0]}allMetaContent(e){const t=[];for(const n of e){const a=[`meta[name="${n}"]`,`meta[property="${n}"]`,`meta[name="${n.toLowerCase()}"]`,`meta[property="${n.toLowerCase()}"]`].join(",");for(const i of Array.from(document.querySelectorAll(a))){const o=this.cleanText(i.getAttribute("content")??"");o&&t.push(o)}}return this.unique(t)}cleanDoi(e){const t=this.unique([this.pathnameFromPossibleUrl(e)??"",e]);for(const n of t){const i=this.decodeDoiSource(n).match(iy),o=i?this.trimDoiTail(i[0]):void 0;if(o)return o}}firstDoi(e){for(const t of e){const n=this.cleanDoi(t);if(n)return n}}yearFromText(e){const t=e.match(oy);return t?Number.parseInt(t[1],10):void 0}normalizeIssn(e){const t=e.trim().toUpperCase().replace(/[^0-9X]/g,"");if(/^\d{7}[\dX]$/.test(t))return`${t.slice(0,4)}-${t.slice(4)}`}trimDoiTail(e){let t=e.replace(/[,.;\s]+$/g,"");for(;t.endsWith(")")&&this.countCharacter(t,")")>this.countCharacter(t,"(");)t=t.slice(0,-1).replace(/[,.;\s]+$/g,"");return t}countCharacter(e,t){return Array.from(e).filter(n=>n===t).length}isExcludedDoiContext(e){return!!e.closest(qo)||!!this.closestExcludedSection(e)||this.isAfterExcludedModuleHeading(e)||!!Array.from(e.parentElement?.children??[]).some(t=>/^References?$/i.test(this.cleanText(t.textContent??"")))}textWithoutExcludedDoiContexts(e){const t=e.cloneNode(!0);return t.querySelectorAll(qo).forEach(n=>n.remove()),Array.from(t.querySelectorAll("section, aside, nav, div")).forEach(n=>{this.hasExcludedSectionLabel(n)&&n.remove()}),t.textContent??""}toNativeFullTextUrl(e){const t=this.toAbsoluteUrl(e);if(t)try{const n=new URL(t);return n.protocol!=="https:"||n.hostname.toLowerCase()!=="www.tandfonline.com"?void 0:/^\/doi\/(?:pdf|epdf)\//i.test(n.pathname)?t:void 0}catch{return}}toArticleUrl(e){const t=this.toAbsoluteUrl(e);if(t)try{const n=new URL(t);return n.searchParams.delete("af"),n.searchParams.delete("campaign"),n.href}catch{return t}}isArticleLink(e){try{const t=new URL(e.getAttribute("href")??e.href,location.origin);return/^\/doi\/(?:abs\/|full\/|pdf\/|epdf\/|book\/)?10\./i.test(t.pathname)||/^\/doi\/(?:abs\/|full\/)?no-visible-doi$/i.test(t.pathname)}catch{return!1}}isChapterDoi(e){return/\b(?:\.ch\d+|_chap\d+|\.chapter\d+|-\d+)$/i.test(e??"")}decodeDoiSource(e){try{return decodeURIComponent(e)}catch{return e}}isChallengePage(){const e=document.title;return/Just a moment|Enable JavaScript and cookies|Access denied|Attention Required|Cloudflare/i.test(e)||document.querySelector('.cf-turnstile, .cf-error-code, iframe[src*="challenges.cloudflare.com"], script[src*="/cdn-cgi/challenge-platform/"]')?!0:/Enable JavaScript and cookies to continue|Checking if the site connection is secure|Sorry, you have been blocked|Cloudflare Ray ID/i.test(document.body?.textContent??"")}cleanVenue(e){return this.cleanText(e).replace(/^In\s+/i,"").replace(/^(?:Published in|Publication|Source)\s*:?\s*/i,"").replace(/^Journal\s*:?\s*/i,"").replace(/\b(?:Volume|Vol\.?|Issue|No\.?|Pages?|pp\.?)\b[\s\S]*$/i,"").replace(/\b((?:19|20)\d{2})\b[\s\S]*$/i,"").replace(/[,.;:\s]+$/g,"").trim()}isLikelyVenueText(e){return!e||/^(?:Article|Chapter|PDF|Full text|Research Article)$/i.test(e)||/^(?:Taylor\s*&\s*Francis(?:\s+Online)?|Published online)$/i.test(e)||/\b(?:published online|first published|volume|issue|research article)\b/i.test(e)?!1:!/^\d{4}$/.test(e)}toAbsoluteUrl(e){const t=e.trim();if(!(!t||/^javascript:/i.test(t)||/^data:/i.test(t)))try{const n=new URL(t,location.origin);return/^https?:$/.test(n.protocol)?n.href:void 0}catch{return}}cleanText(e){return e.replace(/\s+/g," ").trim()}toTitleCase(e){return e.toLowerCase().replace(/\b\w/g,t=>t.toUpperCase())}unique(e){return Array.from(new Set(e.filter(Boolean)))}uniqueElements(e){return Array.from(new Set(e))}toSearchResultHost(e){return e.matches(ln)?e:e.closest(ln)??e.closest("li, .search-result, .search-result__item, .issue-item, article")??e}isExcludedSearchContext(e){let t=e;for(;t&&t!==document.body;){if(/^(ASIDE|NAV|FOOTER)$/i.test(t.tagName)||t.getAttribute("role")==="complementary"||this.hasExcludedSectionLabel(t))return!0;t=t.parentElement}return!1}pathnameFromPossibleUrl(e){const t=e.trim();if(t)try{const n=new URL(t,location.origin);if(n.hostname.toLowerCase()==="doi.org"||n.pathname.includes("/doi/")||n.pathname.startsWith("/10."))return n.pathname}catch{return}}closestExcludedSection(e){let t=e.parentElement;for(;t&&t!==document.body;){if(!t.matches(ln)&&this.hasExcludedSectionLabel(t))return t;t=t.parentElement}return null}hasExcludedSectionLabel(e){const t=[e.getAttribute("aria-label")??"",e.getAttribute("aria-labelledby")??"",e.getAttribute("id")??"",e.getAttribute("class")??""].join(" ");return this.isExcludedModuleMarkerText(t)?!0:/^(ARTICLE|MAIN|BODY|HTML)$/i.test(e.tagName)||e.matches(ln)||!this.shouldScanSectionLabelText(e)?!1:this.sectionLabelTexts(e).some(n=>this.isExcludedModuleHeadingText(n))}isExcludedModuleMarkerText(e){return/(?:references?|bibliography|related|recommend(?:ed|ations?)?|cited(?:\s+by)?|most\s+read|most\s+viewed|popular|latest|recent|recently\s+viewed|also\s+read|trending|sidebar|side[-_\s]*bar|right[-_\s]*rail|layout__secondary|secondary[-_\s]*(?:rail|content|column|module)?)/i.test(e)}isExcludedModuleHeadingText(e){const t=this.cleanModuleHeadingText(e);return/^(?:references?|bibliography|related(?:\s+articles?)?|recommend(?:ed(?:\s+(?:articles?|for\s+you))?|ations?(?:\s+for\s+you)?)|cited(?:\s+by)?|most\s+read(?:\s+articles?)?|most\s+viewed(?:\s+articles?)?|popular(?:\s+articles?)?|latest(?:\s+(?:articles?|papers?|publications?|research))?|recent(?:\s+(?:articles?|papers?|publications?|research))?|recently\s+viewed|(?:people\s+)?also\s+read|you\s+may\s+also\s+like|trending(?:\s+articles?)?)$/i.test(t)}cleanModuleHeadingText(e){return this.cleanText(e).replace(/\s*(?:\(\s*\d+\s*\)|\[\s*\d+\s*\]|\{\s*\d+\s*\})\s*$/g,"").replace(/\s+\d+\s*$/g,"").trim()}candidateDoi(e){return this.extractDoi(e,{allowTextFallback:!1})}lastNoDoiCandidate(e){const t=e.filter(n=>!this.candidateDoi(n));return t[t.length-1]}leafHeadingCandidates(e){const t=e.filter(n=>!e.some(a=>a!==n&&n.contains(a)));return t.length>0?t:e}hasDetailArticleEvidence(e){return!!e.querySelector([".journal-title",".meta__journal",".citation__journal-title",'[data-testid*="journal"]',".source-title",".meta__source",".publication-year","time",".publication-type",".content-type",".abstract",'[class*="abstract"]',".citation__authors",".author-name",".loa__author-name","[data-author-name]"].join(","))}shouldScanSectionLabelText(e){return/^(SECTION|ASIDE|NAV)$/i.test(e.tagName)||Array.from(e.children).some(t=>(/^H[1-6]$/i.test(t.tagName)||t.getAttribute("role")==="heading")&&this.isExcludedModuleHeadingText(t.textContent??""))?!0:/(?:content[-_\s]*block|module|widget|rail|sidebar|recommend|related|latest|recent|reference|bibliography|cited)/i.test(`${e.getAttribute("id")??""} ${e.getAttribute("class")??""}`)||Array.from(e.children).some(t=>/(?:content[-_\s]*block|module[-_\s]*header|moduleHeader|section[-_\s]*title|sectionTitle)/i.test(`${t.getAttribute("id")??""} ${t.getAttribute("class")??""}`))}isAfterExcludedModuleHeading(e){let t=e;for(;t&&t!==document.body;){let n=t.previousElementSibling;for(;n;){if(this.isExcludedHeadingElement(n))return!0;n=n.previousElementSibling}if(/^(ARTICLE|MAIN)$/i.test(t.tagName))break;t=t.parentElement}return!1}isExcludedHeadingElement(e){return/^H[1-6]$/i.test(e.tagName)||e.getAttribute("role")==="heading"||e.matches('.section-title, .sectionTitle, .module-header, .moduleHeader, [class*="section-title"], [class*="sectionTitle"], [class*="module-header"], [class*="moduleHeader"]')?this.isExcludedModuleHeadingText(e.textContent??""):this.isExcludedModuleHeadingText(e.textContent??"")&&!e.querySelector("a[href], button, input, select, textarea")}sectionLabelTexts(e){const t=[],n=(a,i)=>{if(a.matches(ln))return;const o=Array.from(a.childNodes).filter(s=>s.nodeType===3).map(s=>this.cleanText(s.textContent??"")).filter(Boolean).join(" ");o&&t.push(o);for(const s of Array.from(a.children)){if(s.matches(ln)||s.matches(Mo)||/^(ASIDE|NAV|FOOTER)$/i.test(s.tagName)||s.getAttribute("role")==="complementary")continue;if(/^H[1-6]$/i.test(s.tagName)||s.getAttribute("role")==="heading"||s.matches('.section-title, .sectionTitle, .module-header, .moduleHeader, [class*="section-title"], [class*="sectionTitle"], [class*="module-header"], [class*="moduleHeader"]')){t.push(this.cleanText(s.textContent??""));continue}const l=this.cleanText(s.textContent??"");if(this.isExcludedModuleHeadingText(l)){t.push(l);continue}i<20&&n(s,i+1)}};return n(e,0),t.filter(Boolean)}}const dy=/\b10\.\d{4,9}\/[^\s"'<>?#]+/i,py=/\b((?:19|20)\d{2})\b/,cn=["li.search-results__item",".search-results__item","li.search-result",".search-result",".searchResult",".article-card",".al-article-box",".al-article-item"].join(","),jo=[".search-results",".search-results-list",".searchResultList",'[data-testid*="search-results"]'].join(","),hy=[jo,'[data-testid*="search"]','[data-test*="search"]',"main"].join(","),fy=["#ContentColumn article","#main-content article","main article","#ContentColumn","#main-content","main","article","body"],$o=['[id*="reference"]','[id*="Reference"]','[class*="reference"]','[class*="Reference"]','[class*="ref-list"]','[class*="refList"]','[role="doc-bibliography"]','section[aria-label*="Reference"]','section[aria-label*="reference"]','section[aria-labelledby*="Reference"]','section[aria-labelledby*="reference"]','[id*="related"]','[id*="Related"]','[class*="related"]','[class*="Related"]','[id*="recommend"]','[id*="Recommend"]','[class*="recommend"]','[class*="Recommend"]','[id*="cited"]','[class*="cited"]','[data-test*="reference"]','[data-testid*="reference"]'].join(",");class my extends j{id="oxford-academic";name="Oxford Academic";matches=["*://academic.oup.com/*"];isSearchPage(){return this.isChallengePage()?!1:location.pathname==="/search-results"||location.pathname.startsWith("/search-results")||location.pathname==="/search"||location.pathname.startsWith("/search")&&new URLSearchParams(location.search).has("q")}isArticlePage(){return this.isChallengePage()?!1:/\/article(?:-abstract)?\//i.test(location.pathname)||!!this.firstMetaContent(["citation_title"])}parseSearchResults(){const e=[],t=new Set;for(const n of this.getSearchResultHosts())try{const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;if(t.has(i))continue;t.add(i),e.push(a)}catch(a){console.error("[OxfordAcademicAdapter] Failed to parse search result:",a)}return e}parseArticlePage(){if(this.isChallengePage())return null;const e=this.getDetailHostElement();if(!e)return null;try{return this.parseMetadataArticle(e)??this.parseDetailDom(e)}catch(t){return console.error("[OxfordAcademicAdapter] Failed to parse article page:",t),null}}getMetricBarAnchor(e){const t=e.querySelector('.ww-citation-primary, .authors, [class*="authors"], [class*="meta"]');if(this.isArticlePage()&&t)return{element:t,position:"after"};const n=e.querySelector('h1, h2, h3, .wi-article-title, .article-title, .al-title, [class*="title"]');return n?{element:n,position:"after"}:t?{element:t,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return this.getSearchResultLists()[0]??document.querySelector('[data-testid*="search"]')??document.querySelector("main")??document.body}getPageInfo(){const e=new URLSearchParams(location.search),t=Number.parseInt(e.get("page")??e.get("startPage")??"1",10),n=Number.isFinite(t)&&t>0?t:1,i=this.cleanText(document.querySelector('.result-count, .search-result-count, [class*="result-count"], [data-testid*="result-count"]')?.textContent??"").match(/\b([\d,]+)\s+results?\b/i),o=i?Number.parseInt(i[1].replace(/,/g,""),10):void 0;return{pageNum:n,totalPages:o?Math.max(1,Math.ceil(o/20)):1,url:location.href,itemsPerPage:20,totalItems:o}}getSearchResultHosts(){if(this.isChallengePage())return[];const e=this.getSearchResultLists(),t=e.length>0?e:Array.from(document.querySelectorAll(hy)),n=t.length>0?t:[document],a=n.flatMap(o=>Array.from(o.querySelectorAll(cn))),i=n.flatMap(o=>Array.from(o.querySelectorAll('a[href*="/article/"], a[href*="/article-abstract/"]'))).map(o=>this.toSearchResultHost(o)).filter(o=>!!o);return this.uniqueElements([...a,...i]).map(o=>this.toSearchResultHost(o)).filter(o=>!!o).filter(o=>this.looksLikeSearchResult(o))}getSearchResultLists(){return Array.from(document.querySelectorAll(jo)).filter(e=>!this.isExcludedSearchContext(e))}looksLikeSearchResult(e){return e.closest('[class^="paperlens-"], [class*=" paperlens-"]')||this.isExcludedSearchContext(e)||e.closest($o)?!1:!!this.findTitleLink(e)}getDetailHostElement(){const e=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??"").replace(/\s*\|\s*Oxford Academic\s*$/i,""),t=this.uniqueElements(fy.flatMap(c=>Array.from(document.querySelectorAll(c))));if(e){const c=e.toLowerCase(),u=t.find(d=>(d===document.body||!this.isExcludedSearchContext(d))&&this.cleanText(d.textContent??"").toLowerCase().includes(c));if(u)return u}const n=t.filter(c=>c!==document.body&&!this.isExcludedSearchContext(c)&&!!c.querySelector("h1, .wi-article-title, .article-title, .al-title")),a=this.leafHeadingCandidates(n),i=this.cleanDoi(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),o=i?a.find(c=>this.extractDoi(c,{allowTextFallback:!1})===i):void 0;if(o)return o;const s=a.find(c=>!this.extractDoi(c,{allowTextFallback:!1})&&this.hasDetailArticleEvidence(c));if(s)return s;const l=a.filter(c=>!this.extractDoi(c,{allowTextFallback:!1}));return l.length>0?l[l.length-1]:a.length>0?a[a.length-1]:t.find(c=>c===document.body||!this.isExcludedSearchContext(c))??null}parseSearchHost(e){const t=this.findTitleLink(e),n=this.cleanText(t?.textContent??e.querySelector('h2, h3, .article-title, .al-title, [class*="title"]')?.textContent??"");if(!n)return null;const a=this.toArticleUrl(t?.getAttribute("href")??t?.href??""),i=this.cleanDoi(a??"")??this.extractDoi(e,{allowTextFallback:!1}),o=this.extractTypeText(e),s=this.extractVenue(e),l=this.inferRecordKind(o,a,"",i),c=this.buildJournalInfo(s,a);return{title:n,journalName:c.journalName,journalCandidates:c.journalCandidates,authors:this.extractAuthorsFromDom(e),year:this.extractYear(e),doi:i,sourceId:this.sourceIdFor(i,a),url:a,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:l.articleTypes,source:this.id,citationType:l.citationType}}parseMetadataArticle(e){const t=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??"").replace(/\s*\|\s*Oxford Academic\s*$/i,"");if(!t)return null;const n=this.toArticleUrl(this.firstMetaContent(["citation_public_url","citation_fulltext_html_url","prism.url","og:url"])??document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),a=this.firstDoi([...this.allMetaContent(["citation_doi","dc.identifier","prism.doi"]),n??""]),i=this.firstMetaContent(["citation_inbook_title","citation_book_title"])??"",o=this.cleanVenue(this.firstMetaContent(["citation_journal_title","prism.publicationName"])??i??""),s=this.firstMetaContent(["citation_article_type","dc.type"])??"",l=this.inferRecordKind(s,n,i,a),c=this.buildJournalInfo(o,n);return{title:t,journalName:c.journalName,journalCandidates:c.journalCandidates,authors:this.allMetaContent(["citation_author","dc.creator"]),year:this.yearFromText(this.firstMetaContent(["citation_publication_date","citation_online_date","prism.publicationDate","dc.date"])??""),doi:a,sourceId:this.sourceIdFor(a,n),url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.firstMetaContent(["citation_abstract","dc.description","description","og:description"])??this.extractAbstract(e),hostElement:e,articleTypes:l.articleTypes,issn:this.normalizeIssn(this.firstMetaContent(["citation_issn","prism.issn"])??""),source:this.id,citationType:l.citationType}}parseDetailDom(e){const t=this.cleanText(e.querySelector("h1, .wi-article-title, .article-title, .al-title")?.textContent??document.title.replace(/\s*\|\s*Oxford Academic\s*$/i,""));if(!t)return null;const n=this.toArticleUrl(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),a=this.cleanDoi(n??"")??this.extractDoi(e,{allowTextFallback:!1}),i=this.extractVenue(e),o=this.inferRecordKind(this.extractTypeText(e),n,"",a),s=this.buildJournalInfo(i,n);return{title:t,journalName:s.journalName,journalCandidates:s.journalCandidates,authors:this.extractAuthorsFromDom(e),year:this.extractYear(e),doi:a,sourceId:this.sourceIdFor(a,n),url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:o.articleTypes,source:this.id,citationType:o.citationType}}inferRecordKind(e,t,n="",a=""){const i=`${e} ${t??""} ${n}`,o=/\/book\/[^/]+\/chapter\//i.test(t??""),s=/book chapter|chapter|book section/i.test(i)||this.cleanText(n).length>0||o&&/\b(?:\.ch\d+|_chap\d+|\.chapter\d+|-\d+)$/i.test(a);return/conference paper|conference proceeding|proceedings/i.test(i)?{articleTypes:["Conference"],citationType:"inproceedings"}:s?{articleTypes:["BookChapter"],citationType:"incollection"}:/\bbook\b/i.test(i)&&!/journal|article/i.test(i)?{articleTypes:["Book"],citationType:"book"}:{articleTypes:["JournalArticle"],citationType:"article"}}findTitleLink(e){return Array.from(e.querySelectorAll('h2 a[href], h3 a[href], .article-title a[href], .al-title a[href], .item-title a[href], a[href*="/article/"], a[href*="/article-abstract/"]')).find(n=>this.isArticleLink(n)&&this.cleanText(n.textContent??"").length>0)??null}extractVenue(e){const t=[".journal-title",".citation-journal-title",".ww-citation-primary",".al-journal-title",".publication-title",".source-title",'[data-testid*="journal"]','[data-test*="journal"]','[class*="journal-title"]','[class*="source"]'].join(",");for(const n of Array.from(e.querySelectorAll(t))){const a=this.cleanVenue(n.textContent??"");if(a&&!/^(Article|Chapter|PDF|Full text)$/i.test(a))return a}return this.cleanVenue(this.firstMetaContent(["citation_journal_title","prism.publicationName","citation_inbook_title","citation_book_title"])??"")}extractTypeText(e){const t=[".publication-type",".content-type",".article-type",'[data-testid*="type"]','[data-test*="type"]','[class*="type"]'].join(",");return Array.from(e.querySelectorAll(t)).map(n=>this.cleanText(n.textContent??"")).filter(Boolean).join(" ")}extractAuthorsFromDom(e){const t=[".author-name",".loa__author-name",".al-authors-list a",".authors a",".authors span",'[class*="author"] a','[class*="author"] span',"[data-author-name]"].join(",");return this.unique(Array.from(e.querySelectorAll(t)).map(n=>this.cleanText(n.getAttribute("data-author-name")??n.textContent??"")).filter(n=>n&&!/^(Authors?|View|Show more)$/i.test(n)))}extractYear(e){for(const t of Array.from(e.querySelectorAll('time, .publication-year, .date, [class*="year"], [class*="date"]'))){const n=this.yearFromText(t.textContent??"");if(n)return n}return this.yearFromText(e.textContent??"")}extractDoi(e,t={}){const n=t.allowTextFallback??!0;for(const a of Array.from(e.querySelectorAll('a[href*="doi.org/"], a[href*="/lookup/doi/10."], a[href*="/doi/10."], a[href*="/doi/full/10."], a[href*="/doi/abs/10."], a[href*="/doi/pdf/10."]'))){if(this.isExcludedDoiContext(a)||this.isExcludedSearchContext(a))continue;const i=this.cleanDoi(a.href);if(i)return i}for(const a of Array.from(e.querySelectorAll('[data-test*="doi"], [data-testid*="doi"], [id*="doi"], [class*="doi"], .epub-doi'))){if(this.isExcludedDoiContext(a)||this.isExcludedSearchContext(a))continue;const i=this.cleanDoi(a.textContent??"");if(i)return i}if(n)return this.cleanDoi(this.textWithoutExcludedDoiContexts(e))}extractNativeFullTextUrl(e){const t=this.toNativeFullTextUrl(this.firstMetaContent(["citation_pdf_url"])??"");if(t)return t;for(const n of Array.from(e.querySelectorAll('a[href*="/article-pdf/"], a[href$=".pdf"], a[href*=".pdf"], a[href*="/pdf/"], a[href*="DownloadFile"]'))){if(this.isExcludedDoiContext(n)||this.isExcludedSearchContext(n))continue;const a=this.toNativeFullTextUrl(n.getAttribute("href")??n.href??"");if(a)return a}}extractAbstract(e){return je(e)}buildJournalInfo(e,t){const n=this.cleanVenue(e),a=this.journalHintFromUrl(t??location.href),i=[],o=d=>{const p=this.cleanVenue(d??"");p&&i.push(p)},s=n.match(/^[A-Z][A-Z0-9&.\s-]{1,16}\s*[:\-]\s*(.+)$/)?.[1];s&&o(s);const l=/^JNCI(?:\s*[:\-]\s*Journal of the National Cancer Institute)?$/i.test(n);l&&(o("Journal of the National Cancer Institute"),o("JNCI-Journal of the National Cancer Institute")),a&&(this.isWeakVenue(n)||l||!n)&&(o(a.full),a.aliases.forEach(o)),n&&!this.isWeakVenue(n)&&o(n),a&&!i.some(d=>d.toLowerCase()===a.full.toLowerCase())&&(o(a.full),a.aliases.forEach(o));const c=this.unique(i);return{journalName:c.find(d=>!this.isWeakVenue(d)&&!/^JNCI-Journal/i.test(d))??c[0]??n,journalCandidates:c}}journalHintFromUrl(e){try{const t=new URL(e,location.origin);if(/^\/jnci(?:\/|$)/i.test(t.pathname))return{full:"Journal of the National Cancer Institute",aliases:["JNCI-Journal of the National Cancer Institute"]}}catch{return}}isWeakVenue(e){const t=this.cleanText(e);return!t||t.includes("...")||/^(Article|Chapter|PDF|Full text|Oxford Academic)$/i.test(t)?!0:/^[A-Z0-9&.\s-]{2,12}$/.test(t)}firstMetaContent(e){return this.allMetaContent(e)[0]}allMetaContent(e){const t=[];for(const n of e){const a=[`meta[name="${n}"]`,`meta[property="${n}"]`,`meta[name="${n.toLowerCase()}"]`,`meta[property="${n.toLowerCase()}"]`].join(",");for(const i of Array.from(document.querySelectorAll(a))){const o=this.cleanText(i.getAttribute("content")??"");o&&t.push(o)}}return this.unique(t)}cleanDoi(e){const t=this.unique([this.pathnameFromPossibleUrl(e)??"",e]);for(const n of t){const i=this.decodeDoiSource(n).match(dy),o=i?this.trimDoiTail(i[0]):void 0;if(o)return o}}firstDoi(e){for(const t of e){const n=this.cleanDoi(t);if(n)return n}}sourceIdFor(e,t){if(e)return`oxford-academic:${e}`;if(t)try{const n=new URL(t);return`oxford-academic:${this.normalizeArticlePathname(n.pathname)}`}catch{return`oxford-academic:${t}`}}normalizeArticlePathname(e){return e.replace(/\/article-abstract\//i,"/article/").replace(/\/+$/g,"")||"/"}yearFromText(e){const t=e.match(py);return t?Number.parseInt(t[1],10):void 0}normalizeIssn(e){const t=e.trim().toUpperCase().replace(/[^0-9X]/g,"");if(/^\d{7}[\dX]$/.test(t))return`${t.slice(0,4)}-${t.slice(4)}`}trimDoiTail(e){let t=e.replace(/[,.;\]\}\s]+$/g,"");for(;t.endsWith(")")&&this.countCharacter(t,")")>this.countCharacter(t,"(");)t=t.slice(0,-1).replace(/[,.;\]\}\s]+$/g,"");return t}countCharacter(e,t){return Array.from(e).filter(n=>n===t).length}isExcludedDoiContext(e){return!!e.closest($o)||!!this.closestExcludedSection(e)||this.isAfterExcludedModuleHeading(e)||!!Array.from(e.parentElement?.children??[]).some(t=>/^References?$/i.test(this.cleanText(t.textContent??"")))}textWithoutExcludedDoiContexts(e){const t=e.cloneNode(!0);return t.querySelectorAll($o).forEach(n=>n.remove()),Array.from(t.querySelectorAll("section, aside, nav, div")).forEach(n=>{this.hasExcludedSectionLabel(n)&&n.remove()}),t.textContent??""}toNativeFullTextUrl(e){const t=this.toAbsoluteUrl(e);if(t)try{const n=new URL(t);if(n.protocol!=="https:")return;const a=n.hostname.toLowerCase(),i=n.pathname.toLowerCase();return(a==="academic.oup.com"||a==="oup.silverchair-cdn.com"||a==="watermark.silverchair.com")&&(a==="academic.oup.com"&&/^\/article-pdf\//i.test(n.pathname)||i.endsWith(".pdf")||i.includes("/pdf/")||i.includes("/article-pdf/"))?n.href:void 0}catch{return}}toArticleUrl(e){const t=this.toAbsoluteUrl(e);if(t)try{const n=new URL(t);return n.searchParams.delete("login"),n.searchParams.delete("redirectedFrom"),n.href}catch{return t}}isArticleLink(e){try{const t=new URL(e.getAttribute("href")??e.href,location.origin);return t.hostname.toLowerCase()==="academic.oup.com"&&/\/article(?:-abstract)?\//i.test(t.pathname)}catch{return!1}}decodeDoiSource(e){try{return decodeURIComponent(e)}catch{return e}}isChallengePage(){const e=document.title;return/Just a moment|Enable JavaScript and cookies|Access denied|Attention Required|Cloudflare/i.test(e)||document.querySelector('.cf-turnstile, .cf-error-code, iframe[src*="challenges.cloudflare.com"], script[src*="/cdn-cgi/challenge-platform/"]')?!0:/Enable JavaScript and cookies to continue|Checking if the site connection is secure|Sorry, you have been blocked|Cloudflare Ray ID/i.test(document.body?.textContent??"")}cleanVenue(e){return this.cleanText(e).replace(/^In\s+/i,"").replace(/^Journal\s*:\s*/i,"").replace(/\b(?:Volume|Vol\.?|Issue|No\.?|Pages?|pp\.?)\b[\s\S]*$/i,"").replace(/\b((?:19|20)\d{2})\b[\s\S]*$/i,"").replace(/[,.;:\s]+$/g,"").trim()}toAbsoluteUrl(e){const t=e.trim();if(!(!t||/^javascript:/i.test(t)||/^data:/i.test(t)))try{const n=new URL(t,location.origin);return/^https?:$/.test(n.protocol)?n.href:void 0}catch{return}}cleanText(e){return e.replace(/\s+/g," ").trim()}unique(e){return Array.from(new Set(e.filter(Boolean)))}uniqueElements(e){return Array.from(new Set(e))}toSearchResultHost(e){return e.matches(cn)?e:e.closest(cn)}isExcludedSearchContext(e){let t=e;for(;t&&t!==document.body;){if(/^(ASIDE|NAV|FOOTER)$/i.test(t.tagName)||t.getAttribute("role")==="complementary"||this.hasExcludedSectionLabel(t))return!0;t=t.parentElement}return!1}pathnameFromPossibleUrl(e){const t=e.trim();if(t)try{const n=new URL(t,location.origin);if(n.hostname.toLowerCase()==="doi.org"||n.pathname.includes("/doi/")||n.pathname.includes("/lookup/doi/")||n.pathname.startsWith("/10."))return n.pathname}catch{return}}closestExcludedSection(e){let t=e.parentElement;for(;t&&t!==document.body;){if(!t.matches(cn)&&this.hasExcludedSectionLabel(t))return t;t=t.parentElement}return null}hasExcludedSectionLabel(e){const t=[e.getAttribute("aria-label")??"",e.getAttribute("aria-labelledby")??"",e.getAttribute("id")??"",e.getAttribute("class")??""].join(" ");return this.isExcludedModuleMarkerText(t)?!0:/^(ARTICLE|MAIN|BODY|HTML)$/i.test(e.tagName)||e.matches(cn)||!this.shouldScanSectionLabelText(e)?!1:this.sectionLabelTexts(e).some(n=>this.isExcludedModuleHeadingText(n))}isExcludedModuleMarkerText(e){return/(?:references?|bibliography|related|recommend(?:ed|ations?)?|cited(?:\s+by)?|most\s+read|most\s+viewed|popular|latest|recent|recently\s+viewed|also\s+read|you\s+may\s+also\s+like|trending|sidebar|side[-_\s]*bar|right[-_\s]*rail|layout__secondary|secondary[-_\s]*(?:rail|content|column|module)?)/i.test(e)}isExcludedModuleHeadingText(e){const t=this.cleanModuleHeadingText(e);return/^(?:references?|bibliography|related(?:\s+articles?)?|recommend(?:ed(?:\s+(?:articles?|for\s+you))?|ations?(?:\s+for\s+you)?)|cited(?:\s+by)?|most\s+read(?:\s+articles?)?|most\s+viewed(?:\s+articles?)?|popular(?:\s+articles?)?|latest(?:\s+(?:articles?|papers?|publications?|research))?|recent(?:\s+(?:articles?|papers?|publications?|research))?|recently\s+viewed|(?:people\s+)?also\s+read|you\s+may\s+also\s+like|trending(?:\s+articles?)?)$/i.test(t)}cleanModuleHeadingText(e){return this.cleanText(e).replace(/\s*(?:\(\s*\d+\s*\)|\[\s*\d+\s*\]|\{\s*\d+\s*\})\s*$/g,"").replace(/\s+\d+\s*$/g,"").trim()}leafHeadingCandidates(e){const t=e.filter(n=>!e.some(a=>a!==n&&n.contains(a)));return t.length>0?t:e}hasDetailArticleEvidence(e){return!!e.querySelector([".journal-title",".citation-journal-title",".ww-citation-primary",".al-journal-title",".publication-title",".source-title",'[data-testid*="journal"]',".publication-year","time",".publication-type",".content-type",".article-type",".abstract",'[class*="abstract"]',".author-name",".loa__author-name","[data-author-name]"].join(","))}shouldScanSectionLabelText(e){return/^(SECTION|ASIDE|NAV)$/i.test(e.tagName)||Array.from(e.children).some(t=>(/^H[1-6]$/i.test(t.tagName)||t.getAttribute("role")==="heading")&&this.isExcludedModuleHeadingText(t.textContent??""))?!0:/(?:content[-_\s]*block|module|widget|rail|sidebar|recommend|related|latest|recent|reference|bibliography|cited)/i.test(`${e.getAttribute("id")??""} ${e.getAttribute("class")??""}`)||Array.from(e.children).some(t=>/(?:content[-_\s]*block|module[-_\s]*header|moduleHeader|section[-_\s]*title|sectionTitle)/i.test(`${t.getAttribute("id")??""} ${t.getAttribute("class")??""}`))}isAfterExcludedModuleHeading(e){let t=e;for(;t&&t!==document.body;){let n=t.previousElementSibling;for(;n;){if(this.isExcludedHeadingElement(n))return!0;n=n.previousElementSibling}if(/^(ARTICLE|MAIN)$/i.test(t.tagName))break;t=t.parentElement}return!1}isExcludedHeadingElement(e){return/^H[1-6]$/i.test(e.tagName)||e.getAttribute("role")==="heading"||e.matches('.section-title, .sectionTitle, .module-header, .moduleHeader, [class*="section-title"], [class*="sectionTitle"], [class*="module-header"], [class*="moduleHeader"]')?this.isExcludedModuleHeadingText(e.textContent??""):this.isExcludedModuleHeadingText(e.textContent??"")&&!e.querySelector("a[href], button, input, select, textarea")}sectionLabelTexts(e){const t=[],n=(a,i)=>{if(a.matches(cn))return;const o=Array.from(a.childNodes).filter(s=>s.nodeType===3).map(s=>this.cleanText(s.textContent??"")).filter(Boolean).join(" ");o&&t.push(o);for(const s of Array.from(a.children)){if(s.matches(cn)||s.matches(jo)||/^(ASIDE|NAV|FOOTER)$/i.test(s.tagName)||s.getAttribute("role")==="complementary")continue;if(/^H[1-6]$/i.test(s.tagName)||s.getAttribute("role")==="heading"||s.matches('.section-title, .sectionTitle, .module-header, .moduleHeader, [class*="section-title"], [class*="sectionTitle"], [class*="module-header"], [class*="moduleHeader"]')){t.push(this.cleanText(s.textContent??""));continue}const l=this.cleanText(s.textContent??"");if(this.isExcludedModuleHeadingText(l)){t.push(l);continue}i<20&&n(s,i+1)}};return n(e,0),t.filter(Boolean)}}const by=/\b10\.\d{4,9}\/[^\s"'<>?#]+/i,gy=/\b((?:19|20)\d{2})\b/,Oo=[".representation.overview.search",'[data-test-id="searchItem"]'].join(","),Lu=['[id*="reference"]','[id*="Reference"]','[class*="reference"]','[class*="Reference"]','[class*="references"]','[role="doc-bibliography"]','section[aria-label*="Reference"]','section[aria-labelledby*="reference"]','[id*="related"]','[class*="related"]','[id*="recommend"]','[class*="recommend"]','[id*="cited"]','[class*="cited"]','[data-test*="reference"]','[data-testid*="reference"]'].join(",");class yy extends j{id="cambridge-core";name="Cambridge Core";matches=["*://www.cambridge.org/*"];isSearchPage(){return this.isBlockedPage()?!1:location.pathname==="/core/search"||location.pathname.startsWith("/core/search")||location.pathname==="/core/"&&new URLSearchParams(location.search).has("q")}isArticlePage(){return this.isBlockedPage()||!this.isArticleOrBookRecordPath(location.pathname)?!1:!!this.firstMetaContent(["citation_title","dc.title","og:title"])}parseSearchResults(){const e=[],t=new Set;for(const n of this.getSearchResultHosts())try{const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;if(t.has(i))continue;t.add(i),e.push(a)}catch(a){console.error("[CambridgeCoreAdapter] Failed to parse search result:",a)}return e}parseArticlePage(){if(this.isBlockedPage())return null;const e=this.getDetailHostElement();if(!e)return null;try{return this.parseMetadataArticle(e)??this.parseDetailDom(e)}catch(t){return console.error("[CambridgeCoreAdapter] Failed to parse article page:",t),null}}getMetricBarAnchor(e){const t=e.querySelector('.details, .author, [class*="meta"], [class*="author"]');if(this.isArticlePage()&&t)return{element:t,position:"after"};const n=e.querySelector('h1, h2, h3, .title, .heading_08, [class*="title"]');return n?{element:n,position:"after"}:t?{element:t,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector(".search-results-listing .results")??document.querySelector(".search-results-listing")??document.querySelector("main")??document.body}getPageInfo(){const e=new URLSearchParams(location.search),t=Number.parseInt(e.get("pageNum")??e.get("page")??"1",10),n=this.cleanText(document.querySelector('[data-test-id="textNoOfSearchResults"], .result-number')?.textContent??""),a=n.match(/\b([\d,]+)\s+results?\b/i)??n.match(/\b([\d,]+)\b/),i=a?Number.parseInt(a[1].replace(/,/g,""),10):void 0;return{pageNum:Number.isFinite(t)&&t>0?t:1,totalPages:i?Math.max(1,Math.ceil(i/20)):1,url:location.href,itemsPerPage:20,totalItems:i}}getSearchResultHosts(){if(this.isBlockedPage())return[];const e=Array.from(document.querySelectorAll('[data-test-id="searchItem"]')),t=Array.from(document.querySelectorAll(".representation.overview.search")).filter(n=>!n.querySelector('[data-test-id="searchItem"]'));return[...e,...t].filter(n=>this.looksLikeSearchResult(n))}looksLikeSearchResult(e){return e.closest('[class^="paperlens-"], [class*=" paperlens-"]')||this.isExcludedSearchContext(e)?!1:!!this.findTitleLink(e)}getDetailHostElement(){const e=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??""),t=this.uniqueElements([...Array.from(document.querySelectorAll("main article, #maincontent article, .article, main, #maincontent, body"))]);if(e){const n=e.toLowerCase(),a=t.find(i=>(i===document.body||!this.isExcludedSearchContext(i))&&this.cleanText(i.textContent??"").toLowerCase().includes(n));if(a)return a}return t.find(n=>n===document.body||!this.isExcludedSearchContext(n))??document.body}parseSearchHost(e){const t=this.findTitleLink(e),n=this.cleanText(t?.textContent??"");if(!n)return null;const a=this.toArticleUrl(t?.getAttribute("href")??t?.href??""),i=this.extractTypeText(e),o=this.inferRecordKind(i,a,this.extractInputProductType(e),this.extractVenueLabel(e)),s=this.extractVenue(e),l=this.extractDoi(e,{allowTextFallback:!1});return{title:n,journalName:s,journalCandidates:s?[s]:[],authors:this.extractAuthorsFromDom(e),year:this.extractYear(e),doi:l,sourceId:this.sourceIdFor(l,e,a),url:a,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:o.articleTypes,source:this.id,citationType:o.citationType}}parseMetadataArticle(e){const t=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??"").replace(/\s*\|\s*Cambridge Core\s*$/i,"");if(!t)return null;const n=this.toArticleUrl(this.firstMetaContent(["citation_public_url","citation_fulltext_html_url","og:url"])??document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),a=this.firstDoi([...this.allMetaContent(["citation_doi","dc.identifier","prism.doi"]),n??""])??this.extractDoi(e,{allowTextFallback:!1}),i=this.firstMetaContent(["citation_inbook_title","citation_book_title"])??"",o=this.cleanVenue(this.firstMetaContent(["citation_journal_title","prism.publicationName"])??i??""),s=this.inferRecordKind(this.firstMetaContent(["citation_article_type","dc.type"])??"",n,"",o?i?"Book":"Journal":""),l=o||(s.citationType==="book"?t:"");return{title:t,journalName:l,journalCandidates:l?[l]:[],authors:this.allMetaContent(["citation_author","dc.creator"]),year:this.yearFromText(this.firstMetaContent(["citation_publication_date","citation_online_date","dc.date"])??""),doi:a,sourceId:this.sourceIdFor(a,e,n),url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.firstMetaContent(["citation_abstract","dc.description","description","og:description"])??this.extractAbstract(e),hostElement:e,articleTypes:s.articleTypes,issn:this.normalizeIssn(this.firstMetaContent(["citation_issn","prism.issn"])??""),source:this.id,citationType:s.citationType}}parseDetailDom(e){const t=this.cleanText(e.querySelector("h1, .heading_08 .title, .title")?.textContent??document.title.replace(/\s*\|\s*Cambridge Core\s*$/i,""));if(!t)return null;const n=this.toArticleUrl(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),a=this.extractVenue(e),i=this.extractTypeText(e),o=this.inferRecordKind(i,n,this.extractInputProductType(e),this.extractVenueLabel(e)),s=this.cleanDoi(n??"")??this.extractDoi(e,{allowTextFallback:!1});return{title:t,journalName:a,journalCandidates:a?[a]:[],authors:this.extractAuthorsFromDom(e),year:this.extractYear(e),doi:s,sourceId:this.sourceIdFor(s,e,n),url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:o.articleTypes,source:this.id,citationType:o.citationType}}inferRecordKind(e,t,n="",a=""){const i=n.trim().toUpperCase(),o=this.bookRouteKind(t),s=`${e} ${t??""} ${i} ${a}`;return i==="BOOK_PART"||o==="chapter"||/\b(chapter|book chapter)\b/i.test(s)?{articleTypes:["BookChapter"],citationType:"incollection"}:i==="BOOK"||o==="book"||/\bbook\b/i.test(s)?{articleTypes:["Book"],citationType:"book"}:/journal_article|type article|\barticle\b|journal:/i.test(s)?{articleTypes:["JournalArticle"],citationType:"article"}:{articleTypes:["JournalArticle"],citationType:"article"}}bookRouteKind(e){try{const n=new URL(e??location.href,location.origin).pathname.split("/").filter(Boolean);return n[0]?.toLowerCase()!=="core"||n[1]?.toLowerCase()!=="books"||!/^[A-F0-9]{16,}$/i.test(n[n.length-1]??"")?void 0:n.slice(2).length>2?"chapter":"book"}catch{return}}findTitleLink(e){return Array.from(e.querySelectorAll('.title h3 a[href], li.title a[href], h1 a[href], h2 a[href], h3 a[href], a.part-link[href], a[href*="/core/journals/"], a[href*="/core/books/"]')).find(n=>this.isRecordLink(n)&&this.cleanText(n.textContent??"").length>0)??null}extractVenue(e){const t=this.extractVenueFromDefinitionList(e);return t||this.cleanVenue(this.firstMetaContent(["citation_journal_title","prism.publicationName","citation_inbook_title","citation_book_title"])??"")}extractVenueFromDefinitionList(e){for(const t of Array.from(e.querySelectorAll("dt.source"))){const n=t.nextElementSibling;if(!n)continue;const a=n.querySelector(".productParent")??n,i=this.cleanVenue(a.textContent??"");if(i)return i}return""}extractVenueLabel(e){return this.cleanText(Array.from(e.querySelectorAll("dt.source")).map(t=>t.textContent??"").join(" "))}extractTypeText(e){return this.cleanText([...Array.from(e.querySelectorAll('.access .type, li.type, [class*="type"]')).map(t=>t.textContent??""),this.extractInputProductType(e)].join(" "))}extractInputProductType(e){return this.cleanText(e.querySelector("input[data-prod-type]")?.getAttribute("data-prod-type")??"")}extractAuthorsFromDom(e){const t=Array.from(e.querySelectorAll(".author.chapter .author-name, li.author.chapter a.more-by-this-author")),n=Array.from(e.querySelectorAll('li.author:not(.chapter) > a.more-by-this-author, .citation_author a, [class*="author"] [data-author-name]')),a=t.length>0?t:n;return this.unique(a.map(i=>this.cleanText(i.getAttribute("data-author-name")??i.textContent??"")).filter(i=>i&&!/^(Authors?|Edited by|View|Show more)$/i.test(i)))}extractYear(e){for(const t of Array.from(e.querySelectorAll('time, .date, [class*="year"], [class*="date"]'))){const n=this.yearFromText(t.textContent??"");if(n)return n}return this.yearFromText(e.textContent??"")}extractDoi(e,t={}){const n=t.allowTextFallback??!0;for(const a of Array.from(e.querySelectorAll("[data-doi]"))){if(this.isExcludedDoiContext(a)||this.isExcludedSearchContext(a))continue;const i=this.cleanDoi(a.getAttribute("data-doi")??"");if(i)return i}for(const a of Array.from(e.querySelectorAll('a[href*="doi.org/"], a[href*="/doi/"], a[href*="/core/services/aop-cambridge-core/content/view/"]'))){if(this.isExcludedDoiContext(a)||this.isExcludedSearchContext(a))continue;const i=this.cleanDoi(a.href);if(i)return i}for(const a of Array.from(e.querySelectorAll('[data-test*="doi"], [data-testid*="doi"], [id*="doi"], [class*="doi"], .meta-info'))){if(this.isExcludedDoiContext(a)||this.isExcludedSearchContext(a))continue;const i=this.cleanDoi(a.textContent??"");if(i)return i}if(n)return this.cleanDoi(this.textWithoutExcludedDoiContexts(e))}extractNativeFullTextUrl(e){const t=this.toNativeFullTextUrl(this.firstMetaContent(["citation_pdf_url"])??"");if(t)return t;for(const n of Array.from(e.querySelectorAll('a[href*="/core/services/aop-cambridge-core/content/view/"], a[href$=".pdf"], a[href*=".pdf"]'))){if(this.isExcludedDoiContext(n)||this.isExcludedSearchContext(n))continue;const a=this.toNativeFullTextUrl(n.getAttribute("href")??n.href??"");if(a)return a}}extractAbstract(e){return je(e)}firstMetaContent(e){return this.allMetaContent(e)[0]}allMetaContent(e){const t=new Set(e.map(a=>a.toLowerCase())),n=[];for(const a of Array.from(document.querySelectorAll("meta[name], meta[property]"))){const i=(a.getAttribute("name")??a.getAttribute("property")??"").trim().toLowerCase();if(!t.has(i))continue;const o=this.cleanText(a.getAttribute("content")??"");o&&n.push(o)}return this.unique(n)}cleanDoi(e){const t=this.unique([this.pathnameFromPossibleUrl(e)??"",e]);for(const n of t){const i=this.decodeDoiSource(n).match(by),o=i?this.trimDoiTail(i[0]):void 0;if(o)return o}}firstDoi(e){for(const t of e){const n=this.cleanDoi(t);if(n)return n}}sourceIdFor(e,t,n){if(e)return`cambridge-core:${e}`;const a=this.scopedProductId(t)??this.productIdFromUrl(n);if(a)return`cambridge-core:${a}`;if(n)try{return`cambridge-core:${new URL(n).pathname.replace(/\/+$/g,"")||"/"}`}catch{return`cambridge-core:${n}`}}scopedProductId(e){if(e.matches(Oo))return e.querySelector("[data-prod-id]")?.getAttribute("data-prod-id")??e.getAttribute("data-prod-id")??void 0}yearFromText(e){const t=e.match(gy);return t?Number.parseInt(t[1],10):void 0}normalizeIssn(e){const t=e.trim().toUpperCase().replace(/[^0-9X]/g,"");if(/^\d{7}[\dX]$/.test(t))return`${t.slice(0,4)}-${t.slice(4)}`}trimDoiTail(e){let t=e.replace(/[,.;\]\}\s]+$/g,"");for(;t.endsWith(")")&&this.countCharacter(t,")")>this.countCharacter(t,"(");)t=t.slice(0,-1).replace(/[,.;\]\}\s]+$/g,"");return t}productIdFromUrl(e){if(e)try{const n=new URL(e,location.origin).pathname.split("/").filter(Boolean).pop()??"";return/^[A-F0-9]{16,}$/i.test(n)?n:void 0}catch{return}}decodeDoiSource(e){try{return decodeURIComponent(e)}catch{return e}}countCharacter(e,t){return Array.from(e).filter(n=>n===t).length}isExcludedDoiContext(e){return!!e.closest(Lu)||!!this.closestExcludedSection(e)||this.isAfterExcludedModuleHeading(e)}textWithoutExcludedDoiContexts(e){const t=e.cloneNode(!0);return t.querySelectorAll(Lu).forEach(n=>n.remove()),Array.from(t.querySelectorAll("section, aside, nav, div")).forEach(n=>{this.hasExcludedSectionLabel(n)&&n.remove()}),t.textContent??""}toNativeFullTextUrl(e){const t=this.toAbsoluteUrl(e);if(t)try{const n=new URL(t);return n.protocol!=="https:"||n.hostname.toLowerCase()!=="www.cambridge.org"||!/^\/core\/services\/aop-cambridge-core\/content\/view\//i.test(n.pathname)?void 0:n.pathname.toLowerCase().endsWith(".pdf")?n.href:void 0}catch{return}}toArticleUrl(e){const t=this.toAbsoluteUrl(e);if(t)try{const n=new URL(t);return n.searchParams.delete("fromSearch"),n.href}catch{return t}}isRecordLink(e){try{const t=new URL(e.getAttribute("href")??e.href,location.origin);return t.hostname.toLowerCase()==="www.cambridge.org"&&this.isArticleOrBookRecordPath(t.pathname)}catch{return!1}}isArticleOrBookRecordPath(e){return/^\/core\/journals\/[^/]+\/article\//i.test(e)?!0:this.bookRouteKind(`https://www.cambridge.org${e}`)!==void 0}isBlockedPage(){const e=document.title;return/Just a moment|Enable JavaScript and cookies|Access denied|Attention Required|Cloudflare|Sorry, an error occurred/i.test(e)||document.querySelector('.cf-turnstile, .cf-error-code, iframe[src*="challenges.cloudflare.com"], script[src*="/cdn-cgi/challenge-platform/"]')?!0:/Enable JavaScript and cookies to continue|Checking if the site connection is secure|Sorry, you have been blocked|Sorry, an error occurred|Cloudflare Ray ID/i.test(document.body?.textContent??"")}cleanVenue(e){return this.cleanText(e).replace(/^In\s+/i,"").replace(/^Journal\s*:\s*/i,"").replace(/^Book\s*:\s*/i,"").replace(/\s*\/\s*(?:Volume|Issue|Spring|Summer|Autumn|Fall|Winter)\b[\s\S]*$/i,"").replace(/\b(?:Volume|Vol\.?|Issue|No\.?|Pages?|pp\.?)\b[\s\S]*$/i,"").replace(/\b((?:19|20)\d{2})\b[\s\S]*$/i,"").replace(/[,.;:\s]+$/g,"").trim()}toAbsoluteUrl(e){const t=e.trim();if(!(!t||/^javascript:/i.test(t)||/^data:/i.test(t)||t==="#"))try{const n=new URL(t,location.origin);return/^https?:$/.test(n.protocol)?n.href:void 0}catch{return}}cleanText(e){return e.replace(/\s+/g," ").trim()}unique(e){return Array.from(new Set(e.filter(Boolean)))}uniqueElements(e){return Array.from(new Set(e))}isExcludedSearchContext(e){let t=e;for(;t&&t!==document.body;){if(/^(ASIDE|NAV|FOOTER)$/i.test(t.tagName)||t.getAttribute("role")==="complementary"||this.hasExcludedSectionLabel(t))return!0;t=t.parentElement}return!1}pathnameFromPossibleUrl(e){const t=e.trim();if(t)try{const n=new URL(t,location.origin);if(n.hostname.toLowerCase()==="doi.org"||n.pathname.includes("/doi/")||n.pathname.startsWith("/10."))return n.pathname}catch{return}}closestExcludedSection(e){let t=e.parentElement;for(;t&&t!==document.body;){if(!t.matches(Oo)&&this.hasExcludedSectionLabel(t))return t;t=t.parentElement}return null}hasExcludedSectionLabel(e){const t=[e.getAttribute("aria-label")??"",e.getAttribute("aria-labelledby")??"",e.getAttribute("id")??"",e.getAttribute("class")??""].join(" ");return this.isExcludedModuleMarkerText(t)?!0:/^(ARTICLE|MAIN|BODY|HTML)$/i.test(e.tagName)||e.matches(Oo)||e.matches('.article, #maincontent, [role="main"]')?!1:Array.from(e.children).some(n=>this.isExcludedModuleHeadingText(n.textContent??""))}isExcludedModuleMarkerText(e){return/(?:references?|bibliography|related|recommend(?:ed|ations?)?|cited(?:\s+by)?|most\s+read|most\s+viewed|popular|latest|recent|also\s+read|right[-_\s]*rail|sidebar)/i.test(e)}isExcludedModuleHeadingText(e){const t=this.cleanText(e).replace(/\s*(?:\(\s*\d+\s*\)|\[\s*\d+\s*\]|\{\s*\d+\s*\})\s*$/g,"").replace(/\s+\d+\s*$/g,"").trim();return/^(?:references?|bibliography|related(?:\s+articles?)?|recommend(?:ed(?:\s+(?:articles?|for\s+you))?|ations?)|cited(?:\s+by)?|most\s+read(?:\s+articles?)?|most\s+viewed(?:\s+articles?)?|latest(?:\s+(?:articles?|papers?|publications?))?|recent(?:\s+(?:articles?|papers?|publications?))?|(?:people\s+)?also\s+read)$/i.test(t)}isAfterExcludedModuleHeading(e){let t=e;for(;t&&t!==document.body;){let n=t.previousElementSibling;for(;n;){if(this.isExcludedHeadingElement(n))return!0;n=n.previousElementSibling}if(/^(ARTICLE|MAIN)$/i.test(t.tagName))break;t=t.parentElement}return!1}isExcludedHeadingElement(e){return/^H[1-6]$/i.test(e.tagName)||e.getAttribute("role")==="heading"||e.matches('.section-title, .module-header, [class*="section-title"], [class*="module-header"]')?this.isExcludedModuleHeadingText(e.textContent??""):this.isExcludedModuleHeadingText(e.textContent??"")&&!e.querySelector("a[href], button, input, select, textarea")}}const xy=/\b10\.\d{4,9}\/[^\s"'<>]+/i,Ay=/\b((?:19|20)\d{2})\b/,Br=["li.search__item",".search__item",".search-result__item",".resultItem",".issue-item",".search-result-card",'[data-testid*="searchResultItem"]','[data-testid*="search-result"]'].join(","),Cy=[Br,".art_title",".hlFld-Title",".publication_title"].join(","),Ru=[".search-results",".searchResultList",'[aria-label="Search results"]',".results-shell"].join(","),vy=["#main-content article","main article","#main-content","main","article",".article","body"].join(","),Uo=['[id*="reference"]','[id*="Reference"]','[class*="reference"]','[class*="Reference"]','[class*="ref-list"]','[class*="refList"]','[role="doc-bibliography"]','section[aria-label*="Reference"]','section[aria-label*="reference"]','section[aria-labelledby*="Reference"]','section[aria-labelledby*="reference"]','[id*="related"]','[class*="related"]','[id*="recommend"]','[class*="recommend"]','[id*="cited"]','[class*="cited"]','[data-test*="reference"]','[data-testid*="reference"]'].join(",");class Sy extends j{id="sage-journals";name="Sage Journals";matches=["*://journals.sagepub.com/*"];isSearchPage(){if(this.isChallengePage())return!1;const e=location.pathname.toLowerCase();return e==="/action/dosearch"||e.startsWith("/action/dosearch")||!e.startsWith("/doi/")&&new URLSearchParams(location.search).has("AllField")}isArticlePage(){return this.isChallengePage()||this.isSearchPage()||/^\/doi\/(?:pdf|epdf)\//i.test(location.pathname)?!1:/^\/doi\/(?:abs\/|full\/)?10\./i.test(location.pathname)||/^\/doi\/10\./i.test(location.pathname)||/^\/doi\/book\/10\./i.test(location.pathname)||!!this.firstMetaContent(["citation_title"])}parseSearchResults(){const e=[],t=new Set;for(const n of this.getSearchResultHosts())try{const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;if(t.has(i))continue;t.add(i),e.push(a)}catch(a){console.error("[SageJournalsAdapter] Failed to parse search result:",a)}return e}parseArticlePage(){if(this.isChallengePage()||/^\/doi\/(?:pdf|epdf)\//i.test(location.pathname))return null;const e=this.getDetailHostElement();if(!e)return null;try{return this.parseMetadataArticle(e)??this.parseDetailDom(e)}catch(t){return console.error("[SageJournalsAdapter] Failed to parse article page:",t),null}}getMetricBarAnchor(e){if(!this.isSearchPage()){const a=this.findDetailDoiLine(e);if(a)return{element:a,position:"after"}}const t=e.querySelector('h1, h2, h3, .citation__title, .hlFld-Title, .art_title a, [class*="title"]');if(t)return{element:t,position:"after"};const n=e.querySelector('.citation__authors, .publication_meta, [class*="authors"], [class*="meta"]');return n?{element:n,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector(Ru)??document.querySelector("main")??document.body}getPageInfo(){const e=new URLSearchParams(location.search),t=Number.parseInt(e.get("startPage")??e.get("page")??"0",10),n=Number.isFinite(t)?t+1:1,a=this.cleanText(document.querySelector('.result__count, .search-result__count, [class*="result-count"], [data-testid*="result-count"]')?.textContent??""),i=a.match(/\b([\d,]+)\s+results?\b/i)??a.match(/\b([\d,]+)\b/),o=i?Number.parseInt(i[1].replace(/,/g,""),10):void 0;return{pageNum:n,totalPages:o?Math.max(1,Math.ceil(o/20)):1,url:location.href,itemsPerPage:20,totalItems:o}}getSearchResultHosts(){if(this.isChallengePage())return[];const e=this.getSearchResultLists(),t=document.querySelector("main")??document.body,n=e.length>0?e:t?[t]:[];return this.uniqueElements(n.flatMap(a=>Array.from(a.querySelectorAll(Cy))).map(a=>this.toSearchResultHost(a)).filter(a=>!!a).filter(a=>this.looksLikeSearchResult(a)))}getSearchResultLists(){return Array.from(document.querySelectorAll(Ru)).filter(e=>!this.isExcludedSearchContext(e))}looksLikeSearchResult(e){return e.closest('[class^="paperlens-"], [class*=" paperlens-"]')||this.isExcludedSearchContext(e)||e.closest(Uo)||this.isIssueModuleSearchCard(e)?!1:!!this.findTitleLink(e)}isIssueModuleSearchCard(e){return e.matches(".issue-item")?Array.from(e.querySelectorAll('h1, h2, h3, h4, h5, h6, [role="heading"], .section-title, .module-header, [class*="section-title"], [class*="module-header"]')).some(t=>this.isExcludedModuleHeadingText(t.textContent??"")):!1}getDetailHostElement(){const e=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??"").replace(/\s*\|\s*Sage Journals\s*$/i,""),t=this.uniqueElements(Array.from(document.querySelectorAll(vy)));if(e){const s=e.toLowerCase(),l=t.find(c=>(c===document.body||!this.isExcludedSearchContext(c))&&this.cleanText(c.textContent??"").toLowerCase().includes(s));if(l)return l}const n=this.cleanDoi(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href);if(n){const s=t.find(l=>l!==document.body&&!this.isExcludedSearchContext(l)&&this.extractDoi(l,{allowTextFallback:!1})===n);if(s)return s}const a=t.filter(s=>s!==document.body&&!this.isExcludedSearchContext(s)&&!!s.querySelector("h1, .citation__title, .hlFld-Title")),i=this.leafHeadingCandidates(a),o=n?i.find(s=>this.candidateDoi(s)===n)??i.find(s=>!this.candidateDoi(s)&&this.hasDetailArticleEvidence(s))??this.lastNoDoiCandidate(i):i.find(s=>!this.candidateDoi(s)&&this.hasDetailArticleEvidence(s))??this.lastNoDoiCandidate(i)??i[i.length-1];return o||(t.find(s=>s===document.body||!this.isExcludedSearchContext(s))??document.body)}parseSearchHost(e){const t=this.findTitleLink(e),n=this.cleanText(t?.textContent??e.querySelector('h2, h3, .art_title, .publication_title, .search-result__title, [class*="title"]')?.textContent??"");if(!n)return null;const a=this.toArticleUrl(t?.getAttribute("href")??t?.href??""),i=this.cleanDoi(a??"")??this.extractDoi(e,{allowTextFallback:!1,currentUrl:a}),o=this.extractVenue(e),s=this.inferRecordKind(this.extractTypeText(e),a);return{title:n,journalName:o,journalCandidates:o?[o]:[],authors:this.extractAuthorsFromDom(e),year:this.extractYear(e),doi:i,sourceId:this.sourceIdFor(i,a),url:a,nativeFullTextUrl:this.extractNativeFullTextUrl(e,i,a),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:s.articleTypes,source:this.id,citationType:s.citationType}}parseMetadataArticle(e){const t=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??"").replace(/\s*\|\s*Sage Journals\s*$/i,"");if(!t)return null;const n=this.toArticleUrl(this.firstMetaContent(["citation_public_url","citation_fulltext_html_url","prism.url","og:url"])??document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),a=this.firstDoi([...this.allMetaContent(["citation_doi","dc.identifier","prism.doi"]),n??""])??this.extractDoi(e,{allowTextFallback:!1,currentUrl:n}),i=this.firstMetaContent(["citation_inbook_title"])??"",o=this.firstMetaContent(["citation_book_title"])??"",s=this.cleanVenue(this.firstMetaContent(["citation_journal_title","prism.publicationName"])||i||o),l=this.firstMetaContent(["citation_article_type","dc.type"])??"",c=this.inferRecordKind(`${l} ${i}`,n,i,o);return{title:t,journalName:s,journalCandidates:s?[s]:[],authors:this.allMetaContent(["citation_author","dc.creator"]),year:this.yearFromText(this.firstMetaContent(["citation_publication_date","citation_online_date","prism.publicationDate","dc.date"])??""),doi:a,sourceId:this.sourceIdFor(a,n),url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e,a,n),abstractSnippet:this.firstMetaContent(["citation_abstract","dc.description","description","og:description"])??this.extractAbstract(e),hostElement:e,articleTypes:c.articleTypes,issn:this.normalizeIssn(this.firstMetaContent(["citation_issn","prism.issn"])??""),source:this.id,citationType:c.citationType}}parseDetailDom(e){const t=this.cleanText(e.querySelector("h1, .citation__title, .hlFld-Title")?.textContent??document.title.replace(/\s*\|\s*Sage Journals\s*$/i,""));if(!t)return null;const n=this.toArticleUrl(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),a=this.cleanDoi(n??"")??this.extractDoi(e,{allowTextFallback:!1,currentUrl:n}),i=this.extractVenue(e),o=this.inferRecordKind(this.extractTypeText(e),n);return{title:t,journalName:i,journalCandidates:i?[i]:[],authors:this.extractAuthorsFromDom(e),year:this.extractYear(e),doi:a,sourceId:this.sourceIdFor(a,n),url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e,a,n),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:o.articleTypes,source:this.id,citationType:o.citationType}}inferRecordKind(e,t,n="",a=""){const i=`${e} ${this.pathnameFromArticleUrl(t)}`;return/conference paper|conference proceeding/i.test(i)?{articleTypes:["Conference"],citationType:"inproceedings"}:this.cleanText(n).length>0||this.isBookTitleOnlyChapter(e,t,a)||/book chapter|chapter|inbook|book section/i.test(i)?{articleTypes:["BookChapter"],citationType:"incollection"}:/^\/doi\/book\//i.test(this.pathnameFromArticleUrl(t))?{articleTypes:["Book"],citationType:"book"}:this.isWholeBookType(e,t,a)?{articleTypes:["Book"],citationType:"book"}:/\bbook\b/i.test(i)&&!/book review|journal|article/i.test(i)?{articleTypes:["Book"],citationType:"book"}:{articleTypes:["JournalArticle"],citationType:"article"}}findDetailDoiLine(e){if(this.isSearchPage())return null;const t=this.firstDoi([...this.allMetaContent(["citation_doi","dc.identifier","prism.doi"]),document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href]),n=[".epub-doi","[data-doi]",'[data-test*="doi"]','[data-testid*="doi"]','[id*="doi"]','[class*="doi"]','a[href*="doi.org/"]','a[href*="/doi/"]'].join(",");for(const a of Array.from(e.querySelectorAll(n))){if(this.isExcludedDoiContext(a)||this.isExcludedSearchContext(a))continue;const i=a.getAttribute("data-doi")??a.getAttribute("href")??a.textContent??"",o=this.cleanText(a.textContent??i);if(!o)continue;const s=this.cleanDoi(i)??this.cleanDoi(o);if(t&&(!s||s.toLowerCase()!==t.toLowerCase())&&!o.toLowerCase().includes(t.toLowerCase()))continue;const l=this.findDetailMetadataRowFromDoi(a,e,t);if(l)return l;const c=a instanceof HTMLElement?a:null,u=a.closest("div, p, li, section");if(!u)return c;if(this.isExcludedDoiContext(u)||this.isExcludedSearchContext(u)){if(c&&!this.isExcludedDoiContext(c)&&!this.isExcludedSearchContext(c))return c;continue}const d=this.cleanText(u.textContent??"");if(!d||d.length>240){if(c)return c;continue}if(!/\bdoi\b/i.test(d)&&!u.className.toLowerCase().includes("doi")&&!u.id.toLowerCase().includes("doi")){if(c)return c;continue}return u}return null}findDetailMetadataRowFromDoi(e,t,n){let a=e.parentElement,i=null;for(;a&&a!==t&&a!==document.body&&!(this.isExcludedDoiContext(a)||this.isExcludedSearchContext(a));){const o=this.cleanText(a.textContent??"");if(!o||o.length>420)break;if(n&&!o.toLowerCase().includes(n.toLowerCase())){a=a.parentElement;continue}if(a.querySelector("h1, h2, h3"))break;const s=!!(this.cleanDoi(o)||n&&o.toLowerCase().includes(n.toLowerCase())),l=/\b(?:volume|vol\.?|issue|first published|research article|restricted access)\b/i.test(o);s&&l&&(i=a),a=a.parentElement}return i}isWholeBookType(e,t,n=""){const a=`${e} ${this.pathnameFromArticleUrl(t)}`;return/\bbooks?\b/i.test(`${a} ${n}`)?!/book\s+chapter|chapter|inbook|book section|journal|article|review/i.test(a):!1}isBookTitleOnlyChapter(e,t,n=""){return!this.cleanText(n)||/\bbooks?\b/i.test(e)&&!/book\s+chapter|chapter|inbook|book section/i.test(e)?!1:!/^\/doi\/book\//i.test(this.pathnameFromArticleUrl(t))}pathnameFromArticleUrl(e){if(!e)return"";try{return new URL(e,location.origin).pathname}catch{return e}}findTitleLink(e){return Array.from(e.querySelectorAll('h2 a[href], h3 a[href], .art_title a[href], .publication_title a[href], a.publication_title[href], .search-result__title a[href], a[href^="/doi/abs/"], a[href^="/doi/full/"], a[href^="/doi/book/"], a[href*="/doi/10."], a[href*="/doi/abs/10."], a[href*="/doi/full/10."], a[href*="/doi/book/10."]')).find(n=>this.isArticleLink(n)&&this.cleanText(n.textContent??"").length>0)??null}leafHeadingCandidates(e){return e.filter(t=>!e.some(n=>n!==t&&t.contains(n)))}candidateDoi(e){return this.extractDoi(e,{allowTextFallback:!1})}hasDetailArticleEvidence(e){return e.querySelector("h1, .citation__title, .hlFld-Title")?!!e.querySelector([".abstract",'[class*="abstract"]',".authors",".citation__authors",".journal-title",".publication-title",".epub-doi","[data-doi]",'a[href*="doi.org/"]','a[href*="/doi/pdf/"]','a[href*="/doi/epdf/"]'].join(",")):!1}lastNoDoiCandidate(e){return[...e].reverse().find(t=>!this.candidateDoi(t)&&this.hasDetailArticleEvidence(t))}extractVenue(e){const t=[".journal-title",".publication-title",".meta__journal",".citation__journal-title",".source-title",".meta__source",'[data-testid*="journal-title"]','[data-testid*="source"]','[data-testid*="journal"]'].join(",");for(const n of Array.from(e.querySelectorAll(t))){const a=this.cleanVenue(n.textContent??"");if(a&&!/^(Article|Chapter|PDF|Full text)$/i.test(a))return a}return this.cleanVenue(this.firstMetaContent(["citation_journal_title","prism.publicationName","citation_inbook_title","citation_book_title"])??"")}extractTypeText(e){const t=[".publication-type",".content-type",".issue-item__type",'[data-testid*="type"]','[class*="type"]'].join(",");return Array.from(e.querySelectorAll(t)).map(n=>this.cleanText(n.textContent??"")).filter(Boolean).join(" ")}extractAuthorsFromDom(e){const t=[".author-name",".loa__author-name",".citation__author",".authors a",".authors span",'[class*="author"] a','[class*="author"] span',"[data-author-name]"].join(",");return this.unique(Array.from(e.querySelectorAll(t)).map(n=>this.cleanText(n.getAttribute("data-author-name")??n.textContent??"")).filter(n=>n&&!/^(Authors?|View|Show more)$/i.test(n)))}extractYear(e){for(const t of Array.from(e.querySelectorAll('time, .publication-year, .date, [class*="year"], [class*="date"]'))){const n=this.yearFromText(t.textContent??"");if(n)return n}return this.yearFromText(e.textContent??"")}extractDoi(e,t={}){const n=t.allowTextFallback??!0,a=t.currentUrl;for(const i of Array.from(e.querySelectorAll('a[href*="doi.org/"], a[href*="/doi/10."], a[href*="/doi/abs/10."], a[href*="/doi/full/10."], a[href*="/doi/pdf/10."], a[href*="/doi/epdf/10."]'))){if(this.isExcludedDoiContext(i)||this.isExcludedSearchContext(i)||!this.isMatchingArticleDoiLink(i.getAttribute("href")??i.href??"",a))continue;const o=this.cleanDoi(i.href);if(o)return o}for(const i of Array.from(e.querySelectorAll('[data-doi], [data-test*="doi"], [data-testid*="doi"], [id*="doi"], [class*="doi"], .epub-doi'))){if(this.isExcludedDoiContext(i)||this.isExcludedSearchContext(i))continue;const o=this.cleanDoi(i.getAttribute("data-doi")??i.textContent??"");if(o)return o}if(n)return this.cleanDoi(this.textWithoutExcludedDoiContexts(e))}extractNativeFullTextUrl(e,t,n){const a=this.toNativeFullTextUrl(this.firstMetaContent(["citation_pdf_url"])??"",t,n);if(a)return a;for(const i of Array.from(e.querySelectorAll('a[href*="/doi/pdf/"], a[href*="/doi/epdf/"], a[href$=".pdf"], a[href*="/pdf"]'))){if(this.isExcludedDoiContext(i)||this.isExcludedSearchContext(i))continue;const o=this.toNativeFullTextUrl(i.getAttribute("href")??i.href??"",t,n);if(o)return o}}extractAbstract(e){return je(e)}firstMetaContent(e){return this.allMetaContent(e)[0]}allMetaContent(e){const t=new Set(e.map(a=>a.toLowerCase())),n=[];for(const a of Array.from(document.querySelectorAll("meta[name], meta[property]"))){const i=(a.getAttribute("name")??a.getAttribute("property")??"").trim().toLowerCase();if(!t.has(i))continue;const o=this.cleanText(a.getAttribute("content")??"");o&&n.push(o)}return this.unique(n)}cleanDoi(e){const t=this.unique([this.pathnameFromPossibleUrl(e)??"",e]);for(const n of t){const i=this.decodeDoiSource(n).match(xy),o=i?this.trimDoiTail(i[0]):void 0;if(o)return o}}firstDoi(e){for(const t of e){const n=this.cleanDoi(t);if(n)return n}}sourceIdFor(e,t){if(e)return`sage-journals:${e}`;if(t)try{const n=new URL(t);return`sage-journals:${this.normalizedArticlePath(n.pathname)}`}catch{return`sage-journals:${t}`}}normalizedArticlePath(e){return e.replace(/^\/doi\/(?:abs|full|pdf|epdf)\//i,"/doi/full/").replace(/\/+$/g,"")||"/"}expectedPdfPathForArticleUrl(e){if(!e)return;const t=this.normalizedArticlePath(this.pathnameFromArticleUrl(e));if(/^\/doi\/full\//i.test(t))return t.replace(/^\/doi\/full\//i,"/doi/pdf/")}yearFromText(e){const t=e.match(Ay);return t?Number.parseInt(t[1],10):void 0}normalizeIssn(e){const t=e.trim().toUpperCase().replace(/[^0-9X]/g,"");if(/^\d{7}[\dX]$/.test(t))return`${t.slice(0,4)}-${t.slice(4)}`}trimDoiTail(e){let t=e.replace(/[,.;\]\}\s]+$/g,"");for(;t.endsWith(")")&&this.countCharacter(t,")")>this.countCharacter(t,"(");)t=t.slice(0,-1).replace(/[,.;\]\}\s]+$/g,"");return t}toNativeFullTextUrl(e,t,n){const a=this.toAbsoluteUrl(e);if(a)try{const i=new URL(a);if(i.protocol!=="https:"||i.hostname.toLowerCase()!=="journals.sagepub.com"||!/^\/doi\/(?:pdf|epdf)\//i.test(i.pathname))return;if(t){const o=this.cleanDoi(i.href);if(!o||o.toLowerCase()!==t.toLowerCase())return}else if(n){const o=this.expectedPdfPathForArticleUrl(n);if(!o||i.pathname!==o)return}return i.href}catch{return}}toArticleUrl(e){const t=this.toAbsoluteUrl(e);if(t)try{const n=new URL(t);return n.searchParams.delete("af"),n.searchParams.delete("campaign"),n.href}catch{return t}}isArticleLink(e){try{const t=new URL(e.getAttribute("href")??e.href,location.origin);return t.hostname.toLowerCase()==="journals.sagepub.com"&&(/^\/doi\/(?:abs\/|full\/|pdf\/|epdf\/|book\/)?10\./i.test(t.pathname)||/^\/doi\/(?:abs\/|full\/)[^/?#]+$/i.test(t.pathname))}catch{return!1}}isMatchingArticleDoiLink(e,t){if(!t)return!0;const n=this.toAbsoluteUrl(e);if(!n)return!1;try{const a=new URL(n);if(!/^\/doi\/(?:pdf|epdf)\//i.test(a.pathname))return!0;const i=this.expectedPdfPathForArticleUrl(t);return!!(i&&a.pathname===i)}catch{return!1}}isChallengePage(){const e=document.title,t=this.hasArticleMetadata(),n=document.body?.textContent??"";return this.isChallengeInterstitial(e,n)||/Just a moment|Enable JavaScript and cookies|Access(?:\s+denied|\s+to\s+this\s+page\s+has\s+been\s+denied)|Attention Required|Cloudflare|Imperva|Incapsula/i.test(e)&&!t||/(?:Please\s+)?Verify(?:ing)? you are human|Robot Check/i.test(e)&&!t||document.querySelector('.cf-error-code, iframe[src*="challenges.cloudflare.com"], script[src*="/cdn-cgi/challenge-platform/"]')||!t&&document.querySelector('.cf-turnstile, iframe[src*="recaptcha"], .g-recaptcha, [data-sitekey]')||!t&&/Enable JavaScript and cookies to continue|Please make sure that JavaScript and cookies are enabled|Sorry, you have been blocked|Cloudflare Ray ID|Imperva|Incapsula/i.test(n)||/Checking if the site connection is secure|(?:Please\s+)?Verify(?:ing)? you are human|review the security of your connection|needs to review the security|Robot Check/i.test(n)&&!t?!0:!t&&/\b(?:reCAPTCHA|captcha)\b/i.test(n)&&/\b(?:verify|human|robot|security|challenge|blocked|access denied)\b/i.test(n)}isChallengeInterstitial(e,t){const n=this.cleanText(e),a=this.cleanText(t);return/Just a moment|Attention Required/i.test(n)&&/Enable JavaScript and cookies to continue|Sorry, you have been blocked|Cloudflare Ray ID/i.test(a)||/^(?:Please\s+)?Verify(?:ing)? you are human$/i.test(n)||/^Robot Check$/i.test(n)||/^Access(?:\s+Denied|\s+to\s+this\s+page\s+has\s+been\s+denied)[.!?]?$/i.test(n)||/(?:Please\s+)?Verify(?:ing)? you are human by completing the action below/i.test(a)||/Access\s+to\s+this\s+page\s+has\s+been\s+denied[.!?]?/i.test(a)||/Request unsuccessful/i.test(a)&&/Incapsula incident ID|Imperva/i.test(a)?!0:/Access Denied/i.test(a)&&/(?:do not|don't|don’t|does not|not) have permission|permission denied/i.test(a)}hasArticleMetadata(){if(this.firstMetaContent(["citation_title","citation_doi","prism.doi"]))return!0;const e=this.cleanText(this.firstMetaContent(["dc.title"])??"");return!!(e&&!/^SAGE\s+Journals?$/i.test(e))}isExcludedDoiContext(e){return!!e.closest(Uo)||!!this.closestExcludedSection(e)||this.isAfterExcludedModuleHeading(e)}textWithoutExcludedDoiContexts(e){const t=e.cloneNode(!0);return t.querySelectorAll(Uo).forEach(n=>n.remove()),Array.from(t.querySelectorAll("section, aside, nav, div")).forEach(n=>{this.hasExcludedSectionLabel(n)&&n.remove()}),t.textContent??""}closestExcludedSection(e){let t=e.parentElement;for(;t&&t!==document.body;){if(!t.matches(Br)&&this.hasExcludedSectionLabel(t))return t;t=t.parentElement}return null}hasExcludedSectionLabel(e){const t=[e.getAttribute("aria-label")??"",e.getAttribute("aria-labelledby")??"",e.getAttribute("id")??"",e.getAttribute("class")??""].join(" ");return this.isExcludedModuleMarkerText(t)?!0:/^(ARTICLE|MAIN|BODY|HTML)$/i.test(e.tagName)||e.matches(Br)||e.matches('.article, #main-content, [role="main"]')?!1:Array.from(e.children).some(n=>this.isExcludedModuleHeadingText(n.textContent??""))}isAfterExcludedModuleHeading(e){let t=e;for(;t&&t!==document.body;){let n=t.previousElementSibling;for(;n;){if(this.isExcludedHeadingElement(n))return!0;n=n.previousElementSibling}if(/^(ARTICLE|MAIN)$/i.test(t.tagName))break;t=t.parentElement}return!1}isExcludedHeadingElement(e){return/^H[1-6]$/i.test(e.tagName)||e.getAttribute("role")==="heading"||e.matches('.section-title, .module-header, [class*="section-title"], [class*="module-header"]')?this.isExcludedModuleHeadingText(e.textContent??""):this.isExcludedModuleHeadingText(e.textContent??"")&&!e.querySelector("a[href], button, input, select, textarea")}isExcludedModuleMarkerText(e){return/(?:references?|bibliography|related|related\s+content|recommend(?:ed|ations?)?|article\s+recommendations?|recommended\s+content|we\s+also\s+recommend|similar\s+articles?|more\s+like\s+this|more\s+from\s+(?:this\s+)?(?:journal|sage(?:\s+journals?)?)|also\s+from\s+(?:this\s+)?(?:journal|sage(?:\s+journals?)?)|cited(?:\s+by)?|most\s+read|most\s+viewed|popular|latest|latest\s+issue|current\s+issue|browse\s+issue|issue\s+module|recent|also\s+read|you\s+may\s+also\s+like|may\s+also\s+like|trending|right[-_\s]*rail|secondary[-_\s]*(?:rail|content)|sidebar|captcha|recaptcha|imperva|incapsula)/i.test(e)}isExcludedModuleHeadingText(e){const t=this.normalizeModuleHeadingText(e);return/^(?:references?|bibliography|related(?:\s+(?:articles?|content))?|recommend(?:ed(?:\s+(?:articles?|for\s+you|content))?|ations?)|article\s+recommendations?|we\s+also\s+recommend|similar(?:\s+articles?)?|more\s+like\s+this|more\s+from\s+(?:this\s+)?(?:journal|sage(?:\s+journals?)?)|also\s+from\s+(?:this\s+)?(?:journal|sage(?:\s+journals?)?)|cited(?:\s+by)?|most\s+read(?:\s+articles?)?|most\s+viewed(?:\s+articles?)?|popular|trending|latest(?:\s+(?:articles?|papers?|publications?|issue))?|current\s+issue|browse\s+issue|issue\s+module|recent(?:\s+(?:articles?|papers?|publications?))?|(?:people\s+)?also\s+read|you\s+may\s+also\s+like|may\s+also\s+like)$/i.test(t)}normalizeModuleHeadingText(e){let t=this.cleanText(e);for(let n=0;n<3;n+=1){const a=t.replace(/\s*(?:\(\s*\d+\s*\)|\[\s*\d+\s*\]|\{\s*\d+\s*\})\s*$/g,"").replace(/\s+\d+\s*$/g,"").replace(/(?:\s+|(?=[A-Z]))(?:view|see|show|browse)\s*(?:all|more)(?:\s*(?:articles?|papers?|publications?|content|items?|references?))?\s*$/i,"").trim();if(a===t)break;t=a}return t}isExcludedSearchContext(e){let t=e;for(;t&&t!==document.body;){if(/^(ASIDE|NAV|FOOTER)$/i.test(t.tagName)||t.getAttribute("role")==="complementary"||this.hasExcludedSectionLabel(t))return!0;t=t.parentElement}return!1}pathnameFromPossibleUrl(e){const t=e.trim();if(t)try{const n=new URL(t,location.origin);if(n.hostname.toLowerCase()==="doi.org"||n.pathname.includes("/doi/")||n.pathname.startsWith("/10."))return n.pathname}catch{return}}decodeDoiSource(e){try{return decodeURIComponent(e)}catch{return e}}countCharacter(e,t){return Array.from(e).filter(n=>n===t).length}cleanVenue(e){const t=this.cleanText(e).replace(/^Sage\s+Journals?\s*[·|]\s*/i,"").replace(/^Published\s+in\s*:?\s*/i,"").replace(/^Source\s*:?\s*/i,"").replace(/^In\s+/i,"").replace(/^Journal\s*:?\s*/i,"").replace(/\b(?:Volume|Vol\.?|Issue|No\.?|Pages?|pp\.?)\b[\s\S]*$/i,"").replace(/\b((?:19|20)\d{2})\b[\s\S]*$/i,"").replace(/[,.;:\s]+$/g,"").trim();return/^Published\s+online(?:\s*:?\s*.*)?$/i.test(t)?"":t}toAbsoluteUrl(e){const t=e.trim();if(!(!t||/^javascript:/i.test(t)||/^data:/i.test(t)||t==="#"))try{const n=new URL(t,location.origin);return/^https?:$/.test(n.protocol)?n.href:void 0}catch{return}}cleanText(e){return e.replace(/\s+/g," ").trim()}unique(e){return Array.from(new Set(e.filter(Boolean)))}uniqueElements(e){return Array.from(new Set(e))}toSearchResultHost(e){return e.matches(Br)?e:e.closest(Br)??e.closest("li, .search-result, .search-result__item, .issue-item, article")??e}}const wy=/\b10\.\d{4,9}\/[^\s"'<>?#]+/i,Ty=/\b((?:19|20)\d{2})\b/,Pu=["li.app-article-list-row__item","article.c-card",'[data-test="search-result"]','[data-test="article-item"]'].join(","),Bu=["article","#content","#main-content","main","body"].join(","),Ho=['[id*="reference"]','[id*="Reference"]','[class*="reference"]','[class*="Reference"]','[role="doc-bibliography"]','section[aria-label*="reference"]','section[aria-label*="Reference"]','section[aria-labelledby*="reference"]','section[aria-labelledby*="Reference"]','[aria-label*="reference"]','[aria-label*="Reference"]','[aria-labelledby*="reference"]','[aria-labelledby*="Reference"]','[id*="related"]','[id*="Related"]','[class*="related"]','[class*="Related"]','[aria-label*="related"]','[aria-label*="Related"]','[id*="recommend"]','[id*="Recommend"]','[class*="recommend"]','[class*="Recommend"]','[id*="further-reading"]','[class*="further-reading"]','[id*="more-on-this-story"]','[class*="more-on-this-story"]','[aria-label*="more on this story"]','[aria-label*="More on this story"]','[aria-label*="further reading"]','[aria-label*="Further reading"]','[data-test*="reference"]','[data-testid*="reference"]','[data-test*="supplementary"]','[data-testid*="supplementary"]','[aria-label*="supplementary"]','[aria-label*="Supplementary"]','[aria-labelledby*="supplementary"]','[aria-labelledby*="Supplementary"]',".c-article-supplementary__item",".c-article-associated-content",".c-reading-companion"].join(",");class Ey extends j{id="nature";name="Nature.com";matches=["*://www.nature.com/*"];isSearchPage(){return this.isChallengePage()?!1:this.isSearchRoute()}isArticlePage(){if(this.isChallengePage()||this.isSearchRoute())return!1;if(/^\/articles\/[^/]+\/?$/i.test(location.pathname))return!0;const e=this.firstMetaContent(["citation_fulltext_html_url","prism.url","og:url"])??document.querySelector('link[rel="canonical"]')?.getAttribute("href")??"";return!!(this.isNatureArticleUrl(e)&&this.hasArticleMetadata())}parseSearchResults(){if(this.isChallengePage())return[];const e=[],t=new Set;for(const n of this.getSearchResultHosts())try{const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;if(t.has(i))continue;t.add(i),e.push(a)}catch(a){console.error("[NatureAdapter] Failed to parse search result:",a)}return e}parseArticlePage(){if(this.isChallengePage())return null;const e=this.getDetailHost();if(!e)return null;try{return this.parseMetadataArticle(e)??this.parseDetailDom(e)}catch(t){return console.error("[NatureAdapter] Failed to parse article page:",t),null}}getMetricBarAnchor(e){if(this.isSearchPage()&&this.isSearchResultHost(e)){const a=this.findSearchContentAnchor(e)??this.findSearchMetaAnchor(e);if(a)return{element:a,position:"after"}}if(!this.isSearchPage()){const a=this.findDetailMetricsAnchor(e);if(a)return{element:a,position:"after"};const i=this.findDetailTitleAnchor(e);if(i)return{element:i,position:"after"}}const t=e.querySelector('h1, h2, h3, .c-article-title, .c-card__title, [itemprop="headline"], [itemprop="name"]');if(t)return{element:t,position:"after"};const n=e.querySelector(".c-article-author-list, .app-author-list, .c-card__section.c-meta, .c-meta");return n?{element:n,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector(".app-article-list-row")??document.querySelector('[data-test="search-results"]')??document.querySelector('[data-test="search-result-list"]')??document.querySelector("main")??document.body}getPageInfo(){const e=new URLSearchParams(location.search),t=Number.parseInt(e.get("page")??"1",10)||1,a=this.cleanText(document.querySelector('[data-test="results-count"], .app-search-result-list__count, .c-list-results__count, .c-results-heading')?.textContent??"").match(/\b([\d,]+)\s+(?:results?|articles?)\b/i),i=a?Number.parseInt(a[1].replace(/,/g,""),10):void 0,o=this.extractPaginationTotalPages();return{pageNum:t,totalPages:o??(i?Math.max(1,Math.ceil(i/20)):1),url:location.href,itemsPerPage:20,totalItems:i}}getSearchResultHosts(){return this.uniqueElements(Array.from(document.querySelectorAll(Pu)).filter(e=>this.looksLikeSearchResult(e)))}isSearchResultHost(e){return e.matches(Pu)||e.matches(".c-card")}findSearchContentAnchor(e){const t=e.querySelector('.app-author-list, .c-article-author-list, [data-test="authors"], [data-testid*="author"], [class*="author-list"]');return t||(e.querySelector('[data-test="journal-title-and-link"], [data-test="journal-title"], [data-testid*="journal"], .journal-title')??null)}findSearchMetaAnchor(e){const t=e.querySelector('h1, h2, h3, .c-article-title, .c-card__title, [itemprop="headline"], [itemprop="name"]'),n=[".c-card__section.c-meta",".c-meta",'[data-test*="article-metadata"], [data-testid*="article-metadata"], [data-test*="metadata"], [data-testid*="metadata"]','[class*="meta"]'];for(const o of n){const s=Array.from(e.querySelectorAll(o)).filter(c=>this.looksLikeSearchMeta(c)),l=this.pickTrailingMetaCandidate(s,t)??s[0];if(l)return l}const a=Array.from(e.querySelectorAll('time[datetime], time, [data-test*="date"], [data-testid*="date"], [data-test*="type"], [data-testid*="type"], .c-meta__type')).filter(o=>this.looksLikeSearchMeta(o));return this.pickTrailingMetaCandidate(a,t,"last")??a[a.length-1]??null}looksLikeSearchMeta(e){return this.cleanText(e.textContent??"")?e.matches('time, [data-test*="date"], [data-testid*="date"], [data-test*="type"], [data-testid*="type"], [data-test="journal-title-and-link"], [data-test="journal-title"], .c-meta__type')?!0:!!e.querySelector('time, [data-test*="date"], [data-testid*="date"], [data-test*="type"], [data-testid*="type"], [data-test="journal-title-and-link"], [data-test="journal-title"], .c-meta__type'):!1}followsElement(e,t){const n=t.ownerDocument?.defaultView?.Node;return n?!!(t.compareDocumentPosition(e)&n.DOCUMENT_POSITION_FOLLOWING):!1}pickTrailingMetaCandidate(e,t,n="first"){if(!t)return e[0]??null;const a=e.filter(i=>this.followsElement(i,t));return a.length===0?null:n==="last"?a[a.length-1]:a[0]}findDetailTitleAnchor(e){const t=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??document.title).replace(/\s*\|\s*Nature\s*$/i,""),n=this.titleKey(t);if(!n)return e.querySelector('h1, .c-article-title, [itemprop="headline"]');const a=Array.from(e.querySelectorAll('h1, .c-article-title, [itemprop="headline"], h2, h3, .c-card__title')),i=a.find(o=>this.titleKey(o.textContent??"")===n);return i||(a.find(o=>{const s=this.titleKey(o.textContent??"");return s.length>=12&&(s.includes(n)||n.includes(s))})??null)}findDetailMetricsAnchor(e){const t=[".c-article-metrics-bar__wrapper",".c-article-metrics-bar",'[data-test="access-count"]','[data-test="citation-count"]','[data-test="altmetric-score"]','a[href$="/metrics"]','a[href*="/metrics?"]'];for(const n of t)for(const a of Array.from(e.querySelectorAll(n))){const i=a.closest(".c-article-metrics-bar__wrapper, .c-article-metrics-bar, header, .c-article-header");if(i&&!this.isExcludedContext(i)){if(i.matches(".c-article-header")){const o=i.querySelector(".c-article-metrics-bar__wrapper, .c-article-metrics-bar");if(o&&!this.isExcludedContext(o))return o}return i}}return null}getDetailHost(){const e=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??document.title).replace(/\s*\|\s*Nature\s*$/i,"");let t=null,n=-1;for(const a of Bu.split(","))for(const i of Array.from(document.querySelectorAll(a.trim()))){const o=this.getDetailHostScore(i,e);(o>n||o===n&&this.breaksDetailHostTie(i,t))&&(t=i,n=o)}return t??document.querySelector(Bu)}getDetailHostScore(e,t){let n=e.matches("article")?2:0;const a=this.titleKey(this.findDetailTitleAnchor(e)?.textContent??""),i=this.titleKey(t);return i&&a===i?n+=8:i&&a&&(a.includes(i)||i.includes(a))&&(n+=4),e.querySelector('[data-test="download-pdf"], a[data-article-pdf="true"], a[href$=".pdf"]')&&(n+=3),e.querySelector("h1, .c-article-title")&&(n+=2),e.querySelector('[data-test="journal-title-and-link"], .c-meta, .c-card__section.c-meta')&&(n+=1),n}breaksDetailHostTie(e,t){if(!t)return!0;const n=this.detailHostRank(e),a=this.detailHostRank(t);if(n!==a)return n<a;const i=this.cleanText(e.textContent??"").length,o=this.cleanText(t.textContent??"").length;return i<o}detailHostRank(e){return e.matches("article")?0:e.matches("#content, #main-content, main")?1:e===document.body?3:2}titleKey(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}looksLikeSearchResult(e){return e.closest('[class^="paperlens-"], [class*=" paperlens-"]')||e.closest(Ho)||e.matches("article.c-card")&&e.parentElement?.closest("li.app-article-list-row__item")?!1:!!this.findTitleLink(e)}parseSearchHost(e){const t=this.findTitleLink(e),n=this.cleanText(t?.textContent??e.querySelector('h2, h3, .c-card__title, [itemprop="headline"], [itemprop="name"]')?.textContent??"");if(!n)return null;const a=this.toArticleUrl(t?.getAttribute("href")??t?.href??""),i=this.doiFromArticleUrl(a??"")??this.extractDoi(e,{allowTextFallback:!1}),o=this.extractTypeText(e),s=this.inferRecordKind(o,a,i),l=s.metricsAllowed?this.extractVenue(e):"";return{title:n,journalName:l,journalCandidates:l?[l]:[],authors:this.extractAuthorsFromDom(e),year:this.extractYear(e),doi:i,sourceId:i?`nature:${i}`:a?`nature:${new URL(a).pathname}`:void 0,url:a,nativeFullTextUrl:this.extractNativeFullTextUrl(e,i,a),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:s.articleTypes,source:this.id,citationType:s.citationType}}parseMetadataArticle(e){const t=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??"").replace(/\s*\|\s*Nature\s*$/i,"");if(!t)return null;const n=this.toArticleUrl(this.firstMetaContent(["citation_fulltext_html_url","prism.url","og:url"])??document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),a=this.firstDoi([...this.allMetaContent(["citation_doi","dc.identifier","prism.doi"]),n??""]),i=this.firstMetaContent(["citation_article_type","dc.type","prism.section"])??"",o=this.inferRecordKind(i,n,a),s=o.metricsAllowed?this.cleanVenue(this.firstMetaContent(["citation_journal_title","prism.publicationName"])??this.journalFromPageContext()??""):"";return{title:t,journalName:s,journalCandidates:s?[s]:[],authors:this.allMetaContent(["citation_author","dc.creator"]),year:this.yearFromText(this.firstMetaContent(["citation_publication_date","citation_online_date","prism.publicationDate","dc.date"])??""),doi:a,sourceId:a?`nature:${a}`:n?`nature:${new URL(n).pathname}`:void 0,url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e,a,n),abstractSnippet:this.firstMetaContent(["citation_abstract","dc.description","description","og:description"])??this.extractAbstract(e),hostElement:e,articleTypes:o.articleTypes,issn:o.metricsAllowed?this.normalizeIssn(this.firstMetaContent(["citation_issn","prism.issn"])??""):void 0,source:this.id,citationType:o.citationType}}parseDetailDom(e){const t=this.cleanText(e.querySelector('h1, .c-article-title, [itemprop="headline"]')?.textContent??document.title.replace(/\s*\|\s*Nature\s*$/i,""));if(!t)return null;const n=this.toArticleUrl(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),a=this.doiFromArticleUrl(n??"")??this.extractDoi(e,{allowTextFallback:!1}),i=this.inferRecordKind(this.extractTypeText(e),n,a),o=i.metricsAllowed?this.extractVenue(e):"";return{title:t,journalName:o,journalCandidates:o?[o]:[],authors:this.extractAuthorsFromDom(e),year:this.extractYear(e),doi:a,sourceId:a?`nature:${a}`:n?`nature:${new URL(n).pathname}`:void 0,url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e,a,n),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:i.articleTypes,source:this.id,citationType:i.citationType}}inferRecordKind(e,t,n){const a=this.cleanText(`${e} ${t??""} ${n??""}`).toLowerCase();return/\b(?:news\s*&\s*views|news|research highlight|career feature|technology feature|books?\s*&\s*arts|nature briefing|where i work|world view|obituary)\b/.test(a)||/10\.1038\/d41586-/i.test(a)?{articleTypes:["News"],citationType:"misc",metricsAllowed:!1}:/\b(?:comment|opinion|editorial|correspondence)\b/.test(a)?{articleTypes:["Comment"],citationType:"misc",metricsAllowed:!1}:{articleTypes:["JournalArticle"],citationType:"article",metricsAllowed:!0}}findTitleLink(e){return Array.from(e.querySelectorAll('h2 a[href], h3 a[href], .c-card__title a[href], a[itemprop="url"][href], a[href*="/articles/"]')).find(n=>this.isArticleLink(n)&&this.cleanText(n.textContent??"").length>0)??null}extractTypeText(e){const t=['[data-test="article.type"]','[data-test*="type"]','[data-testid*="type"]',".c-meta__type",".c-card__section.c-meta",'[class*="type"]'].join(",");return Array.from(e.querySelectorAll(t)).map(n=>this.cleanText(n.textContent??"")).filter(Boolean).join(" ")}extractVenue(e){const t=['[data-test="journal-title"]','[data-test="article.journal"]','[data-testid*="journal"]','.c-card__section [data-test*="journal"]',".journal-title",".c-meta__item--journal"].join(",");for(const n of Array.from(e.querySelectorAll(t))){const a=this.cleanVenue(n.textContent??"");if(a)return a}return this.cleanVenue(this.firstMetaContent(["citation_journal_title","prism.publicationName"])??this.journalFromPageContext()??"")}extractAuthorsFromDom(e){const t=['[itemprop="author"]',".c-article-author-list__item",".app-author-list__item",'[data-test="author-name"]','[class*="author"] a','[class*="author"] span'].join(",");return this.unique(Array.from(e.querySelectorAll(t)).map(n=>this.cleanText(n.getAttribute("data-author-name")??n.textContent??"")).map(n=>n.replace(/^\s*(?:By|Author)\s+/i,"")).filter(n=>n&&!/^(Authors?|View author publications|PubMed|Google Scholar|Show more)$/i.test(n)))}extractYear(e){for(const t of Array.from(e.querySelectorAll('time[datetime], time, [data-test*="date"], .c-meta__item'))){const n=t.getAttribute("datetime")??"",a=this.yearFromText(n)??this.yearFromText(t.textContent??"");if(a)return a}return this.yearFromText(e.textContent??"")}extractDoi(e,t={}){const n=t.allowTextFallback??!0;for(const a of Array.from(e.querySelectorAll('a[href*="doi.org/"], a[href*="/articles/"]'))){if(this.isExcludedContext(a))continue;const i=this.cleanDoi(a.href)??this.doiFromArticleUrl(a.href);if(i)return i}for(const a of Array.from(e.querySelectorAll('[data-test*="doi"], [data-testid*="doi"], [id*="doi"], [class*="doi"], .c-article-identifiers__item'))){if(this.isExcludedContext(a))continue;const i=this.cleanDoi(a.textContent??"");if(i)return i}if(n)return this.cleanDoi(this.textWithoutExcludedContexts(e))}extractNativeFullTextUrl(e,t,n){const a=this.toNativeFullTextUrl(this.firstMetaContent(["citation_pdf_url"])??"",t,n);if(a)return a;const i=Array.from(e.querySelectorAll('a[data-test="download-pdf"], a[data-article-pdf="true"], a[href$=".pdf"], a[href*="/articles/"][href*=".pdf"]')).find(o=>!this.isExcludedContext(o));return this.toNativeFullTextUrl(i?.getAttribute("href")??i?.href??"",t,n)}extractAbstract(e){return je(e)}isExcludedContext(e){if(e.closest(Ho))return!0;const t=e.closest("section, aside, nav, div, article");if(!t||t===document.body)return!1;const n=t.getAttribute("aria-labelledby")??"",a=t.getAttribute("aria-label")??"",i=this.cleanText(Array.from(t.querySelectorAll(":scope > h1, :scope > h2, :scope > h3, :scope > header h1, :scope > header h2, :scope > header h3")).map(o=>o.textContent??"").join(" "));return this.isExcludedModuleText(`${a} ${n} ${i}`)}isChallengePage(){const e=document.title,t=this.cleanText(document.body?.textContent??"");return!!(/Client Challenge|Just a moment|Access denied|Robot Check|Verify you are human/i.test(e)||document.querySelector('.cf-turnstile, iframe[src*="challenges.cloudflare.com"], script[src*="/cdn-cgi/challenge-platform/"], script[src*="/_fs-ch-"]')||!this.hasArticleMetadata()&&/JavaScript is disabled in your browser|Please enable JavaScript to proceed|A required part of this site couldn't load|A required part of this site couldn’t load|Client Challenge/i.test(t))}firstMetaContent(e){return this.allMetaContent(e)[0]}allMetaContent(e){const t=[];for(const n of e){const a=[`meta[name="${n}"]`,`meta[property="${n}"]`,`meta[name="${n.toLowerCase()}"]`,`meta[property="${n.toLowerCase()}"]`].join(",");for(const i of Array.from(document.querySelectorAll(a))){const o=this.cleanText(i.getAttribute("content")??"");o&&t.push(o)}}return this.unique(t)}firstDoi(e){for(const t of e){const n=this.cleanDoi(t)??this.doiFromArticleUrl(t);if(n)return n}}cleanDoi(e){return this.decodeDoiSource(e).match(wy)?.[0].replace(/[),.;\s]+$/g,"")}doiFromArticleUrl(e){const t=this.toAbsoluteUrl(e);if(t)try{const n=new URL(t);if(n.hostname.toLowerCase()!=="www.nature.com")return;const a=n.pathname.match(/^\/articles\/([^/?#]+?)(?:\.pdf)?\/?$/i);if(!a)return;const i=a[1].replace(/\/+$/g,"");return/^(?:s\d|d\d|nature\d|n[a-z]+\.\d)/i.test(i)?`10.1038/${i}`:void 0}catch{return}}toNativeFullTextUrl(e,t,n){const a=this.toAbsoluteUrl(e);if(a)try{const i=new URL(a);if(i.protocol!=="https:"||i.hostname.toLowerCase()!=="www.nature.com"||!/^\/articles\/[^/]+\.pdf$/i.test(i.pathname))return;const o=t?.replace(/^10\.1038\//i,"")??this.articleSuffixFromUrl(n??"");return!o||!i.pathname.toLowerCase().includes(`/${o.toLowerCase()}.pdf`)?void 0:a}catch{return}}isArticleLink(e){try{const t=new URL(e.getAttribute("href")??e.href,location.origin);return t.hostname.toLowerCase()==="www.nature.com"&&/^\/articles\/[^/]+\/?$/i.test(t.pathname)}catch{return!1}}isSearchRoute(){return location.pathname==="/search"||location.pathname.startsWith("/search/")||/^\/[a-z0-9-]+\/(?:articles|research-articles)\/?$/i.test(location.pathname)}isNatureArticleUrl(e){const t=this.toAbsoluteUrl(e);if(!t)return!1;try{const n=new URL(t);return n.hostname.toLowerCase()==="www.nature.com"&&/^\/articles\/[^/]+\/?$/i.test(n.pathname)}catch{return!1}}hasArticleMetadata(){return!!(this.firstMetaContent(["citation_title","dc.title"])&&(this.firstMetaContent(["citation_doi","prism.doi"])||this.firstMetaContent(["citation_article_type","prism.section"])||this.isNatureArticleUrl(this.firstMetaContent(["citation_fulltext_html_url","prism.url","og:url"])??"")))}toArticleUrl(e){const t=this.toAbsoluteUrl(e);if(t)try{const n=new URL(t);return n.hash="",n.searchParams.delete("error"),n.searchParams.delete("tracking_referrer"),n.href}catch{return t}}toAbsoluteUrl(e){const t=e.trim();if(!(!t||/^javascript:/i.test(t)||/^data:/i.test(t)))try{const n=new URL(t,location.origin);return/^https?:$/.test(n.protocol)?n.href:void 0}catch{return}}articleSuffixFromUrl(e){const t=this.toAbsoluteUrl(e);if(t)try{const n=new URL(t);return n.hostname.toLowerCase()!=="www.nature.com"?void 0:n.pathname.match(/^\/articles\/([^/?#]+?)(?:\.pdf)?\/?$/i)?.[1]?.replace(/\/+$/g,"")}catch{return}}extractPaginationTotalPages(){const e=Array.from(document.querySelectorAll('[data-page], .c-pagination a[href*="page="], nav[aria-label*="pagination"] a[href*="page="]')).map(t=>{const n=t.getAttribute("data-page");if(n)return Number.parseInt(n,10);const a=t.getAttribute?.("href")??"";try{return Number.parseInt(new URL(a,location.href).searchParams.get("page")??"",10)}catch{return NaN}}).filter(t=>Number.isFinite(t)&&t>0);if(e.length!==0)return Math.max(...e)}journalFromPageContext(){const t=(document.querySelector('script[data-test="dataLayer"]')?.textContent??"").match(/"journal"\s*:\s*\{[\s\S]*?"title"\s*:\s*"([^"]+)"/);if(t)return this.cleanVenue(t[1]);const n=document.title.replace(/\s*\|\s*Nature\s*$/i,"");if(/^Articles$/i.test(this.cleanText(n)))return"Nature"}normalizeIssn(e){const t=e.trim().toUpperCase().replace(/[^0-9X]/g,"");if(/^\d{7}[\dX]$/.test(t))return`${t.slice(0,4)}-${t.slice(4)}`}yearFromText(e){const t=e.match(Ty);return t?Number.parseInt(t[1],10):void 0}cleanVenue(e){return this.cleanText(e).replace(/^Journal\s*:?\s*/i,"").replace(/\b(?:Volume|Vol\.?|Issue|No\.?|Pages?|pp\.?)\b[\s\S]*$/i,"").replace(/\b((?:19|20)\d{2})\b[\s\S]*$/i,"").replace(/[,.;:\s]+$/g,"").trim()}decodeDoiSource(e){try{return decodeURIComponent(e)}catch{return e}}isExcludedModuleText(e){return/(?:references?|bibliography|related|recommend(?:ed|ations?)?|further\s+reading|more\s+on\s+this\s+story|supplementary|associated\s+content|additional\s+information|cited\s+by|metrics|figures|tables|right[-_\s]*rail|sidebar)/i.test(e)}textWithoutExcludedContexts(e){const t=e.cloneNode(!0);return t.querySelectorAll(Ho).forEach(n=>n.remove()),t.textContent??""}cleanText(e){return e.replace(/\s+/g," ").trim()}unique(e){return Array.from(new Set(e.filter(Boolean)))}uniqueElements(e){return Array.from(new Set(e))}}const Fy=/\b10\.\d{4,9}\/[^\s"'<>?#]+/i,Dy=/\b((?:19|20)\d{2})\b/,zo=["li.search__item",".search__item",".search-result__item",".resultItem",".search-result",".issue-item"].join(","),Jo=[zo,".search-result__body"].join(","),_y=["Science Translational Medicine","Science Signaling","Science Robotics","Science Immunology","Science Advances","Science"],ky=[["scitranslmed.","Science Translational Medicine"],["scisignal.","Science Signaling"],["scirobotics.","Science Robotics"],["sciimmunol.","Science Immunology"],["sciadv.","Science Advances"],["science.","Science"]],Ny={"Science Translational Medicine":["1946-6234","1946-6242"],"Science Signaling":["1945-0877","1937-9145"],"Science Robotics":["2470-9476"],"Science Immunology":["2470-9468"],"Science Advances":["2375-2548"],Science:["0036-8075","1095-9203"]},Vo=[".search-results",".search__results",'[data-testid*="search-results"]','[data-test*="search-results"]'].join(","),Ly=["#pb-page-content article","#main-content article","main article","#pb-page-content","#main-content","main","article","body"],Wo=['[id*="reference"]','[id*="Reference"]','[class*="reference"]','[class*="Reference"]','[role="doc-bibliography"]','[role="complementary"]','section[aria-label*="reference"]','section[aria-label*="Reference"]','section[aria-labelledby*="reference"]','section[aria-labelledby*="Reference"]','[id*="related"]','[id*="Related"]','[class*="related"]','[class*="Related"]','[id*="recommend"]','[id*="Recommend"]','[class*="recommend"]','[class*="Recommend"]','[aria-label*="related"]','[aria-label*="Related"]','[aria-label*="recommended"]','[aria-label*="Recommended"]','[aria-label*="Current Issue"]','[aria-label*="current issue"]','[aria-label*="You may also like"]','[aria-label*="you may also like"]','[data-test*="reference"]','[data-testid*="reference"]','[data-test*="related"]','[data-testid*="related"]','[class*="current-issue"]','[class*="CurrentIssue"]','[class*="latestArticles"]','[class*="LatestArticles"]','[class*="recentArticles"]','[class*="RecentArticles"]','[class*="most-read"]','[class*="MostRead"]','[class*="trending"]','[class*="Trending"]','[class*="rightRail"]','[class*="RightRail"]','[class*="right_rail"]','[class*="Right_Rail"]','[class*="right-sidebar"]','[class*="left-sidebar"]','[class*="rail-sidebar"]','[data-widget*="RightRail"]','[data-widget*="rightRail"]','[data-widget*="right_rail"]','[data-widget*="right-rail"]','[data-widget*="Right-Rail"]','[data-testid*="RightRail"]','[data-testid*="rightRail"]','[data-testid*="right_rail"]','[data-testid*="right-rail"]','[data-test*="RightRail"]','[data-test*="rightRail"]','[data-test*="right_rail"]','[data-test*="right-rail"]',".related-content",".article__references",".references",".recommended",".right-rail",".sidebar"].join(",");class Ry extends j{id="science-org";name="Science.org";matches=["*://www.science.org/*"];isSearchPage(){if(this.isChallengePage())return!1;const e=location.pathname.toLowerCase();if(e==="/action/dosearch"||e.startsWith("/action/dosearch/"))return!0;if(e.startsWith("/doi/")||e.startsWith("/content/article/"))return!1;const t=this.hasSearchParam("AllField"),n=e.replace(/\/+$/,"")||"/";return t&&/^(?:\/|\/search|\/search-results)$/.test(n)}isArticlePage(){return this.isChallengePage()||this.isSearchPage()||/^\/doi\/(?:pdf|epdf)\//i.test(location.pathname)?!1:/^\/doi\/(?:abs\/|full\/)?10\./i.test(location.pathname)||/^\/content\/(?:article|webinar|blog-post)\//i.test(location.pathname)||!!this.hasArticleMetadata()}parseSearchResults(){if(this.isChallengePage())return[];const e=[],t=new Set;for(const n of this.getSearchResultHosts())try{const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;if(t.has(i))continue;t.add(i),e.push(a)}catch(a){console.error("[ScienceOrgAdapter] Failed to parse search result:",a)}return e}parseArticlePage(){if(this.isChallengePage()||/^\/doi\/(?:pdf|epdf)\//i.test(location.pathname))return null;const e=this.getDetailHost();if(!e)return null;try{return this.parseMetadataArticle(e)??this.parseDetailDom(e)}catch(t){return console.error("[ScienceOrgAdapter] Failed to parse article page:",t),null}}getMetricBarAnchor(e){const t=new WeakMap;if(!this.isSearchPage()){const i=this.findDetailMetadataLine(e,t);if(i)return{element:i,position:"after"};const o=this.firstVisibleElement(e,'.journal-title, .citation__journal-title, .publication_meta .journal, .publication-meta .journal, [data-testid*="journal"], [data-test*="journal"]',t);if(o)return{element:o,position:"before"}}const n=this.firstVisibleElement(e,'h1, h2, h3, .citation__title, .publication_title, .hlFld-Title, [class*="title"]',t);if(n)return{element:n,position:"after"};const a=this.firstVisibleElement(e,'.citation__authors, .authors, .loa, .publication-meta, .article__meta, [class*="meta"]',t);return a?{element:a,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){const e=this.getSearchContainers();return e.length===0?document.querySelector("main")??document.body:e.length===1?e[0]:this.getSharedSearchContainer(e)??document.body}getPageInfo(){const e=new URLSearchParams(location.search),t=Number.parseInt(e.get("startPage")??e.get("page")??"0",10),n=Number.isFinite(t)?t+1:1,i=this.cleanText(document.querySelector('.result__count, .search-result__count, [class*="result-count"], [data-testid*="result-count"]')?.textContent??"").match(/\b([\d,]+)\s+results?\b/i),o=i?Number.parseInt(i[1].replace(/,/g,""),10):void 0;return{pageNum:n,totalPages:o?Math.max(1,Math.ceil(o/20)):1,url:location.href,itemsPerPage:20,totalItems:o}}getSearchResultHosts(){const e=new WeakMap,t=this.getSearchContainers().flatMap(a=>{const i=Array.from(a.querySelectorAll(Jo));return a.matches(Jo)&&i.unshift(a),i.map(o=>this.getCompleteSearchResultHost(o))}),n=this.getTitleLinkFallbackHosts(e);return this.uniqueElements([...t,...n].filter(a=>this.looksLikeSearchResult(a,e)))}getTitleLinkFallbackHosts(e){const t=document.querySelector("main")??document.body;return t?this.collectValidTitleLinks(t).map(n=>this.getSearchHostFromTitleLink(n,e)).filter(n=>!!n):[]}getSearchHostFromTitleLink(e,t){let n=e.closest("article, li, section, div")??e.parentElement;for(;n&&n!==document.body;){if(n===e){n=n.parentElement;continue}if(this.isExcludedContext(n)){n=n.parentElement;continue}if(this.looksLikeStandaloneSearchCard(n,e,t))return n;n=n.parentElement}return null}looksLikeStandaloneSearchCard(e,t,n){if(e===document.body||e===document.documentElement||!e.contains(t)||e.matches("main, form, nav, aside, header, footer")||this.isHiddenDomElement(e,n))return!1;const a=this.collectValidTitleLinks(e);if(a.length!==1||a[0]!==t)return!1;const i=this.cleanText([e.className,e.id,e.getAttribute("data-testid")??"",e.getAttribute("data-test")??"",e.getAttribute("aria-label")??""].join(" "));if(/\b(?:filters?|search(?:\s+results?)?|results?\s+found|refine|sort|pagination|toolbar|header)\b/i.test(i)&&!/\b(?:item|card|article|record|result|row)\b/i.test(i))return!1;const o=this.cleanText(e.textContent??"");return!o||o.length<=this.cleanText(t.textContent??"").length?!1:!!(e.querySelector("time, button")||/(?:^|•)\s*(?:Science(?: Advances| Immunology| Robotics| Signaling| Translational Medicine)?|Vol\.|Issue|NO\.|pp\.)/i.test(o)||/\bby\b/i.test(o))}getCompleteSearchResultHost(e){if(!e.matches(".search-result__body"))return e;const t=this.findTitleLink(e);let n=e.parentElement;for(;n&&n!==document.body;){if(this.looksLikeCompleteSearchResultWrapper(n,e,t))return n;n=n.parentElement}return e}looksLikeCompleteSearchResultWrapper(e,t,n){if(e===t||this.countVisibleResultBodies(e)!==1)return!1;const i=this.collectValidTitleLinks(e);if(i.length!==1||n&&i[0]!==n)return!1;const o=this.cleanText([e.className,e.id,e.getAttribute("data-testid")??"",e.getAttribute("data-test")??""].join(" ")),s=e.matches(zo)||/\b(?:search|result|item|row|issue)\b/i.test(o),l=!!e.querySelector(".journal-title, .search-result__meta, .publication-year, time, .authors, .doi-link");return s||l}getSearchContainers(){const e=new WeakMap,t=this.uniqueElements([...Array.from(document.querySelectorAll(Vo)),...Array.from(document.querySelectorAll("[aria-label], [aria-labelledby]")).filter(n=>/\bsearch\s+results?\b/i.test(this.accessibleLabelText(n)))]).filter(n=>!this.isHiddenDomElement(n,e)&&!this.isExcludedContext(n));return t.length>0?t:document.body?[document.body]:[]}getSharedSearchContainer(e){let t=e[0];for(;t;){if(e.every(n=>t&&t.contains(n)))return t;t=t.parentElement}return null}getDetailHost(){const e=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??document.title).replace(/\s*\|\s*Science\s*$/i,"");let t=null,n=0;const a=new WeakMap;for(const i of Ly)for(const o of Array.from(document.querySelectorAll(i))){const s=this.getDetailHostScore(o,e,a);(s>n||s===n&&s>0&&this.breaksDetailHostTie(o,t))&&(t=o,n=s)}return t}getDetailHostScore(e,t,n){if(this.isHiddenDomElement(e,n)||e!==document.body&&this.isExcludedContext(e)||e!==document.body&&this.isLikelyTeaserHost(e))return 0;const a=this.cleanText(this.firstVisibleElementText(e,"h1, .citation__title, .publication_title, .hlFld-Title",n)),i=e!==document.body&&this.hasCurrentArticleEvidence(e);if(!t||!a&&e!==document.body)return i?2:0;if(!a)return 1;const o=this.titleKey(t),s=this.titleKey(a);return o.length===0?i?2:1:s===o?e===document.body?3:this.isArticleHost(e)?5:4:!(o.length>=12&&s.length>=12&&(s.includes(o)||o.includes(s)))||!i?0:this.isArticleHost(e)?3:2}isArticleHost(e){return e.tagName.toLowerCase()==="article"}isLikelyTeaserHost(e){const t=this.cleanText([e.className,e.id,e.getAttribute("data-testid")??"",e.getAttribute("data-test")??""].join(" "));return/\b(?:teaser|promo|promotion|recommended|recommendation|related|sidebar|right[-_\s]*rail)\b/i.test(t)}breaksDetailHostTie(e,t){if(!t)return!0;const n=e!==document.body&&this.hasCurrentArticleEvidence(e),a=t!==document.body&&this.hasCurrentArticleEvidence(t);if(n!==a)return n;const i=this.cleanText(e.textContent??"").length,o=this.cleanText(t.textContent??"").length;return Math.abs(i-o)>40?i>o:!1}looksLikeSearchResult(e,t){return this.isHiddenDomElement(e,t)||e.closest('[class^="paperlens-"], [class*=" paperlens-"]')||e.closest(Wo)&&!this.isAllowedSearchRegion(e)||this.isExcludedContext(e)||e.matches(zo)&&(this.countVisibleResultBodies(e)>1||this.collectValidTitleLinks(e).length>1)?!1:!!this.findTitleLink(e)}countVisibleResultBodies(e){const t=new WeakMap;return Array.from(e.querySelectorAll(".search-result__body")).filter(n=>!this.isHiddenElement(n,t)).length}parseSearchHost(e){const t=this.findTitleLink(e),n=this.cleanText(t?.textContent??e.querySelector('h2, h3, .publication_title, .hlFld-Title, [class*="title"]')?.textContent??"");if(!n)return null;const a=this.toArticleUrl(t?.getAttribute("href")??t?.href??""),i=this.cleanDoi(a??"")??this.extractDoi(e,{allowTextFallback:!1}),o=this.extractTypeText(e)||this.extractTypeNearTitle(e),s=this.extractVenue(e,{allowGlobalFallback:!1}),l=this.scienceFamilyVenueFromDoi(i),c=this.inferRecordKind(o,a,n),u=c.metricsAllowed?l??s:"";return{title:n,journalName:u,journalCandidates:u?[u]:[],authors:this.extractAuthorsFromDom(e),year:this.extractYear(e),doi:i,sourceId:i?`science-org:${i}`:a?`science-org:${new URL(a).pathname}`:void 0,url:a,nativeFullTextUrl:this.extractNativeFullTextUrl(e,i),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:c.articleTypes,source:this.id,citationType:c.citationType}}parseMetadataArticle(e){const t=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??"").replace(/\s*\|\s*Science\s*$/i,"");if(!t)return null;const n=this.toArticleUrl(this.firstMetaContent(["citation_fulltext_html_url","prism.url","og:url"])??document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),a=this.firstDoi([...this.allMetaContent(["citation_doi","dc.identifier","prism.doi"]),n??""]),i=this.firstMetaContent(["citation_article_type","dc.type","prism.section"])||this.extractTypeText(e)||this.extractTypeNearTitle(e)||this.extractDetailArticleTypeText(e),o=this.inferRecordKind(i,n,t),s=this.scienceFamilyVenueFromDoi(a),l=o.metricsAllowed?s??this.cleanVenue(this.firstMetaContent(["citation_journal_title","prism.publicationName"])??""):"",c=this.normalizeIssn(this.firstMetaContent(["citation_issn","prism.issn"])??"");return{title:t,journalName:l,journalCandidates:l?[l]:[],authors:this.allMetaContent(["citation_author","dc.creator"]),year:this.yearFromText(this.firstMetaContent(["citation_publication_date","citation_online_date","prism.publicationDate","dc.date"])??""),doi:a,sourceId:a?`science-org:${a}`:n?`science-org:${new URL(n).pathname}`:void 0,url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e,a),abstractSnippet:this.extractMetadataAbstract(e,t),hostElement:e,articleTypes:o.articleTypes,issn:o.metricsAllowed?this.scienceFamilyCompatibleIssn(l,c):void 0,source:this.id,citationType:o.citationType}}parseDetailDom(e){const t=this.cleanText(this.firstVisibleElementText(e,"h1, .citation__title, .publication_title, .hlFld-Title")||document.title.replace(/\s*\|\s*Science\s*$/i,""));if(!t)return null;const n=this.toArticleUrl(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),a=this.cleanDoi(n??"")??this.extractDoi(e,{allowTextFallback:!1}),i=this.inferRecordKind(this.extractTypeText(e)||this.extractTypeNearTitle(e),n,t),o=this.scienceFamilyVenueFromDoi(a),s=i.metricsAllowed?o??this.extractVenue(e):"";return{title:t,journalName:s,journalCandidates:s?[s]:[],authors:this.extractAuthorsFromDom(e),year:this.extractYear(e),doi:a,sourceId:a?`science-org:${a}`:n?`science-org:${new URL(n).pathname}`:void 0,url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e,a),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:i.articleTypes,source:this.id,citationType:i.citationType}}inferRecordKind(e,t,n=""){const a=this.cleanText(e),i=this.cleanText(n),o=this.cleanText(`${a} ${t??""}`).toLowerCase(),s=/\b(?:news|news feature|editorial|opinion|commentary|books? et al\.?|book review|podcast|video|webinar|careers?|news at a glance|scienceinsider|in the pipeline|blog)\b/i,l=/^(?:news(?: feature| at a glance)?|editorial|opinion|commentary|books? et al\.?|book review)(?::|\s+-\s+|\s+\|)/i;return!a||/\/content\/(?:article|webinar|blog-post)\//i.test(o)||s.test(a)||l.test(i)?{articleTypes:[/editorial/i.test(a)||/^editorial/i.test(i)?"Editorial":/book review|books? et al\./i.test(a)||/^(?:book review|books? et al\.)/i.test(i)?"BookReview":"News"],citationType:"misc",metricsAllowed:!1}:{articleTypes:["JournalArticle"],citationType:"article",metricsAllowed:!0}}findTitleLink(e){const t=new WeakMap,a=this.collectTitleLinks(e).find(o=>!this.isHiddenElement(o,t)&&this.isArticleLink(o)&&this.cleanText(o.textContent??"").length>0);return a||(Array.from(e.querySelectorAll('a[href*="/doi/10."], a[href*="/doi/abs/10."], a[href*="/doi/full/10."], a[href*="/content/article/"], a[href*="/content/webinar/"], a[href*="/content/blog-post/"]')).find(o=>!this.isHiddenElement(o,t)&&this.isArticleLink(o)&&this.cleanText(o.textContent??"").length>0)??null)}collectTitleLinks(e){return Array.from(e.querySelectorAll("h2 a[href], h3 a[href], .publication_title a[href], a.publication_title[href], .hlFld-Title a[href], a.hlFld-Title[href], .art_title a[href], a.art_title[href]"))}collectValidTitleLinks(e){const t=new WeakMap,n=new Set;return this.collectTitleLinks(e).filter(a=>{if(this.isHiddenElement(a,t)||!this.isArticleLink(a))return!1;const i=this.cleanText(a.textContent??"");if(!i)return!1;const o=`${a.href}::${i}`;return n.has(o)?!1:(n.add(o),!0)})}firstVisibleElementText(e,t,n){const a=this.firstVisibleElement(e,t,n);return a?this.cleanText(a.textContent??""):""}firstVisibleElement(e,t,n){for(const a of Array.from(e.querySelectorAll(t)))if(!this.isHiddenElement(a,n)&&this.cleanText(a.textContent??""))return a;return null}extractVenue(e,t={}){const n=new WeakMap,a=[".journal-title",".citation__journal-title",".publication_meta .journal",".publication-meta .journal",'[data-testid*="journal"]','[data-test*="journal"]',".source-title",".meta__source"].join(",");for(const o of Array.from(e.querySelectorAll(a))){if(o instanceof HTMLElement&&this.isHiddenElement(o,n))continue;const s=this.cleanVenue(o.textContent??"");if(s&&!/^(Article|Research Article|PDF|Full Text)$/i.test(s))return s}const i=[...Array.from(e.querySelectorAll("div, span, p, li, strong, em")),e];for(const o of i){if(o instanceof HTMLElement&&this.isHiddenElement(o,n))continue;const s=this.cleanText(o.textContent??"");if(!(!s||s.length>120))for(const l of _y){const c=l.replace(/\s+/g,"\\s+");if(new RegExp(`^(?:\u2022\\s*)?${c}(?=$|[\u2022,:\\s])`,"i").test(s))return l}}return t.allowGlobalFallback===!1?"":this.cleanVenue(this.firstMetaContent(["citation_journal_title","prism.publicationName"])??"")}extractTypeText(e){const t=new WeakMap,n=[".publication-type",".content-type",".issue-item__type",".article-type",".c-meta__type",'[data-testid*="type"]','[data-test*="type"]','[class*="type"]'].join(",");return Array.from(e.querySelectorAll(n)).filter(a=>!(a instanceof HTMLElement)||!this.isHiddenElement(a,t)).map(a=>this.cleanText(a.textContent??"")).filter(Boolean).join(" ")}extractTypeNearTitle(e){const t=new WeakMap,n=this.findTitleLink(e),a=n?.closest("h1, h2, h3, h4, h5, h6")??n;if(!a)return"";const i=[a.previousElementSibling,a.parentElement?.previousElementSibling??null,a.parentElement?.firstElementChild&&a.parentElement.firstElementChild!==a?a.parentElement.firstElementChild:null].filter(o=>!!o);for(const o of i){if(o instanceof HTMLElement&&this.isHiddenElement(o,t))continue;const s=this.cleanText(o.textContent??"");if(!(!s||s.length>48)&&s!==this.cleanText(n?.textContent??"")&&!/\b(?:by|vol\.?|issue|no\.|pp\.?|access|authors?)\b/i.test(s))return s}return""}extractDetailArticleTypeText(e){if(this.isSearchPage())return"";const t=new WeakMap,n=this.firstVisibleElement(e,"h1, .citation__title, .publication_title, .hlFld-Title",t),a=Array.from(e.querySelectorAll("div, span, p, li, section"));for(const i of a){if(this.isHiddenElement(i,t)||this.isExcludedContext(i)||n&&i.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_PRECEDING)continue;const o=this.cleanText(i.textContent??"");if(!o||o.length>180)continue;const s=o.match(/\b(?:research\s+article|research\s+articles?|perspective|report)\b/i);if(s)return s[0]}return""}findDetailMetadataLine(e,t){const n=this.firstDoi([...this.allMetaContent(["citation_doi","dc.identifier","prism.doi"]),document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href]),a=Array.from(e.querySelectorAll('a[href*="doi.org/"], a[href*="/doi/10."]')).find(l=>{if(this.isHiddenElement(l,t)||this.isExcludedContext(l)||!/\bDOI\b/i.test(this.cleanText(l.textContent??""))&&!(l.getAttribute("href")??l.href??"").includes("doi.org/"))return!1;if(!n)return!0;const c=this.cleanDoi(l.getAttribute("href")??l.href??"");return!!(c&&c.toLowerCase()===n.toLowerCase())});if(!a)return this.findPlainTextDetailDoiLine(e,n,t);const i=this.findDetailMetadataRowFromDoi(a,e,n,t);if(i)return i;const o=a.closest("p, div, section, li");if(!(o instanceof HTMLElement)||this.isHiddenElement(o,t)||this.isExcludedContext(o))return a;const s=this.cleanText(o.textContent??"");return n&&!s.toLowerCase().includes(n.toLowerCase())&&this.cleanDoi(s)?.toLowerCase()!==n.toLowerCase()?a:!/\bDOI\b/i.test(s)&&!/doi\.org\//i.test(a.getAttribute("href")??a.href??"")?null:s.length>240?a:o}findPlainTextDetailDoiLine(e,t,n){const a=["[data-doi]",'[data-test*="doi"]','[data-testid*="doi"]','[id*="doi"]','[class*="doi"]',".epub-doi","p","div","li","section"].join(",");for(const i of Array.from(e.querySelectorAll(a))){if(this.isHiddenElement(i,n)||this.isExcludedContext(i))continue;const o=this.cleanText([i.id,i.className,i.getAttribute("data-testid")??"",i.getAttribute("data-test")??""].join(" ")),s=i.getAttribute("data-doi")??i.textContent??"",l=this.cleanText(s);if(!l||l.length>240)continue;const c=this.cleanDoi(s);if(t&&(!c||c.toLowerCase()!==t.toLowerCase())&&!l.toLowerCase().includes(t.toLowerCase())||!/\bdoi\b/i.test(l)&&!/\bdoi\b/i.test(o)&&!i.hasAttribute("data-doi"))continue;const u=this.findDetailMetadataRowFromDoi(i,e,t,n);if(u)return u;const d=i.closest("p, div, section, li")??i;if(this.isHiddenElement(d,n)||this.isExcludedContext(d))continue;const p=this.cleanText(d.textContent??"");if(!(!p||p.length>240)&&!(t&&!p.toLowerCase().includes(t.toLowerCase())&&this.cleanDoi(p)?.toLowerCase()!==t.toLowerCase()))return d}return null}findDetailMetadataRowFromDoi(e,t,n,a){let i=e.parentElement,o=null;for(;i&&i!==t&&i!==document.body&&!(this.isHiddenElement(i,a)||this.isExcludedContext(i));){const s=this.cleanText(i.textContent??"");if(!s||s.length>420)break;if(n&&!s.toLowerCase().includes(n.toLowerCase())){i=i.parentElement;continue}if(i.querySelector("h1, h2, h3"))break;const l=!!(this.cleanDoi(s)||n&&s.toLowerCase().includes(n.toLowerCase())),c=/\b(?:science(?:\s+(?:advances|immunology|robotics|signaling|translational medicine))?|vol\.?|issue|first release|research article|perspective|report|date|apr|may|jun|jul|aug|sep|oct|nov|dec)\b/i.test(s);l&&c&&(o=i),i=i.parentElement}return o}extractAuthorsFromDom(e){const t=new WeakMap,n=[".author-name",".loa__author-name",".citation__author",".authors a",".authors span",'[class*="author"] a','[class*="author"] span',"[data-author-name]"].join(",");return this.unique(Array.from(e.querySelectorAll(n)).filter(a=>!(a instanceof HTMLElement)||!this.isHiddenElement(a,t)).map(a=>this.cleanText(a.getAttribute("data-author-name")??a.textContent??"")).filter(a=>a&&!/^(Authors?|View|Show more)$/i.test(a)))}extractYear(e){const t=new WeakMap;for(const n of Array.from(e.querySelectorAll('time, .publication-year, .date, [class*="year"], [class*="date"]'))){if(n instanceof HTMLElement&&this.isHiddenElement(n,t))continue;const a=this.yearFromText(n.getAttribute("datetime")??"")??this.yearFromText(n.textContent??"");if(a)return a}return this.yearFromText(e.textContent??"")}extractDoi(e,t={}){const n=t.allowTextFallback??!0;for(const a of Array.from(e.querySelectorAll('a[href*="doi.org/"], a[href*="/doi/10."]'))){if(this.isExcludedContext(a))continue;const i=this.cleanDoi(a.href);if(i)return i}for(const a of Array.from(e.querySelectorAll('[data-test*="doi"], [data-testid*="doi"], [id*="doi"], [class*="doi"], .epub-doi'))){if(this.isExcludedContext(a))continue;const i=this.cleanDoi(a.textContent??"");if(i)return i}if(n)return this.cleanDoi(this.textWithoutExcludedContexts(e))}extractNativeFullTextUrl(e,t){const n=this.toNativeFullTextUrl(this.firstMetaContent(["citation_pdf_url"])??"",t);if(n)return n;for(const a of Array.from(e.querySelectorAll('a[href*="/doi/pdf/"], a[href*="/doi/epdf/"], a[href$=".pdf"], a[href*="/pdf"]'))){if(this.isExcludedContext(a))continue;const i=this.toNativeFullTextUrl(a.getAttribute("href")??a.href??"",t);if(i)return i}}extractAbstract(e){const t=new WeakMap,n=this.extractAbstractByHeading(e,t);if(n)return n;const a=[".hlFld-Abstract",".abstract",'[class*="abstract"]','[data-test*="abstract"]','[data-testid*="abstract"]','section[id*="abstract"]','section[aria-labelledby*="abstract"]','div[id*="abstract"]',".search-result__body"];for(const i of a)for(const o of Array.from(e.querySelectorAll(i))){if(this.isHiddenElement(o,t)||this.isExcludedContext(o))continue;const s=this.cleanAbstractText(o.textContent??"");if(this.isUsableAbstractText(s))return s}}extractMetadataAbstract(e,t){const n=this.cleanAbstractText(this.firstMetaContent(["citation_abstract"])??"");if(this.isUsableAbstractText(n)&&!this.isTitleLikeAbstract(n,t))return n;const a=this.extractAbstract(e);if(a)return a;const i=this.cleanAbstractText(this.firstMetaContent(["dc.description","description","og:description","twitter:description"])??"");if(this.isUsableAbstractText(i)&&!this.isTitleLikeAbstract(i,t))return i}extractAbstractByHeading(e,t){const n=Array.from(e.querySelectorAll('h2, h3, h4, [role="heading"]'));for(const a of n){if(this.isHiddenElement(a,t)||this.isExcludedContext(a)||!/^abstract\b/i.test(this.cleanText(a.textContent??"")))continue;const i=this.collectFollowingAbstractText(a.nextElementSibling,t);if(i)return i;const o=this.collectFollowingAbstractText(a.parentElement?.nextElementSibling??null,t);if(o)return o;const s=a.closest("section, div");if(s&&s!==e){if(s instanceof HTMLElement&&this.isHiddenElement(s,t)||this.isExcludedContext(s))continue;const l=this.cleanAbstractText(s.textContent??"");if(this.isUsableAbstractText(l))return l}}}collectFollowingAbstractText(e,t){const n=[];let a=e;for(;a&&!this.isAbstractStopElement(a);){if(a instanceof HTMLElement&&this.isHiddenElement(a,t)){a=a.nextElementSibling;continue}if(this.isExcludedContext(a))break;const i=this.cleanAbstractText(a.textContent??"");this.isUsableAbstractText(i)&&n.push(i),a=a.nextElementSibling}return n.length?this.cleanText(n.join(" ")):void 0}isAbstractStopElement(e){const t=this.cleanText(e.textContent??""),n=e.matches('h1, h2, h3, h4, [role="heading"]')?t:"",a=this.cleanText(e.querySelector(':scope > h1, :scope > h2, :scope > h3, :scope > h4, :scope > [role="heading"]')?.textContent??""),i=n||a;if(i&&!/^abstract\b/i.test(i))return!0;const o=this.cleanText([e.id,e.className,e.getAttribute("role")??"",e.getAttribute("aria-label")??"",e.getAttribute("data-test")??"",e.getAttribute("data-testid")??""].join(" "));return/\b(?:introduction|materials?|methods?|results?|discussion|references?|bibliography|acknowledg|supplement|figures?|tables?|metrics?|citations?|related)\b/i.test(o)}cleanAbstractText(e){return this.cleanText(e).replace(/^abstract\s*/i,"").replace(/^summary\s*/i,"").trim()}isUsableAbstractText(e){return e.length>=12&&!/^(?:abstract|summary|figures?|tables?|references?|metrics?|citations?|related|authors?|article)(?:\s+(?:figures?|tables?|references?|metrics?|citations?|related|authors?|article))*$/i.test(e)}isTitleLikeAbstract(e,t){const n=this.titleKey(e.replace(/\s*\|\s*Science(?:\.org)?\s*$/i,"")),a=this.titleKey(t);return!!(n&&a&&(n===a||n.startsWith(a)&&e.length<=t.length+30))}isExcludedContext(e){if(e.closest(Wo)&&!this.isAllowedSearchRegion(e))return!0;const t=this.findContextSection(e);if(!t||t===document.body)return!1;if(t.matches("aside, nav")&&!/\bsearch\s+results?\b/i.test(this.accessibleLabelText(t)))return!0;const n=this.accessibleLabelText(t),a=this.cleanText(Array.from(t.querySelectorAll(":scope > h1, :scope > h2, :scope > h3")).map(c=>c.textContent??"").join(" ")),i=this.cleanText(`${n} ${a}`);if(/references?|bibliography|related|recommend(?:ed|ations?)?|you\s+may\s+also\s+like|current\s+issue|from\s+this\s+issue|in\s+this\s+issue|cited\s+by|right[-_\s]*rail|sidebar/i.test(i))return!0;const o=t===e||t.matches(Jo)?n:i;if(!/most\s+read|popular|latest|recent|trending/i.test(o))return!1;const s=/\bsearch\s+results?\b/i.test(o)||t.matches(Vo)||!!t.querySelector(Vo),l=!!t.closest('aside, nav, [role="complementary"], .right-rail, .sidebar, [class*="sidebar"], [class*="right-rail"], [class*="rightRail"], [class*="RightRail"], [class*="right_rail"], [class*="right-sidebar"], [class*="left-sidebar"], [class*="rail-sidebar"], [data-widget*="RightRail"], [data-widget*="rightRail"], [data-widget*="right_rail"], [data-widget*="right-rail"], [data-widget*="Right-Rail"], [data-testid*="RightRail"], [data-testid*="rightRail"], [data-testid*="right_rail"], [data-testid*="right-rail"], [data-test*="RightRail"], [data-test*="rightRail"], [data-test*="right_rail"], [data-test*="right-rail"]');return l&&!/\bsearch\s+results?\b/i.test(n)?!0:!s||l}isAllowedSearchRegion(e){const t=e.closest('.search-results, .search__results, [data-testid*="search-results"], [data-test*="search-results"], [aria-label], [aria-labelledby]');return!t||t.closest('aside, nav, [role="complementary"], .right-rail, .sidebar, [class*="sidebar"], [class*="right-rail"], [class*="rightRail"], [class*="RightRail"], [class*="right_rail"], [class*="right-sidebar"], [class*="left-sidebar"], [class*="rail-sidebar"]')?!1:/\bsearch\s+results?\b/i.test(this.accessibleLabelText(t))||t.matches('.search-results, .search__results, [data-testid*="search-results"], [data-test*="search-results"]')}findContextSection(e){const t=e.closest("section, aside, nav");if(t)return t;let n=e.closest("div");for(;n&&n!==document.body;){if(this.accessibleLabelText(n)||n.matches('[role="complementary"], .right-rail, .sidebar, [class*="sidebar"], [class*="right-rail"], [class*="rightRail"], [class*="RightRail"], [class*="right_rail"], [class*="right-sidebar"], [class*="left-sidebar"], [class*="rail-sidebar"], [data-widget*="RightRail"], [data-widget*="rightRail"], [data-widget*="right_rail"], [data-widget*="right-rail"], [data-widget*="Right-Rail"], [data-testid*="RightRail"], [data-testid*="rightRail"], [data-testid*="right_rail"], [data-testid*="right-rail"], [data-test*="RightRail"], [data-test*="rightRail"], [data-test*="right_rail"], [data-test*="right-rail"]'))return n;n=n.parentElement?.closest("div")??null}return e.closest("div")}isChallengePage(){const e=document.title,t=this.cleanText(document.body?.textContent??""),n=/Enable JavaScript and cookies to continue|Checking if the site connection is secure|Just a moment|Sorry,\s*you have been blocked|Cloudflare Ray ID|This website is using a security service|blocked from proceeding/i,a=this.hasRenderableContent();return!!(!a&&/Just a moment|Enable JavaScript and cookies|Access denied|Attention Required|Robot Check|Verif(?:y|ying) you are human/i.test(e)||this.hasVisibleChallengeWidget()||!a&&document.querySelector('script[src*="/cdn-cgi/challenge-platform/"]')||n.test(t)&&this.hasBodyChallengeCopy(n,a)||this.hasVerificationChallengeCopy())}hasSearchParam(e){const t=e.toLowerCase();return Array.from(new URLSearchParams(location.search).keys()).some(n=>n.toLowerCase()===t)}accessibleLabelText(e){const t=e.getAttribute("aria-label")??"",n=(e.getAttribute("aria-labelledby")??"").split(/\s+/).map(a=>a?document.getElementById(a)?.textContent??"":"").join(" ");return this.cleanText(`${t} ${n}`)}hasRenderableContent(){const e=new WeakMap;return Array.from(document.querySelectorAll(["article h1","article .citation__title","article .publication_title","article .hlFld-Title",'article a[href*="/doi/"]',"#pb-page-content h1",'#pb-page-content a[href*="/doi/"]',"#main-content h1",'#main-content a[href*="/doi/"]',"main h1",'main a[href*="/doi/"]',".search-results",".search__results",".search-result__item",".search-result__body","li.search__item"].join(","))).some(t=>!this.isHiddenElement(t,e))}hasBodyChallengeCopy(e,t){const n=document.body;if(!n)return!1;const a=/challenge|captcha|verify|robot|overlay|modal|dialog|turnstile|blocked|block|access|security|cloudflare|(?:^|\s)cf[-_]|(?:^|\s)cferror/i,i=new WeakMap;for(const o of this.visibleChallengeTextCandidates(n,i)){const{element:s,text:l}=o;if(!e.test(l))continue;if(!t)return!0;const c=s.closest("article, .search-results, .search__results, li.search__item, .search-result__item, .search-result__body");if(c){if(c instanceof HTMLElement&&this.hasBlockingOverlayContext(s,c))return!0;continue}if(this.hasChallengeContext(s,a))return!0}return!1}hasVerificationChallengeCopy(){const e=/verif(?:y|ying) (?:that )?you are (?:human|not a robot)|please verify (?:that )?you are (?:human|not a robot)|review the security of your connection|robot check|human verification/i,t=document.body;if(!t||!e.test(t.textContent??""))return!1;const n=/challenge|captcha|verify|robot|overlay|modal|dialog|turnstile|blocked|access|(?:^|\s)cf[-_]|(?:^|\s)cferror/i,a=this.hasRenderableContent(),i=new WeakMap;for(const o of this.visibleChallengeTextCandidates(t,i)){const{element:s,text:l}=o;if(!e.test(l))continue;if(!a)return!0;const c=s.closest("article, .search-results, .search__results, li.search__item, .search-result__item, .search-result__body");if(c){if(c instanceof HTMLElement&&this.hasBlockingOverlayContext(s,c))return!0;continue}if(this.hasChallengeContext(s,n))return!0}return!1}hasVisibleChallengeWidget(){const e=new WeakMap;return Array.from(document.querySelectorAll('.cf-turnstile, iframe[src*="challenges.cloudflare.com"]')).some(t=>!this.isHiddenElement(t,e))}hasChallengeContext(e,t){let n=e;for(;n&&n!==document.body;){const a=this.cleanText([n.id,n.className,n.getAttribute("role")??"",n.getAttribute("aria-label")??"",n.getAttribute("data-testid")??"",n.getAttribute("data-test")??""].join(" "));if(t.test(a)||this.isLikelyBlockingOverlay(n))return!0;n=n.parentElement}return!1}hasBlockingOverlayContext(e,t){let n=e;for(;n&&n!==t;){if(this.isLikelyBlockingOverlay(n))return!0;const a=this.cleanText([n.id,n.className,n.getAttribute("role")??"",n.getAttribute("aria-label")??"",n.getAttribute("data-testid")??"",n.getAttribute("data-test")??""].join(" "));if(/\b(?:modal|overlay|dialog|alertdialog|turnstile|blocked|access[-_\s]*blocked)\b|(?:^|\s)cf[-_]|(?:^|\s)cferror/i.test(a))return!0;n=n.parentElement}return!1}isLikelyBlockingOverlay(e){if(e.tagName.toLowerCase()==="dialog"&&e.hasAttribute("open"))return!0;const t=e.getAttribute("style")??"";if(/position\s*:\s*fixed/i.test(t)){const c=/inset\s*:\s*0(?:[;\s]|$)/i.test(t)||/top\s*:\s*0/i.test(t)&&/right\s*:\s*0/i.test(t)&&/bottom\s*:\s*0/i.test(t)&&/left\s*:\s*0/i.test(t),u=/z-index\s*:\s*(?:[1-9]\d{3,}|2147483647)/i.test(t);if(c||u)return!0}const n=typeof window<"u"&&typeof window.getComputedStyle=="function"?window.getComputedStyle(e):null;if(!n||n.position!=="fixed")return!1;const a=Number.parseFloat(n.top||"0"),i=Number.parseFloat(n.right||"0"),o=Number.parseFloat(n.bottom||"0"),s=Number.parseFloat(n.left||"0"),l=Number.parseInt(n.zIndex||"0",10);return a===0&&i===0&&o===0&&s===0||l>=1e3}isHiddenDomElement(e,t){return e instanceof HTMLElement&&this.isHiddenElement(e,t)}isHiddenElement(e,t){let n=e;const a=[];for(;n&&n!==document.body;){const i=t?.get(n);if(i!==void 0)return a.forEach(c=>t?.set(c,i)),i;if(a.push(n),n.matches('.cf-turnstile, iframe[src*="challenges.cloudflare.com"]')&&n.getAttribute("data-size")==="invisible")return a.forEach(c=>t?.set(c,!0)),!0;if(n.hidden||n.getAttribute("aria-hidden")==="true")return a.forEach(c=>t?.set(c,!0)),!0;const s=n.getAttribute("style")??"";if(/display\s*:\s*none|visibility\s*:\s*hidden|opacity\s*:\s*0(?:[;\s]|$)|clip\s*:\s*rect\(\s*0/i.test(s))return a.forEach(c=>t?.set(c,!0)),!0;const l=typeof window<"u"&&typeof window.getComputedStyle=="function"?window.getComputedStyle(n):null;if(l){const c=Number.parseFloat(l.left||"0"),u=Number.parseFloat(l.top||"0"),d=Number.parseFloat(l.right||"0"),p=Number.parseFloat(l.bottom||"0"),h=l.clip??"",f=l.clipPath??"",y=l.transform??"",x=Number.parseFloat(l.width||"0"),T=Number.parseFloat(l.height||"0"),E=!!(h&&h!=="auto")||!!(f&&f!=="none"),w=["absolute","fixed"].includes(l.position)&&(Math.abs(c)>1e3||Math.abs(u)>1e3||Math.abs(d)>1e3||Math.abs(p)>1e3),v=/matrix\([^)]*(?:-?[1-9]\d{3,}|,\s*-?[1-9]\d{3,})|translate(?:3d|X|Y)?\([^)]*-?[1-9]\d{3,}/i.test(y),g=x<=1&&T<=1;if(l.display==="none"||l.visibility==="hidden"||l.opacity==="0"||E||w||v||g)return a.forEach(C=>t?.set(C,!0)),!0}n=n.parentElement}return a.forEach(i=>t?.set(i,!1)),!1}visibleTextNodes(e,t){const n=[],a=document.createTreeWalker(e,4);let i=a.nextNode();for(;i;){const o=i.parentElement;o&&!this.isHiddenElement(o,t)&&n.push(i),i=a.nextNode()}return n}visibleChallengeTextCandidates(e,t){const n=new Map;for(const a of this.visibleTextNodes(e,t)){const i=a.textContent??"";if(!i.trim())continue;let o=a.parentElement;for(;o;){const s=n.get(o)??[];if(s.push(i),n.set(o,s),o===e)break;o=o.parentElement}}return Array.from(n.entries()).map(([a,i])=>({element:a,text:this.cleanText(i.join(" "))})).filter(a=>a.text.length>0)}hasArticleMetadata(){return!!(this.firstMetaContent(["citation_title","dc.title"])&&(this.firstMetaContent(["citation_doi","prism.doi"])||this.firstMetaContent(["citation_article_type","dc.type","prism.section"])||this.firstMetaContent(["citation_fulltext_html_url","prism.url"])))}hasCurrentArticleEvidence(e){const t=this.firstDoi([...this.allMetaContent(["citation_doi","dc.identifier","prism.doi"]),document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href]);return t?Array.from(e.querySelectorAll('a[href*="doi.org/"], a[href*="/doi/10."], a[href*="/doi/pdf/"], a[href*="/doi/epdf/"]')).some(n=>{const a=n.getAttribute("href")??n.href??"";return this.cleanDoi(a)===t||!!this.toNativeFullTextUrl(a,t)}):!1}firstMetaContent(e){return this.allMetaContent(e)[0]}allMetaContent(e){const t=[];for(const n of e){const a=[`meta[name="${n}"]`,`meta[property="${n}"]`,`meta[name="${n.toLowerCase()}"]`,`meta[property="${n.toLowerCase()}"]`].join(",");for(const i of Array.from(document.querySelectorAll(a))){const o=this.cleanText(i.getAttribute("content")??"");o&&t.push(o)}}return this.unique(t)}firstDoi(e){for(const t of e){const n=this.cleanDoi(t);if(n)return n}}cleanDoi(e){return this.decodeDoiSource(e).match(Fy)?.[0].replace(/[),.;/\s]+$/g,"").toLowerCase()}scienceFamilyVenueFromDoi(e){const t=e?.toLowerCase().match(/^10\.1126\/(.+)$/)?.[1];if(t){for(const[n,a]of ky)if(t.startsWith(n))return a}}normalizeIssn(e){const t=e.trim().toUpperCase().replace(/[^0-9X]/g,"");if(/^\d{7}[\dX]$/.test(t))return`${t.slice(0,4)}-${t.slice(4)}`}scienceFamilyCompatibleIssn(e,t){if(!t)return;const n=Ny[e];return n?n.includes(t)?t:void 0:t}yearFromText(e){const t=e.match(Dy);return t?Number.parseInt(t[1],10):void 0}isArticleLink(e){try{const t=new URL(e.getAttribute("href")??e.href,location.origin);return t.hostname.toLowerCase()==="www.science.org"&&(/^\/doi\/(?:abs\/|full\/)?10\./i.test(t.pathname)||/^\/content\/(?:article|webinar|blog-post)\//i.test(t.pathname))}catch{return!1}}toNativeFullTextUrl(e,t){const n=this.toAbsoluteUrl(e);if(n&&t)try{const a=new URL(n);if(a.protocol!=="https:"||a.hostname.toLowerCase()!=="www.science.org"||!/^\/doi\/(?:pdf|epdf)\//i.test(a.pathname))return;const i=this.extractDoiFromScienceFullTextPath(a.pathname);return!i||i!==t.toLowerCase()?void 0:n}catch{return}}extractDoiFromScienceFullTextPath(e){const n=this.decodeDoiSource(e).match(/^\/doi\/(?:pdf|epdf)\/(.+)$/i);return n?this.cleanDoi(n[1]):void 0}toArticleUrl(e){const t=this.toAbsoluteUrl(e);if(t)try{const n=new URL(t);return n.hash="",n.searchParams.delete("af"),n.searchParams.delete("campaign"),n.href}catch{return t}}cleanVenue(e){return this.cleanText(e).replace(/^Journal\s*:?\s*/i,"").replace(/\b(?:Volume|Vol\.?|Issue|No\.?|Pages?|pp\.?)\b[\s\S]*$/i,"").replace(/\b((?:19|20)\d{2})\b[\s\S]*$/i,"").replace(/[,.;:\s]+$/g,"").trim()}toAbsoluteUrl(e){const t=e.trim();if(!(!t||/^javascript:/i.test(t)||/^data:/i.test(t)))try{const n=new URL(t,location.origin);return/^https?:$/.test(n.protocol)?n.href:void 0}catch{return}}decodeDoiSource(e){try{return decodeURIComponent(e)}catch{return e}}textWithoutExcludedContexts(e){const t=e.cloneNode(!0);return t.querySelectorAll(Wo).forEach(n=>n.remove()),t.textContent??""}cleanText(e){return e.replace(/\s+/g," ").trim()}titleKey(e){return this.cleanText(e).toLowerCase().replace(/[^a-z0-9]+/g,"")}unique(e){return Array.from(new Set(e.filter(Boolean)))}uniqueElements(e){return Array.from(new Set(e))}}const Iu=/\b10\.\d{4,9}\/[^\s"'<>?#]+/i,Py=/\b((?:19|20)\d{2})\b/,Qa=[".highwire-search-results-list > li.search-result","li.search-result-highwire-citation","li.search-result"].join(","),By=[".highwire-search-results",".highwire-search-results-list","#hw-advance-search-result"].join(","),Iy=["article",".highwire-article",".pane-content","main","#content"].join(",");class My extends j{id="preprint-servers";name="bioRxiv / medRxiv / arXiv";matches=["*://www.biorxiv.org/*","*://biorxiv.org/*","*://www.medrxiv.org/*","*://medrxiv.org/*","*://arxiv.org/*"];isSearchPage(){return this.isArxivHost()?/^\/search\/?$/i.test(location.pathname)||/^\/list\//i.test(location.pathname):this.isChallengePage()?!1:/^\/search(?:\/|$)/i.test(location.pathname)}isArticlePage(){return this.isArxivHost()?/^\/abs\//i.test(location.pathname):this.isChallengePage()||/\.full\.pdf$/i.test(location.pathname)?!1:/^\/content\/10\./i.test(location.pathname)||this.hasArticleMetadata()}parseSearchResults(){if(this.isChallengePage())return[];const e=[],t=new Set;for(const n of this.getSearchResultHosts())try{const a=this.parseSearchResultHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;if(t.has(i))continue;t.add(i),e.push(a)}catch(a){console.error("[PreprintServersAdapter] Failed to parse search result:",a)}return e}parseArticlePage(){if(this.isArxivHost()){const t=this.getDetailHost();return t?this.parseArxivArticlePage(t):null}if(this.isChallengePage()||/\.full\.pdf$/i.test(location.pathname))return null;const e=this.getDetailHost();if(!e)return null;try{const t=this.getServerInfo(),n=this.cleanTitle(this.queryText(e,["h1.highwire-cite-title","h1.article-title","h1",".highwire-cite-title"])),a=this.cleanTitle(n||this.firstMetaContent(["citation_title","dc.title","og:title"]));if(!a)return null;const i=this.extractDoiFromPath(location.pathname),o=this.cleanDoi(i??this.firstMetaContent(["citation_doi","dc.identifier","prism.doi"])??this.extractDoi(e)),s=this.getCanonicalUrl()??location.href,l=this.extractNativePdfUrl(e,o);return{title:a,journalName:t.name,journalCandidates:[],authors:this.extractDetailAuthors(e),year:this.extractYear(this.firstMetaContent(["citation_publication_date","citation_date","dc.date","prism.publicationDate"])??this.queryText(e,[".published",".highwire-cite-metadata","time"])),doi:o,sourceId:this.buildSourceId(t,o,s),url:s,nativeFullTextUrl:l,abstractSnippet:this.cleanAbstract(this.firstMetaContent(["citation_abstract","dc.description","description"])??this.queryText(e,[".section.abstract",".abstract",".abstract p",'[class*="abstract"]'])),hostElement:e,articleTypes:["Preprint"],source:this.id,citationType:"misc"}}catch(t){return console.error("[PreprintServersAdapter] Failed to parse article page:",t),null}}getMetricBarAnchor(e){const t=this.queryFirstForHost(e,["h1.title",".title",".title.is-5",".title.is-5.mathjax",".list-title",".list-title.mathjax","p.title","a.highwire-cite-linked-title",".highwire-cite-title a","h1.highwire-cite-title","h1.article-title","h1","h2","h3"]);if(t)return{element:t,position:"after"};const n=this.queryFirstForHost(e,[".authors",".list-authors",".tags",".is-size-7",".submitted-date",".highwire-cite-authors",".highwire-cite-metadata",".article-meta",".published"]);return n?{element:n,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return this.isArxivHost()?this.isArticlePage()?this.getDetailHost()??document.querySelector("main")??document.body:document.querySelector("ol.arxiv-results")??document.querySelector("ol.breathe-horizontal")??document.querySelector("#dlpage > dl")??document.querySelector("#dlpage")??document.querySelector("main")??document.body:this.isArticlePage()?this.getDetailHost()??document.body:document.querySelector(".highwire-search-results-list")??document.querySelector(".highwire-search-results")??document.querySelector("#hw-advance-search-result")??document.querySelector("main")??document.body}getPageInfo(){if(this.isArxivHost()){const i=new URLSearchParams(location.search),o=Number.parseInt(i.get("size")??"50",10),s=Number.parseInt(i.get("start")??"0",10),l=this.cleanText(document.body?.textContent??""),c=l.match(/\bof\s+([\d,]+)\s+results\b/i)??l.match(/\bTotal of\s+([\d,]+)\s+entries\b/i),u=c?.[1]?Number.parseInt(c[1].replace(/,/g,""),10):void 0,d=Number.isFinite(s)&&s>=0&&Number.isFinite(o)&&o>0?Math.floor(s/o)+1:1,p=u&&Number.isFinite(o)&&o>0?Math.max(1,Math.ceil(u/o)):1;return{pageNum:d,totalPages:p,totalItems:u,itemsPerPage:Number.isFinite(o)&&o>0?o:void 0,url:location.href}}const e=new URLSearchParams(location.search),t=Number.parseInt(e.get("page")??"0",10),n=Number.isFinite(t)&&t>=0?t+1:1,a=Array.from(document.querySelectorAll(".pager a, .pager-current")).map(i=>this.cleanText(i.textContent??"")).map(i=>Number.parseInt(i.replace(/,/g,""),10)).filter(i=>Number.isFinite(i)&&i>0);return{pageNum:n,totalPages:Math.max(1,n,...a),url:location.href,itemsPerPage:10}}parseSearchResultHost(e){if(this.isArxivHost())return this.parseArxivSearchResultHost(e);const t=this.cloneWithoutNestedResults(e),n=this.getServerInfo(),a=this.queryFirstVisible(t,["a.highwire-cite-linked-title[href]",".highwire-cite-title a[href]","h3 a[href]","h2 a[href]"]),i=this.cleanTitle(a?.textContent??this.queryText(t,[".highwire-cite-title","h3","h2"]));if(!i)return null;const o=this.absoluteUrl(a?.getAttribute("href")??void 0),s=o?this.extractDoiFromPath(new URL(o).pathname):void 0,l=this.cleanDoi(s||this.queryText(t,[".highwire-cite-metadata-doi"])||this.queryText(t,[".doi"])||this.extractDoi(t));return{title:i,journalName:n.name,journalCandidates:[],authors:this.extractAuthors(t),year:this.extractYear(this.queryText(t,[".highwire-cite-metadata-pages",".highwire-cite-metadata","time"])),doi:l,sourceId:this.buildSourceId(n,l,this.extractStableToken(e)??o??i),url:o,nativeFullTextUrl:this.buildPdfUrlFromArticleUrl(o),abstractSnippet:this.cleanAbstract(this.queryText(t,[".highwire-cite-snippet",".highwire-cite-abstract",".abstract"])),hostElement:e,articleTypes:["Preprint"],source:this.id,citationType:"misc"}}getSearchResultHosts(){if(this.isArxivHost()){const a=location.pathname;return/^\/list\//i.test(a)?this.uniqueElements(Array.from(document.querySelectorAll("#dlpage > dl > dd, dl > dd"))).filter(s=>!this.isHiddenDomElement(s)).filter(s=>!!this.queryText(s,[".list-title",".meta > .list-title"])):this.uniqueElements(Array.from(document.querySelectorAll("li.arxiv-result"))).filter(o=>!this.isHiddenDomElement(o)).filter(o=>!!this.queryText(o,[".title",".title.is-5",".title.is-5.mathjax"]))}const e=Array.from(document.querySelectorAll(By)),t=e.length>0?e:[document.body].filter(Boolean),n=this.uniqueElements(t.flatMap(a=>{const i=Array.from(a.querySelectorAll(Qa));return a.matches(Qa)&&i.unshift(a),i})).filter(a=>!this.isHiddenDomElement(a)).filter(a=>!!this.queryText(a,[".highwire-cite-title","h3","h2"]));return n.filter(a=>!n.some(i=>i!==a&&i.contains(a)))}cloneWithoutNestedResults(e){const t=e.cloneNode(!0);return t.querySelectorAll(Qa).forEach(n=>n.remove()),t}getDetailHost(){if(this.isArxivHost())return this.uniqueElements(Array.from(document.querySelectorAll("main, article, #abs"))).filter(a=>!this.isHiddenDomElement(a)).find(a=>!!this.queryText(a,["h1.title",".title"]))??document.querySelector("main")??document.body;const e=this.extractDoiFromPath(location.pathname),t=this.uniqueElements(Array.from(document.querySelectorAll(Iy))).filter(a=>!this.isHiddenDomElement(a)),n=e?t.find(a=>this.elementContainsDoi(a,e)):void 0;return n||(t.find(a=>!!this.queryText(a,["h1.highwire-cite-title","h1.article-title","h1",".highwire-cite-title"]))??t[0]??document.body)}hasArticleMetadata(){return!!(this.firstMetaContent(["citation_title"])&&(this.firstMetaContent(["citation_doi"])||this.firstMetaContent(["citation_pdf_url"])))}isChallengePage(){if(this.isArxivHost())return!1;const e=this.hasUsableContent();if(this.hasBlockingChallenge(e))return!0;if(e)return!1;const t=this.getVisibleDetailHeading();if(t&&this.isChallengeText(t))return!0;const n=document.title??"";if(/just a moment|attention required|cloudflare/i.test(n)||document.querySelector('.g-recaptcha, [class*="captcha" i], [id*="captcha" i]'))return!0;const a=document.documentElement?.innerHTML??"";return/_cf_chl_opt|Enable JavaScript and cookies to continue|Verifying you are human|verify you are human|Checking if the site connection is secure|article access|verify access|verification required|security check|complete security check|access denied|forbidden|sorry, you have been blocked|you do not have permission|not a robot|recaptcha|captcha/i.test(a)}hasBlockingChallenge(e=this.hasUsableContent()){return!!(document.querySelector("#challenge-error-text, .cf-error-details, .cf-browser-verification")||this.hasCloudflareChallengeSignature(e)||document.querySelector('form.access-check, [class*="access-check" i], [id*="access-check" i]')||this.hasBlockingTurnstile()||this.hasBlockingCaptcha())}hasCloudflareChallengeSignature(e=this.hasUsableContent()){const t=document.documentElement?.innerHTML??"";if(/_cf_chl_opt|cf_chl_|cf_clearance/i.test(t)||!e&&document.querySelector('script[src*="challenges.cloudflare.com/turnstile"], script[src*="/cdn-cgi/challenge-platform/"]'))return!0;const n=this.cleanText(`${document.title??""} ${document.body?.textContent??""}`);return!e&&/checking if the site connection is secure|verifying you are human|cloudflare ray id|enable javascript and cookies to continue/i.test(n)?!0:Array.from(document.querySelectorAll('iframe[src*="challenges.cloudflare.com"]')).some(a=>this.isBlockingChallengeElement(a))}hasBlockingTurnstile(){return Array.from(document.querySelectorAll('#cf-turnstile, .cf-turnstile, iframe[src*="challenges.cloudflare.com"]')).some(e=>this.isBlockingChallengeElement(e))}hasBlockingCaptcha(){return Array.from(document.querySelectorAll('.g-recaptcha, [class*="captcha" i], [id*="captcha" i]')).some(t=>this.isBlockingChallengeElement(t))}isBlockingChallengeElement(e){return this.isHiddenDomElement(e)?!1:!e.closest([".email-forward",".email-form","#forward-form",".pane-forward-form",'[class*="email-forward" i]','[class*="email-form" i]','[class*="forward-form" i]','form[class*="email" i]','form[id*="email" i]','form[class*="forward" i]','form[id*="forward" i]'].join(","))}hasUsableContent(){const e=this.getVisibleDetailHeading(),t=!!this.extractDoiFromPath(location.pathname),n=this.cleanTitle(this.firstMetaContent(["citation_title"])),a=!!(e&&n&&this.cleanTitle(e).toLowerCase()===n.toLowerCase()&&(this.firstMetaContent(["citation_doi"])||this.firstMetaContent(["citation_pdf_url"])||t)),i=!!(e&&(!this.isChallengeText(e)||a));return!!(this.getSearchResultHosts().length>0||i&&(a||t))}getVisibleDetailHeading(){const e=this.getDetailHost();return e?this.queryText(e,["h1.highwire-cite-title","h1.article-title","h1",".highwire-cite-title"]):""}isChallengeText(e){const t=this.cleanText(e).toLowerCase();return/^(?:article access|access denied|forbidden|security check|verify access|verification required|sorry, you have been blocked|verifying you are human|checking if the site connection is secure)$/.test(t)||/^(?:please\s+)?(?:verify|complete)\s+(?:your\s+)?(?:access|security check|captcha)(?:\s+before continuing)?\.?$/.test(t)?!0:/you do not have permission to access|sorry, you have been blocked|enable javascript and cookies to continue/i.test(e)}getServerInfo(){const e=location.hostname.toLowerCase();return e.includes("arxiv.org")?{name:"arXiv",slug:"arxiv"}:e.includes("medrxiv")?{name:"medRxiv",slug:"medrxiv"}:{name:"bioRxiv",slug:"biorxiv"}}isArxivHost(){return/(^|\.)arxiv\.org$/i.test(location.hostname)}extractAuthors(e){const t=Array.from(e.querySelectorAll(".highwire-citation-author"));return t.length>0?this.unique(t.map(n=>this.cleanText(n.textContent??""))):this.splitAuthors(this.queryText(e,[".highwire-cite-authors",".authors"]))}extractStableToken(e){const t=e.matches("[data-pisa-master], [data-pisa], [data-apath]")?e:e.querySelector("[data-pisa-master], [data-pisa], [data-apath]");return t?.getAttribute("data-pisa-master")??t?.getAttribute("data-pisa")??t?.getAttribute("data-apath")??void 0}extractDetailAuthors(e){if(this.isArxivHost())return this.extractArxivAuthors(e);const t=this.metaContents("citation_author");return t.length>0?this.unique(t):this.extractAuthors(e)}extractNativePdfUrl(e,t){const n=this.buildPdfUrlFromArticleUrl(location.href),a=this.unique([n,this.firstMetaContent(["citation_pdf_url"]),...Array.from(e.querySelectorAll("a[href]")).filter(i=>/\.full\.pdf(?:$|[?#])|\/content\/10\.[^"'\s]+\.pdf(?:$|[?#])|pdf/i.test(`${i.href} ${i.textContent??""}`)).map(i=>i.getAttribute("href")??"")]);for(const i of a){const o=this.absoluteUrl(i);if(!(!o||!this.isNativePreprintUrl(o))&&(!t||this.urlContainsDoi(o,t)))return o}}buildPdfUrlFromArticleUrl(e){if(e)try{const t=new URL(e,location.href);if(this.isArxivAbsoluteUrl(t.href)){const i=this.extractArxivIdFromPath(t.pathname)??this.extractArxivIdFromText(t.pathname);return i?(t.pathname=`/pdf/${i}.pdf`,t.search="",t.hash="",t.href):void 0}if(!this.isNativePreprintUrl(t.href)||!/^\/content\/10\./i.test(t.pathname))return;const n=t.pathname.replace(/\/+$/,"");if(/\.full\.pdf$/i.test(n))return t.href;const a=this.stripContentRouteSuffix(n);return t.pathname=/\.full$/i.test(a)?a.replace(/\.full$/i,".full.pdf"):a+".full.pdf",t.search="",t.hash="",t.href}catch{return}}isNativePreprintUrl(e){try{const t=new URL(e,location.href).hostname.toLowerCase();return/(^|\.)biorxiv\.org$/i.test(t)||/(^|\.)medrxiv\.org$/i.test(t)||/(^|\.)arxiv\.org$/i.test(t)}catch{return!1}}urlContainsDoi(e,t){const n=this.cleanDoi(t);if(!n)return!1;try{const a=new URL(e,location.href);return(this.extractDoiFromPath(a.pathname)??this.cleanDoi(decodeURIComponent(a.href)))===n}catch{return this.cleanDoi(decodeURIComponent(e))===n}}elementContainsDoi(e,t){return this.extractDoi(e)===t?!0:Array.from(e.querySelectorAll("a[href]")).some(n=>this.urlContainsDoi(n.href,t))}extractDoi(e){const t=this.cleanText(e.textContent??"").match(Iu);return t?this.cleanDoi(t[0]):void 0}extractDoiFromPath(e){const t=decodeURIComponent(e).match(/^\/content\/(10\.\d{4,9}\/[^/?#]+)/i);return t?this.cleanDoi(this.stripContentRouteSuffix(t[1])):void 0}stripContentRouteSuffix(e){return e.replace(/(?:\.article-info|\.figures-only|\.full(?:\.pdf)?)$/i,"")}cleanDoi(e){if(!e)return;const t=e.replace(/^doi:\s*/i,"").match(Iu);if(t)return t[0].replace(/^https?:\/\/(?:dx\.)?doi\.org\//i,"").replace(/(?:\.full)?\.pdf$/i,"").replace(/[.,;)\]]+$/g,"").replace(/v\d+$/i,"").toLowerCase()}buildSourceId(e,t,n){const a=t||n;return`preprint-servers:${e.slug}:${this.cleanText(a).toLowerCase()}`}extractYear(e){const t=e?.match(Py);return t?Number.parseInt(t[1],10):void 0}cleanTitle(e){return this.cleanText(e??"").replace(/\s*\|\s*(?:bioRxiv|medRxiv)\s*$/i,"").replace(/\s*\|\s*arXiv\s*$/i,"").replace(/^Title:\s*/i,"").replace(/^\[PDF\]\s*/i,"")}cleanAbstract(e){return this.cleanText(e??"").replace(/^Abstract\s*:?\s*/i,"")||void 0}parseArxivSearchResultHost(e){const t=this.extractArxivIdForHost(e),n=this.extractArxivAbsUrl(e)??(t?this.absoluteUrl(`/abs/${t}`):void 0),a=this.cleanTitle(this.queryText(e,[".title.is-5.mathjax",".title.is-5",".title",".list-title.mathjax",".list-title"]));if(!a||!n)return null;const i=this.extractArxivPdfUrl(e,t,n),o=this.buildArxivDoi(t),s=this.extractYear(this.queryText(e,[".is-size-7",".submitted-date",".list-date"]))??this.extractYearFromArxivId(t);return{title:a,journalName:"arXiv",journalCandidates:[],authors:this.extractArxivAuthors(e),year:s,doi:o,sourceId:this.buildSourceId(this.getServerInfo(),t,n),url:n,nativeFullTextUrl:i,abstractSnippet:this.cleanAbstract(this.queryText(e,[".abstract-full.has-text-grey-dark.mathjax",".abstract-full.mathjax",".abstract-full",".mathjax"])),hostElement:e,articleTypes:["Preprint"],source:this.id,citationType:"misc"}}parseArxivArticlePage(e){const t=this.extractArxivIdFromPath(location.pathname)??this.extractArxivIdFromText(this.cleanText(e.textContent??"")),n=this.cleanTitle(this.firstMetaContent(["citation_title","dc.title","og:title"])??this.queryText(e,["h1.title",".title.mathjax",".title"]));if(!n)return null;const a=this.getCanonicalUrl()??(t?this.absoluteUrl(`/abs/${t}`):location.href)??location.href,i=this.cleanDoi(this.firstMetaContent(["citation_doi","dc.identifier","prism.doi"])??this.queryFirstVisible(e,['a[href*="doi.org/10.48550/arXiv."]'])?.getAttribute("href")??this.buildArxivDoi(t));return{title:n,journalName:"arXiv",journalCandidates:[],authors:this.extractArxivAuthors(e),year:this.extractYear(this.queryText(e,[".dateline",".submission-history",".is-size-7"]))??this.extractYearFromArxivId(t),doi:i,sourceId:this.buildSourceId(this.getServerInfo(),t,a),url:a,nativeFullTextUrl:this.extractArxivPdfUrl(e,t,a),abstractSnippet:this.cleanAbstract(this.queryText(e,["blockquote.abstract.mathjax","blockquote.abstract",".abstract.mathjax",".abstract"])),hostElement:e,articleTypes:["Preprint"],source:this.id,citationType:"misc"}}extractArxivAuthors(e){return this.unique(Array.from(e.querySelectorAll(".authors a, .list-authors a, p.authors a")).map(t=>this.cleanText(t.textContent??"")).filter(Boolean))}extractArxivIdForHost(e){const t=e.matches("dd")?e.previousElementSibling:e;return this.extractArxivIdFromText(this.queryText(t??e,[".list-title.is-inline-block",".list-identifier",'a[href*="/abs/"]']))??this.extractArxivIdFromPath(this.extractArxivAbsUrl(e,t??void 0)?new URL(this.extractArxivAbsUrl(e,t??void 0),location.href).pathname:"")}extractArxivAbsUrl(e,t){const n=this.queryFirstVisible(t??e,['a[href^="/abs/"]','a[href*="arxiv.org/abs/"]']);return this.absoluteUrl(n?.getAttribute("href")??n?.href)}extractArxivPdfUrl(e,t,n){const a=this.queryFirstVisible(e.matches("dd")&&e.previousElementSibling?e.previousElementSibling:e,['a[title*="Download PDF" i]','a[href^="/pdf/"]','a[href*="arxiv.org/pdf/"]']),i=this.absoluteUrl(a?.getAttribute("href")??a?.href);if(i&&this.isArxivAbsoluteUrl(i)){if(/\.pdf(?:$|[?#])/i.test(i))return i;const o=this.buildPdfUrlFromArticleUrl(i);if(o)return o}if(n){const o=this.buildPdfUrlFromArticleUrl(n);if(o)return o}return t?this.absoluteUrl(`/pdf/${t}.pdf`):void 0}buildArxivDoi(e){return e?`10.48550/arXiv.${e}`.toLowerCase():void 0}extractArxivIdFromPath(e){const t=decodeURIComponent(e),n=t.match(/^\/abs\/([^/?#]+)/i);if(n?.[1])return n[1].replace(/v\d+$/i,"");const a=t.match(/^\/pdf\/([^/?#]+?)(?:\.pdf)?$/i);if(a?.[1])return a[1].replace(/v\d+$/i,"")}extractArxivIdFromText(e){const t=this.cleanText(e??""),n=t.match(/\barXiv:\s*([A-Za-z.\-]+\/\d{7}|\d{4}\.\d{4,5})(?:v\d+)?\b/i);return n?.[1]?n[1].replace(/v\d+$/i,""):t.match(/\b([A-Za-z.\-]+\/\d{7}|\d{4}\.\d{4,5})(?:v\d+)?\b/)?.[1]?.replace(/v\d+$/i,"")}extractYearFromArxivId(e){if(!e)return;const t=e.match(/^(\d{2})(\d{2})\.\d{4,5}$/);if(!t)return;const n=Number.parseInt(t[1],10);return n>=91?1900+n:2e3+n}isArxivAbsoluteUrl(e){try{return/(^|\.)arxiv\.org$/i.test(new URL(e,location.href).hostname)}catch{return!1}}queryFirstVisible(e,t){for(const n of t){const a=Array.from(e.querySelectorAll(n)).find(i=>!this.isHiddenDomElement(i));if(a)return a}return null}queryFirstForHost(e,t){for(const n of t){const a=Array.from(e.querySelectorAll(n));for(const i of a){if(this.isHiddenDomElement(i))continue;const o=i.closest(Qa);if(!o||o===e)return i}}return null}queryText(e,t){for(const n of t){const a=this.cleanText(this.queryFirstVisible(e,[n])?.textContent??"");if(a)return a}return""}isHiddenDomElement(e){if(!(e instanceof HTMLElement))return!1;let t=e;for(;t&&t!==document.body;){if(t.hidden||t.getAttribute("aria-hidden")==="true")return!0;const n=t.getAttribute("style")??"";if(/display\s*:\s*none|visibility\s*:\s*hidden|opacity\s*:\s*0(?:[;\s]|$)|clip\s*:\s*rect\(\s*0/i.test(n)||/clip-path\s*:\s*(?!none\b)[^;]+/i.test(n)||/(?:position\s*:\s*(?:absolute|fixed)[^;]*;?|(?:left|right|top|bottom)\s*:\s*-?[1-9]\d{3,}px)/i.test(n)&&/(?:left|right|top|bottom)\s*:\s*-?[1-9]\d{3,}px/i.test(n)||/transform\s*:\s*(?:matrix\([^)]*(?:-?[1-9]\d{3,}|,\s*-?[1-9]\d{3,})|translate(?:3d|x|y)?\([^)]*-?[1-9]\d{3,})/i.test(n)||/width\s*:\s*0(?:px)?(?:[;\s]|$)/i.test(n)&&/height\s*:\s*0(?:px)?(?:[;\s]|$)/i.test(n)&&/overflow\s*:\s*hidden/i.test(n))return!0;const a=typeof window<"u"&&typeof window.getComputedStyle=="function"?window.getComputedStyle(t):null;if(a){const i=Number.parseFloat(a.left||"0"),o=Number.parseFloat(a.top||"0"),s=Number.parseFloat(a.right||"0"),l=Number.parseFloat(a.bottom||"0"),c=a.clip??"",u=a.clipPath??"",d=a.transform??"",p=Number.parseFloat(a.width||""),h=Number.parseFloat(a.height||""),f=!!(c&&c!=="auto")||!!(u&&u!=="none"),y=["absolute","fixed"].includes(a.position)&&(Math.abs(i)>1e3||Math.abs(o)>1e3||Math.abs(s)>1e3||Math.abs(l)>1e3),x=/matrix\([^)]*(?:-?[1-9]\d{3,}|,\s*-?[1-9]\d{3,})|translate(?:3d|X|Y)?\([^)]*-?[1-9]\d{3,}/i.test(d),T=Number.isFinite(p)&&Number.isFinite(h)&&p<=1&&h<=1&&a.overflow==="hidden";if(a.display==="none"||a.visibility==="hidden"||a.opacity==="0"||f||y||x||T)return!0}t=t.parentElement}return!1}firstMetaContent(e){for(const t of e){const n=document.querySelector(`meta[name="${t}"], meta[property="${t}"]`)?.content,a=this.cleanText(n??"");if(a)return a}}metaContents(e){return this.unique(Array.from(document.querySelectorAll(`meta[name="${e}"], meta[property="${e}"]`)).map(t=>this.cleanText(t.content)).filter(Boolean))}getCanonicalUrl(){return this.absoluteUrl(document.querySelector('link[rel="canonical"]')?.href)}absoluteUrl(e){const t=this.cleanText(e??"");if(!(!t||t==="#"))try{return new URL(t,location.href).href}catch{return}}splitAuthors(e){const t=this.cleanText(e??"");return t?this.unique(t.split(/\s*(?:,|;|\band\b)\s*/i).map(n=>this.cleanText(n)).filter(Boolean)):[]}unique(e){const t=new Set;return e.filter(n=>t.has(n)?!1:(t.add(n),!0))}uniqueElements(e){const t=new Set;return e.filter(n=>t.has(n)?!1:(t.add(n),!0))}cleanText(e){return e.replace(/\s+/g," ").trim()}}const qy=/\b10\.\d{4,9}\/[^\s"'<>?#]+/i,jy=/\b((?:19|20)\d{2})\b/,$y="dt.search-results-title";class Oy extends j{id="plos";name="PLOS";matches=["*://journals.plos.org/*"];isSearchPage(){return/^\/[^/]+\/search\/?$/i.test(location.pathname)}isArticlePage(){return/^\/[^/]+\/article(?:\/|$)/i.test(location.pathname)?!!(location.search.includes("id=")||this.firstMetaContent(["citation_title","citation_journal_title"])||document.querySelector("h1")):!1}parseSearchResults(){if(!this.isSearchPage())return[];const e=[],t=new Set;for(const n of this.getSearchResultTitleHosts())try{const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;if(t.has(i))continue;t.add(i),e.push(a)}catch(a){console.error("[PlosAdapter] Failed to parse search result:",a)}return e}parseArticlePage(){if(!this.isArticlePage())return null;const e=this.getDetailHost();if(!e)return null;try{const t=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??e.querySelector("h1")?.textContent??"");if(!t)return null;const n=this.cleanJournalName(this.firstMetaContent(["citation_journal_title"])??this.extractJournalFromDetailDom(e)??this.getJournalNameFromPath()),a=this.cleanDoi(this.firstMetaContent(["citation_doi"])??this.extractDoi(e)??new URLSearchParams(location.search).get("id")??void 0),i=this.cleanText(this.firstMetaContent(["citation_date","citation_publication_date"])??this.findDetailMetaList(e)?.textContent??""),o=this.toAbsoluteUrl(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href);return{title:t,journalName:n,journalCandidates:this.unique([n,this.getJournalNameFromPath()].filter(Boolean)),authors:this.extractMetadataAuthors().length>0?this.extractMetadataAuthors():this.extractAuthorsFromText(e.querySelector(".authors, .article-authors, .author-list")?.textContent??""),year:this.extractYear(i),publicationDate:i||void 0,doi:a,sourceId:this.buildSourceId(a,o),url:o,nativeFullTextUrl:this.extractNativeFullTextUrl(a,o),abstractSnippet:this.cleanAbstract(this.firstMetaContent(["citation_abstract","description","og:description"])??this.extractDetailAbstract(e)),hostElement:e,articleTypes:this.extractDetailTypes(e),issn:this.normalizeIssn(this.firstMetaContent(["citation_issn"])),volume:this.cleanText(this.firstMetaContent(["citation_volume"])??""),issue:this.cleanText(this.firstMetaContent(["citation_issue"])??""),pages:this.extractPagesFromMetadata(),source:this.id,citationType:"article"}}catch(t){return console.error("[PlosAdapter] Failed to parse article page:",t),null}}getMetricBarAnchor(e){if(this.isArticlePage()){const a=this.findDetailMetaList(e)??this.findDetailMetaList(document.body);if(a)return{element:a,position:"after"};const i=e.querySelector("h1");return i?{element:i,position:"after"}:{element:e,position:"prepend"}}const t=e.querySelector("p:nth-of-type(2), .search-results-details, .search-results-meta");if(t)return{element:t,position:"after"};const n=e.previousElementSibling;return n?.matches("dt.search-results-title")?{element:n,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector("#search-results")??document.querySelector("article.searchResults")??document.querySelector("main")??document.body}getPageInfo(){const e=new URLSearchParams(location.search),t=Number.parseInt(e.get("page")??"1",10)||1,a=this.cleanText(document.querySelector(".search-results-total, .results-total, .search-results-header, .search-results-controls, main")?.textContent??"").match(/\b([\d,]+)\s+results?\s+for\b/i),i=a?Number.parseInt(a[1].replace(/,/g,""),10):void 0;return{pageNum:t,totalPages:i?Math.max(1,Math.ceil(i/10)):1,url:location.href,itemsPerPage:10,totalItems:i}}getSearchResultTitleHosts(){return Array.from(document.querySelectorAll($y)).filter(e=>e.nextElementSibling?.matches("dd"))}parseSearchHost(e){const t=e.nextElementSibling;if(!t?.matches("dd"))return null;const n=e.querySelector('a[href*="/article?id="]'),a=this.cleanText(n?.textContent??e.textContent??"");if(!a)return null;const i=this.toAbsoluteUrl(n?.getAttribute("href")??n?.href??""),o=this.cleanDoi(t.querySelector('a[href*="doi.org/"]')?.textContent??t.querySelector('a[href*="doi.org/"]')?.getAttribute("href")??e.getAttribute("data-doi")??void 0),s=this.extractAuthorsFromText(t.querySelector("p:nth-of-type(1)")?.textContent??""),l=this.cleanText(t.querySelector("p:nth-of-type(2)")?.textContent??""),c=this.parseSearchDetailLine(l),u=c.articleType??"Research Article",d=this.cleanJournalName(c.journalName??this.getJournalNameFromPath()),p=c.publicationDate;return{title:a,journalName:d,journalCandidates:this.unique([d,this.getJournalNameFromPath()].filter(Boolean)),authors:s,year:this.extractYear(p??l),publicationDate:p,doi:o,sourceId:this.buildSourceId(o,i),url:i,nativeFullTextUrl:this.extractNativeFullTextUrl(o,i),hostElement:t,articleTypes:[u],source:this.id,citationType:"article"}}parseSearchDetailLine(e){if(!e)return{};const[t,n]=e.split("|").map(l=>this.cleanText(l)),a=n??e,i=a.match(/(PLOS(?:\s+[A-Za-z0-9&.-]+)+)\s*$/i),o=i?.[1],s=this.cleanText(a.replace(/^published\s*/i,"").replace(i?.[0]??"",""));return{articleType:t||void 0,publicationDate:s||void 0,journalName:this.cleanJournalName(o??"")}}findDetailMetaList(e){const t=["ul.articleinfo",".articleinfo","ul","p","div"];for(const n of t){const a=Array.from(e.querySelectorAll(n)).find(i=>!!i.querySelector('a[href*="doi.org/"]'));if(a)return a}return null}getDetailHost(){return document.querySelector("main")??document.querySelector("article")??document.body}extractDetailAbstract(e){const t=e.querySelector("#abstract0, .abstract, section.abstract");return this.cleanText(t?.textContent??"")}extractDetailTypes(e){const t=this.cleanText(this.firstMetaContent(["citation_article_type"])??e.querySelector('#artType, .type-article, [class*="article-type"]')?.textContent??"");return t?[t]:[]}extractMetadataAuthors(){const e=Array.from(document.querySelectorAll('meta[name="citation_author"]')).map(t=>this.cleanText(t.content)).filter(Boolean);return this.unique(e)}extractAuthorsFromText(e){const t=this.cleanText(e).replace(/\bet al\.?$/i,"").trim();return t?this.unique(t.split(/\s*,\s*|\s+and\s+/i).map(n=>this.cleanText(n)).filter(Boolean)):[]}extractNativeFullTextUrl(e,t){const n=this.toAbsoluteUrl(this.firstMetaContent(["citation_pdf_url"])??"");if(n&&this.isNativePlosUrl(n))return n;const a=e??this.cleanDoi(new URLSearchParams(new URL(t??location.href,location.href).search).get("id")??void 0);if(!a)return;const i=this.getJournalSlug(t);if(i)return`https://journals.plos.org/${i}/article/file?id=${encodeURIComponent(a)}&type=printable`}extractPagesFromMetadata(){const e=this.cleanText(this.firstMetaContent(["citation_firstpage"])??""),t=this.cleanText(this.firstMetaContent(["citation_lastpage"])??"");if(e)return t&&t!==e?`${e}-${t}`:e}extractJournalFromDetailDom(e){return this.cleanText(e.querySelector('.header p, .articleinfo, [class*="journal"]')?.textContent??"").match(/\b(PLOS(?:\s+[A-Za-z0-9&.-]+)+)\b/i)?.[1]??null}extractDoi(e){const t=e.querySelector('a[href*="doi.org/"]');return this.cleanDoi(t?.textContent??t?.getAttribute("href")??void 0)}getJournalSlug(e){try{return new URL(e??location.href,location.href).pathname.split("/").filter(Boolean)[0]||null}catch{return null}}getJournalNameFromPath(){const e=this.getJournalSlug();if(!e)return"PLOS";const t=e.replace(/^plos/i,"").trim();return t?t.toLowerCase()==="one"?"PLOS ONE":`PLOS ${t.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[-_\s]+/).filter(Boolean).map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(" ")}`.trim():"PLOS"}buildSourceId(e,t){return e?`plos:${e.toLowerCase()}`:t?`plos:${t}`:void 0}firstMetaContent(e){for(const t of e){const n=document.querySelector(`meta[name="${t}"], meta[property="${t}"]`),a=this.cleanText(n?.getAttribute("content")??"");if(a)return a}return null}normalizeIssn(e){const t=this.cleanText(e??"");if(!t)return;const n=t.match(/\b\d{4}-?\d{3}[\dX]\b/i);if(!n)return;const a=n[0].replace(/-/g,"");return`${a.slice(0,4)}-${a.slice(4)}`}cleanJournalName(e){const t=this.cleanText(e);return t?t.replace(/\bPLOS One\b/i,"PLOS ONE"):"PLOS"}cleanAbstract(e){return this.cleanText(e).replace(/^Abstract\s*:?\s*/i,"")||void 0}cleanDoi(e){const t=this.cleanText(e??"");return t?t.match(qy)?.[0]?.replace(/[)>.,;]+$/,"").toLowerCase():void 0}extractYear(e){const t=this.cleanText(e??"").match(jy);return t?Number.parseInt(t[1],10):void 0}isNativePlosUrl(e){try{return new URL(e,location.href).hostname==="journals.plos.org"}catch{return!1}}toAbsoluteUrl(e){const t=this.cleanText(e);if(t)try{return new URL(t,location.href).href}catch{return}}unique(e){return Array.from(new Set(e.map(t=>this.cleanText(t)).filter(Boolean)))}cleanText(e){return e.replace(/\u00a0/g," ").replace(/\s+/g," ").trim()}}const Uy=/\b10\.\d{4,9}\/[^\s"'<>?#]+/i,Hy=/\b((?:19|20)\d{2})\b/,Go=/^(official\s+(?:review|comment|decision)|reviewer\s|public comment|author response|rebuttal)/i;class zy extends j{id="openreview";name="OpenReview";matches=["*://openreview.net/*"];isSearchPage(){return/^\/search\/?$/i.test(location.pathname)}isArticlePage(){return/^\/forum\/?$/i.test(location.pathname)&&!!(new URLSearchParams(location.search).get("id")||this.firstMetaContent(["citation_title"])||document.querySelector("main .note, main .legacy-forum, main h2.note_content_title, main h2.citation_title"))}parseSearchResults(){if(!this.isSearchPage())return[];const e=[],t=new Set;for(const n of this.getSearchResultHosts())try{const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;if(t.has(i))continue;t.add(i),e.push(a)}catch(a){console.error("[OpenReviewAdapter] Failed to parse search result:",a)}return e}parseArticlePage(){if(!this.isArticlePage())return null;const e=this.getDetailHost();if(!e)return null;try{const t=this.cleanText(this.firstMetaContent(["citation_title","og:title"])??e.querySelector("h2.note_content_title, h2.citation_title, h2")?.textContent??"");if(!t)return null;const n=this.extractForumId(location.href),a=this.cleanText(this.firstMetaContent(["citation_conference_title"])??""),i=this.extractDetailVenue(e),o=this.cleanDoi(this.extractOpenWebsiteLink(e)?.getAttribute("href")??this.firstMetaContent(["citation_doi"])??void 0),s=this.inferRecordKind(t,[i,a].filter(Boolean),o),l=this.resolveVenueInfo([i,a].filter(Boolean),s,o),c=this.extractDetailPublicationDate(e)??this.cleanText(this.firstMetaContent(["citation_online_date"])??"");return{title:t,journalName:l.journalName,journalCandidates:l.candidates,authors:this.extractMetadataAuthors().length>0?this.extractMetadataAuthors():this.extractDetailAuthors(e),year:this.extractYear(c||l.journalName),publicationDate:c||void 0,doi:o,sourceId:n?`openreview:${n}`:void 0,url:this.toAbsoluteUrl(location.href),nativeFullTextUrl:this.extractNativePdfUrl(e,n),abstractSnippet:this.cleanAbstract(this.firstMetaContent(["citation_abstract","description","og:description"])??this.extractDetailAbstract(e)),hostElement:e,articleTypes:s.articleTypes,source:this.id,citationType:s.citationType}}catch(t){return console.error("[OpenReviewAdapter] Failed to parse article page:",t),null}}getMetricBarAnchor(e){if(this.isArticlePage()){const i=e.querySelector(".meta_row");if(i)return{element:i,position:"after"};const o=e.querySelector("h2.note_content_title, h2.citation_title, h2");return o?{element:o,position:"after"}:{element:e,position:"prepend"}}const t=e.querySelector(".note-meta-info, .note-metadata, ul");if(t)return{element:t,position:"after"};const n=e.querySelector(".note-authors");if(n)return{element:n,position:"after"};const a=e.querySelector("h4");return a?{element:a,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return this.findSearchResultsContainer()??document.querySelector("main")??document.body}getPageInfo(){const e=this.cleanText(document.querySelector('[aria-current="page"], .ant-pagination-item-active, .pagination li.active')?.textContent??""),t=Number.parseInt(e,10)||1,n=this.getSearchResultHosts().length||void 0;return{pageNum:t,totalPages:1,itemsPerPage:n,url:location.href}}getSearchResultHosts(){const t=this.findSearchResultsContainer()??document.querySelector("main")??document.body;return Array.from(t.querySelectorAll("li")).filter(n=>this.looksLikePaperSearchResult(n))}findSearchResultsContainer(){return Array.from(document.querySelectorAll("ul")).find(e=>!!e.querySelector('div.note h4 a[href^="/forum?id="]'))??null}looksLikePaperSearchResult(e){const t=e.querySelector('h4 a[href^="/forum?id="]'),n=this.cleanText(t?.textContent??"");return!n||Go.test(n)||!e.querySelector(".note-authors")?!1:!!e.querySelector(".note-meta-info li, .note-metadata li, ul li")}parseSearchHost(e){const t=e.querySelector('h4 a[href^="/forum?id="]'),n=this.cleanText(t?.textContent??"");if(!n||Go.test(n))return null;const a=this.toAbsoluteUrl(t?.getAttribute("href")??t?.href??""),i=this.extractForumId(a),o=e.querySelector("a.pdf-link[href]"),s=e.querySelector("a.html-link[href]"),l=Array.from(e.querySelectorAll(".note-meta-info li, .note-metadata li, ul li")).map(f=>this.cleanText(f.textContent??"")).filter(Boolean),c=l.find(f=>!/^Published:/i.test(f)&&!/^Readers:/i.test(f))??"",u=l.find(f=>/^Published:/i.test(f))?.replace(/^Published:\s*/i,""),d=this.cleanDoi(s?.getAttribute("href")??void 0),p=this.inferRecordKind(n,[c],d),h=this.resolveVenueInfo([c],p,d);return{title:n,journalName:h.journalName,journalCandidates:h.candidates,authors:this.extractSearchAuthors(e),year:this.extractYear(u??c),publicationDate:u||void 0,doi:d,sourceId:i?`openreview:${i}`:void 0,url:a,nativeFullTextUrl:this.toAbsoluteUrl(o?.getAttribute("href")??"")??this.buildPdfUrl(i),hostElement:e,articleTypes:p.articleTypes,source:this.id,citationType:p.citationType}}getDetailHost(){return document.querySelector("main .note")??document.querySelector("main .legacy-forum .note")??document.querySelector("main")??document.body}extractSearchAuthors(e){const t=Array.from(e.querySelectorAll(".note-authors a")).map(n=>this.cleanText(n.textContent??"")).filter(Boolean);return this.unique(t)}extractMetadataAuthors(){const e=Array.from(document.querySelectorAll('meta[name="citation_author"]')).map(t=>this.cleanText(t.content)).filter(Boolean);return this.unique(e)}extractDetailAuthors(e){const t=Array.from(e.querySelectorAll(".meta_row .signatures a, .meta_row .author a, h3.signatures a")).map(n=>this.cleanText(n.textContent??"")).filter(Boolean);return this.unique(t)}extractDetailVenue(e){return Array.from(e.querySelectorAll(".meta_row .item")).map(n=>this.cleanText(n.textContent??"")).filter(Boolean).find(n=>!/^Published:/i.test(n)&&!/^Readers:/i.test(n))??""}extractDetailPublicationDate(e){return this.cleanText(e.querySelector(".meta_row .date, .meta_row .item.date")?.textContent??"").replace(/^Published:\s*/i,"")||void 0}extractDetailAbstract(e){const t=Array.from(e.querySelectorAll(".note_content_field")).filter(n=>/^Abstract:/i.test(this.cleanText(n.textContent??"")));for(const n of t){const a=n.parentElement;if(!a)continue;const i=a.cloneNode(!0);i.querySelectorAll(".note_content_field").forEach(s=>s.remove());const o=this.cleanText(i.textContent??"");if(o)return o}return""}extractNativePdfUrl(e,t){const n=this.toAbsoluteUrl(this.firstMetaContent(["citation_pdf_url"])??"");if(n)return n;const a=e.querySelector('a[href^="/pdf?id="], a.pdf-link[href]');return this.toAbsoluteUrl(a?.getAttribute("href")??"")??this.buildPdfUrl(t)}extractOpenWebsiteLink(e){return e.querySelector('a.html-link[href], a[href*="doi.org/"], a[href*="arxiv.org/"]')}buildPdfUrl(e){return e?`https://openreview.net/pdf?id=${encodeURIComponent(e)}`:void 0}inferRecordKind(e,t,n){if(Go.test(e))return{articleTypes:["Reply"],citationType:"misc",metricsAllowed:!1};const a=this.cleanText([e,...t,n??""].join(" ")).toLowerCase();return/corr|arxiv|preprint/.test(a)||/^10\.48550\/arxiv\./i.test(n??"")?{articleTypes:["Preprint"],citationType:"misc",metricsAllowed:!1}:/conference|workshop|poster|oral|submission|neurips|iclr|icml|kdd|cvpr|eccv|aaai|acl|emnlp|coling|corl/.test(a)?{articleTypes:["Conference Paper"],citationType:"inproceedings",metricsAllowed:!1}:{articleTypes:["JournalArticle"],citationType:"article",metricsAllowed:!0}}resolveVenueInfo(e,t,n){const a=e.map(o=>this.cleanText(o)).filter(Boolean);if(t.citationType==="misc"){const o=this.unique([...a.map(s=>this.normalizePreprintVenue(s)),/^10\.48550\/arxiv\./i.test(n??"")?"arXiv":""].filter(Boolean));return{journalName:o[0]??"CoRR",candidates:o}}if(t.citationType==="inproceedings"){const o=this.unique(a.map(s=>this.normalizeConferenceVenue(s)));return{journalName:o[0]??"OpenReview",candidates:o}}const i=this.unique(a.map(o=>this.normalizeJournalVenue(o)));return{journalName:i[0]??"OpenReview",candidates:i}}normalizePreprintVenue(e){const t=this.cleanText(e);return/corr/i.test(t)?"CoRR":/arxiv/i.test(t)?"arXiv":t||"CoRR"}normalizeConferenceVenue(e){let t=this.cleanText(e);return t&&(t=t.replace(/\b\d{4}\b/g," ").replace(/\b(?:poster|oral|spotlight|workshop|demo|submission)\b/gi," ").replace(/\b\d+\b/g," ").replace(/\s+/g," ").trim(),t=t.replace(/^\d+(?:st|nd|rd|th)\s+Annual\s+/i,""),t=t.replace(/\bConference on Robot Learning\b/i,"CoRL"),t=t.replace(/\bNeural Information Processing Systems\b/i,"NeurIPS"),/^KDD$/i.test(t)?"SIGKDD":/^NIPS$/i.test(t)?"NeurIPS":t)}normalizeJournalVenue(e){return this.cleanText(e).replace(/\b\d{4}\b/g," ").replace(/\s+/g," ").trim()}extractForumId(e){if(e)try{return new URL(e,location.href).searchParams.get("id")??void 0}catch{return}}firstMetaContent(e){for(const t of e){const n=document.querySelector(`meta[name="${t}"], meta[property="${t}"]`),a=this.cleanText(n?.getAttribute("content")??"");if(a)return a}return null}cleanAbstract(e){return this.cleanText(e).replace(/^Abstract:\s*/i,"")||void 0}cleanDoi(e){const t=this.cleanText(e??"");return t?t.match(Uy)?.[0]?.replace(/[)>.,;]+$/,"").toLowerCase():void 0}extractYear(e){const t=this.cleanText(e??"").match(Hy);return t?Number.parseInt(t[1],10):void 0}toAbsoluteUrl(e){const t=this.cleanText(e);if(t)try{return new URL(t,location.href).href}catch{return}}unique(e){return Array.from(new Set(e.map(t=>this.cleanText(t)).filter(Boolean)))}cleanText(e){return e.replace(/\u00a0/g," ").replace(/\s+/g," ").trim()}}const Mu=/\b10\.\d{4,9}\/[^\s"'<>?#]+/i,Jy=/\b((?:19|20)\d{2})\b/,Vy=/\/(?:fulltext|abstract)\/([^/?#]+)/i,Wy=/^S?(\d{4})-?(\d{3}[\dX])/i,qu=["li.search__item",".search__item",".search-result__item",".resultItem","ol.search-results > li","li.search-result-item",".search-result-item",".search-result","article.search-result",'[data-e2e*="search-result"]',".issue-item"].join(","),Gy=[qu,".art_title",".hlFld-Title",".publication_title"].join(","),ju=[".search-results",".searchResultList",".search__list",'[aria-label="Search results"]',".results-shell"].join(",");class Zy extends j{id="cell-com";name="Cell.com";matches=["*://www.cell.com/*"];isSearchPage(){if(this.isChallengePage())return!1;const e=location.pathname.toLowerCase();return e==="/action/dosearch"||e.startsWith("/action/dosearch")||e==="/search"||e==="/search/"||!/^\/[^/]+\/(?:fulltext|abstract)\/[^/]+/i.test(location.pathname)&&(new URLSearchParams(location.search).has("text1")||new URLSearchParams(location.search).has("text"))}isArticlePage(){return this.isChallengePage()?!1:/^\/[^/]+\/(?:fulltext|abstract)\/[^/]+/i.test(location.pathname)?!0:!!this.firstMetaContent(["citation_title"])}parseSearchResults(){if(!this.isSearchPage())return[];const e=[],t=new Set;for(const n of this.getSearchResultHosts())try{const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;if(t.has(i))continue;t.add(i),e.push(a)}catch(a){console.error("[CellComAdapter] Failed to parse search result:",a)}return e}parseArticlePage(){if(!this.isArticlePage())return null;const e=this.getDetailHost();if(!e)return null;try{const t=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??e.querySelector("h1")?.textContent??"");if(!t)return null;const n=this.toAbsoluteUrl(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??this.firstMetaContent(["citation_public_url","citation_fulltext_html_url","prism.url","og:url"])??location.href),a=this.toAbsoluteUrl(this.firstMetaContent(["citation_pdf_url"])??e.querySelector('a[href$=".pdf"], a[href*="/pdf"], a[data-track-action*="pdf"]')?.getAttribute("href")??""),i=this.extractPii(n??"")??this.extractPii(a??""),o=this.deriveJournalCandidatesFromUrl(n??location.href),s=this.cleanText(this.firstMetaContent(["citation_publication_date","citation_online_date","citation_date"])??this.extractDetailMetaText(e)??""),l=this.cleanDoi(this.firstMetaContent(["citation_doi","prism.doi"])??this.extractDoi(e)??void 0),c=this.sanitizeJournalCandidate(this.firstMetaContent(["citation_journal_title","prism.publicationName"])??this.extractDetailJournal(e)??"",t),u=this.extractIssnFromPii(i)??this.normalizeIssn(this.firstMetaContent(["citation_issn","prism.issn"]));return{title:t,journalName:c||o[0]||"",journalCandidates:this.unique([c,...o].filter(Boolean)),authors:this.extractMetadataAuthors().length>0?this.extractMetadataAuthors():this.extractDomAuthors(e),year:this.extractYear(s),publicationDate:s||void 0,doi:l,sourceId:i?`cell-com:${i}`:l?`cell-com:${l}`:void 0,url:n,nativeFullTextUrl:a??n,abstractSnippet:this.cleanAbstract(this.firstMetaContent(["citation_abstract","description","og:description"])??this.extractDetailAbstract(e)),hostElement:e,articleTypes:this.extractDetailTypes(e),issn:u,volume:this.cleanText(this.firstMetaContent(["citation_volume"])??""),issue:this.cleanText(this.firstMetaContent(["citation_issue"])??""),pages:this.extractPagesFromMetadata(),source:this.id,citationType:"article"}}catch(t){return console.error("[CellComAdapter] Failed to parse article page:",t),null}}getMetricBarAnchor(e){if(this.isArticlePage()){const i=this.findDetailIssueAnchor(e)??this.findDetailIssueAnchor(document.body);if(i)return{element:i,position:"after"};const o=this.findDetailMetaAnchor(e)??this.findDetailMetaAnchor(document.body);if(o)return{element:o,position:"after"};const s=e.querySelector("h1");return s?{element:s,position:"after"}:{element:e,position:"prepend"}}const t=e.querySelector('.result-meta, .search-result__meta, .journal-title, .publication-title, .meta, [class*="meta"]');if(t)return{element:t,position:"after"};const n=e.querySelector('.authors, .author-list, [class*="author"]');if(n)return{element:n,position:"after"};const a=e.querySelector('h2, h3, [class*="title"]');return a?{element:a,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector(ju)??document.querySelector("ol.search-results")??document.querySelector(".search-results")??document.querySelector("#search-results")??document.querySelector("main")??document.body}getPageInfo(){const e=new URLSearchParams(location.search),t=Number.parseInt(e.get("page")??"1",10)||1,a=this.cleanText(document.querySelector('.search-results-count, .results-found, .result__count, .search-result__count, [data-e2e="results-count"], main')?.textContent??"").match(/\b([\d,]+)\s+results?\b/i),i=a?Number.parseInt(a[1].replace(/,/g,""),10):void 0,o=this.getSearchResultHosts().length||void 0;return{pageNum:t,totalPages:i&&o?Math.max(1,Math.ceil(i/o)):1,itemsPerPage:o,totalItems:i,url:location.href}}getSearchResultHosts(){if(this.isChallengePage())return[];const e=Array.from(document.querySelectorAll(ju)),t=e.length>0?e:[document.querySelector("main")??document.body];return this.uniqueElements(t.flatMap(n=>Array.from(n.querySelectorAll(Gy))).map(n=>this.toSearchResultHost(n)).filter(n=>!!n).filter(n=>this.looksLikeSearchResult(n)))}looksLikeSearchResult(e){return e.closest('[class^="paperlens-"], [class*=" paperlens-"]')||e.closest('[id*="reference"], [class*="reference"], [id*="related"], [class*="related"]')?!1:!!this.findArticleLink(e)&&!!this.cleanText(e.textContent??"")}parseSearchHost(e){const t=this.findArticleLink(e),n=this.cleanText(t?.textContent??e.querySelector('h2, h3, .art_title, .hlFld-Title, .publication_title, [class*="title"]')?.textContent??"");if(!n)return null;const a=this.toAbsoluteUrl(t?.getAttribute("href")??t?.href??""),i=this.toAbsoluteUrl(e.querySelector('a[href$=".pdf"], a[href*="/pdf"], a[data-track-action*="pdf"], a[href*="/pdf?"]')?.getAttribute("href")??""),o=this.extractPii(a??"")??this.extractPii(i??""),s=this.deriveJournalCandidatesFromUrl(a??""),l=this.cleanText(e.querySelector('time, .publication-date, .meta__epubDate, .epub-date, [class*="date"]')?.textContent??""),c=this.cleanDoi(e.querySelector('a[href*="doi.org/"]')?.getAttribute("href")??e.querySelector('a[href*="doi.org/"]')?.textContent??this.extractDoi(e)??void 0),u=this.cleanText(e.querySelector('.article-type, .publication-type, .result-type, .meta__type, [class*="type"]')?.textContent??""),d=this.sanitizeJournalCandidate(e.querySelector('.journal-title, .publication-title, .publication_title, .source-title, .meta__title, [class*="journal"]')?.textContent??"",n),p=l||this.cleanText(e.textContent??""),h=this.extractIssnFromPii(o);return{title:n,journalName:d||s[0]||"",journalCandidates:this.unique([d,...s].filter(Boolean)),authors:this.extractDomAuthors(e),year:this.extractYear(p),publicationDate:l||void 0,doi:c,sourceId:o?`cell-com:${o}`:c?`cell-com:${c}`:void 0,url:a,nativeFullTextUrl:i??a,hostElement:e,articleTypes:u?[u]:[],issn:h,source:this.id,citationType:"article"}}getDetailHost(){return document.querySelector("main")??document.querySelector("article")??document.body}findDetailMetaAnchor(e){const t=[".article-header__meta",".article-identifiers",".article-source",".publication-details",".doi","ul","p","div"];for(const n of t){const a=Array.from(e.querySelectorAll(n)).find(i=>/doi/i.test(this.cleanText(i.textContent??""))||!!i.querySelector('a[href*="doi.org/"]'));if(a)return a}return null}findDetailIssueAnchor(e){const t=this.uniqueElements([e instanceof Element?e:document.body,...Array.from(document.querySelectorAll("article, header, .article-header, .article-header__meta, .article-header__journal, .publication-details, .article-source, .article-identifiers"))]),n=[".publication-details",".article-header__meta",".article-source",".article-header__journal",".journal-reference",".article-citation",".article-identifiers",".article-source","li","p","div","span"];for(const a of t){for(const i of n){const o=Array.from(a.querySelectorAll(i)).find(s=>this.looksLikeIssueLine(s));if(o)return o}if(a instanceof Element&&this.looksLikeIssueLine(a))return a}return e instanceof Element&&this.looksLikeIssueLine(e)?e:null}findArticleLink(e){return e.querySelector('a[href*="/fulltext/"], a[href*="/abstract/"], .art_title a, .hlFld-Title a, .publication_title a, a[data-e2e*="title-link"]')}extractDomAuthors(e){const t=Array.from(e.querySelectorAll('.authors a, .author-list a, .meta__authors a, [class*="author"] a, .authors span, .author-list span, .meta__authors span')).map(a=>this.cleanText(a.textContent??"")).filter(Boolean).filter(a=>!/^and$/i.test(a));if(t.length>0)return this.unique(t);const n=this.cleanText(e.querySelector('.authors, .author-list, [class*="author"]')?.textContent??"");return n?this.unique(n.split(/\s*,\s*|\s+and\s+/i).map(a=>this.cleanText(a)).filter(Boolean)):[]}extractMetadataAuthors(){const e=Array.from(document.querySelectorAll('meta[name="citation_author"]')).map(t=>this.cleanText(t.content)).filter(Boolean);return this.unique(e)}extractDetailJournal(e){const t=[".article-source",".journal__title",".journal-name",".journal-title",".publication-title",'[class*="journal"]'];for(const n of t){const a=this.cleanText(e.querySelector(n)?.textContent??"");if(a)return a}return null}extractDetailMetaText(e){return this.cleanText(e.querySelector(".article-header__meta, .publication-details, .article-identifiers")?.textContent??"")||null}extractDetailAbstract(e){return this.cleanText(e.querySelector('.abstract, .section-paragraph, [data-title="Abstract"], section[aria-labelledby*="abstract"]')?.textContent??"")}extractDetailTypes(e){const t=this.cleanText(this.firstMetaContent(["citation_article_type"])??e.querySelector('.article-type, .publication-type, .type, [class*="article-type"]')?.textContent??"");return t?[t]:[]}extractPagesFromMetadata(){const e=this.cleanText(this.firstMetaContent(["citation_firstpage"])??""),t=this.cleanText(this.firstMetaContent(["citation_lastpage"])??"");if(e)return t&&t!==e?`${e}-${t}`:e}extractPii(e){return this.cleanText(e).match(Vy)?.[1]??void 0}extractIssnFromPii(e){const n=this.cleanText(e??"").match(Wy);if(n)return`${n[1]}-${n[2].toUpperCase()}`}extractDoi(e){return this.cleanText(e.textContent??"").match(Mu)?.[0]}normalizeIssn(e){const n=this.cleanText(e??"").match(/\b\d{4}-?\d{3}[\dX]\b/i);if(!n)return;const a=n[0].replace(/-/g,"");return`${a.slice(0,4)}-${a.slice(4)}`}firstMetaContent(e){for(const t of e){const n=document.querySelector(`meta[name="${t}"], meta[property="${t}"]`),a=this.cleanText(n?.getAttribute("content")??"");if(a)return a}return null}cleanJournalName(e){return this.cleanText(e).replace(/\b\d{4}\b/g," ").replace(/\s+/g," ").trim()}sanitizeJournalCandidate(e,t){const n=this.cleanJournalName(e);return n?n.toLowerCase()===this.cleanText(t).toLowerCase()?"":n:""}cleanAbstract(e){return this.cleanText(e).replace(/^Abstract\s*:?\s*/i,"")||void 0}cleanDoi(e){const t=this.cleanText(e??"");return t?t.match(Mu)?.[0]?.replace(/[)>.,;]+$/,"").toLowerCase():void 0}extractYear(e){const t=this.cleanText(e??"").match(Jy);return t?Number.parseInt(t[1],10):void 0}toAbsoluteUrl(e){const t=this.cleanText(e);if(t)try{return new URL(t,location.href).href}catch{return}}unique(e){return Array.from(new Set(e.map(t=>this.cleanText(t)).filter(Boolean)))}uniqueElements(e){return Array.from(new Set(e))}toSearchResultHost(e){return e.closest(qu)??e.closest("article")??e}isChallengePage(){const e=this.cleanText(document.title);if(/^just a moment/i.test(e)||/请稍候/i.test(e)||document.querySelector('.cf-error-code, .cf-turnstile, iframe[src*="challenges.cloudflare.com"], script[src*="/cdn-cgi/challenge-platform/"]'))return!0;const t=this.cleanText(document.body?.textContent??"");return t.length>0&&/\b(?:enable javascript and cookies to continue|verify you are human|security check|access denied)\b/i.test(t)}looksLikeIssueLine(e){const t=this.cleanText(e.textContent??"");if(!t||t.length>240||/doi:/i.test(t)||e.querySelector('a[href*="doi.org/"]'))return!1;const n=this.cleanText(this.firstMetaContent(["citation_volume"])??""),a=this.cleanText(this.firstMetaContent(["citation_issue"])??""),i=this.cleanText(this.firstMetaContent(["citation_firstpage"])??""),o=this.cleanText(this.firstMetaContent(["citation_lastpage"])??""),s=o&&o!==i?`${i}-${o}`:i,l=n?new RegExp(`\\b(?:volume|vol\\.?)\\s*${this.escapeRegExp(n)}\\b`,"i").test(t):!1,c=a?new RegExp(`\\b(?:issue|no\\.?|number)\\s*${this.escapeRegExp(a)}\\b`,"i").test(t):!1,u=s?t.toLowerCase().includes(s.toLowerCase())||t.toLowerCase().includes(i.toLowerCase()):!1;return l&&c||l&&u||c&&u?!0:/\b(?:volume|vol\.?)\s*\d+/i.test(t)||/\bissue\s*\d+/i.test(t)||/\be\d{3,}\b/i.test(t)||/\b\d+\s*\(\d+\)\b/.test(t)}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}deriveJournalCandidatesFromUrl(e){const t=this.cleanText(e);if(!t)return[];try{const a=new URL(t,location.href).pathname.split("/").filter(Boolean),i=a.findIndex(s=>/^(?:fulltext|abstract)$/i.test(s)),o=i>0?a.slice(0,i):a.slice(0,1);return o.length===0?[]:o[0]?.toLowerCase()==="trends"&&o[1]?[`Trends in ${this.titleCaseSlug(o[1])}`]:[o.map(s=>this.titleCaseSlug(s)).join(" ")]}catch{return[]}}titleCaseSlug(e){return e.split("-").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}cleanText(e){return e.replace(/\u00a0/g," ").replace(/\s+/g," ").trim()}}const Yy=/\b10\.\d{4,9}\/[-._;()/:A-Z0-9]+/i,Ky=/\b((?:19|20)\d{2})\b/,Qy=["li.search__item","article.search__item",".search__item","li.issue-item","article.issue-item",".issue-item",'[data-testid*="search-item"]','[data-test*="search-item"]',"article","li"].join(","),Xy=["main","article","#skip-to-main-content","body"].join(","),ex=['a[href*="/doi/proceedings/"]','a[href*="/proceedings/"]','a[href*="/journal/"]','a[href*="/magazine/"]','a[href*="/doi/book/"]','a[href*="/book/"]'].join(",");class tx extends j{id="acm-dl";name="ACM Digital Library";matches=["*://dl.acm.org/*"];isSearchPage(){return/^\/action\/doSearch\/?$/i.test(location.pathname)}isArticlePage(){return/^\/doi\/(?:abs\/)?10\.\d{4,9}\//i.test(location.pathname)?!0:/^\/doi\/(?:proceedings|book)\//i.test(location.pathname)?!1:!!this.firstMetaContent(["citation_title"])&&!!this.findDetailTitle()}parseSearchResults(){if(!this.isSearchPage())return[];const e=[],t=new Set;for(const n of this.getSearchResultHosts())try{const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;if(t.has(i))continue;t.add(i),e.push(a)}catch(a){console.error("[AcmDigitalLibraryAdapter] Failed to parse search result:",a)}return e}parseArticlePage(){if(!this.isArticlePage())return null;const e=document.querySelector(Xy);if(!e)return null;try{const t=this.cleanText(this.firstMetaContent(["citation_title","dc.title","og:title"])??this.findDetailTitle(e)?.textContent??"").replace(/\s*\|\s*ACM Digital Library\s*$/i,"");if(!t)return null;const n=this.toAbsoluteUrl(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??this.firstMetaContent(["citation_public_url","og:url"])??location.href),a=this.cleanDoi(this.firstMetaContent(["citation_doi"])??this.findDoiLink(e)?.getAttribute("href")??this.findDoiLink(e)?.textContent??n??""),i=this.cleanText(this.findVenueLink(e)?.textContent??this.extractDetailVenueFromText(e)??""),o=this.cleanText(this.firstMetaContent(["citation_journal_title","citation_conference_title"])??i??""),s=this.cleanText(this.firstMetaContent(["citation_article_type"])??this.extractTopQualifier(e)??""),l=this.inferRecordKind(s,o,n??location.href),c=this.resolveVenueInfo(o,l),u=i||o,d=this.cleanText(this.firstMetaContent(["citation_publication_date","citation_online_date","dc.date"])??this.findPublicationLine(e)?.textContent??"");return{title:t,journalName:c.journalName,journalCandidates:c.candidates,authors:this.extractMetadataAuthors().length>0?this.extractMetadataAuthors():this.extractDetailAuthors(e),year:this.extractYear(d||o||s),publicationDate:d||void 0,doi:a,sourceId:a?`acm:${a}`:n?`acm:${new URL(n).pathname}`:void 0,url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.cleanAbstract(this.firstMetaContent(["description","og:description","dc.description"])??this.extractDetailAbstract(e)),hostElement:e,articleTypes:l.articleTypes,issn:this.normalizeIssn(this.firstMetaContent(["citation_issn"])),volume:this.extractVolume(u),issue:this.extractIssue(u),pages:this.extractPages(e),source:this.id,citationType:l.citationType}}catch(t){return console.error("[AcmDigitalLibraryAdapter] Failed to parse article page:",t),null}}getMetricBarAnchor(e){if(this.isArticlePage()){const a=this.findDoiContainer(e);if(a)return{element:a,position:"after"};const i=this.findPagesContainer(e);if(i)return{element:i,position:"after"};const o=this.findVenueLink(e);if(o)return{element:o,position:"after"};const s=this.findDetailTitle(e);return s?{element:s,position:"after"}:{element:e,position:"prepend"}}const t=e.querySelector(".issue-item__detail, .search__item__meta, .meta, .publication_meta");if(t)return{element:t,position:"after"};const n=this.findSearchTitleLink(e);return n?{element:n,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector(".search-results, .search-result-list, .issue-items, main")??document.querySelector("main")??document.body}getPageInfo(){const t=this.cleanText(document.querySelector("main")?.textContent??"").match(/\b([\d,]+)\s+Results?\s+for\b/i),n=t?Number.parseInt(t[1].replace(/,/g,""),10):void 0,a=this.parseSearchResults().length||void 0;return{pageNum:1,totalPages:n&&a?Math.max(1,Math.ceil(n/a)):1,itemsPerPage:a,totalItems:n,url:location.href}}getSearchResultHosts(){const e=Array.from(document.querySelectorAll(Qy)).filter(t=>this.looksLikeSearchResult(t));return this.uniqueElements(e)}looksLikeSearchResult(e){if(e.closest('[class^="paperlens-"], [class*=" paperlens-"]')||!this.findSearchTitleLink(e))return!1;const n=this.cleanText(e.textContent??"");return/export citation|view online with ereader|pages?\s+\d|research-article|acm transactions|proceedings/i.test(n)}parseSearchHost(e){const t=this.findSearchTitleLink(e),n=this.cleanText(t?.textContent??"");if(!n)return null;const a=this.toAbsoluteUrl(t?.getAttribute("href")??t?.href??""),i=this.cleanText(this.findVenueLink(e)?.textContent??this.extractSearchVenueFromText(e)??""),o=this.cleanText(this.extractSearchType(e)??""),s=this.inferRecordKind(o,i,a??""),l=this.resolveVenueInfo(i,s),c=this.cleanText(this.extractSearchPublicationDate(e)??""),u=this.cleanDoi(e.querySelector('a[href*="doi.org/10."]')?.getAttribute("href")??e.querySelector('a[href*="doi.org/10."]')?.textContent??a??"");return{title:n,journalName:l.journalName,journalCandidates:l.candidates,authors:this.extractSearchAuthors(e),year:this.extractYear(c||i||o),publicationDate:c||void 0,doi:u,sourceId:u?`acm:${u}`:a?`acm:${new URL(a).pathname}`:void 0,url:a,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.cleanAbstract(this.extractSearchAbstract(e)),hostElement:e,articleTypes:s.articleTypes,volume:this.extractVolume(i),issue:this.extractIssue(i),pages:this.extractPages(e),source:this.id,citationType:s.citationType}}findSearchTitleLink(e){const t=['h2 a[href^="/doi/10."]','h3 a[href^="/doi/10."]','h4 a[href^="/doi/10."]','h5 a[href^="/doi/10."]','.issue-item__title a[href^="/doi/10."]','.art_title a[href^="/doi/10."]','.hlFld-Title a[href^="/doi/10."]','a[href^="/doi/10."]'];for(const n of t){const a=e.querySelector(n);if(a&&!/^https?:\/\/doi\.org\//i.test(a.href)&&!/epdf|pdf/i.test(a.getAttribute("href")??""))return a}return null}findDetailTitle(e=document){return e.querySelector("h1")??e.querySelector(".citation__title, .article__title, .issue-item__title")}findVenueLink(e){return e.querySelector(ex)}findDoiLink(e){return e.querySelector('a[href*="doi.org/10."]')}findDoiContainer(e){return this.findDoiLink(e)?.parentElement??null}findPagesContainer(e){return Array.from(e.querySelectorAll("div, p, li, span")).find(t=>/^Pages?\b/i.test(this.cleanText(t.textContent??"")))??null}findPublicationLine(e){return Array.from(e.querySelectorAll("div, p, li, span")).find(t=>/^Published\s*:/i.test(this.cleanText(t.textContent??"")))??null}extractTopQualifier(e){return Array.from(e.querySelectorAll("div, p, span")).map(n=>this.cleanText(n.textContent??"")).find(n=>/^(research|review|editorial|case|short|article|book)/i.test(n))||void 0}extractDetailVenueFromText(e){return Array.from(e.querySelectorAll("div, p, span")).map(n=>this.cleanText(n.textContent??"")).filter(Boolean).find(n=>/(?:proceedings|conference|transactions|computing surveys|journal|magazine)/i.test(n))}extractSearchVenueFromText(e){return Array.from(e.querySelectorAll("div, p, span")).map(n=>this.cleanText(n.textContent??"")).filter(Boolean).find(n=>/(?:proceedings|conference|transactions|computing surveys|journal|magazine|volume\s+\d+)/i.test(n))}extractSearchType(e){return Array.from(e.querySelectorAll("div, p, span")).map(n=>this.cleanText(n.textContent??"")).find(n=>/^(research-article|review-article|article|editorial|magazine article|book chapter|chapter|book)/i.test(n))||void 0}extractSearchPublicationDate(e){return Array.from(e.querySelectorAll("div, p, span")).map(n=>this.cleanText(n.textContent??"")).filter(Boolean).find(n=>/\b(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec|January|February|March|April|June|July|August|September|October|November|December)\b/i.test(n))}extractSearchAuthors(e){const t=Array.from(e.querySelectorAll('a[href*="/profile/"], a[href*="/author/"], .authors a, .issue-item__authors a, .author a')).map(n=>this.cleanText(n.textContent??"")).filter(Boolean);return this.unique(t)}extractMetadataAuthors(){return this.unique(Array.from(document.querySelectorAll('meta[name="citation_author"]')).map(e=>this.cleanText(e.content)).filter(Boolean))}extractDetailAuthors(e){const t=Array.from(e.querySelectorAll('a[href*="/profile/"], a[href*="/author/"], .author-name, .authors a, button')).map(n=>this.cleanText(n.textContent??"")).filter(n=>!!n&&!/^(authors?\s*:|authors info & claims|share on)$/i.test(n));return this.unique(t)}extractSearchAbstract(e){return this.cleanText(e.querySelector(".abstract, .issue-item__abstract, .summary, p")?.textContent??"")}extractDetailAbstract(e){const t=Array.from(e.querySelectorAll("h2, h3, strong")).find(n=>/^abstract$/i.test(this.cleanText(n.textContent??"")));return t?.parentElement?this.cleanText(t.parentElement.textContent??""):this.cleanText(e.querySelector('.abstractSection, .abstract, [id*="abstract"]')?.textContent??"")}extractPages(e){return this.cleanText(this.findPagesContainer(e)?.textContent??"").match(/Pages?\s+(.+)$/i)?.[1]?.trim()||void 0}extractNativeFullTextUrl(e){const t=e.querySelector('a[href*="/doi/pdf/"], a[href*="/doi/epdf/"], a[href*="/doi/reader/"], a[href*="/doi/full/"], a[href*="/doi/fullHtml/"]');if(t)return this.toAbsoluteUrl(t.getAttribute("href")??t.href??"");const n=Array.from(e.querySelectorAll("a")).find(a=>/^(?:download\s+pdf|pdf|view online with ereader|get access)$/i.test(this.cleanText(a.textContent??"")));return this.toAbsoluteUrl(n?.getAttribute("href")??n?.href??"")}resolveVenueInfo(e,t){const n=this.cleanVenue(e);if(!n)return{journalName:"",candidates:[]};const a=[n],i=n.match(/^(.*?)(?:,\s*Vol(?:ume)?\.?\s*\d+.*)$/i),o=i?.[1]?this.cleanVenue(i[1]):"";o&&a.push(o);const s=this.cleanVenue((o||n).replace(/\s*\(([^)]+)\)\s*/g," ").trim());if(s&&s!==o&&a.push(s),t.citationType==="inproceedings"){const l=n.match(/^([A-Z][A-Z0-9+&/-]{1,20})(?:\s*'\d{2})?\s*:/);l?.[1]&&a.unshift(this.cleanText(l[1]));const c=n.match(/\b(?:ACM\s+)?(SIG[A-Z0-9]+)\b/i);c?.[1]&&(a.unshift(c[1].toUpperCase()),a.push(`ACM ${c[1].toUpperCase()}`));const u=n.replace(/^[^:]+:\s*/,"");u&&u!==n&&a.push(this.cleanVenue(u))}return{journalName:t.metricsAllowed&&o||n,candidates:this.unique(a)}}inferRecordKind(e,t,n){const a=`${e} ${t} ${n}`.toLowerCase();return/proceedings|conference|symposium|workshop|sig(ir|kdd|mod|chi|graph|plan)|\b[kicnrvw][a-z]{1,8}\s*'\d{2}\b/.test(a)?{articleTypes:["Conference"],citationType:"inproceedings",metricsAllowed:!1}:/book chapter|chapter/.test(a)?{articleTypes:["Book Chapter"],citationType:"incollection",metricsAllowed:!1}:/\bbook\b/.test(a)?{articleTypes:["Book"],citationType:"book",metricsAllowed:!1}:/magazine/.test(a)?{articleTypes:["Magazine Article"],citationType:"article",metricsAllowed:!1}:{articleTypes:[this.cleanText(e)||"Journal Article"],citationType:"article",metricsAllowed:!0}}extractVolume(e){return this.cleanText(e).match(/\bVol(?:ume)?\.?\s*([A-Za-z0-9.-]+)/i)?.[1]}extractIssue(e){return this.cleanText(e).match(/\bIssue\s*([A-Za-z0-9.-]+)/i)?.[1]}cleanVenue(e){return this.cleanText(e).replace(/\s{2,}/g," ").replace(/\s+\|\s+.*$/i,"").trim()}normalizeIssn(e){const t=this.cleanText(e??"").toUpperCase();if(!(!t||t==="N/A"))return t}firstMetaContent(e){for(const t of e){const n=document.querySelector(`meta[name="${t}"], meta[property="${t}"]`),a=this.cleanText(n?.getAttribute("content")??"");if(a)return a}return null}cleanAbstract(e){return this.cleanText(e).replace(/^Abstract\s*:?\s*/i,"")||void 0}cleanDoi(e){const t=this.cleanText(e??"");return t?t.match(Yy)?.[0]?.replace(/[)>.,;]+$/,"").toLowerCase():void 0}extractYear(e){const t=this.cleanText(e??"").match(Ky);return t?Number.parseInt(t[1],10):void 0}toAbsoluteUrl(e){const t=this.cleanText(e);if(t)try{return new URL(t,location.href).href}catch{return}}unique(e){return Array.from(new Set(e.map(t=>this.cleanText(t)).filter(Boolean)))}uniqueElements(e){return Array.from(new Set(e))}cleanText(e){return e.replace(/\u00a0/g," ").replace(/\s+/g," ").trim()}}const nx=/\b10\.\d{4,9}\/[-._;()/:A-Z0-9]+/i,rx=/\b((?:18|19|20)\d{2})\b/;class ax extends j{id="jstor";name="JSTOR";matches=["*://www.jstor.org/*","*://jstor.org/*"];isSearchPage(){return/^\/action\/doBasicSearch\/?$/i.test(location.pathname)}isArticlePage(){return!/^\/stable\/[^/?#]+/i.test(location.pathname)||/\/stable\/pdf\//i.test(location.pathname)?!1:!!(this.getStructuredRecord()||document.querySelector("main h1, article h1"))}parseSearchResults(){if(!this.isSearchPage())return[];const e=[],t=new Set;for(const n of this.getSearchResultHosts())try{const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;if(t.has(i))continue;t.add(i),e.push(a)}catch(a){console.error("[JstorAdapter] Failed to parse search result:",a)}return e}parseArticlePage(){if(!this.isArticlePage())return null;const e=this.getDetailHost();if(!e)return null;try{const t=this.getStructuredRecord(),n=this.cleanText(this.firstMetaContent(["citation_title","og:title"])??t?.headline??t?.name??e.querySelector("h1")?.textContent??"");if(!n)return null;const a=this.cleanText(this.firstMetaContent(["citation_article_type"])??this.extractDetailType(e)??this.structuredType(t)??""),i=this.structuredPartType(t),o=this.cleanText(this.structuredPartName(t)??""),s=this.cleanText(this.firstMetaContent(["citation_journal_title","citation_journal_abbrev"])??""),l=this.cleanText(this.extractDetailSourceLine(e)??""),c=this.cleanText(this.extractDetailVenueContext(e)??s??o??l),u=this.inferRecordKind(a,i,c||l),d=this.resolveVenueInfo(c||l,u),p=this.parseSourceMetadata(l||c),h=this.cleanText(this.firstMetaContent(["citation_publication_date","prism.publicationDate"])??t?.datePublished??this.extractDetailPublicationDate(e)??""),f=this.normalizeStableUrl(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??t?.url??location.href),y=this.cleanDoi(this.firstMetaContent(["citation_doi"])??this.extractDoi(e)??this.extractStructuredDoi(t)??void 0),x=this.extractStableId(f??location.href);return{title:n,journalName:d.journalName||p.title,journalCandidates:d.candidates,authors:this.extractStructuredAuthors(t).length>0?this.extractStructuredAuthors(t):this.extractDetailAuthors(e),year:this.extractYear(h||l||c),publicationDate:h||void 0,doi:y,sourceId:x?`jstor:${x}`:void 0,url:f,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.cleanAbstract(this.firstMetaContent(["description","og:description"])??t?.description??this.extractDetailAbstract(e)),hostElement:e,articleTypes:u.articleTypes,issn:this.normalizeIssn(this.extractStructuredIssn(t)),volume:this.cleanText(this.structuredVolume(t)??p.volume??""),issue:this.cleanText(this.structuredIssue(t)??p.issue??""),pages:this.cleanText(t?.pagination??p.pages??""),source:this.id,citationType:u.citationType}}catch(t){return console.error("[JstorAdapter] Failed to parse article page:",t),null}}getMetricBarAnchor(e){if(this.isArticlePage()){const a=this.findDoiContainer(e);if(a)return{element:a,position:"after"};const i=this.findDetailSourceElement(e);if(i)return{element:i,position:"after"};const o=e.querySelector("h1");return o?{element:o,position:"after"}:{element:e,position:"prepend"}}const t=this.findSearchSourceElement(e);if(t)return{element:t,position:"after"};const n=this.findSearchTitleLink(e);return n?{element:n,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector('[data-testid="search-results"], .search-results, .result-list, main')??document.querySelector("main")??document.body}getPageInfo(){const t=this.cleanText(document.querySelector("main")?.textContent??"").match(/\b([\d,]+)\s+results?\b/i),n=t?Number.parseInt(t[1].replace(/,/g,""),10):void 0,a=this.parseSearchResults().length||void 0;return{pageNum:1,totalPages:n&&a?Math.max(1,Math.ceil(n/a)):1,itemsPerPage:a,totalItems:n,url:location.href}}getSearchResultHosts(){const e=Array.from(document.querySelectorAll('a[href*="/stable/"]')).filter(t=>this.isStableTitleLink(t)).map(t=>this.findSearchResultHost(t)).filter(t=>!!t).filter(t=>this.looksLikeSearchResult(t));return this.uniqueElements(e)}findSearchResultHost(e){const t=e.closest('article, li, .search-result, .result-item, [data-result], [data-result-item], [data-search-result], [role="listitem"]');if(t)return t;const n=this.getResultsContainer()??document.body;let a=e.parentElement,i=null;for(;a&&a!==document.body&&a!==document.documentElement;){if(this.isLikelySearchResultHost(a)&&(i??=a,this.findSearchActionContainer(a)))return a;if(a===n)break;a=a.parentElement}return i??e.parentElement}isLikelySearchResultHost(e){if(Array.from(e.querySelectorAll('a[href*="/stable/"]')).filter(i=>this.isStableTitleLink(i)).length!==1)return!1;if(this.findSearchActionContainer(e))return!0;const n=this.findBestSearchSourceElement(e);if(n&&n!==e)return!0;const a=this.cleanText(e.textContent??"");return/(journal article|book chapter|research report|read online|download|save to workspace|cite)/i.test(a)}looksLikeSearchResult(e){if(e.closest('[class^="paperlens-"], [class*=" paperlens-"]')||!this.findSearchTitleLink(e))return!1;const t=this.cleanText(e.textContent??"");return/(journal article|book chapter|research report|book|read online|download|save to workspace|cite)/i.test(t)}parseSearchHost(e){const t=this.findSearchTitleLink(e),n=this.cleanText(t?.textContent??"");if(!n)return null;const a=this.normalizeStableUrl(t?.getAttribute("href")??t?.href??""),i=this.extractStableId(a??""),o=this.cleanText(this.extractSearchType(e)??""),s=this.cleanText(this.extractSearchSourceLine(e)??""),l=this.cleanText(this.extractSearchVenueContext(e)??s),c=this.inferRecordKind(o,"",l||s),u=this.resolveVenueInfo(l||s,c),d=this.parseSourceMetadata(s||l);return{title:n,journalName:u.journalName||d.title,journalCandidates:u.candidates,authors:this.extractSearchAuthors(e),year:this.extractYear(s||l),doi:this.cleanDoi(e.getAttribute("data-doi")??e.querySelector('a[href*="doi.org/10."]')?.href??e.querySelector('a[href*="doi.org/10."]')?.textContent??void 0),sourceId:i?`jstor:${i}`:void 0,url:a,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.cleanAbstract(this.extractSearchAbstract(e)),hostElement:e,articleTypes:c.articleTypes,volume:d.volume,issue:d.issue,pages:d.pages,source:this.id,citationType:c.citationType}}inferRecordKind(e,t,n){const a=`${e} ${t} ${n}`.toLowerCase();return/journal article|scholarlyarticle|periodical/.test(a)?{articleTypes:["Journal Article"],citationType:"article"}:/book chapter|chapter/.test(a)?{articleTypes:["Book Chapter"],citationType:"incollection"}:/research report|report/.test(a)?{articleTypes:["Research Report"],citationType:"misc"}:/\bbook\b/.test(a)?{articleTypes:["Book"],citationType:"book"}:/article/.test(a)?{articleTypes:["Journal Article"],citationType:"article"}:{articleTypes:[this.toTitleLabel(e||"Item")],citationType:"misc"}}resolveVenueInfo(e,t){const n=this.parseSourceMetadata(e),a=this.unique(n.candidates);return{journalName:t.citationType==="article"?n.title:n.title||this.cleanText(e),candidates:t.citationType==="article"?a:[]}}parseSourceMetadata(e){const t=this.cleanText(e).replace(/\s+,/g,",").replace(/\s+\)/g,")").replace(/https?:\/\/\S+/gi,"").replace(/<[^>]+>/g,"").replace(/\bnull\s*\(\d+\s+pages?\)/gi,"").replace(/\bPublished By:\s*/gi,"").trim();if(!t)return{title:"",candidates:[]};const n=this.cleanSourceTitle(t.replace(/,\s*Vol(?:ume)?\.?.*$/i,"").replace(/,\s*No\.?.*$/i,"").replace(/,\s*pp\.?.*$/i,"").replace(/\(\s*(?:Spring|Summer|Fall|Winter|Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec|\d{4}).*$/i,"").trim()),a=[n];n.includes(":")&&(a.push(n.replace(/\s*:\s*/g,"-")),a.push(n.replace(/^.*?:\s*/,"")));const i=t.match(/\bVol(?:ume)?\.?\s*([A-Za-z0-9.-]+)/i)?.[1],o=t.match(/\bNo\.?\s*([A-Za-z0-9.-]+)/i)?.[1],s=t.match(/(?:^|,\s*)pp?\.?\s*([A-Za-z0-9.\-–—]+)/i)?.[1];return{title:n,candidates:this.unique(a.filter(Boolean)),volume:i,issue:o,pages:s}}cleanSourceTitle(e){return this.cleanText(e).replace(/^In\s+/i,"").replace(/\s+[|•·].*$/i,"").trim()}findSearchTitleLink(e){return Array.from(e.querySelectorAll('a[href*="/stable/"]')).find(t=>this.isStableTitleLink(t))??null}isStableTitleLink(e){const t=e.getAttribute("href")??e.href??"";return!/\/stable\/[^/?#]+/i.test(t)||/\/stable\/pdf\//i.test(t)?!1:this.cleanText(e.textContent??"").length>0}extractSearchType(e){return Array.from(e.querySelectorAll("div, p, span, li")).map(t=>this.cleanText(t.textContent??"")).find(t=>/^(journal article|book chapter|research report|book)$/i.test(t))}extractSearchSourceLine(e){return this.cleanText(this.findBestSearchSourceElement(e,{preferJournalLink:!1})?.textContent??"")||void 0}extractSearchVenueContext(e){return this.cleanText(this.findJournalLink(e)?.textContent??this.extractPublishedByText(e)??this.findBestSearchSourceElement(e)?.textContent??"")||void 0}findSearchSourceElement(e){return this.findJournalLink(e)??this.findBestSearchSourceElement(e,{preferJournalLink:!1})}extractSearchAuthors(e){const t=Array.from(e.querySelectorAll('.authors a, .result-authors a, [data-testid="authors"] a, a[href*="/action/doBasicSearch?Query=au:"]')).map(n=>this.cleanText(n.textContent??"")).filter(Boolean);return this.unique(t)}extractSearchAbstract(e){const t=e.querySelector(".abstract, .snippet, .summary, .item-snippet");return t?this.cleanText(t.textContent??""):this.cleanText(Array.from(e.querySelectorAll("p")).map(n=>this.cleanText(n.textContent??"")).find(n=>n.length>80)??"")}findBestSearchSourceElement(e,t){if(t?.preferJournalLink){const i=this.findJournalLink(e);if(i)return i}const n=e.querySelector('.source-line, .result-source, .citation, .item-details, .result-details, .item-meta, .src-line, [data-testid="source-line"]');return n||(Array.from(e.querySelectorAll("div, p, span, li")).map(i=>({element:i,text:this.cleanText(i.textContent??"")})).filter(({text:i})=>this.isLikelySearchSourceText(i)).sort((i,o)=>i.text.length-o.text.length)[0]?.element??null)}isLikelySearchSourceText(e){return!e||/(read online|save to workspace|cite|download)/i.test(e)||e.length>240?!1:/(?:\bVol\.?\b|\bNo\.?\b|\bpp?\.?\b|^In\b|^From:\b|Open Access\b|Published By:|Journal\b|Medical Journal\b|Press\b|University\b|Report\b|Corporation\b)/i.test(e)}findSearchActionContainer(e){const t=e.querySelector('.actions, .result-actions, .search-result__actions, .item-actions, [data-testid*="actions"], [class*="actions"]');if(t&&this.countSearchActionItems(t)>0)return t;const n=Array.from(e.querySelectorAll("button, a, span, div, li")).filter(o=>this.isSearchActionItem(o));if(n.length===0)return null;const a=n[0]?.parentElement;if(a&&n.every(o=>o.parentElement===a)&&a!==e)return a;let i=n[0]??null;for(;i?.parentElement&&i.parentElement!==e;){const o=i.parentElement;if(this.countSearchActionItems(o)!==n.length)break;i=o}return i&&i!==e?i:null}countSearchActionItems(e){return Array.from(e.querySelectorAll("button, a, span, div, li")).filter(t=>this.isSearchActionItem(t)).length}isSearchActionItem(e){const t=this.cleanText(e.textContent??"");return!t||t.length>48?!1:/^(read online|download|save(?: to workspace)?|cite|this content is not available for download)$/i.test(t)}getDetailHost(){return document.querySelector("main article")??document.querySelector("article")??document.querySelector("main")??document.body}extractDetailType(e){return Array.from(e.querySelectorAll("div, p, span")).map(t=>this.cleanText(t.textContent??"")).find(t=>/^(journal article|book chapter|research report|book)$/i.test(t))}extractDetailSourceLine(e){return this.cleanText(this.findBestDetailSourceElement(e,{preferJournalLink:!1})?.textContent??"")||void 0}extractDetailVenueContext(e){return this.cleanText(this.firstMetaContent(["citation_journal_title","citation_journal_abbrev"])??this.findJournalLink(e)?.textContent??this.extractPublishedByText(e)??this.findBestDetailSourceElement(e)?.textContent??"")||void 0}findDetailSourceElement(e){return this.findJournalLink(e)??this.findBestDetailSourceElement(e,{preferJournalLink:!1})}extractDetailPublicationDate(e){return Array.from(e.querySelectorAll("div, p, span, time")).map(t=>this.cleanText(t.textContent??"")).find(t=>/\b(?:18|19|20)\d{2}\b/.test(t))}extractDetailAuthors(e){const t=Array.from(e.querySelectorAll('.authors a, .contributors a, [data-testid="authors"] a, a[href*="/action/doBasicSearch?Query=au:"]')).map(n=>this.cleanText(n.textContent??"")).filter(Boolean);return this.unique(t)}extractDetailAbstract(e){return this.cleanText(e.querySelector('.abstract, .item-description, [data-testid="abstract"], .summary')?.textContent??"")}extractDoi(e){const t=e.querySelector('a[href*="doi.org/10."]');if(t)return this.cleanDoi(t.href)??this.cleanDoi(t.textContent??"");const n=this.cleanText(e.textContent??"");return this.cleanDoi(n)}findDoiContainer(e){const t=e.querySelector('a[href*="doi.org/10."]');return t?t.parentElement:Array.from(e.querySelectorAll("div, p, span, li")).find(n=>!!this.cleanDoi(n.textContent??""))??null}extractNativeFullTextUrl(e){const t=Array.from(e.querySelectorAll("a[href]")).find(n=>{const a=n.getAttribute("href")??n.href??"",i=this.cleanText(n.textContent??"");return/\/stable\/pdf\//i.test(a)||/^(download|read online)$/i.test(i)});return this.normalizeStableUrl(t?.getAttribute("href")??t?.href??"")}findBestDetailSourceElement(e,t){if(t?.preferJournalLink){const i=this.findJournalLink(e);if(i)return i}const n=e.querySelector('.source-line, .item-details, .citation, .item-meta, .src-line, [data-testid="source-line"]');return n||(Array.from(e.querySelectorAll("div, p, span, li, a")).map(i=>({element:i,text:this.cleanText(i.textContent??"")})).filter(({text:i})=>this.isLikelyDetailSourceText(i)).sort((i,o)=>i.text.length-o.text.length)[0]?.element??null)}isLikelyDetailSourceText(e){return!e||/(download|read online|save to workspace|cite|abstract|references)/i.test(e)||e.length>240?!1:/(?:\bVol\.?\b|\bNo\.?\b|\bpp?\.?\b|Published By:|Journal\b|Medical Journal\b|Review\b|Reports\b|Quarterly\b|Transactions\b|Press\b|University\b|Corporation\b)/i.test(e)}extractPublishedByText(e){const t=Array.from(e.querySelectorAll("div, p, span, li")).map(n=>this.cleanText(n.textContent??"")).find(n=>n.length<=160&&/Published By:/i.test(n));if(t)return this.cleanText(t.replace(/^.*?Published By:\s*/i,""))||void 0}findJournalLink(e){return Array.from(e.querySelectorAll('a[href*="/journal/"]')).find(t=>{const n=this.cleanText(t.textContent??"");return!!n&&!/^https?:\/\//i.test(n)&&!/\/journal\//i.test(n)})??null}getStructuredRecord(){for(const e of document.querySelectorAll('script[type="application/ld+json"]'))try{const t=JSON.parse(e.textContent??""),a=(Array.isArray(t)?t:[t,...t["@graph"]??[]]).find(i=>this.isStructuredRecord(i));if(a)return a}catch{continue}return null}isStructuredRecord(e){const t=this.structuredType(e);return/Article|ScholarlyArticle|Chapter|Book|Report|CreativeWork/i.test(t)||!!e.headline||!!e.name}structuredType(e){const t=e?.["@type"];return Array.isArray(t)?t.join(" "):t??""}structuredPartType(e){const t=e?.isPartOf;if(!t||typeof t=="string")return"";const n=t["@type"];return Array.isArray(n)?n.join(" "):n??""}structuredPartName(e){const t=e?.isPartOf;if(t)return typeof t=="string"?t:t.name}structuredVolume(e){const t=e?.isPartOf;if(!(!t||typeof t=="string"))return t.volumeNumber?String(t.volumeNumber):void 0}structuredIssue(e){const t=e?.isPartOf;if(!(!t||typeof t=="string"))return t.issueNumber?String(t.issueNumber):void 0}extractStructuredIssn(e){const t=e?.isPartOf;if(!t||typeof t=="string")return;const n=t.issn;return Array.isArray(n)?n[0]:n}extractStructuredAuthors(e){const t=e?.author;if(!t)return[];const n=Array.isArray(t)?t:[t];return this.unique(n.map(a=>typeof a=="string"?a:a.name??"").filter(Boolean))}extractStructuredDoi(e){const t=e?.identifier;if(!t)return;const n=Array.isArray(t)?t:[t];for(const a of n){if(typeof a=="string"){const o=this.cleanDoi(a);if(o)return o;continue}const i=this.cleanDoi(a.value??a.propertyID??"");if(i)return i}}firstMetaContent(e){for(const t of e){const n=document.querySelector(`meta[name="${t}"], meta[property="${t}"]`),a=this.cleanText(n?.getAttribute("content")??"");if(a)return a}return null}extractStableId(e){const t=this.normalizeStableUrl(e);if(t)try{return new URL(t).pathname.match(/^\/stable\/([^/?#]+)/i)?.[1]}catch{return}}normalizeStableUrl(e){const t=this.cleanText(e??"");if(t)try{const n=new URL(t,location.href);return n.hash="",/\/stable\/pdf\//i.test(n.pathname)||/^\/stable\//i.test(n.pathname)&&(n.search=""),n.href}catch{return}}cleanAbstract(e){return this.cleanText(e??"").replace(/^abstract\s*:?\s*/i,"")||void 0}cleanDoi(e){const t=this.cleanText(e??"");return t?t.match(nx)?.[0]?.replace(/[)>.,;]+$/,"").toLowerCase():void 0}normalizeIssn(e){const t=this.cleanText(e??"").toUpperCase();if(!(!t||t==="N/A"))return t}toTitleLabel(e){const t=this.cleanText(e);return t?t.toLowerCase().replace(/\b\w/g,n=>n.toUpperCase()):""}extractYear(e){const t=this.cleanText(e??"").match(rx);return t?Number.parseInt(t[1],10):void 0}unique(e){return Array.from(new Set(e.map(t=>this.cleanText(t)).filter(Boolean)))}uniqueElements(e){return Array.from(new Set(e))}cleanText(e){return e.replace(/\u00a0/g," ").replace(/\s+/g," ").trim()}}const ix=/\b10\.\d{4,9}\/[^\s"'<>?#]+/i,$u=/\b((?:19|20)\d{2})\b/;class ox extends j{id="mdpi";name="MDPI";matches=["*://www.mdpi.com/*"];isSearchPage(){return/^\/search\/?$/i.test(location.pathname)}isArticlePage(){return/^\/\d{4}-\d{4}\/\d+\/\d+\/\d+\/?$/i.test(location.pathname)&&!!(this.firstMetaContent(["citation_title","citation_journal_title"])||document.querySelector("main h1, article h1"))}parseSearchResults(){if(!this.isSearchPage())return[];const e=[],t=new Set;for(const n of this.getSearchResultHosts())try{const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;if(t.has(i))continue;t.add(i),e.push(a)}catch(a){console.error("[MdpiAdapter] Failed to parse search result:",a)}return e}parseArticlePage(){if(!this.isArticlePage())return null;const e=this.getDetailHost();if(!e)return null;try{const t=this.cleanText(this.firstMetaContent(["citation_title","og:title"])??e.querySelector("h1")?.textContent??"");if(!t)return null;const n=this.toAbsoluteUrl(document.querySelector('link[rel="canonical"]')?.getAttribute("href")??location.href),a=this.cleanText(this.queryText(e,[".source-line",".bib-identity",".html-published",".entry-meta",".article-citation"])??""),i=this.parseCitationLine(a),o=this.cleanDoi(this.firstMetaContent(["citation_doi"])??i.doi??this.queryText(e,['a[href*="doi.org/10."]'])??void 0),s=this.cleanText(this.firstMetaContent(["citation_journal_title"])??this.queryText(e,[".journal-title",".belongsTo a",".breadcrumb a"])??i.journalName),l=this.cleanText(this.firstMetaContent(["citation_publication_date","citation_online_date"])??this.extractPublicationDate(e)??"");return{title:t,journalName:s,journalCandidates:this.unique([s,i.journalName].filter(Boolean)),authors:this.extractMetadataAuthors().length>0?this.extractMetadataAuthors():this.extractDetailAuthors(e),year:i.year??this.extractYear(l),publicationDate:l||void 0,doi:o,sourceId:o?`mdpi:${o}`:n?`mdpi:${new URL(n).pathname}`:void 0,url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.cleanAbstract(this.firstMetaContent(["citation_abstract","description","og:description"])??this.queryText(e,[".abstract","#abstract",".art-abstract"])??""),hostElement:e,articleTypes:[this.cleanTypeLabel(this.firstMetaContent(["citation_article_type"])??this.queryText(e,[".article-type",".type-label",".pubhistory .label"])??"Article")],issn:this.normalizeIssn(this.firstMetaContent(["citation_issn"])??this.extractIssnFromUrl(n??location.href)),volume:this.cleanText(this.firstMetaContent(["citation_volume"])??i.volume??""),issue:this.cleanText(this.firstMetaContent(["citation_issue"])??i.issue??""),pages:this.cleanText(this.firstMetaContent(["citation_firstpage"])??i.pages??""),source:this.id,citationType:"article"}}catch(t){return console.error("[MdpiAdapter] Failed to parse article page:",t),null}}getMetricBarAnchor(e){if(this.isArticlePage()){const a=e.querySelector(".source-line, .bib-identity, .html-published, .entry-meta, .article-citation");if(a)return{element:a,position:"after"};const i=e.querySelector("h1");return i?{element:i,position:"after"}:{element:e,position:"prepend"}}const t=e.querySelector(".source-line, .entry-meta, .article-citation, .belongsTo");if(t)return{element:t,position:"after"};const n=this.findSearchTitleLink(e);return n?{element:n,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector(".search-results, .article-list, main")??document.querySelector("main")??document.body}getPageInfo(){const t=this.cleanText(document.querySelector("main")?.textContent??"").match(/\(([\d,]+)\)/),n=t?Number.parseInt(t[1].replace(/,/g,""),10):void 0,a=this.parseSearchResults().length||void 0;return{pageNum:1,totalPages:n&&a?Math.max(1,Math.ceil(n/a)):1,itemsPerPage:a,totalItems:n,url:location.href}}getSearchResultHosts(){const e=Array.from(document.querySelectorAll('a[href^="/"][href*="/"]')).filter(t=>this.isMdpiArticleLink(t)).map(t=>t.closest("article, li, .article-content, .entry, [data-result]")??t.parentElement).filter(t=>!!t).filter(t=>this.looksLikeSearchResult(t));return this.uniqueElements(e)}looksLikeSearchResult(e){if(e.closest('[class^="paperlens-"], [class*=" paperlens-"]')||!this.findSearchTitleLink(e))return!1;const t=this.cleanText(e.textContent??"");return/(article pdf|https:\/\/doi\.org\/10\.|open access|article|review|editorial)/i.test(t)}parseSearchHost(e){const t=this.findSearchTitleLink(e),n=this.cleanText(t?.textContent??"");if(!n)return null;const a=this.toAbsoluteUrl(t?.getAttribute("href")??t?.href??""),i=this.cleanText(this.queryText(e,[".source-line",".entry-meta",".article-citation",".belongsTo"])??""),o=this.parseCitationLine(i),s=this.normalizeIssn(this.extractIssnFromUrl(a??"")),l=this.cleanText(this.queryText(e,[".article-type",".type-label",".oa",".label"])??"Article"),c=this.cleanDoi(o.doi??this.queryText(e,['a[href*="doi.org/10."]'])??void 0);return{title:n,journalName:this.cleanText(o.journalName),journalCandidates:this.unique([o.journalName].filter(Boolean)),authors:this.extractSearchAuthors(e),year:o.year,doi:c,sourceId:c?`mdpi:${c}`:a?`mdpi:${new URL(a).pathname}`:void 0,url:a,nativeFullTextUrl:this.extractNativeFullTextUrl(e),abstractSnippet:this.cleanAbstract(this.queryText(e,[".abstract",".snippet",".summary"])??""),hostElement:e,articleTypes:[this.cleanTypeLabel(l)],issn:s,volume:o.volume,issue:o.issue,pages:o.pages,source:this.id,citationType:"article"}}findSearchTitleLink(e){return Array.from(e.querySelectorAll("a[href]")).find(t=>this.isMdpiArticleLink(t)&&this.cleanText(t.textContent??"").length>0)??null}isMdpiArticleLink(e){const t=e.getAttribute("href")??e.href??"";return/^\/\d{4}-\d{4}\/\d+\/\d+\/\d+\/?$/i.test(t)||/^https?:\/\/(?:www\.)?mdpi\.com\/\d{4}-\d{4}\/\d+\/\d+\/\d+\/?$/i.test(t)}getDetailHost(){return document.querySelector("main article")??document.querySelector("article")??document.querySelector("main")??document.body}extractSearchAuthors(e){const t=Array.from(e.querySelectorAll('.authors a, .author-list a, [class*="author"] a')).map(n=>this.cleanText(n.textContent??"")).filter(Boolean);return this.unique(t)}extractMetadataAuthors(){return this.unique(Array.from(document.querySelectorAll('meta[name="citation_author"]')).map(e=>this.cleanText(e.content)).filter(Boolean))}extractDetailAuthors(e){const t=Array.from(e.querySelectorAll('.authors a, .art-authors a, .author-list a, [class*="author"] a')).map(n=>this.cleanText(n.textContent??"")).filter(Boolean);return this.unique(t)}extractPublicationDate(e){return Array.from(e.querySelectorAll("div, p, span, time")).map(t=>this.cleanText(t.textContent??"")).find(t=>/^published\s*:/i.test(t)||/^\d{1,2}\s+\w+\s+\d{4}$/i.test(t))}extractNativeFullTextUrl(e){const t=Array.from(e.querySelectorAll("a[href]")).find(a=>{const i=a.getAttribute("href")??a.href??"",o=this.cleanText(a.textContent??"");return/\/pdf$/i.test(i)||/^article pdf$/i.test(o)||/^download$/i.test(o)}),n=this.toAbsoluteUrl(t?.getAttribute("href")??t?.href??"");if(n)try{const a=new URL(n).hostname.toLowerCase();return a==="www.mdpi.com"||a==="mdpi.com"?n:void 0}catch{return}}extractIssnFromUrl(e){const t=this.toAbsoluteUrl(e);if(t)try{return new URL(t).pathname.match(/^\/(\d{4}-\d{4})\//)?.[1]}catch{return}}parseCitationLine(e){const t=this.cleanText(e).replace(/\s*;\s*/g,"; ").trim();if(!t)return{journalName:""};const n=this.cleanDoi(t),a=t.match($u),i=a?Number.parseInt(a[1],10):void 0,o=this.cleanText(a?t.slice(0,a.index).replace(/[,\s]+$/,""):t),s=a?t.slice((a.index??0)+a[0].length).trim():"",l=s.match(/^,\s*([A-Za-z0-9.-]+)/)?.[1],c=s.match(/\(\s*([A-Za-z0-9.-]+)\s*\)/)?.[1],u=s.match(/\)\s*,\s*([^;]+?)(?:;|$)/)?.[1]??s.match(/^,\s*[A-Za-z0-9.-]+\s*,\s*([^;]+?)(?:;|$)/)?.[1];return{journalName:o,year:i,volume:l,issue:c,pages:this.cleanText(u??""),doi:n}}firstMetaContent(e){for(const t of e){const n=document.querySelector(`meta[name="${t}"], meta[property="${t}"]`),a=this.cleanText(n?.getAttribute("content")??"");if(a)return a}return null}queryText(e,t){for(const n of t){const a=e.querySelector(n),i=this.cleanText(a?.textContent??"");if(i)return i}}cleanTypeLabel(e){return this.cleanText(e).replace(/^open access\s*/i,"").replace(/\s+/g," ").trim()||"Article"}cleanAbstract(e){return this.cleanText(e).replace(/^abstract\s*:?\s*/i,"")||void 0}cleanDoi(e){const t=this.cleanText(e??"");return t?t.match(ix)?.[0]?.replace(/[)>.,;]+$/,"").toLowerCase():void 0}normalizeIssn(e){const t=this.cleanText(e??"").toUpperCase();if(!(!t||t==="N/A"))return t}extractYear(e){const t=this.cleanText(e??"").match($u);return t?Number.parseInt(t[1],10):void 0}toAbsoluteUrl(e){const t=this.cleanText(e);if(t)try{return new URL(t,location.href).href}catch{return}}unique(e){return Array.from(new Set(e.map(t=>this.cleanText(t)).filter(Boolean)))}uniqueElements(e){return Array.from(new Set(e))}cleanText(e){return e.replace(/\u00a0/g," ").replace(/\s+/g," ").trim()}}const sx=['a[href*="/journals/"][href*="/article/"]','a[href*="/article/"][href*="/abstract"]','a[href*="/article/"][href*="/fulltext"]'].join(","),Zo=["li.search__item",".search__item",".search-result__item",".resultItem",".search-result","li.search-result-item","article"].join(","),Ou=[".search-results",".searchResultList",'[aria-label="Search results"]',"main"].join(","),lx=["main article","#main-content article","article","main","#main-content","body"].join(","),cx=['[class*="doi" i], [id*="doi" i], a[href*="doi.org"]','[class*="author" i], .authors','.article-header__meta, .publication-meta, [class*="ArticleHeader"], [class*="publication-meta" i]'],ux=['[class*="doi" i], [id*="doi" i], a[href*="doi.org"]','[class*="author" i], .authors','.publication-title, [class*="journal-title" i], [class*="publication" i], [class*="meta" i], [class*="date" i]'],dx={ebiom:"eBioMedicine",eclinm:"eClinicalMedicine",lanafr:"The Lancet Regional Health \u2013 Africa",lanam:"The Lancet Regional Health \u2013 Americas",lancet:"The Lancet",lanchi:"The Lancet Child & Adolescent Health",landia:"The Lancet Diabetes & Endocrinology",landig:"The Lancet Digital Health",lanepe:"The Lancet Regional Health \u2013 Europe",langas:"The Lancet Gastroenterology & Hepatology",langlo:"The Lancet Global Health",lanhae:"The Lancet Haematology",lanhl:"The Lancet Healthy Longevity",lanhiv:"The Lancet HIV",laninf:"The Lancet Infectious Diseases",lanmic:"The Lancet Microbe",laneur:"The Lancet Neurology",lanogw:"The Lancet Obstetrics, Gynaecology, & Women's Health",lanonc:"The Lancet Oncology",lanplh:"The Lancet Planetary Health",lanprc:"The Lancet Primary Care",lanpsy:"The Lancet Psychiatry",lanpub:"The Lancet Public Health",lanres:"The Lancet Respiratory Medicine",lanrhe:"The Lancet Rheumatology",lansea:"The Lancet Regional Health \u2013 Southeast Asia",lanwpc:"The Lancet Regional Health \u2013 Western Pacific"};class px extends j{id="lancet";name="The Lancet";matches=["*://www.thelancet.com/*","*://thelancet.com/*","*://www.lancet.com/*","*://lancet.com/*"];isSearchPage(){if(le())return!1;const e=location.pathname.toLowerCase();return e.startsWith("/action/dosearch")||e.startsWith("/search")||!this.isArticlePath(e)&&new URLSearchParams(location.search).has("searchText")}isArticlePage(){return le()||this.isSearchPage()?!1:this.isArticlePath(location.pathname)||!!F(["citation_title"])}parseSearchResults(){const e=[],t=new Set;for(const n of this.getSearchResultHosts()){const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;t.has(i)||(t.add(i),e.push(a))}return e}parseArticlePage(){if(le())return null;const e=document.querySelector(lx);if(!e)return null;const t=m(F(["citation_title","dc.title","og:title"])??e.querySelector("h1")?.textContent).replace(/\s*\|\s*The Lancet.*$/i,"");if(!t)return null;const n=$n(),a=this.extractPii(n??location.href),i=Ne(F(["citation_doi","prism.doi"]))??this.doiFromPii(a)??Z(e.textContent),o=m(F(["citation_publication_date","citation_online_date","prism.publicationDate","article:published_time"])),s=this.journalFromUrl(n??location.href),l=m(F(["citation_journal_title","prism.publicationName"]))||s||this.extractJournalFromDom(e)||"The Lancet",c=this.extractPdfUrl(e,n);return{title:t,journalName:l,journalCandidates:this.buildJournalCandidates(l,s),authors:Je("citation_author"),year:qe(o),publicationDate:o||void 0,doi:i,sourceId:a?`lancet:${a}`:i?`lancet:${i}`:void 0,url:n,nativeFullTextUrl:c,abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:this.extractArticleTypes(e),issn:m(F(["citation_issn","prism.issn"])),volume:m(F(["citation_volume"])),issue:m(F(["citation_issue"])),pages:this.extractPages(),source:this.id,citationType:"article"}}getMetricBarAnchor(e){if(this.isArticlePage()){const a=this.findAnchorByPriority(e,cx);if(a)return{element:a,position:"after"};const i=e.querySelector("h1");return i?{element:i,position:"after"}:{element:e,position:"prepend"}}const t=this.findAnchorByPriority(e,ux);if(t)return{element:t,position:"after"};const n=e.querySelector('h2, h3, .hlFld-Title, .art_title, [class*="title"]');return n?{element:n,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector(Ou)??document.body}getPageInfo(){const e=new URLSearchParams(location.search),t=Number.parseInt(e.get("page")??e.get("startPage")??"1",10)||1,a=m(document.querySelector('[class*="result-count"], [class*="results-count"], main')?.textContent).match(/\b([\d,]+)\s+results?\b/i),i=a?Number.parseInt(a[1].replace(/,/g,""),10):void 0;return{pageNum:t,totalPages:i?Math.max(1,Math.ceil(i/20)):1,url:location.href,itemsPerPage:20,totalItems:i}}isArticlePath(e){return/\/journals\/[^/]+\/article\//i.test(e)}getSearchResultHosts(){return U(Array.from(document.querySelectorAll(Zo)).map(e=>this.toSearchHost(e)).filter(e=>!!e).filter(e=>this.looksLikeSearchResult(e)))}toSearchHost(e){return e.matches(Zo)&&this.looksLikeSearchResult(e,!1)?e:e.closest(Zo)}looksLikeSearchResult(e,t=!0){return e.closest('[class^="paperlens-"], [class*=" paperlens-"]')||t&&!e.closest(Ou)?!1:!!this.findArticleLink(e)}parseSearchHost(e){const t=this.findArticleLink(e),n=m(t?.textContent??e.querySelector('h2, h3, .hlFld-Title, .art_title, [class*="title"]')?.textContent);if(!n)return null;const a=B(t?.getAttribute("href")),i=this.extractPii(a??"")??this.extractPii(e.textContent??""),o=Z(e.textContent)??this.doiFromPii(i),s=this.journalFromUrl(a??""),l=this.extractJournalFromDom(e)||s||"The Lancet";return{title:n,journalName:l,journalCandidates:this.buildJournalCandidates(l,s),authors:this.extractAuthorsFromDom(e),year:qe(e.textContent),doi:o,sourceId:i?`lancet:${i}`:o?`lancet:${o}`:void 0,url:a,nativeFullTextUrl:this.extractPdfUrl(e,a),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:this.extractArticleTypes(e),source:this.id,citationType:"article"}}findArticleLink(e){return Array.from(e.querySelectorAll(sx)).find(t=>!/\.pdf(?:[?#]|$)|\/pdfs\//i.test(t.href))??null}extractPii(e){const t=e.match(/\bPII([A-Z0-9()\-]+)\b/i)??e.match(/\b(S\d{4}-?\d{3}[\dX]\(\d{2}\)\d{5}-\d)\b/i);return t?(t[1].toUpperCase().startsWith("PII")?t[1]:`PII${t[1]}`).replace(/\.pdf$/i,""):void 0}doiFromPii(e){if(!e)return;const t=e.replace(/^PII/i,"");return/^S/i.test(t)?`10.1016/${t}`:void 0}journalFromUrl(e){if(/\/medical-imaging-theranostics(?:\/|$)/i.test(e))return"The Lancet Medical Imaging & Theranostics";if(/\/regional-health\/eastern-mediterranean(?:\/|$)/i.test(e))return"The Lancet Regional Health \u2013 Eastern Mediterranean";const t=e.match(/\/journals\/([^/]+)\//i)?.[1]?.toLowerCase();return t?dx[t]:void 0}extractPdfUrl(e,t){const n=B(F(["citation_pdf_url"]));if(n)return n;const a=B(e.querySelector('a[href*="/pdfs/"], a[href$=".pdf"]')?.getAttribute("href"));if(a)return a;const i=this.extractPii(t??location.href),o=(t??location.href).match(/\/journals\/([^/]+)\//i)?.[1];if(!(!i||!o))return B(`/pdfs/journals/${o}/${i}.pdf`)}extractJournalFromDom(e){return m(e.querySelector('[class*="journal-title"], [class*="journalTitle"], .publication-title, [data-test*="journal"]')?.textContent)||void 0}extractAuthorsFromDom(e){return U(Array.from(e.querySelectorAll('[class*="author"] a, [class*="author-name"], .authors a')).map(t=>m(t.textContent)).filter(t=>t.length>1&&!/author information|view/i.test(t)))}extractAbstract(e){return m(F(["citation_abstract","description","og:description"])??je(e))||void 0}extractArticleTypes(e){const t=m(e.querySelector('[class*="article-type"], [class*="ArticleType"], [data-test*="article-type"]')?.textContent);return t?[t]:[]}extractPages(){const e=m(F(["citation_firstpage"])),t=m(F(["citation_lastpage"]));return e&&t&&e!==t?`${e}-${t}`:e||void 0}buildJournalCandidates(...e){const t=[],n=a=>{const i=m(a);i&&(t.push(i),/^the\s+lancet\b/i.test(i)&&t.push(i.replace(/^the\s+/i,"")))};return e.forEach(n),U(t)}findAnchorByPriority(e,t){for(const n of t){const i=Array.from(e.querySelectorAll(n)).filter(o=>!o.closest('[class^="paperlens-"], [class*=" paperlens-"]')).filter(o=>m(o.textContent).length>0||o instanceof HTMLAnchorElement).at(-1);if(i)return i}return null}}const hx=['a[href*="/content/"]','a[href*="/lookup/doi/"]'].join(","),Yo=[".highwire-article-citation",".search-result",".search-results__item","li.search-result",".result-item","article"].join(","),Uu=[".search-results","#search-results",".highwire-search-results",'[aria-label="Search results"]',"main"].join(","),fx=["main article","#main-content article","article","#content","main","body"].join(","),mx=['[class*="doi" i], [id*="doi" i], a[href*="doi.org"]','.article-metadata, .highwire-cite-metadata, [class*="article-meta" i]'],bx=[".contrib-group",".contrib-list",".contributor-list",".contributors-list",".highwire-cite-authors",".highwire-citation-authors",".contributors",".authors",".article-authors",".loa-authors",'[class*="author-list" i]','[class*="authors" i]','[class*="contrib-group" i]','[class*="contrib-list" i]','[class*="contributor-list" i]','[class*="contributors" i]',".highwire-citation-author",'[class*="author-name" i]'].join(","),gx=['[class*="doi" i], [id*="doi" i], a[href*="doi.org"]','.highwire-citation-authors, .contributors, .authors, [class*="author" i]','.highwire-cite-metadata, .search-result__meta, [class*="citation" i], [class*="meta" i]'],yx={adc:"Archives of Disease in Childhood",ard:"Annals of the Rheumatic Diseases",bjsm:"British Journal of Sports Medicine",bmj:"The BMJ",bmjopen:"BMJ Open",bmjmedicine:"BMJ Medicine",bmjmilitaryhealth:"BMJ Military Health",bmjophth:"BMJ Open Ophthalmology",bmjpaedsopen:"BMJ Paediatrics Open",casereports:"BMJ Case Reports",ebm:"BMJ Evidence-Based Medicine",emj:"Emergency Medicine Journal",fg:"Frontline Gastroenterology",gut:"Gut",heart:"Heart",jech:"Journal of Epidemiology & Community Health",jme:"Journal of Medical Ethics",jnnp:"Journal of Neurology, Neurosurgery & Psychiatry",openheart:"Open Heart",rapm:"Regional Anesthesia & Pain Medicine",sti:"Sexually Transmitted Infections",thorax:"Thorax",tobaccocontrol:"Tobacco Control"};class xx extends j{id="bmj";name="BMJ Journals";matches=["*://www.bmj.com/content/*","*://www.bmj.com/search*","*://*.bmj.com/content/*","*://*.bmj.com/search*"];isSearchPage(){if(le())return!1;const e=location.pathname.toLowerCase();return e.startsWith("/search")||!this.isArticlePagePath(e)&&new URLSearchParams(location.search).has("query")}isArticlePage(){return le()||this.isSearchPagePath(location.pathname)?!1:this.isArticlePagePath(location.pathname)||!!F(["citation_title"])}parseSearchResults(){const e=[],t=new Set;for(const n of this.getSearchResultHosts()){const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;t.has(i)||(t.add(i),e.push(a))}return e}parseArticlePage(){if(le())return null;const e=document.querySelector(fx);if(!e)return null;const t=m(F(["citation_title","dc.title","og:title"])??e.querySelector("h1")?.textContent).replace(/\s*\|\s*BMJ.*$/i,"");if(!t)return null;const n=$n(),a=m(F(["citation_publication_date","citation_online_date","article:published_time","dc.Date"])),i=Ne(F(["citation_doi","dc.Identifier","prism.doi"]))??this.doiFromArticleUrl(n??location.href)??Z(e.textContent),o=this.journalFromHost(location.hostname),s=m(F(["citation_journal_title","prism.publicationName"]))||this.extractJournalFromDom(e)||o||"BMJ Journals",l=this.extractPdfUrl(e,n);return{title:t,journalName:s,journalCandidates:this.buildJournalCandidates(s,o),authors:Je("citation_author").length>0?Je("citation_author"):this.extractAuthorsFromDom(e),year:qe(a),publicationDate:a||void 0,doi:i,sourceId:i?`bmj:${i}`:n?`bmj:${n}`:void 0,url:n,nativeFullTextUrl:l,abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:this.extractArticleTypes(e),issn:m(F(["citation_issn","prism.issn"])),volume:m(F(["citation_volume"])),issue:m(F(["citation_issue"])),pages:this.extractPages(),source:this.id,citationType:"article"}}getMetricBarAnchor(e){if(this.isArticlePage()){if(this.isMainSiteHost(location.hostname)){const s=this.findMainSiteAcceptedAnchor(e);if(s)return{element:s,position:"after"}}const a=this.findDetailAuthorAnchor(e);if(a)return{element:a,position:"after"};const i=this.findAnchorByPriority(e,mx);if(i)return{element:i,position:"after"};const o=e.querySelector("h1");return o?{element:o,position:"after"}:{element:e,position:"prepend"}}const t=this.findAnchorByPriority(e,gx);if(t)return{element:t,position:"after"};const n=e.querySelector('h2, h3, .highwire-cite-title, [class*="title"]');return n?{element:n,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector(Uu)??document.body}getPageInfo(){const e=new URLSearchParams(location.search),t=Number.parseInt(e.get("page")??"1",10)||1,a=m(document.querySelector('[class*="result-count"], [class*="results-count"], main')?.textContent).match(/\b([\d,]+)\s+results?\b/i),i=a?Number.parseInt(a[1].replace(/,/g,""),10):void 0;return{pageNum:t,totalPages:i?Math.max(1,Math.ceil(i/10)):1,url:location.href,itemsPerPage:10,totalItems:i}}isSearchPagePath(e){return e.toLowerCase().startsWith("/search")}isArticlePagePath(e){return/^\/content\//i.test(e)&&!/\.pdf$/i.test(e)}getSearchResultHosts(){return U(Array.from(document.querySelectorAll(Yo)).map(e=>this.toSearchHost(e)).filter(e=>!!e).filter(e=>this.looksLikeSearchResult(e)))}toSearchHost(e){return e.matches(Yo)&&this.looksLikeSearchResult(e,!1)?e:e.closest(Yo)}looksLikeSearchResult(e,t=!0){return e.closest('[class^="paperlens-"], [class*=" paperlens-"]')||t&&!e.closest(Uu)?!1:!!this.findArticleLink(e)}parseSearchHost(e){const t=this.findArticleLink(e),n=m(t?.textContent??e.querySelector('h2, h3, .highwire-cite-title, [class*="title"]')?.textContent);if(!n)return null;const a=B(t?.getAttribute("href")),i=Z(e.textContent)??this.doiFromArticleUrl(a??""),o=this.journalFromHost(a?new URL(a).hostname:location.hostname),s=this.extractJournalFromDom(e)||o||"BMJ Journals";return{title:n,journalName:s,journalCandidates:this.buildJournalCandidates(s,o),authors:this.extractAuthorsFromDom(e),year:qe(e.textContent),doi:i,sourceId:i?`bmj:${i}`:a?`bmj:${a}`:void 0,url:a,nativeFullTextUrl:this.extractPdfUrl(e,a),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:this.extractArticleTypes(e),source:this.id,citationType:"article"}}findArticleLink(e){return Array.from(e.querySelectorAll(hx)).find(t=>!/\.pdf(?:[?#]|$)/i.test(t.href))??null}doiFromArticleUrl(e){const t=B(e);if(!t)return;const a=new URL(t).pathname.split("/").filter(Boolean).at(-1);if(!(!a||a.includes(".")||/^\d+$/.test(a)))return/^10\./i.test(a)?Ne(a):/^[a-z][a-z0-9-]+-\d{4}-\d+/i.test(a)?`10.1136/${a}`:void 0}extractPdfUrl(e,t){const n=B(F(["citation_pdf_url"]));if(n)return n;const a=B(e.querySelector('a[href*=".full.pdf"], a[href$=".pdf"], a[href*="/content/"][href*="pdf"]')?.getAttribute("href"));if(a)return a;const i=B(t);if(!i)return;const o=new URL(i);if(!(!/^\/content\//i.test(o.pathname)||/\.pdf$/i.test(o.pathname)))return`${o.origin}${o.pathname}.full.pdf`}journalFromHost(e){const t=e.replace(/^www\./,"").replace(/\.bmj\.com$/i,"").toLowerCase();return this.isMainSiteHost(e)?"The BMJ":yx[t]??this.titleCaseSubdomain(t)}isMainSiteHost(e){return e.replace(/^www\./,"").toLowerCase()==="bmj.com"}titleCaseSubdomain(e){if(!(!e||e==="journals")&&/^bmj/.test(e))return e.replace(/^bmj/,"BMJ ").replace(/-/g," ").replace(/\b\w/g,t=>t.toUpperCase())}extractJournalFromDom(e){return m(e.querySelector('.journal-title, .highwire-cite-journal, [class*="journal-title"], [class*="journalTitle"]')?.textContent)||void 0}extractAuthorsFromDom(e){return U(Array.from(e.querySelectorAll([".highwire-citation-author",".highwire-cite-authors a",".highwire-citation-authors a",".contributors a",".authors a",'[class*="author-name" i]'].join(","))).map(t=>m(t.textContent)).filter(t=>t.length>1&&!/author information|view/i.test(t)))}extractAbstract(e){return m(F(["citation_abstract","description","og:description"])??je(e))||void 0}extractArticleTypes(e){const t=m(e.querySelector('.article-type, .highwire-cite-metadata-article-type, [class*="article-type"]')?.textContent);return t?[t]:[]}extractPages(){const e=m(F(["citation_firstpage"])),t=m(F(["citation_lastpage"]));return e&&t&&e!==t?`${e}-${t}`:e||void 0}findDetailAuthorAnchor(e){const t=e.querySelector("h1"),n=this.findAnchorByPriority(e,['[class*="doi" i], [id*="doi" i], a[href*="doi.org"]']);return U(Array.from(e.querySelectorAll(bx)).map(i=>this.normalizeAuthorAnchor(i)).filter(i=>!i.closest('[class^="paperlens-"], [class*=" paperlens-"]')).filter(i=>m(i.textContent).length>0).filter(i=>!t||this.isAfter(i,t)).filter(i=>!n||this.isBefore(i,n))).at(-1)??null}findMainSiteAcceptedAnchor(e){const t=e.querySelector("h1");return U(Array.from(e.querySelectorAll("p, li, div, span, dd, dt")).filter(a=>!a.closest('[class^="paperlens-"], [class*=" paperlens-"]')).filter(a=>this.isAcceptedDateText(m(a.textContent))).map(a=>this.normalizeAcceptedAnchor(a,e)).filter(a=>!t||this.isAfter(a,t)).filter(a=>this.isAcceptedAnchorCandidate(a))).sort((a,i)=>this.scoreAcceptedAnchor(i)-this.scoreAcceptedAnchor(a)).at(0)??null}normalizeAcceptedAnchor(e,t){let n=e;for(;n.parentElement&&n.parentElement!==t;){const a=n.parentElement,i=m(a.textContent);if(!this.isAcceptedDateText(i)||i.length>180||!this.isInlineElement(n)&&!/^accepted\b/i.test(i))break;n=a}return n}isAcceptedAnchorCandidate(e){const t=m(e.textContent);return t.length===0||t.length>180||e.querySelector("h1, h2, h3, h4, h5, h6, nav, table")?!1:this.isAcceptedDateText(t)}scoreAcceptedAnchor(e){const t=m(e.textContent);let n=0;return/^accepted\b/i.test(t)&&(n+=100),/^(p|li|div|dd|dt)$/i.test(e.tagName)&&(n+=30),this.isInlineElement(e)&&(n-=20),n-=Math.min(t.length,180)/10,n}isAcceptedDateText(e){return/\baccepted\s+(?:\d{1,2}\s+[A-Za-z]+\s+\d{4}|[A-Za-z]+\s+\d{1,2},?\s+\d{4}|\d{4}[-/]\d{1,2}[-/]\d{1,2})\b/i.test(e)}isInlineElement(e){return/^(a|span|strong|em|b|i|small|sup|sub)$/i.test(e.tagName)}normalizeAuthorAnchor(e){return e.closest([".contrib-group",".contrib-list",".contributor-list",".contributors-list",".highwire-cite-authors",".highwire-citation-authors",".contributors",".authors",".article-authors",".loa-authors",'[class*="author-list" i]','[class*="authors" i]','[class*="contrib-group" i]','[class*="contrib-list" i]','[class*="contributor-list" i]','[class*="contributors" i]'].join(","))??e}isBefore(e,t){return!!(e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING)}isAfter(e,t){return!!(t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING)}buildJournalCandidates(...e){const t=[],n=a=>{const i=m(a);i&&(t.push(i),(/^the\s+bmj$/i.test(i)||/^bmj$/i.test(i))&&(t.push("BMJ"),t.push("BMJ-British Medical Journal"),t.push("British Medical Journal")))};return e.forEach(n),U(t)}findAnchorByPriority(e,t){for(const n of t){const i=Array.from(e.querySelectorAll(n)).filter(o=>!o.closest('[class^="paperlens-"], [class*=" paperlens-"]')).filter(o=>m(o.textContent).length>0||o instanceof HTMLAnchorElement).at(-1);if(i)return i}return null}}const Ax=['a[href*="/doi/full/"]','a[href*="/doi/abs/"]','a[href*="/doi/"]'].join(","),Ko=["article",".search-result",".search-results__item",".result-item",'li[class*="result" i]','[class*="search-result" i]'].join(","),Hu=[".search-results","#search-results",'[aria-label="Search results"]',"main"].join(","),Cx=["main article","#main-content article","article","main","#main-content","body"].join(","),vx=[".article-citation",'[data-testid*="citation" i]','[data-test*="citation" i]','[class*="citation"]','[class*="citation" i]','[class*="article-meta" i]','[class*="article-info" i]','[class*="metadata" i]','[class*="doi" i], [id*="doi" i], a[href*="doi.org"]'],Sx=[".search-result__meta, .article-citation",'[class*="citation"], [class*="meta"], [class*="publication"], [class*="date"]','[class*="citation" i], [class*="meta" i], [class*="publication" i], [class*="date" i]','[class*="doi" i], [id*="doi" i], a[href*="doi.org"]','[class*="author" i], .authors'];class wx extends j{id="nejm";name="NEJM";matches=["*://www.nejm.org/*","*://nejm.org/*"];isSearchPage(){if(le())return!1;const e=location.pathname.toLowerCase();return e.startsWith("/search")||e.startsWith("/action/dosearch")}isArticlePage(){return le()||this.isSearchPage()?!1:this.isArticlePath(location.pathname)||!!F(["citation_title"])}parseSearchResults(){const e=[],t=new Set;for(const n of this.getSearchResultHosts()){const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;t.has(i)||(t.add(i),e.push(a))}return e}parseArticlePage(){if(le())return null;const e=document.querySelector(Cx);if(!e)return null;const t=m(F(["citation_title","dc.title","DC.Title","og:title"])??e.querySelector("h1")?.textContent).replace(/\s*\|\s*(?:NEJM|New England Journal of Medicine).*$/i,"");if(!t)return null;const n=$n(),a=Ne(F(["citation_doi","dc.Identifier","DC.Identifier","prism.doi"]))??this.doiFromUrl(n??location.href)??Z(e.textContent),i=m(F(["citation_publication_date","citation_online_date","prism.publicationDate","article:published_time"])),o=m(F(["citation_journal_title","prism.publicationName","og:site_name"]))||this.extractJournalFromDom(e)||"New England Journal of Medicine";return{title:t,journalName:o,journalCandidates:this.buildJournalCandidates(o),authors:Je("citation_author").length>0?Je("citation_author"):this.extractAuthorsFromDom(e),year:qe(i||e.textContent),publicationDate:i||void 0,doi:a,sourceId:a?`nejm:${a}`:n?`nejm:${n}`:void 0,url:n,nativeFullTextUrl:this.extractPdfUrl(e,n),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:this.extractArticleTypes(e),issn:m(F(["citation_issn","prism.issn"])),volume:m(F(["citation_volume"])),issue:m(F(["citation_issue"])),pages:this.extractPages(),source:this.id,citationType:"article"}}getMetricBarAnchor(e){if(this.isArticlePage()){const a=this.findDetailCitationAnchor(e);if(a)return{element:a,position:"after"};const i=this.findAnchorByPriority(e,vx);if(i)return{element:i,position:"after"};const o=e.querySelector("h1");return o?{element:o,position:"after"}:{element:e,position:"prepend"}}const t=this.findAnchorByPriority(e,Sx);if(t)return{element:t,position:"after"};const n=e.querySelector('h2, h3, [class*="title" i]');return n?{element:n,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector(Hu)??document.body}getPageInfo(){const e=new URLSearchParams(location.search),t=Number.parseInt(e.get("page")??e.get("startPage")??"1",10)||1,a=m(document.querySelector('[class*="result-count" i], [class*="results-count" i], main')?.textContent).match(/\b([\d,]+)\s+results?\b/i),i=a?Number.parseInt(a[1].replace(/,/g,""),10):void 0;return{pageNum:t,totalPages:i?Math.max(1,Math.ceil(i/20)):1,url:location.href,itemsPerPage:20,totalItems:i}}isArticlePath(e){return/^\/doi\/(?:full|abs|pdf|epdf)?\/?10\./i.test(e)}getSearchResultHosts(){return U(Array.from(document.querySelectorAll(Ko)).map(e=>this.toSearchHost(e)).filter(e=>!!e).filter(e=>this.looksLikeSearchResult(e)))}toSearchHost(e){return e.matches(Ko)&&this.looksLikeSearchResult(e,!1)?e:e.closest(Ko)}looksLikeSearchResult(e,t=!0){return e.closest('[class^="paperlens-"], [class*=" paperlens-"]')||t&&!e.closest(Hu)?!1:!!this.findArticleLink(e)}parseSearchHost(e){const t=this.findArticleLink(e),n=m(t?.textContent??e.querySelector('h2, h3, [class*="title" i]')?.textContent);if(!n)return null;const a=B(t?.getAttribute("href")),i=this.doiFromUrl(a??"")??Z(e.textContent),o=this.extractJournalFromDom(e)||"New England Journal of Medicine";return{title:n,journalName:o,journalCandidates:this.buildJournalCandidates(o),authors:this.extractAuthorsFromDom(e),year:qe(e.textContent),doi:i,sourceId:i?`nejm:${i}`:a?`nejm:${a}`:void 0,url:a,nativeFullTextUrl:this.extractPdfUrl(e,a),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:this.extractArticleTypes(e),source:this.id,citationType:"article"}}findArticleLink(e){return Array.from(e.querySelectorAll(Ax)).find(t=>!/\/doi\/(?:pdf|epdf)\//i.test(t.href))??null}doiFromUrl(e){const t=B(e);if(!t)return;const a=new URL(t).pathname.match(/\/doi\/(?:full|abs|pdf|epdf)?\/?(10\.\d{4,9}\/.+)$/i);if(a)try{return Ne(decodeURIComponent(a[1]))}catch{return Ne(a[1])}}extractPdfUrl(e,t){const n=B(F(["citation_pdf_url"]));if(n)return n;const a=B(e.querySelector('a[href*="/doi/pdf/"], a[href*="/doi/epdf/"], a[href$=".pdf"]')?.getAttribute("href"));if(a)return a;const i=this.doiFromUrl(t??location.href)??Z(e.textContent);return i?B(`/doi/pdf/${i}`):void 0}extractJournalFromDom(e){const t=m(e.querySelector(['[class*="journal-title" i]','[class*="journalTitle" i]','[data-testid*="journal" i]','[data-test*="journal" i]','[class*="publication" i]','[class*="citation" i]','[class*="meta" i]'].join(","))?.textContent),n=this.extractJournalFromCitationText(t)??this.extractJournalFromCitationText(e.textContent);if(n)return n;if(t)return/^nejm$/i.test(t)?"New England Journal of Medicine":t}extractJournalFromCitationText(e){const t=m(e);if(/\bN\s*Engl\s*J\s*Med\b/i.test(t))return"N Engl J Med";if(/\bNew\s+England\s+Journal\s+of\s+Medicine\b/i.test(t)||/^NEJM\b/i.test(t))return"New England Journal of Medicine"}extractAuthorsFromDom(e){return U(Array.from(e.querySelectorAll(['[class*="author" i] a','[class*="author-name" i]','[data-testid*="author" i]',".authors a"].join(","))).map(t=>m(t.textContent)).filter(t=>t.length>1&&!/author information|view/i.test(t)))}extractAbstract(e){return m(F(["citation_abstract","description","og:description"])??je(e))||void 0}extractArticleTypes(e){const t=m(e.querySelector('[class*="article-type" i], [data-test*="article-type" i]')?.textContent);return t?[t]:[]}extractPages(){const e=m(F(["citation_firstpage"])),t=m(F(["citation_lastpage"]));return e&&t&&e!==t?`${e}-${t}`:e||void 0}findDetailCitationAnchor(e){const t=e.querySelector("h1");return U(Array.from(e.querySelectorAll("p, div, section, header, span")).map(a=>this.normalizeCitationAnchor(a,e)).filter(a=>!a.closest('[class^="paperlens-"], [class*=" paperlens-"]')).filter(a=>!t||this.isAfter(a,t)).filter(a=>this.isCitationAnchorCandidate(a))).sort((a,i)=>this.scoreCitationAnchor(i)-this.scoreCitationAnchor(a)).at(0)??null}normalizeCitationAnchor(e,t){let n=e;for(;n.parentElement&&n.parentElement!==t;){const a=n.parentElement;if(a.matches("article, main, body"))break;const i=m(a.textContent);if(i.length>260||!this.hasCitationSignals(i))break;n=a}return n}isCitationAnchorCandidate(e){const t=m(e.textContent);return e.matches("article, main, body")||!t||t.length>260||e.querySelector("h1, h2, h3, h4, h5, h6, nav, table")?!1:this.hasCitationSignals(t)}scoreCitationAnchor(e){const t=m(e.textContent);let n=0;return(/\bdoi\b/i.test(t)||Z(t))&&(n+=80),(/\bdoi\b/i.test(t)||Z(t))&&/\b(?:vol(?:ume)?|no\.?|issue)\b/i.test(t)&&(n+=60),/\bN\s*Engl\s*J\s*Med\b/i.test(t)&&(n+=70),/\b(?:19|20)\d{2}\s*;\s*\d+/i.test(t)&&(n+=40),/\b(?:vol(?:ume)?|issue)\b/i.test(t)&&(n+=20),/(citation|article-meta|article-info|metadata|doi)/i.test(e.getAttribute("class")??"")&&(n+=25),/^(p|div|section|header)$/i.test(e.tagName)&&(n+=15),n-=Math.min(t.length,260)/20,n}hasCitationSignals(e){return!!(Z(e)||/\bdoi\b/i.test(e)||/\bN\s*Engl\s*J\s*Med\b/i.test(e)||/\bNEJM\b/i.test(e))}buildJournalCandidates(...e){const t=[],n=a=>{const i=m(a);i&&(t.push(i),/^(?:nejm|n\s*engl\s*j\s*med|new england journal of medicine)$/i.test(i)&&(t.push("New England Journal of Medicine"),t.push("N Engl J Med"),t.push("NEJM")))};return e.forEach(n),U(t)}findAnchorByPriority(e,t){for(const n of t){const i=Array.from(e.querySelectorAll(n)).map(o=>this.normalizeCitationAnchor(o,e)).filter(o=>!o.matches("article, main, body")).filter(o=>!o.closest('[class^="paperlens-"], [class*=" paperlens-"]')).filter(o=>m(o.textContent).length>0||o instanceof HTMLAnchorElement).at(-1);if(i)return i}return null}isAfter(e,t){return!!(t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING)}}const Tx=['a[href*="/journals/"][href*="/fullarticle/"]','a[href*="/journals/"][href*="/article-abstract/"]'].join(","),Qo=["li.article.search-result","li.search-result",".article.search-result",".search-result","article"].join(","),zu=[".search-results-list",".search-results",'[aria-label="Search results"]',"main"].join(","),Ex=["main article","#main-content article",".article-full-text",".article-main-content",".article-page-content","article","main","body"].join(","),Fx=[".article--citation","cite.article--citation",'[class*="citation" i]','[class*="doi" i], [id*="doi" i], a[href*="doi.org"]','[class*="article-meta" i]','[class*="article-info" i]'],Dx=[".article--citation","cite.article--citation",".article--information",'[class*="citation" i]','[class*="meta" i]','[class*="publication" i]','[class*="date" i]',".article--authors",'[class*="author" i]'],Ju={jama:"JAMA-JOURNAL OF THE AMERICAN MEDICAL ASSOCIATION",jamanetworkopen:"JAMA Network Open","jama-health-forum":"JAMA Health Forum",jamahealthforum:"JAMA Health Forum",jamacardiology:"JAMA Cardiology",jamadermatology:"JAMA Dermatology",jamainternalmedicine:"JAMA Internal Medicine",jamaneurology:"JAMA Neurology",jamaoncology:"JAMA Oncology",jamaophthalmology:"JAMA Ophthalmology",jamaotolaryngology:"JAMA Otolaryngology-Head & Neck Surgery",jamapediatrics:"JAMA Pediatrics",jamapsychiatry:"JAMA Psychiatry",jamasurgery:"JAMA Surgery",archneurpsyc:"Archives of Neurology & Psychiatry"},_x={"JAMA-JOURNAL OF THE AMERICAN MEDICAL ASSOCIATION":["JAMA","Journal of the American Medical Association","JAMA Journal of the American Medical Association"],"JAMA Network Open":["JAMA Netw Open"],"JAMA Cardiology":["JAMA Cardiol"],"JAMA Dermatology":["JAMA Dermatol"],"JAMA Health Forum":["JAMA Health Forum"],"JAMA Internal Medicine":["JAMA Intern Med"],"JAMA Neurology":["JAMA Neurol"],"JAMA Oncology":["JAMA Oncol"],"JAMA Ophthalmology":["JAMA Ophthalmol"],"JAMA Otolaryngology-Head & Neck Surgery":["JAMA Otolaryngol Head Neck Surg","JAMA Otolaryngology Head Neck Surgery"],"JAMA Pediatrics":["JAMA Pediatr"],"JAMA Psychiatry":["JAMA Psychiatry"],"JAMA Surgery":["JAMA Surg"],"Archives of Neurology & Psychiatry":["Archives of Neurology and Psychiatry","Arch Neurol Psychiatry"]},Vu=[[/\bJAMA\s+Netw\s+Open\b/i,"JAMA Network Open"],[/\bJAMA\s+Cardiol\b/i,"JAMA Cardiology"],[/\bJAMA\s+Dermatol\b/i,"JAMA Dermatology"],[/\bJAMA\s+Health\s+Forum\b/i,"JAMA Health Forum"],[/\bJAMA\s+Intern\s+Med\b/i,"JAMA Internal Medicine"],[/\bJAMA\s+Neurol\b/i,"JAMA Neurology"],[/\bJAMA\s+Oncol\b/i,"JAMA Oncology"],[/\bJAMA\s+Ophthalmol\b/i,"JAMA Ophthalmology"],[/\bJAMA\s+Otolaryngol(?:\s+Head\s+Neck\s+Surg)?\b/i,"JAMA Otolaryngology-Head & Neck Surgery"],[/\bJAMA\s+Pediatr\b/i,"JAMA Pediatrics"],[/\bJAMA\s+Psychiatry\b/i,"JAMA Psychiatry"],[/\bJAMA\s+Surg\b/i,"JAMA Surgery"],[/\bJAMA\b/i,"JAMA-JOURNAL OF THE AMERICAN MEDICAL ASSOCIATION"]];class kx extends j{id="jama-network";name="JAMA Network";matches=["*://jamanetwork.com/*","*://www.jamanetwork.com/*"];isSearchPage(){if(le())return!1;const e=location.pathname.toLowerCase();return e.startsWith("/search")||e.startsWith("/searchresults")}isArticlePage(){return le()||this.isSearchPage()?!1:this.isArticlePath(location.pathname)||!!F(["citation_title"])}parseSearchResults(){const e=[],t=new Set;for(const n of this.getSearchResultHosts()){const a=this.parseSearchHost(n);if(!a)continue;const i=a.sourceId??a.doi??a.url??a.title;t.has(i)||(t.add(i),e.push(a))}return e}parseArticlePage(){if(le())return null;const e=this.findDetailHost();if(!e)return null;const t=m(F(["citation_title","dc.title","DC.Title","og:title"])??e.querySelector("h1")?.textContent).replace(/\s*\|\s*(?:JAMA Network|JAMA).*$/i,"");if(!t)return null;const n=$n(),a=Ne(F(["citation_doi","dc.Identifier","DC.Identifier","prism.doi"]))??Z(e.textContent),i=m(F(["citation_publication_date","citation_online_date","publish_date","prism.publicationDate","article:published_time"])),o=this.journalFromUrl(n??location.href),s=m(F(["citation_journal_title","prism.publicationName","og:site_name"]))||this.extractJournalFromDom(e)||o||"JAMA Network";return{title:t,journalName:s,journalCandidates:this.buildJournalCandidates(s,o),authors:Je("citation_author").length>0?Je("citation_author"):this.extractAuthorsFromDom(e),year:qe(i||e.textContent),publicationDate:i||void 0,doi:a,pmid:m(F(["citation_pmid"]))||void 0,sourceId:a?`jama-network:${a}`:n?`jama-network:${n}`:void 0,url:n,nativeFullTextUrl:this.extractPdfUrl(e),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:this.extractArticleTypes(e),issn:m(F(["citation_issn","prism.issn"])),volume:m(F(["citation_volume"])),issue:m(F(["citation_issue"])),pages:this.extractPages(),source:this.id,citationType:"article"}}getMetricBarAnchor(e){if(this.isArticlePage()){const a=this.findDetailCitationAnchor(e),i=this.findDetailHeaderAnchor(e);if(a&&this.isPreferredDetailCitationAnchor(a,i))return{element:a,position:"after"};if(i)return{element:i,position:"after"};const o=this.findAnchorByPriority(e,Fx);if(o)return{element:o,position:"after"};const s=e.querySelector("h1");return s?{element:s,position:"after"}:{element:e,position:"prepend"}}const t=this.findAnchorByPriority(e,Dx);if(t)return{element:t,position:"after"};const n=e.querySelector('h2, h3, [class*="title" i]');return n?{element:n,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector(zu)??document.body}getPageInfo(){const e=new URLSearchParams(location.search),t=Number.parseInt(e.get("page")??e.get("startPage")??"1",10)||1,n=m(document.querySelector('.sr-statistics, [class*="result-count" i], [class*="results-count" i], main')?.textContent),a=n.match(/\bof\s+([\d,]+)\b/i)??n.match(/\b([\d,]+)\s+results?\b/i),i=a?Number.parseInt(a[1].replace(/,/g,""),10):void 0;return{pageNum:t,totalPages:i?Math.max(1,Math.ceil(i/20)):1,url:location.href,itemsPerPage:20,totalItems:i}}isArticlePath(e){return/^\/journals\/[^/]+\/(?:fullarticle|article-abstract)\/\d+/i.test(e)}findDetailHost(){const e=m(F(["citation_title","dc.title","DC.Title","og:title"])).replace(/\s*\|\s*(?:JAMA Network|JAMA).*$/i,""),t=this.findCurrentTitleElement(e);if(t){const n=this.findTitleScopedHost(t);if(n)return n}return Array.from(document.querySelectorAll(Ex)).find(n=>this.looksLikeDetailHost(n,e))??document.body}findCurrentTitleElement(e){const t=Array.from(document.querySelectorAll(["h1.meta-article-title",".meta-article-title",'h1[class*="title" i]',"h1"].join(","))).filter(n=>!this.isHiddenUiElement(n)).filter(n=>!this.isSupplementaryUiElement(n)).filter(n=>m(n.textContent).length>0);if(e){const n=this.normalizeTitleForCompare(e),a=t.find(o=>this.normalizeTitleForCompare(m(o.textContent))===n);if(a)return a;const i=t.find(o=>{const s=this.normalizeTitleForCompare(m(o.textContent));return s.includes(n)||n.includes(s)});if(i)return i}return t.at(0)??null}normalizeTitleForCompare(e){return m(e).replace(/\s*\|\s*(?:JAMA Network|JAMA).*$/i,"").replace(/[^\p{L}\p{N}]+/gu," ").toLowerCase().trim()}findTitleScopedHost(e){let t=e;for(;t&&t!==document.body;){if(!this.isHiddenUiElement(t)&&!this.isSupplementaryUiElement(t)&&this.containsDetailHeaderSignals(t))return t;t=t.parentElement}return e.closest('article, main, [role="main"]')??document.querySelector("main")??document.body}containsDetailHeaderSignals(e){if(e.matches("h1, h2, h3"))return!1;const t=m(e.textContent);return t?!!(e.querySelector('.meta-authors, .article--authors, [class*="authors" i], [class*="author-list" i]')||e.querySelector('a[href*="/articlepdf/"], [data-article-url*="/articlepdf/"]')||Z(t)):!1}looksLikeDetailHost(e,t){return this.isHiddenUiElement(e)||this.isSupplementaryUiElement(e)||t&&!m(e.textContent).includes(t)?!1:!!e.querySelector("h1, .meta-article-title, .meta-authors, .article--authors")}getSearchResultHosts(){return U(Array.from(document.querySelectorAll(Qo)).map(e=>this.toSearchHost(e)).filter(e=>!!e).filter(e=>this.looksLikeSearchResult(e)))}toSearchHost(e){return e.matches(Qo)&&this.looksLikeSearchResult(e,!1)?e:e.closest(Qo)}looksLikeSearchResult(e,t=!0){return e.closest('[class^="paperlens-"], [class*=" paperlens-"]')||t&&!e.closest(zu)?!1:!!this.findArticleLink(e)}parseSearchHost(e){const t=this.findArticleLink(e),n=m(t?.textContent??e.querySelector('h2, h3, [class*="title" i]')?.textContent);if(!n)return null;const a=B(t?.getAttribute("href")),i=Z(e.textContent),o=m(e.querySelector('.article--pub-date, [class*="pub-date" i], [class*="date" i]')?.textContent),s=this.journalFromUrl(a),l=this.extractJournalFromDom(e)||s||"JAMA Network";return{title:n,journalName:l,journalCandidates:this.buildJournalCandidates(l,s),authors:this.extractAuthorsFromDom(e),year:qe(o||e.textContent),publicationDate:o||void 0,doi:i,sourceId:i?`jama-network:${i}`:a?`jama-network:${a}`:void 0,url:a,nativeFullTextUrl:this.extractPdfUrl(e),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:this.extractArticleTypes(e),source:this.id,citationType:"article"}}findArticleLink(e){return Array.from(e.querySelectorAll(Tx)).find(t=>!/\/articlepdf\/|\.pdf(?:[?#]|$)/i.test(t.href))??null}extractPdfUrl(e){const t=B(F(["citation_pdf_url"],e))??B(F(["citation_pdf_url"]));if(t)return t;const n=B(e.querySelector('[data-article-url*="/articlepdf/"]')?.dataset.articleUrl);return n||B(e.querySelector('a[href*="/articlepdf/"], a[href$=".pdf"]')?.getAttribute("href"))}journalFromUrl(e){const t=B(e);if(!t)return;const n=new URL(t).pathname.match(/\/journals\/([^/]+)/i);if(n)return Ju[n[1].toLowerCase()]}extractJournalFromDom(e){const t=m(e.querySelector([".article--journal",'[class*="journal-title" i]','[class*="journalTitle" i]','[data-testid*="journal" i]','[data-test*="journal" i]'].join(","))?.textContent);if(t)return this.normalizeJournalName(t);const n=m(e.querySelector("cite.article--citation i, .article--citation i, cite i")?.textContent);if(n)return this.normalizeJournalName(n)}normalizeJournalName(e){const t=m(e).replace(/\.$/,"");if(!t)return;const n=Object.values(Ju).find(a=>a.toLowerCase()===t.toLowerCase());if(n)return n;for(const[a,i]of Vu)if(a.test(t))return i;return t}extractJournalFromCitationText(e){const t=m(e);for(const[n,a]of Vu)if(n.test(t))return a}extractAuthorsFromDom(e){return U(Array.from(e.querySelectorAll([".article--authors a",".article--authors",".meta-authors a",'[class*="author" i] a','[class*="author-name" i]','[data-testid*="author" i]'].join(","))).map(t=>m(t.textContent)).filter(t=>t.length>1&&!/author information|view|affiliation/i.test(t)))}extractAbstract(e){return m(F(["citation_abstract","description","og:description"])??e.querySelector(".article--excerpt")?.textContent??je(e))||void 0}extractArticleTypes(e){return U(Array.from(e.querySelectorAll([".article--article-type",".article--superclassification",'[class*="article-type" i]','[data-test*="article-type" i]'].join(","))).map(t=>m(t.textContent)).filter(Boolean))}extractPages(){const e=m(F(["citation_firstpage"])),t=m(F(["citation_lastpage"]));return e&&t&&e!==t?`${e}-${t}`:e||void 0}findDetailCitationAnchor(e){const t=e.querySelector("h1");return U(Array.from(e.querySelectorAll("p, div, section, header, span, cite")).map(a=>this.normalizeCitationAnchor(a,e)).filter(a=>!this.isHiddenUiElement(a)).filter(a=>!a.closest('[class^="paperlens-"], [class*=" paperlens-"]')).filter(a=>!t||this.isAfter(a,t)).filter(a=>this.isCitationAnchorCandidate(a))).sort((a,i)=>this.scoreCitationAnchor(i)-this.scoreCitationAnchor(a)).at(0)??null}normalizeCitationAnchor(e,t){let n=e;for(;n.parentElement&&n.parentElement!==t;){const a=n.parentElement;if(a.matches("article, main, body"))break;const i=m(a.textContent);if(i.length>300||!this.hasCitationSignals(i))break;n=a}return n}findDetailHeaderAnchor(e){const t=this.findFirstVisible(e,[".meta-authors",".article--authors",'[class*="authors" i]','[class*="author-list" i]']);return t||this.findFirstVisible(e,[".meta-article-title-wrap",".article-title-wrap","h1"])}findFirstVisible(e,t){for(const n of t){const a=Array.from(e.querySelectorAll(n)).find(i=>m(i.textContent).length>0&&!this.isHiddenUiElement(i));if(a)return a}return null}isPreferredDetailCitationAnchor(e,t){if(e.matches(".article--citation, cite.article--citation")||e.closest(".article--citation")||!t)return!0;if(this.isSupplementaryUiElement(e))return!1;const n=e.parentElement,a=t.parentElement;return!n||!a?!1:!!(n===a||n.contains(t)&&m(n.textContent).length<1600||a.contains(e)&&m(a.textContent).length<1600)}isCitationAnchorCandidate(e){const t=m(e.textContent);return e.matches("article, main, body")||this.isHiddenUiElement(e)||!t||t.length>300||e.querySelector("h1, h2, h3, h4, h5, h6, nav, table")?!1:this.hasCitationSignals(t)}scoreCitationAnchor(e){const t=m(e.textContent);let n=0;return(/\bdoi\b/i.test(t)||Z(t))&&(n+=90),this.extractJournalFromCitationText(t)&&(n+=70),(/\bdoi\b/i.test(t)||Z(t))&&/\b(?:vol(?:ume)?|no\.?|issue|\d+\(\d+\)|\d+;?\d*)\b/i.test(t)&&(n+=35),/\b(?:19|20)\d{2}\s*;?\s*\d+/i.test(t)&&(n+=30),/(article--citation|citation|article-meta|article-info|metadata|doi)/i.test(e.getAttribute("class")??"")&&(n+=30),/^(cite|p|div|section|header)$/i.test(e.tagName)&&(n+=15),n-=Math.min(t.length,300)/20,n}hasCitationSignals(e){return!!(Z(e)||/\bdoi\b/i.test(e)||this.extractJournalFromCitationText(e))}buildJournalCandidates(...e){const t=[],n=a=>{const i=m(a);if(!i)return;const o=this.normalizeJournalName(i)??i;t.push(i),t.push(o),t.push(..._x[o]??[])};return e.forEach(n),U(t)}findAnchorByPriority(e,t){for(const n of t){const i=Array.from(e.querySelectorAll(n)).map(o=>this.normalizeCitationAnchor(o,e)).filter(o=>!this.isHiddenUiElement(o)).filter(o=>!o.matches("article, main, body")).filter(o=>!o.closest('[class^="paperlens-"], [class*=" paperlens-"]')).filter(o=>m(o.textContent).length>0||o instanceof HTMLAnchorElement).at(-1);if(i)return i}return null}isHiddenUiElement(e){return!!e.closest(["[hidden]",'[aria-hidden="true"]',".hide",".hidden",".reveal-modal",".flyout",".get-citation",".citation-download-wrap",".content-scroll-bar",".content-scroll-bar-item",".social-share-wrap",".toolbar",'[role="dialog"]','[role="menu"]'].join(","))}isSupplementaryUiElement(e){return!!e.closest([".personalized-content",'[class*="personalized" i]','[class*="related" i]','[class*="recommend" i]','[class*="sidebar" i]','[class*="right-rail" i]','[class*="rail" i]','[class*="widget" i]','[class*="toc" i]','[id*="article-information" i]','[class*="article-information" i]','[class*="article-info" i]'].join(","))}isAfter(e,t){return!!(t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING)}}const Wu=['a[href*="/fulltext/"]','a[href*="/abstract/"]','a[href^="/10."]','a[href*="journals.lww.com/10."]','a[href*="doi.org/10."]'].join(","),Gu=[".search-results li",".sr-list li",".result-list li",".searchResult",".search-result",".result-item",".article-list-item",".article-listing","article","li"].join(","),Nx=[".search-results",".sr-list",".result-list",'[id*="search" i]','[class*="search" i]',"main"].join(","),Lx=["main article","#main-content article",".article-page",".article__content",".article-content",".articleBody",".main-content","article","main","body"].join(","),Rx=['[class*="citation" i]','[class*="doi" i]','a[href*="doi.org/10."]',"#article-journal-info",".ej-journal-info",'[class*="published" i]','[class*="accepted" i]','[class*="article-meta" i]','[class*="article-info" i]','[class*="authors" i]','[class*="author" i]'],Px=['[class*="citation" i]','[class*="meta" i]','[class*="journal" i]','[class*="source" i]','[class*="date" i]','[class*="publication" i]'],Bx={"anesthesia-analgesia":"Anesthesia & Analgesia",aacr:"A&A Practice"},Zu={"Anesthesia & Analgesia":["Anesthesia and Analgesia","ANESTHESIA AND ANALGESIA","Anesth Analg"],"A&A Practice":["A A Practice","A and A Practice","A A Pract"]},Ix=/^\/(?:10\.\d{4,9}\/.+|[^/]+\/(?:abstract|fulltext)\/(?:\d{4}|9900)\/[^/]+\/[^/]+\.aspx)$/i;class Mx extends j{id="lww";name="LWW / Ovid";matches=["*://journals.lww.com/*","*://*.ovid.com/*"];isSearchPage(){if(le())return!1;const e=location.hostname.toLowerCase(),t=location.pathname.toLowerCase(),n=new URLSearchParams(location.search);if(e==="journals.lww.com")return t.endsWith("/pages/results.aspx")||n.has("txtKeywords")||n.has("txtKeyword")||n.has("q");if(e.endsWith(".ovid.com")){const a=n.get("PAGE")?.toLowerCase()??"";return a==="results"||a==="mainsearch"||a==="search"}return!1}isArticlePage(){if(le()||this.isSearchPage())return!1;const e=location.hostname.toLowerCase(),t=location.pathname;if(e==="journals.lww.com")return Ix.test(t)||!!F(["citation_title","dc.title","DC.Title","wkhealth_title"]);if(e.endsWith(".ovid.com")){const n=new URLSearchParams(location.search).get("PAGE")?.toLowerCase()??"";return n==="fulltext"||n==="article"||!!F(["citation_title","dc.title","DC.Title"])}return!1}parseSearchResults(){const e=[],t=new Set;for(const n of this.getSearchResultHosts()){const a=this.parseSearchHost(n);if(!a)continue;const i=a.doi??a.sourceId??a.url??a.title;t.has(i)||(t.add(i),e.push(a))}return e}parseArticlePage(){if(!this.isArticlePage())return null;const e=this.findDetailHost();if(!e)return null;const t=this.extractTitle(e);if(!t)return null;const n=$n(),a=Ne(F(["citation_doi","dc.Identifier","DC.Identifier","prism.doi","wkhealth_doi"]))??this.extractDoiFromUrl(n??location.href)??Z(e.textContent),i=m(F(["citation_publication_date","citation_online_date","prism.publicationDate","article:published_time","wkhealth_article_publication_date","wkhealth_date"])),o=this.journalFromUrl(n??location.href),s=m(F(["citation_journal_title","prism.publicationName","wkhealth_journal_title","wkhealth_journal_title_legacy","og:site_name"]))||this.extractJournalFromDom(e)||o||"LWW Journal";return{title:t,journalName:s,journalCandidates:this.buildJournalCandidates(s,o),authors:this.extractMetaAuthors().length>0?this.extractMetaAuthors():this.extractAuthors(e),year:qe(i||e.textContent),publicationDate:i||void 0,doi:a,sourceId:a?`lww:${a}`:n?`lww:${n}`:void 0,url:n,nativeFullTextUrl:this.extractNativeFullTextUrl(e,n??location.href),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:this.extractArticleTypes(e),issn:m(F(["citation_issn","prism.issn","wkhealth_issn"]))||void 0,volume:m(F(["citation_volume","wkhealth_volume"]))||this.extractVolumeIssuePages(e).volume,issue:m(F(["citation_issue","wkhealth_issue"]))||this.extractVolumeIssuePages(e).issue,pages:this.extractPages(e),source:this.id,citationType:"article",nativeExportUrls:this.extractNativeExportUrls(e)}}getMetricBarAnchor(e){if(this.isArticlePage()){const a=this.findDetailCitationAnchor(e);if(a)return{element:a,position:"after"};const i=this.findFirstVisible(e,['[class*="authors" i]','[class*="author" i]']);if(i)return{element:i,position:"after"};const o=this.findFirstVisible(e,["h1"]);return o?{element:o,position:"after"}:{element:e,position:"prepend"}}const t=this.findAnchorByPriority(e,Px);if(t)return{element:t,position:"after"};const n=this.findFirstVisible(e,['h2, h3, h4, [class*="title" i]']);return n?{element:n,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector(Nx)??document.body}getPageInfo(){const e=new URLSearchParams(location.search),t=Number.parseInt(e.get("page")??e.get("pg")??"1",10)||1,a=m(document.querySelector('[class*="result" i], main')?.textContent).match(/\b([\d,]+)\s+(?:results?|articles?)\b/i),i=a?Number.parseInt(a[1].replace(/,/g,""),10):void 0;return{pageNum:t,totalPages:i?Math.max(1,Math.ceil(i/20)):1,url:location.href,itemsPerPage:20,totalItems:i}}getSearchResultHosts(){const e=Array.from(document.querySelectorAll(Wu)).map(n=>this.toSearchHost(n)).filter(n=>!!n),t=Array.from(document.querySelectorAll(Gu)).filter(n=>this.looksLikeSearchResult(n));return U([...e,...t].filter(n=>this.looksLikeSearchResult(n)))}toSearchHost(e){return e.closest(Gu)??e.parentElement}looksLikeSearchResult(e){if(e.closest('[class^="paperlens-"], [class*=" paperlens-"]'))return!1;const t=this.findArticleLink(e);if(!t)return!1;const n=m(t.textContent);return n.length>8&&!/login|register|subscribe|alerts?|download citation/i.test(n)}parseSearchHost(e){const t=this.findArticleLink(e),n=m(t?.textContent??e.querySelector('h2, h3, h4, [class*="title" i]')?.textContent);if(!n)return null;const a=B(t?.getAttribute("href")),i=this.extractDoiFromUrl(a)??Z(e.textContent),o=this.journalFromUrl(a),s=this.extractJournalFromDom(e)||this.extractJournalFromCitationText(e.textContent)||o||"LWW Journal",l=m(e.querySelector('[class*="pub" i], [class*="date" i], [class*="citation" i], [class*="meta" i]')?.textContent);return{title:n,journalName:s,journalCandidates:this.buildJournalCandidates(s,o),authors:this.extractAuthors(e),year:qe(l||e.textContent),publicationDate:l||void 0,doi:i,sourceId:i?`lww:${i}`:a?`lww:${a}`:void 0,url:a,nativeFullTextUrl:this.extractNativeFullTextUrl(e,a),abstractSnippet:this.extractAbstract(e),hostElement:e,articleTypes:this.extractArticleTypes(e),source:this.id,citationType:"article",nativeExportUrls:this.extractNativeExportUrls(e)}}findArticleLink(e){return Array.from(e.querySelectorAll(Wu)).find(t=>{const n=t.getAttribute("href")??"";return!/\.pdf(?:[?#]|$)|download|citation|endnote|procite|referencemanager/i.test(n)})??null}findDetailHost(){const e=this.normalizeTitle(F(["citation_title","dc.title","DC.Title","wkhealth_title","og:title"])),t=this.findTitleElement(e);if(t){const n=t.closest('article, main, [role="main"], .article-page, .article-content');if(n)return n}return Array.from(document.querySelectorAll(Lx)).find(n=>this.looksLikeDetailHost(n,e))??document.body}looksLikeDetailHost(e,t){return this.isHiddenUiElement(e)||t&&!this.normalizeTitle(e.textContent).includes(t)?!1:!!e.querySelector('h1, [class*="title" i], [class*="authors" i], [class*="doi" i]')||!!Z(e.textContent)}findTitleElement(e){const t=Array.from(document.querySelectorAll(["h1",'[class*="article-title" i]','[class*="ArticleTitle" i]','[class*="title" i]'].join(","))).filter(n=>!this.isHiddenUiElement(n)).filter(n=>m(n.textContent).length>0);if(e){const n=t.find(i=>this.normalizeTitle(i.textContent)===e);if(n)return n;const a=t.find(i=>{const o=this.normalizeTitle(i.textContent);return o.includes(e)||e.includes(o)});if(a)return a}return t.at(0)??null}extractTitle(e){return this.normalizeTitle(F(["citation_title","dc.title","DC.Title","wkhealth_title","og:title"])??e.querySelector("h1")?.textContent??e.querySelector('[class*="article-title" i], [class*="ArticleTitle" i]')?.textContent,!1)}normalizeTitle(e,t=!0){const n=m(e).replace(/\s*:\s*(?:Anesthesia\s*(?:&|and)\s*Analgesia|A\s*&\s*A\s*Practice|LWW|Ovid|Wolters Kluwer).*$/i,"").replace(/\s*\|\s*(?:LWW|Ovid|Wolters Kluwer).*$/i,"");return t?n.replace(/[^\p{L}\p{N}]+/gu," ").toLowerCase().trim():n}extractAuthors(e){return U(Array.from(e.querySelectorAll(['[class*="authors" i] a','[class*="authors" i]','[class*="author-list" i] a','[class*="author" i] a','[class*="author-name" i]'].join(","))).map(t=>m(t.textContent)).filter(t=>t.length>1&&!/author information|affiliation|correspondence|view all/i.test(t)))}extractMetaAuthors(){const e=Je("citation_author");if(e.length>0)return e;const t=m(F(["wkhealth_authors"]));return t?U(t.split(";").map(n=>m(n)).filter(Boolean)):[]}extractJournalFromDom(e){const t=m(e.querySelector(['[class*="journal-title" i]','[class*="journalTitle" i]','[class*="publication-title" i]',".ej-journal-name",'[data-testid*="journal" i]',"cite i"].join(","))?.textContent);return t?this.normalizeJournalName(t):this.extractJournalFromCitationText(e.textContent)}extractJournalFromCitationText(e){const t=m(e);if(!t)return;const n=Object.keys(Zu).find(i=>new RegExp(`\\b${this.escapeRegExp(i).replace(/&/g,"(?:&|and)")}\\b`,"i").test(t));if(n)return n;const a=t.match(/\b([A-Z][A-Za-z&' -]+(?:\s+[A-Z][A-Za-z&' -]+)*)\.?\s+\d{1,4}\s*\(\d+\)\s*:\s*(?:p\s*)?\d+/);return a?this.normalizeJournalName(a[1]):void 0}normalizeJournalName(e){const t=m(e).replace(/\.$/,"").replace(/\s*\|\s*.*$/,"");if(t)return/^anesthesia\s*(?:&|and)\s*analgesia$/i.test(t)?"Anesthesia & Analgesia":/^a\s*&\s*a\s+practice$/i.test(t)?"A&A Practice":t}buildJournalCandidates(...e){const t=[],n=a=>{const i=m(a);if(!i)return;const o=this.normalizeJournalName(i)??i;t.push(i),t.push(o),t.push(...Zu[o]??[])};return e.forEach(n),U(t)}journalFromUrl(e){const t=B(e);if(!t)return;const n=new URL(t);if(n.hostname!=="journals.lww.com")return;const a=n.pathname.split("/").filter(Boolean).at(0)?.toLowerCase();if(!(!a||a.startsWith("10.")))return Bx[a]??this.slugToTitle(a)}slugToTitle(e){return e.split("-").filter(Boolean).map(t=>t.length<=3?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}extractDoiFromUrl(e){const t=B(e);if(!t)return;const n=new URL(t);return n.hostname==="journals.lww.com"&&/^\/10\./i.test(n.pathname)?Ne(decodeURIComponent(n.pathname.slice(1))):Ne(n.pathname)}extractNativeFullTextUrl(e,t){const n=B(F(["citation_pdf_url"],e))??B(F(["citation_pdf_url","wkhealth_pdf_url"]));if(n)return n;const a=B(e.querySelector("[data-pdf-url]")?.dataset.pdfUrl);if(a)return a;const i=B(e.querySelector('a[href$=".pdf"], a[href*=".pdf?"]')?.getAttribute("href"));if(i)return i;const o=B(e.querySelector('a[href*="/fulltext/"]')?.getAttribute("href"));if(o)return o;const s=B(F(["wkhealth_fulltext_html_url","citation_fulltext_html_url"]));if(s)return s;const l=B(t);if(!l)return;const c=new URL(l);if(c.hostname==="journals.lww.com"){if(/\/fulltext\//i.test(c.pathname)||/^\/10\./i.test(c.pathname))return c.href;if(/\/abstract\//i.test(c.pathname))return c.pathname=c.pathname.replace(/\/abstract\//i,"/fulltext/"),c.href}}extractNativeExportUrls(e){const t=B(Array.from(e.querySelectorAll("a[href]")).find(n=>/end\s*note|procite|reference\s*manager|ris/i.test(m(n.textContent)+" "+n.href))?.getAttribute("href"));return t?{ris:t}:void 0}extractAbstract(e){return m(F(["citation_abstract","description","og:description"])??F(["Description"])??je(e))||void 0}extractArticleTypes(e){return U(Array.from(e.querySelectorAll([".ejp-r-article-subsection__text",'[class*="article-type" i]','[class*="ArticleType" i]','[class*="classification" i]','[class*="category" i]'].join(","))).map(t=>m(t.textContent)).concat([m(F(["wkhealth_toc_section"])),m(F(["wkhealth_toc_sub_section"]))]).filter(t=>t.length>0&&t.length<80))}extractPages(e){const t=m(F(["citation_firstpage","wkhealth_firstpage"])),n=m(F(["citation_lastpage"]));return t&&n&&t!==n?`${t}-${n}`:this.extractVolumeIssuePages(e).pages??(t||void 0)}extractVolumeIssuePages(e){const t=m(e.textContent),n=t.match(/\b\d{4}\s*;\s*(\d+)\s*\(([^)]+)\)\s*:\s*(?:p\s*)?([A-Za-z0-9-]+)\b/)??t.match(/\b(\d+)\s*\(([^)]+)\)\s*:\s*(?:p\s*)?([A-Za-z0-9-]+)\b/);return{volume:n?.[1],issue:n?.[2],pages:n?.[3]}}findDetailCitationAnchor(e){const t=this.findFirstVisible(e,["#article-journal-info",".ej-journal-info"]);if(t)return t;const n=e.querySelector("h1");return U(Array.from(e.querySelectorAll("p, div, span, cite, header, section")).map(i=>this.normalizeAnchorElement(i,e)).filter(i=>!this.isHiddenUiElement(i)).filter(i=>!i.closest('[class^="paperlens-"], [class*=" paperlens-"]')).filter(i=>!n||this.isAfter(i,n)).filter(i=>this.isDetailAnchorCandidate(i))).sort((i,o)=>this.scoreDetailAnchor(o)-this.scoreDetailAnchor(i)).at(0)??this.findAnchorByPriority(e,Rx)}isDetailAnchorCandidate(e){const t=m(e.textContent);return e.matches("article, main, body")||!t||t.length>360||e.querySelector("h1, h2, h3, h4, nav, table, form")?!1:!!(Z(t)||/\bdoi\b/i.test(t)||/\b(?:accepted|published)\b/i.test(t)||this.extractJournalFromCitationText(t))}scoreDetailAnchor(e){const t=m(e.textContent);let n=0;return(Z(t)||/\bdoi\b/i.test(t))&&(n+=100),this.extractJournalFromCitationText(t)&&(n+=70),/\b(?:accepted|published)\b/i.test(t)&&(n+=45),/\b\d{4}\s*;\s*\d+\s*\([^)]+\)\s*:/i.test(t)&&(n+=35),/(citation|doi|accepted|published|article-meta|article-info)/i.test(e.getAttribute("class")??"")&&(n+=30),n-=Math.min(t.length,360)/30,n}findAnchorByPriority(e,t){for(const n of t){const a=Array.from(e.querySelectorAll(n)).map(i=>this.normalizeAnchorElement(i,e)).filter(i=>!this.isHiddenUiElement(i)).filter(i=>!i.matches("article, main, body")).filter(i=>!i.closest('[class^="paperlens-"], [class*=" paperlens-"]')).filter(i=>m(i.textContent).length>0).at(-1);if(a)return a}return null}normalizeAnchorElement(e,t){let n=e;for(;n.parentElement&&n.parentElement!==t;){const a=n.parentElement;if(a.matches("article, main, body"))break;const i=m(a.textContent);if(i.length>360)break;const o=m(n.textContent);if(!o||!i.includes(o))break;n=a}return n}findFirstVisible(e,t){for(const n of t){const a=Array.from(e.querySelectorAll(n)).find(i=>!this.isHiddenUiElement(i)&&m(i.textContent).length>0);if(a)return a}return null}isHiddenUiElement(e){return!!e.closest(["[hidden]",'[aria-hidden="true"]',".hide",".hidden",".modal",".reveal-modal",".flyout",".popup",".toolbar",".sidebar",".right-rail",".related",".advertisement",'[role="dialog"]','[role="menu"]'].join(","))}isAfter(e,t){return!!(t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING)}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}}const Yu=/10\.\d{4,9}\/[^?#\s"'<>]+/i,Ku=[{key:"frontiers",name:"Frontiers",hosts:["frontiersin.org","www.frontiersin.org"],articlePath:/\/(?:journals\/[^/]+\/)?articles\/10\.\d{4,9}\/[^/]+\/full/i,searchPath:/\/search/i,searchQueryParams:["query","q"]},{key:"acs",name:"ACS Publications",hosts:["pubs.acs.org"],articlePath:/\/doi\/(?:full\/|abs\/|epdf\/|pdf\/)?10\.\d{4,9}\//i,searchPath:/\/action\/doSearch|\/toc\//i,searchQueryParams:["AllField","text1"],pdfUrl:r=>`https://pubs.acs.org/doi/pdf/${r}`},{key:"rsc",name:"Royal Society of Chemistry",hosts:["pubs.rsc.org"],articlePath:/\/en\/content\/article(?:landing|html|pdf)\/\d{4}\//i,searchPath:/\/en\/results|\/en\/search/i,searchQueryParams:["searchtext","q"]},{key:"aps",name:"American Physical Society",hosts:["journals.aps.org","link.aps.org"],articlePath:/\/(?:prl|pra|prb|prc|prd|pre|prresearch|prx|rmp|physics|prper)\/(?:abstract|pdf)\/10\.1103\/|\/doi\/10\.1103\//i,searchPath:/\/search/i,searchQueryParams:["q","query"],pdfUrl:(r,e)=>{const n=new URL(e).pathname.split("/").filter(Boolean).at(0);return n?`https://journals.aps.org/${n}/pdf/${r}`:void 0}},{key:"aip",name:"AIP Publishing",hosts:["pubs.aip.org"],articlePath:/\/[^/]+\/[^/]+\/article(?:-abstract|-pdf)?\/|\/doi\/(?:full\/|abs\/|pdf\/)?10\.1063\//i,searchPath:/\/search-results|\/action\/doSearch/i,searchQueryParams:["AllField","q"],pdfUrl:r=>`https://pubs.aip.org/doi/pdf/${r}`},{key:"iop",name:"IOPscience",hosts:["iopscience.iop.org"],articlePath:/\/article\/10\.\d{4,9}\//i,searchPath:/\/(?:nsearch|search)/i,searchQueryParams:["q","searchTerm","terms"],pdfUrl:r=>`https://iopscience.iop.org/article/${r}/pdf`},{key:"karger",name:"Karger",hosts:["karger.com","www.karger.com"],articlePath:/\/article\/doi\/10\.1159\//i,searchPath:/\/search-results|\/search/i,searchQueryParams:["q","search"],pdfUrl:r=>{const e=r.match(/10\.1159\/(\d+)/i)?.[1];return e?`https://karger.com/article-pdf/${e}`:void 0}},{key:"thieme",name:"Thieme Connect",hosts:["www.thieme-connect.de","thieme-connect.de","www.thieme-connect.com","thieme-connect.com"],articlePath:/\/products\/ejournals\/(?:abstract|html|pdf)\/10\.1055\//i,searchPath:/\/products\/ejournals\/search|\/search/i,searchQueryParams:["query","q"],pdfUrl:(r,e)=>`${new URL(e).origin}/products/ejournals/pdf/${r}.pdf`},{key:"jmir",name:"JMIR Publications",hosts:["jmir.org","www.jmir.org","mhealth.jmir.org","formative.jmir.org","medinform.jmir.org"],matches:["*://jmir.org/*","*://www.jmir.org/*","*://*.jmir.org/*"],defaultJournal:"Journal of Medical Internet Research",articlePath:/\/\d{4}\/\d+\/e\d+/i,searchPath:/\/search/i,searchQueryParams:["query","q"],pdfUrl:(r,e)=>`${new URL(e).origin}/api/download?alt_name=${r.replace("/","-")}.pdf`},{key:"annual-reviews",name:"Annual Reviews",hosts:["www.annualreviews.org","annualreviews.org"],articlePath:/\/content\/journals\/10\.1146\//i,searchPath:/\/search/i,searchQueryParams:["AllField","q"],pdfUrl:r=>`https://www.annualreviews.org/content/journals/${r}/pdf`},{key:"elife",name:"eLife",hosts:["elifesciences.org"],defaultJournal:"eLife",articlePath:/\/articles\/\d+/i,searchPath:/\/search/i,searchQueryParams:["q","for"],pdfUrl:(r,e)=>`${new URL(e).origin}${new URL(e).pathname}.pdf`},{key:"pnas",name:"PNAS",hosts:["pnas.org","www.pnas.org"],defaultJournal:"PROCEEDINGS OF THE NATIONAL ACADEMY OF SCIENCES OF THE UNITED STATES OF AMERICA",articlePath:/\/doi\/(?:full\/|abs\/|pdf\/)?10\.1073\/pnas\./i,searchPath:/\/action\/doSearch|\/search/i,searchQueryParams:["AllField","q"],pdfUrl:r=>`https://www.pnas.org/doi/pdf/${r}`},{key:"rup",name:"Rockefeller University Press",hosts:["rupress.org","www.rupress.org"],matches:["*://rupress.org/*","*://www.rupress.org/*","*://*.rupress.org/*"],articlePath:/\/(?:jcb|jem|rupress)\/article\/|\/doi\/10\.1083\//i,searchPath:/\/search-results|\/search/i,searchQueryParams:["q","AllField"],pdfUrl:r=>`https://rupress.org/jcb/article-pdf/doi/${r}`},{key:"csh-perspectives",name:"Cold Spring Harbor Perspectives",hosts:["cshperspectives.cshlp.org"],defaultJournal:"Cold Spring Harbor Perspectives in Biology",articlePath:/\/content\/|\/lookup\/doi\/10\.1101\/cshperspect\./i,searchPath:/\/search/i,searchQueryParams:["q","fulltext"],pdfUrl:(r,e)=>`${new URL(e).origin}${new URL(e).pathname}.full.pdf`},{key:"genes-dev",name:"Genes & Development",hosts:["genesdev.cshlp.org"],defaultJournal:"GENES & DEVELOPMENT",articlePath:/\/content\/|\/lookup\/doi\/10\.1101\/gad\./i,searchPath:/\/search/i,searchQueryParams:["q","fulltext"],pdfUrl:(r,e)=>`${new URL(e).origin}${new URL(e).pathname}.full.pdf`}],Qu=['a[href*="/doi/"]','a[href*="/abstract/10."]','a[href*="/article-abstract/"]','a[href*="/article-pdf/"]','a[href*="/articles/"]','a[href*="/article/"]','a[href*="/content/article"]','a[href*="/content/"]','a[href*="/20"][href*="/e"]','a[href*="/products/ejournals/abstract/"]','a[href*="/lookup/doi/"]'].join(","),Xu=["article",'li[class*="result" i]',".search-result",".search__item",".result-item",'[class*="search-result" i]'].join(","),qx=[".search-results","#search-results",'[aria-label*="Search" i]','[class*="results" i]',"main"].join(","),jx=[".ArticleDetailsV4__main",".ArticleDetailsV4",".ArticlePage","#main-content",'[role="main"]',"main article","main","article","body"],$x=['[class*="citation" i]','[class*="article-meta" i]','[class*="metadata" i]','[class*="publication" i]','[class*="doi" i]','a[href*="doi.org/10."]','[data-test*="citation" i]','[data-testid*="citation" i]'],Ox=['[class*="citation" i]','[class*="meta" i]','[class*="journal" i]','[class*="publication" i]','[class*="date" i]','[class*="author" i]'];class Ux extends j{id="publisher-network";name="Publisher Network";matches=Ku.flatMap(e=>e.matches??e.hosts.map(t=>`*://${t}/*`));isSearchPage(){if(le())return!1;const e=this.currentConfig();if(!e)return!1;const t=location.pathname.toLowerCase(),n=new URLSearchParams(location.search);return e.searchPath.test(t)||!!e.searchQueryParams?.some(a=>n.has(a))}isArticlePage(){if(le()||this.isSearchPage())return!1;const e=this.currentConfig();if(!e)return!1;const t=location.pathname;return e.articlePath.test(t)||!!(this.metaTitle()&&(this.metaDoi()||this.doiFromUrl(location.href)))}parseSearchResults(){const e=this.currentConfig();if(!e)return[];const t=[],n=new Set;for(const a of this.searchHosts()){const i=this.parseSearchHost(a,e);if(!i)continue;const o=i.doi??i.sourceId??i.url??i.title;n.has(o)||(n.add(o),t.push(i))}return t}parseArticlePage(){if(!this.isArticlePage())return null;const e=this.currentConfig();if(!e)return null;const t=this.detailHostElement(e);if(!t)return null;const n=this.cleanTitle(this.metaTitle()??t.querySelector("h1")?.textContent);if(!n)return null;const a=$n(),i=this.metaDoi()??this.doiFromUrl(a??location.href)??Z(t.textContent),o=m(F(["citation_publication_date","citation_online_date","prism.publicationDate","article:published_time","dc.Date","DC.Date"])),s=this.journalName(e,a,t);return{title:n,journalName:s,journalCandidates:this.journalCandidates(s,e),authors:this.metaAuthors().length?this.metaAuthors():this.extractAuthors(t),year:qe(o||t.textContent),publicationDate:o||void 0,doi:i,sourceId:i?`${e.key}:${i}`:a?`${e.key}:${a}`:void 0,url:a,nativeFullTextUrl:this.fullTextUrl(e,t,i,a??location.href),abstractSnippet:this.abstract(t),hostElement:t,articleTypes:this.articleTypes(t),issn:m(F(["citation_issn","prism.issn","dc.Identifier","DC.Identifier"]))||void 0,volume:m(F(["citation_volume","prism.volume"]))||void 0,issue:m(F(["citation_issue","prism.number"]))||void 0,pages:this.pages(),source:this.id,citationType:"article"}}getMetricBarAnchor(e){if(this.isArticlePage()){const a=this.currentConfig(),i=this.detailAnchor(e,a);if(i)return{element:i,position:"after"};const o=e.querySelector("h1");return o?{element:o,position:"after"}:{element:e,position:"prepend"}}const t=this.findAnchor(e,Ox);if(t)return{element:t,position:"after"};const n=e.querySelector('h2, h3, h4, [class*="title" i]');return n?{element:n,position:"after"}:{element:e,position:"prepend"}}getResultsContainer(){return document.querySelector(qx)??document.body}getPageInfo(){return{pageNum:Number.parseInt(new URLSearchParams(location.search).get("page")??"1",10)||1,totalPages:1,url:location.href}}currentConfig(){const e=location.hostname.toLowerCase();return Ku.find(t=>t.hosts.some(n=>e===n||e.endsWith(`.${n}`)))}detailHostElement(e){if(e&&["csh-perspectives","genes-dev"].includes(e.key)){const t=this.coldSpringHarborArticleRoot();if(t)return t}for(const t of jx){const n=document.querySelector(t);if(n)return n}return null}coldSpringHarborArticleRoot(){const e=[".article.fulltext-view",".article.abstract-view",".highwire-article","#content-block .article","#main-content .article","#article",".article"];return Array.from(document.querySelectorAll(e.join(","))).filter(t=>!this.isHidden(t)).find(t=>!!t.querySelector("h1, .article-title, #abstract-1, .section.abstract, .abstract"))??null}metaTitle(){return m(F(["citation_title","dc.title","DC.Title","og:title","twitter:title"]))||void 0}metaDoi(){return Ne(F(["citation_doi","prism.doi","dc.Identifier","DC.Identifier","doi"]))}metaAuthors(){return U([...Je("citation_author"),...Je("dc.Creator"),...Je("DC.Creator")])}doiFromUrl(e){const t=B(e);if(!t)return;const n=new URL(t),a=(n.pathname.match(Yu)?.[0]??n.search.match(Yu)?.[0])?.replace(/\/(?:full|abstract|html|pdf)$/i,"");return Ne(a?decodeURIComponent(a):void 0)}journalName(e,t,n){const a=m(F(["citation_journal_title","prism.publicationName","dc.Source","DC.Source"]));if(a)return this.normalizeJournal(a,e);const i=B(t);if(i&&e.journalFromUrl){const s=e.journalFromUrl(new URL(i));if(s)return s}const o=m(n.querySelector(['[class*="journal-title" i]','[class*="publication-title" i]','[data-testid*="journal" i]',"cite i"].join(","))?.textContent);return o?this.normalizeJournal(o,e):e.defaultJournal??e.name}normalizeJournal(e,t){const n=m(e).replace(/^Frontiers\s+\|\s*/i,"").replace(/\s*\|\s*.*$/,"").replace(/&amp;/g,"&");return/^pnas$/i.test(n)?"PROCEEDINGS OF THE NATIONAL ACADEMY OF SCIENCES OF THE UNITED STATES OF AMERICA":/^jcb$/i.test(n)?"JOURNAL OF CELL BIOLOGY":/^jmir$/i.test(n)?"Journal of Medical Internet Research":n||t.defaultJournal||t.name}journalCandidates(e,t){const n=[e,t.defaultJournal];return t.key==="pnas"&&n.push("PNAS"),t.key==="rup"&&n.push("Journal of Cell Biology","JCB"),t.key==="genes-dev"&&n.push("Genes and Development"),t.key==="acs"&&n.push("J Am Chem Soc","Journal of the American Chemical Society"),t.key==="iop"&&n.push("JOURNAL OF PHYSICS D-APPLIED PHYSICS"),t.key==="annual-reviews"&&n.push("Annual Review of Medicine"),t.key==="rsc"&&n.push("Chemical Science"),U(n.filter(Boolean))}fullTextUrl(e,t,n,a){const i=B(F(["citation_pdf_url","citation_fulltext_html_url"]));if(i)return i;const o=B(t.querySelector(['a[href$=".pdf"]','a[href*=".pdf?"]','a[href*="/pdf/"]','a[href*="articlepdf"]','a[href*="downloadpdf"]'].join(","))?.getAttribute("href"));if(o)return o;if(n&&e.pdfUrl)return e.pdfUrl(n,a)}abstract(e){return m(F(["citation_abstract","description","og:description"])??je(e))||void 0}articleTypes(e){return U(Array.from(e.querySelectorAll(['[class*="article-type" i]','[class*="classification" i]','[data-testid*="article-type" i]'].join(","))).map(t=>m(t.textContent)).filter(t=>t.length>0&&t.length<80))}pages(){const e=m(F(["citation_firstpage","prism.startingPage"])),t=m(F(["citation_lastpage","prism.endingPage"]));return e&&t&&e!==t?`${e}-${t}`:e||void 0}searchHosts(){const e=Array.from(document.querySelectorAll(Qu)).map(n=>n.closest(Xu)??n.parentElement).filter(n=>!!n),t=Array.from(document.querySelectorAll(Xu));return U([...e,...t].filter(n=>this.looksLikeSearchResult(n)))}looksLikeSearchResult(e){return e.closest('[class^="paperlens-"], [class*=" paperlens-"]')?!1:!!this.findArticleLink(e)}parseSearchHost(e,t){const n=this.findArticleLink(e),a=this.cleanTitle(n?.textContent??e.querySelector('h2, h3, h4, [class*="title" i]')?.textContent);if(!a)return null;const i=B(n?.getAttribute("href")),o=this.doiFromUrl(i)??Z(e.textContent),s=this.journalName(t,i,e);return{title:a,journalName:s,journalCandidates:this.journalCandidates(s,t),authors:this.extractAuthors(e),year:qe(e.textContent),doi:o,sourceId:o?`${t.key}:${o}`:i?`${t.key}:${i}`:void 0,url:i,nativeFullTextUrl:this.fullTextUrl(t,e,o,i??location.href),abstractSnippet:this.abstract(e),hostElement:e,articleTypes:this.articleTypes(e),source:this.id,citationType:"article"}}findArticleLink(e){return Array.from(e.querySelectorAll(Qu)).find(t=>{const n=t.getAttribute("href")??"",a=m(t.textContent);return a.length>4&&!/\.pdf(?:[?#]|$)|download|citation|subscribe|login/i.test(n+" "+a)})??null}extractAuthors(e){return U(Array.from(e.querySelectorAll(['[class*="authors" i] a','[class*="author" i] a','[class*="author-name" i]','[data-testid*="author" i]'].join(","))).map(t=>m(t.textContent)).filter(t=>t.length>1&&!/author information|affiliation|view all|correspondence/i.test(t)))}cleanTitle(e){return m(e).replace(/^Frontiers\s+\|\s*/i,"").replace(/\s*\|\s*(?:Frontiers|ACS Publications|RSC Publishing|eLife|PNAS|Annual Reviews).*$/i,"").replace(/\s*-\s*(?:Chemical Science|Thieme E-Journals).*$/i,"")}detailAnchor(e,t){const n=t?this.siteSpecificDetailAnchor(e,t):null;if(n)return n;const a=e.querySelector("h1");return U(Array.from(e.querySelectorAll("p, div, span, section, header")).filter(o=>!this.isHidden(o)).filter(o=>!o.closest('[class^="paperlens-"], [class*=" paperlens-"]')).filter(o=>!a||!!(a.compareDocumentPosition(o)&Node.DOCUMENT_POSITION_FOLLOWING)).filter(o=>this.isCitationCandidate(o))).sort((o,s)=>this.scoreAnchor(s)-this.scoreAnchor(o)).map(o=>this.blockAnchor(o,e)).at(0)??this.findAnchor(e,$x)}siteSpecificDetailAnchor(e,t){switch(t.key){case"aps":return this.findDoiLineAnchor(e,[/10\.1103\//i])??this.findPublicationLineAnchor(e);case"pnas":return this.findTitleAnchor(e)??this.findPnasMetaAnchor(e)??this.findPublicationLineAnchor(e)??null;case"thieme":return this.findTitleAnchor(e);case"frontiers":return this.findFrontiersHeaderAnchor(e)??this.findTitleAnchor(e);case"acs":case"elife":return this.findTitleAnchor(e)??this.findDoiLineAnchor(e)??this.findPublicationLineAnchor(e);case"aip":case"iop":case"annual-reviews":case"rup":return this.findDoiLineAnchor(e)??this.findPublicationLineAnchor(e)??this.findTitleAnchor(e);case"csh-perspectives":case"genes-dev":return this.findColdSpringHarborHeaderAnchor(e)??this.findDoiLineAnchor(e,[/10\.1101\//i])??this.findPublicationLineAnchor(e)??this.findTitleAnchor(e);default:return null}}findPnasMetaAnchor(e){const t=this.findDoiLineAnchor(e,[/10\.1073\/pnas\./i]);if(!t)return null;const n=t.closest("p, div, section, header, li");return!n||n===e||n.matches("article, main, body")?t:n}findColdSpringHarborHeaderAnchor(e){const t=e.querySelector("#abstract-1, .section.abstract, .abstract, h2"),n=this.findTitleAnchor(e);return Array.from(e.querySelectorAll("p, div")).filter(i=>!this.isHidden(i)).filter(i=>!i.closest('[class^="paperlens-"], [class*=" paperlens-"]')).filter(i=>!(n&&!(n.compareDocumentPosition(i)&Node.DOCUMENT_POSITION_FOLLOWING)||t&&!(t.compareDocumentPosition(i)&Node.DOCUMENT_POSITION_PRECEDING))).filter(i=>{const o=m(i.textContent);return!o||o.length>320||i.querySelector("h1, h2, h3, h4, nav, form")?!1:/10\.1101\/|doi\s*:|Genes\s*&?\s*Development|Cold Spring Harb|Cold Spring Harbor|Correspondence/i.test(o)}).map(i=>this.blockAnchor(i,e)).filter((i,o,s)=>s.indexOf(i)===o).at(-1)??null}findFrontiersHeaderAnchor(e){const t=e.querySelector("h1"),n=Array.from(e.querySelectorAll(['[class*="doiVolume" i]','[class*="doi-volume" i]','[class*="ArticleLayoutHeader__info__doi" i]','a[href*="doi.org/10.3389/"]'].join(","))).filter(a=>!this.isHidden(a)).filter(a=>!t||!!(t.compareDocumentPosition(a)&Node.DOCUMENT_POSITION_PRECEDING)).map(a=>this.blockAnchor(a,e)).find(a=>/10\.3389\//i.test(m(a.textContent)));return n||this.findTextLineAnchor(e,a=>/10\.3389\//i.test(a),{relativeToTitle:"before"})}findTitleAnchor(e){return Array.from(e.querySelectorAll(["h1",'[class*="article-title" i]','[class*="ArticleTitle" i]','[data-testid*="title" i]'].join(","))).filter(t=>!this.isHidden(t)).find(t=>m(t.textContent).length>0)??null}findDoiLineAnchor(e,t=[]){const n=t.length>0?t:[/10\.\d{4,9}\//i,/\bdoi\b/i];return this.findTextLineAnchor(e,(a,i)=>{if(!n.some(o=>o.test(a)))return!1;if(/download|citation|export|references|share|permissions|metrics/i.test(a)){const o=i.getAttribute("class")??"";if(!/(doi|citation|article-meta|publication|meta)/i.test(o))return!1}return!0},{preferInnermost:!0})}findPublicationLineAnchor(e){return this.findTextLineAnchor(e,(t,n)=>{if(!/\b(?:vol(?:ume)?|issue|published|accepted)\b/i.test(t)||t.length>420)return!1;const a=n.getAttribute("class")??"";return/(citation|article-meta|metadata|publication|date|history|volume|issue)/i.test(a)||/\b(?:published|accepted)\b/i.test(t)})}findTextLineAnchor(e,t,n={}){const a=n.relativeToTitle??"after",i=e.querySelector("h1"),o=Array.from(e.querySelectorAll("p, div, span, section, header, li")).filter(l=>!this.isHidden(l)).filter(l=>!l.closest('[class^="paperlens-"], [class*=" paperlens-"]')).filter(l=>!l.matches("article, main, body, nav, aside, form")).filter(l=>{if(!i||a==="any")return!0;const c=i.compareDocumentPosition(l);return a==="before"?!!(c&Node.DOCUMENT_POSITION_PRECEDING):!!(c&Node.DOCUMENT_POSITION_FOLLOWING)}).map(l=>this.blockAnchor(l,e)).filter((l,c,u)=>u.indexOf(l)===c).filter(l=>{const c=m(l.textContent);return!c||c.length>520||l.querySelector("h1, h2, h3, h4, nav, form")?!1:t(c,l)});return(n.preferInnermost?o.filter(l=>!o.some(c=>c!==l&&l.contains(c))):o).sort((l,c)=>this.scoreAnchor(c)-this.scoreAnchor(l)).at(0)??null}blockAnchor(e,t){if(!/^(a|span|strong|em|b|i|small|sup|sub)$/i.test(e.tagName)||e.matches('span[class*="doi" i], span[class*="citation" i], span[class*="meta" i]'))return e;const n=e.closest("p, div, section, header, li");return!n||n===t||n.matches("article, main, body")?e:n}isCitationCandidate(e){const t=m(e.textContent);return!t||t.length>360||e.matches("article, main, body")||e.querySelector("h1, h2, h3, h4, nav, form")?!1:!!(Z(t)||/\bdoi\b/i.test(t)||/\b(?:vol(?:ume)?|issue|published|accepted)\b/i.test(t))}scoreAnchor(e){const t=m(e.textContent);let n=0;return(Z(t)||/\bdoi\b/i.test(t))&&(n+=90),/\b(?:vol(?:ume)?|issue|\d+\(\d+\)|published|accepted)\b/i.test(t)&&(n+=45),/(citation|doi|meta|publication|volume|issue)/i.test(e.getAttribute("class")??"")&&(n+=30),n-=Math.min(t.length,360)/30,n}findAnchor(e,t){for(const n of t){const a=Array.from(e.querySelectorAll(n)).filter(i=>!this.isHidden(i)).filter(i=>m(i.textContent).length>0).at(-1);if(a)return a}return null}isHidden(e){return!!e.closest(["[hidden]",'[aria-hidden="true"]',".hidden",".hide",".modal",".popup",".toolbar",'[role="dialog"]','[role="menu"]'].join(","))}}const Hx={nejm:"New England Journal of Medicine","n engl j med":"New England Journal of Medicine","new engl j med":"New England Journal of Medicine",jama:"JAMA-JOURNAL OF THE AMERICAN MEDICAL ASSOCIATION",bmj:"BMJ","br med j":"BMJ","nat commun":"Nature Communications","nat med":"Nature Medicine","nat genet":"Nature Genetics","nat methods":"Nature Methods","nat biotechnol":"Nature Biotechnology","nat cell biol":"Nature Cell Biology","nat immunol":"Nature Immunology","nat neurosci":"Nature Neuroscience","nat rev cancer":"Nature Reviews Cancer","nat rev immunol":"Nature Reviews Immunology","nat rev drug discov":"Nature Reviews Drug Discovery","nat rev genet":"Nature Reviews Genetics","nat rev mol cell biol":"Nature Reviews Molecular Cell Biology","nat rev microbiol":"Nature Reviews Microbiology","nat rev clin oncol":"Nature Reviews Clinical Oncology","nat rev endocrinol":"Nature Reviews Endocrinology","nat struct mol biol":"Nature Structural & Molecular Biology","nat protoc":"Nature Protocols","nat chem biol":"Nature Chemical Biology","nat microbiol":"Nature Microbiology","nat aging":"Nature Aging","nat cancer":"Nature Cancer","sci adv":"Science Advances","sci transl med":"Science Translational Medicine","cell metab":"Cell Metabolism","cell stem cell":"Cell Stem Cell","mol cell":"Molecular Cell","cancer cell":"Cancer Cell","cell rep":"Cell Reports","cell rep med":"Cell Reports Medicine","cancer res":"Cancer Research","cancer discov":"Cancer Discovery","cancer prev res":"Cancer Prevention Research","j clin oncol":"Journal of Clinical Oncology",jco:"Journal of Clinical Oncology","ann oncol":"Annals of Oncology","ca cancer j clin":"CA-A Cancer Journal for Clinicians","clin cancer res":"Clinical Cancer Research","j natl cancer inst":"JNCI-Journal of the National Cancer Institute","br j cancer":"British Journal of Cancer","eur j cancer":"European Journal of Cancer","j egypt natl canc inst":"Journal of the Egyptian National Cancer Institute","j egypt natl cancer inst":"Journal of the Egyptian National Cancer Institute","mol cancer":"Molecular Cancer",oncogene:"Oncogene","j hematol oncol":"Journal of Hematology & Oncology","am j gastroenterol":"American Journal of Gastroenterology","lancet gastroenterol hepatol":"Lancet Gastroenterology & Hepatology","aliment pharmacol ther":"Alimentary Pharmacology & Therapeutics","inflamm bowel dis":"Inflammatory Bowel Diseases","lancet oncol":"Lancet Oncology","lancet neurol":"Lancet Neurology","lancet psychiatry":"Lancet Psychiatry","lancet diab endocrinol":"Lancet Diabetes & Endocrinology","lancet respir med":"Lancet Respiratory Medicine","lancet infect dis":"Lancet Infectious Diseases","lancet glob health":"Lancet Global Health","lancet public health":"Lancet Public Health","int j epidemiol":"International Journal of Epidemiology","am j epidemiol":"American Journal of Epidemiology","am j public health":"American Journal of Public Health","j exp med":"Journal of Experimental Medicine","j immunol":"Journal of Immunology","j am coll cardiol":"Journal of the American College of Cardiology","eur heart j":"European Heart Journal",circulation:"Circulation",blood:"Blood","am j respir crit care med":"American Journal of Respiratory and Critical Care Medicine",chest:"Chest",thorax:"Thorax",brain:"Brain","diabetes care":"Diabetes Care","j clin invest":"Journal of Clinical Investigation",jci:"Journal of Clinical Investigation",pnas:"PNAS","proc natl acad sci u s a":"PNAS","proc natl acad sci":"PNAS","plos med":"PLOS Medicine","plos one":"PLOS ONE","plos biol":"PLOS Biology","bmc med":"BMC Medicine","sci rep":"Scientific Reports",elife:"eLife","front med":"Frontiers in Medicine","int j mol sci":"International Journal of Molecular Sciences","genome med":"Genome Medicine","gut microbes":"Gut Microbes",hepatology:"Hepatology","j hepatol":"Journal of Hepatology",ebiomedicine:"EBioMedicine",theranostics:"Theranostics","signal transduct target ther":"Signal Transduction and Targeted Therapy","ann intern med":"Annals of Internal Medicine","jama oncol":"JAMA Oncology","jama intern med":"JAMA Internal Medicine","jama cardiol":"JAMA Cardiology","jama neurol":"JAMA Neurology","pharmacol rev":"Pharmacological Reviews","physiol rev":"Physiological Reviews"};function un(r){return r.toLowerCase().replace(/[.,;:'\-&]/g," ").replace(/\s+/g," ").replace(/^the\s+/,"").trim()}function zx(r){const e=un(r);return Hx[e]??null}function Xa(r){return r.startsWith("/")?r:`/${r}`}function Jx(r){return Xa(r).replace(/\.json$/i,".index.json")}function Xo(r,e){if(e.startsWith("/"))return e;const t=r.slice(0,r.lastIndexOf("/")+1);return Xa(`${t}${e}`)}async function Ir(r){const e=await fetch(I.runtime.getURL(Xa(r)));if(!e.ok)throw new Error(`Failed to load ${r}: HTTP ${e.status}`);return await e.json()}function Vx(r){if(!r||typeof r!="object")return!1;const e=r;return e.split===!0&&Array.isArray(e.parts)&&(e.format==="array-property"||e.format==="record-property"||e.format==="record")}async function Wx(r,e){const t=Jx(r);let n;try{const i=await Ir(t);if(!Vx(i))throw new Error(`Invalid split index: ${t}`);n=i}catch(i){throw e instanceof Error?e:i}if(n.format==="array-property"){if(!n.property)throw new Error(`Split array JSON is missing property: ${t}`);const i=[];for(const o of n.parts){const l=(await Ir(Xo(t,o)))[n.property];if(!Array.isArray(l))throw new Error(`Split JSON chunk is missing array property ${n.property}: ${o}`);i.push(...l)}return{...n.meta??{},[n.property]:i}}if(n.format==="record-property"){if(!n.property)throw new Error(`Split record JSON is missing property: ${t}`);const i={};for(const o of n.parts){const l=(await Ir(Xo(t,o)))[n.property];if(!l||typeof l!="object"||Array.isArray(l))throw new Error(`Split JSON chunk is missing record property ${n.property}: ${o}`);Object.assign(i,l)}return{...n.meta??{},[n.property]:i}}const a={};for(const i of n.parts){const o=await Ir(Xo(t,i));Object.assign(a,o)}return{...n.meta??{},...a}}async function Mr(r){const e=Xa(r);try{return await Ir(e)}catch(t){return await Wx(e,t)}}function ed(){return"chrome"}function qr(r=ed()){return r==="safari"}function td(r=ed()){return qr(r)?"\u8BF7\u5728 PaperLens Safari App \u5185\u901A\u8FC7 App Store \u5F00\u901A\uFF0C\u6216\u767B\u5F55\u5DF2\u8D2D\u8D26\u53F7\u540E\u4F7F\u7528":"\u8BF7\u5728\u5B98\u7F51\u5F00\u901A\u540E\u4F7F\u7528"}const nd="__paperlensRuntimeRequestId";let es=0;const Gx=Zx();function Zx(){const r=globalThis.crypto;if(typeof r?.randomUUID=="function")return r.randomUUID();if(typeof r?.getRandomValues=="function"){const e=new Uint32Array(4);return r.getRandomValues(e),Array.from(e,t=>t.toString(36)).join("-")}return Math.random().toString(36).slice(2)}function rd(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function ad(r){if(!rd(r))return null;const e=r[nd];return typeof e=="string"&&e?e:null}function id(r){if(!rd(r)||ad(r))return r;es=(es+1)%Number.MAX_SAFE_INTEGER;const e=`${Gx}-${Date.now().toString(36)}-${es.toString(36)}`;return{...r,[nd]:e}}const Yx=7e3,ts="runtime message returned empty response";function Kx(){if(!qr())return null;const r=globalThis.chrome?.runtime;return typeof r?.sendMessage=="function"?r:null}function Qx(){if(!qr())return null;const r=I.runtime;return typeof r?.sendMessage=="function"?r:null}function od(r,e){return new Promise((t,n)=>{try{const a=r.sendMessage?.(e,i=>{const o=r.lastError;if(o){n(new Error(o.message||"runtime message failed"));return}if(i===void 0){n(new Error(ts));return}t(i)});a&&typeof a.then=="function"&&a.then(i=>{if(i===void 0){n(new Error(ts));return}t(i)}).catch(n)}catch(a){n(a)}})}async function sd(r){const e=await I.runtime.sendMessage(r);if(e===void 0)throw new Error(ts);return e}function Xx(r){return r.length===0?Promise.reject(new Error("runtime message unavailable")):r.length===1?r[0]:new Promise((e,t)=>{let n=r.length,a;for(const i of r)i.then(e).catch(o=>{a=o,n-=1,n===0&&t(a instanceof Error?a:new Error(String(a)))})})}function e0(r){if(!qr())return null;const e=id(r),t=[],n=Kx();n&&t.push(od(n,e));const a=Qx();return a&&t.push(od(a,e)),typeof I.runtime?.sendMessage=="function"&&t.push(sd(e)),Xx(t)}async function t0(r){const e=e0(r);return e||sd(r)}function H(r,e=Yx){return new Promise((t,n)=>{let a=!1;const i=window.setTimeout(()=>{a||(a=!0,n(new Error("runtime message timed out")))},e);t0(r).then(o=>{a||(a=!0,window.clearTimeout(i),t(o))}).catch(o=>{a||(a=!0,window.clearTimeout(i),n(o))})})}const n0="paperlens-journals",r0=1,On="journals",a0="__meta__",ld="__data__",i0=2e3,jr="https://api.litlink.cc/api/v1".replace(/\/+$/,""),o0=10080*60*1e3,s0=[["science"],["jncijournalofthenationalcancerinstitute","journalofthenationalcancerinstitute"],["surgicalclinicsofnorthamerica"]];function ns(){return typeof globalThis.indexedDB<"u"}function cd(){return new Promise((r,e)=>{if(!ns()){e(new Error("IndexedDB is not available"));return}const t=globalThis.indexedDB.open(n0,r0);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(On)||n.createObjectStore(On)},t.onsuccess=()=>r(t.result),t.onerror=()=>e(t.error)})}function l0(r){return ns()?cd().then(e=>new Promise((t,n)=>{const o=e.transaction(On,"readonly").objectStore(On).get(r);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})):Promise.resolve(void 0)}function ud(r,e){return ns()?cd().then(t=>new Promise((n,a)=>{const s=t.transaction(On,"readwrite").objectStore(On).put(e,r);s.onsuccess=()=>n(),s.onerror=()=>a(s.error)})):Promise.resolve()}function c0(){return jr.startsWith("http://")&&typeof window<"u"&&window.location.protocol==="https:"&&typeof I<"u"&&!!I.runtime?.sendMessage}async function dd(r,e){if(!jr)return null;if(c0()){const n=await H({type:"FETCH_BACKEND_JSON",payload:{path:r,timeoutMs:e}},e+i0);return!n?.success||!n.data?null:n.data}const t=await fetch(`${jr}${r}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(e)});return t.status===304?{ok:t.ok,status:t.status,data:null}:{ok:t.ok,status:t.status,data:await t.json()}}async function u0(){if(!jr)return null;try{const r=await dd("/journals/meta",5e3);return!r?.ok||!r.data?null:r.data}catch{return null}}async function d0(){if(!jr)return null;try{const r=await u0();if(!r)return null;const e=await pd();if(e&&e.versionHash===r.version_hash)return{version_hash:r.version_hash,journals:e.journals};const t=await dd(`/journals?version_hash=${encodeURIComponent(r.version_hash)}`,3e4);if(!t)return null;if(t.status===304)return e?{version_hash:r.version_hash,journals:e.journals}:null;if(!t.ok)return null;const n=t.data;if(!n)return null;const a=Array.isArray(n)?n:n.journals??[];return await ud(ld,{versionHash:r.version_hash,journals:a,cachedAt:Date.now()}),await ud(a0,{versionHash:r.version_hash,total:r.total,updatedAt:r.updated_at}),{version_hash:r.version_hash,journals:a}}catch{return null}}async function p0(){return{journals:(await Mr("/data/journals.json")).journals}}async function h0(){try{return await Mr("/data/emerging-journal-partitions.json")}catch{return null}}async function pd(){return l0(ld)}function dn(r){return un(r??"").replace(/\s+/g,"")}function hd(r){const e=r?.replace(/[^0-9Xx]/g,"").toUpperCase()??"";return/^\d{7}[\dX]$/.test(e)?e:""}function Un(r,e,t){!e||r.has(e)||r.set(e,t)}function f0(r,e){const t=e?.journals??[];if(t.length===0)return r;const n=r.map(o=>({...o})),a=new Map,i=new Map;n.forEach((o,s)=>{Un(a,dn(o.normalizedName),s),Un(a,dn(o.journalName),s);for(const l of o.issn??[])Un(i,hd(l),s)});for(const o of t){const s=(o.issn??[]).map(hd).filter(Boolean),l=dn(o.normalizedName||o.journalName);let c=a.get(l);if(c===void 0){for(const h of s)if(c=i.get(h),c!==void 0)break}const u={emergingQuartile:o.emergingQuartile,emergingTop:o.emergingTop===!0,emergingCategory:o.category,emergingSource:e?.version?`\u65B0\u9510\u5206\u533A ${e.version}`:"\u65B0\u9510\u5206\u533A"};if(c!==void 0){const h=n[c];n[c]={...h,emergingQuartile:h.emergingQuartile??u.emergingQuartile,emergingTop:h.emergingTop??u.emergingTop,emergingCategory:h.emergingCategory??u.emergingCategory,emergingSource:h.emergingSource??u.emergingSource};continue}const d={journalName:o.journalName,normalizedName:o.normalizedName||l,issn:o.issn??[],jcrQuartile:"N/A",category:o.category?[o.category]:[],year:Number(e?.version)||new Date().getUTCFullYear(),source:"cas",...u},p=n.length;n.push(d),Un(a,dn(d.normalizedName),p),Un(a,dn(d.journalName),p);for(const h of s)Un(i,h,p)}return n}async function ei(r){const e=await h0();return f0(r,e)}function fd(r){const e=new Set;for(const t of r)e.add(dn(t.normalizedName)),e.add(dn(t.journalName));return s0.every(t=>t.some(n=>e.has(n)))}async function m0(){const r=await d0();if(r&&r.journals.length>0&&fd(r.journals))return{source:"server",journals:await ei(r.journals)};const e=await pd();if(e&&e.journals.length>0&&Date.now()-e.cachedAt<o0&&fd(e.journals))return{source:"cache",journals:await ei(e.journals)};try{const t=await p0();return{source:"builtin",journals:await ei(t.journals)}}catch{return e&&e.journals.length>0?{source:"cache",journals:await ei(e.journals)}:{source:"builtin",journals:[]}}}function b0(r,e){if(r===e)return 0;if(r.length===0)return e.length;if(e.length===0)return r.length;r.length>e.length&&([r,e]=[e,r]);const t=r.length,n=e.length;let a=Array.from({length:t+1},(i,o)=>o);for(let i=1;i<=n;i++){const o=new Array(t+1);o[0]=i;for(let s=1;s<=t;s++){const l=r[s-1]===e[i-1]?0:1;o[s]=Math.min(o[s-1]+1,a[s]+1,a[s-1]+l)}a=o}return a[t]}let rs=null,$r=null,Or=null;const md=new Set(["a","an","and","de","for","in","of","the"]),g0=new Set([...md,"at","by","da","das","del","della","delle","den","der","des","di","die","do","dos","du","e","el","et","for","from","fuer","fur","into","la","las","le","les","los","on","to","und","with","y"]);function Ur(r){return r.toLowerCase().replace(/[^a-z0-9]+/g," ").split(/\s+/).map(e=>e.trim()).filter(e=>e.length>0&&!md.has(e))}function bd(r){return Ur(r).filter(e=>!g0.has(e))}function y0(r){return un(r).replace(/\s+/g,"")}function gd(r){return`exact:${r.replace(/\s+/g," ").trim().toLowerCase()}`}function x0(r){return Ur(r).join(" ")}function A0(r){return Ur(r).join("")}function ti(r){const e=r.trim().toUpperCase(),t=e.replace(/[^0-9X]/g,""),n=new Set;return e&&n.add(e),/^\d{7}[\dX]$/.test(t)&&(n.add(t),n.add(`${t.slice(0,4)}-${t.slice(4)}`)),[...n]}function yd(r){return r.replace(/^anaesth/,"anesth").replace(/^foet/,"fet").replace(/^gynae/,"gyne").replace(/^haem/,"hem").replace(/^oest/,"est").replace(/^paed/,"ped")}function xd(r,e){const t=yd(r),n=yd(e);return t===n?!0:(t.length===1,n.startsWith(t))}function C0(r,e){const t=bd(r);if(t.length===0)return!1;const n=bd(e);return t.length!==n.length?!1:t.length===1?t[0]===n[0]:t.every((a,i)=>xd(a,n[i]))}function v0(r){const e=[],t=r.match(/^([A-Z0-9]{2,10})\s*[-–—:]\s*(.+)$/);return t?.[2]&&e.push(t[2]),t?.[1]&&t[1].length<=4&&e.push(t[1]),e}function Hr(r){const e=new Set,t=un(r);t&&e.add(t);const n=y0(r);n&&e.add(n);const a=x0(r);a&&e.add(a);const i=A0(r);return i&&e.add(i),[...e]}function ni(r,e,t,n){if(!t||e.has(t))return;const a=r.get(t);if(!a){r.set(t,n);return}a.journalName!==n.journalName&&(r.delete(t),e.add(t))}function Ad(r,e,t,n){if(!t||e.has(t))return;const a=r.get(t);if(!a){r.set(t,n);return}a.journalName!==n.journalName&&(r.delete(t),e.add(t))}function Cd(r,e,t){if(!e)return;const n=r.get(e)??new Set;n.add(t.journalName),r.set(e,n)}function S0(r){const e=new Map;for(const t of r){Cd(e,t.normalizedName,t);for(const n of Hr(t.journalName))Cd(e,n,t)}return e}function w0(r,e,t){const n=t.get(r);return n?n.size>1||!n.has(e.journalName):!1}function vd(r){let e=r.replace(/\s+/g," ").trim();if(!e)return"";const t=e.split(/\s[-–—]\s/).map(n=>n.trim()).filter(Boolean);return t.length>=2&&(e=t[1]),e=e.replace(/\b(?:19|20)\d{2}\b[\s\S]*$/,"").replace(/\b(?:vol(?:ume)?|issue|no\.?|number|pages?|pp\.?)\b[\s\S]*$/i,"").replace(/\s+\d+\s*(?:\([^)]*\))?[\s\S]*$/,"").replace(/[,.;:\s]+$/,"").trim(),e}function T0(r){return r.trim().match(/^[A-Z0-9]{2,10}\s*[-–—:]\s*(.+)$/)?.[1]?.trim()||null}function E0(r){const e=r.trim().replace(/\s+\([A-Za-z][A-Za-z .'-]{1,40}\)\s*$/,"").trim();return e&&e!==r.trim()?e:null}function F0(r){const e=new Set,t=n=>{const a=n?.replace(/\s+/g," ").trim();a&&e.add(a)};t(r),t(vd(r));for(const n of[...e])t(T0(n)),t(E0(n));return[...e]}function D0(r,e){const t=Ur(r);if(t.length<2)return!1;const n=Ur(e);return t.length>=n.length?!1:t.every((a,i)=>xd(a,n[i]))}function _0(r,e){const t=[],n=new Set;for(const a of e)D0(r,a.journalName)&&(n.has(a.journalName)||(n.add(a.journalName),t.push(a)));return t.length===1?t[0]:null}function k0(r,e){const t=[],n=new Set;for(const a of e)C0(r,a.journalName)&&(n.has(a.journalName)||(n.add(a.journalName),t.push(a)));return t.length===1?t[0]:null}function N0(r){const e=new Map,t=new Map,n=new Set,a=new Set,i=S0(r);for(const o of r){ni(e,n,gd(o.journalName),o),ni(e,n,o.normalizedName,o);for(const l of Hr(o.journalName))ni(e,n,l,o);for(const l of v0(o.journalName))for(const c of Hr(l))w0(c,o,i)||ni(e,n,c,o);const s=o.issn;if(Array.isArray(s))for(const l of s)for(const c of ti(l))Ad(t,a,c,o);else if(typeof s=="string"&&s)for(const l of ti(s))Ad(t,a,l,o)}return{nameMap:e,issnMap:t}}async function Hn(){return rs||Or||(Or=(async()=>{try{const{journals:r}=await m0(),{nameMap:e,issnMap:t}=N0(r);return rs=e,$r=t,e}finally{Or=null}})(),Or)}const Sd=2;function L0(r){return/[\u3400-\u9fff]/.test(r)}function R0(r){return!r||L0(r)?!1:r.replace(/[^a-z0-9]/gi,"").length>=4}async function zr(r,e){const t=un(r),n=e?.trim();if(!t&&!n)return null;const a=await Hn();if(e&&$r)for(const u of ti(e)){const d=$r.get(u);if(d)return{journal:d,confidence:"exact",matchMethod:"issn"}}if($r)for(const u of ti(r)){const d=$r.get(u);if(d)return{journal:d,confidence:"exact",matchMethod:"issn"}}const i=F0(r),o=new Set(a.values());for(const u of i){const d=a.get(gd(u));if(d)return{journal:d,confidence:"exact",matchMethod:"normalizedName"}}for(const u of i)for(const d of Hr(u)){const p=a.get(d);if(p)return{journal:p,confidence:"exact",matchMethod:"normalizedName"}}for(const u of i){const d=zx(u);if(d)for(const p of Hr(d)){const h=a.get(p);if(h)return{journal:h,confidence:"exact",matchMethod:"abbreviation"}}}for(const u of i){const d=k0(u,o);if(d)return{journal:d,confidence:"exact",matchMethod:"abbreviation"}}for(const u of i){const d=_0(u,o);if(d)return{journal:d,confidence:"exact",matchMethod:"shortTitle"}}const s=un(vd(r)||r);if(!R0(s))return null;let l=null,c=1/0;for(const[u,d]of a){if(Math.abs(u.length-s.length)>Sd)continue;const p=b0(s,u);if(p<=Sd&&p<c&&(c=p,l=d,p===1))break}return l?{journal:l,confidence:"fuzzy",matchMethod:"levenshtein",levenshteinDistance:c}:null}async function ri(r){await Hn();const e=new Map;for(const t of r){const n=t.journal?.trim();if(!n&&!t.issn)continue;const a=await zr(n??"",t.issn);a&&e.set(t.id,a)}return e}const ve=`/**
 * PaperLens Design Tokens
 *
 * \u4EE5 CSS Custom Properties \u5F62\u5F0F\u5B9A\u4E49\u7684\u8BBE\u8BA1\u53D8\u91CF\uFF0C\u7EDF\u4E00\u4F7F\u7528 --pl- \u524D\u7F00\u3002
 * \u8FD9\u4E9B token \u88AB\u6CE8\u5165\u5230 Shadow DOM \u5185\u90E8\uFF0C\u4E0E\u5BBF\u4E3B\u9875\u9762\u6837\u5F0F\u5B8C\u5168\u9694\u79BB\u3002
 *
 * \u547D\u540D\u89C4\u8303\uFF1A--pl-{category}-{variant}
 */

:host {
  /* \u2500\u2500 Safari color-scheme support \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
  color-scheme: light;

  /* \u2500\u2500 \u54C1\u724C\u8272 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
  --pl-color-primary:        #2563eb;
  --pl-color-primary-hover:  #1d4ed8;
  --pl-color-primary-light:  #dbeafe;
  --pl-color-secondary:      #4f46e5;
  --pl-color-accent:         #0ea5e9;

  /* \u2500\u2500 \u529F\u80FD\u8272 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
  --pl-color-success:        #10b981;
  --pl-color-success-light:  #d1fae5;
  --pl-color-warning:        #f59e0b;
  --pl-color-warning-light:  #fef3c7;
  --pl-color-error:          #ef4444;
  --pl-color-error-light:    #fee2e2;
  --pl-color-info:           #3b82f6;
  --pl-color-info-light:     #dbeafe;

  /* \u2500\u2500 \u4E2D\u6027\u8272 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
  --pl-color-white:          #ffffff;
  --pl-color-gray-50:        #f9fafb;
  --pl-color-gray-100:       #f3f4f6;
  --pl-color-gray-200:       #e5e7eb;
  --pl-color-gray-300:       #d1d5db;
  --pl-color-gray-400:       #9ca3af;
  --pl-color-gray-500:       #6b7280;
  --pl-color-gray-600:       #4b5563;
  --pl-color-gray-700:       #374151;
  --pl-color-gray-800:       #1f2937;
  --pl-color-gray-900:       #111827;

  /* \u2500\u2500 \u5B57\u53F7\u5C42\u7EA7 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
  --pl-font-xs:    11px;
  --pl-font-sm:    12px;
  --pl-font-base:  14px;
  --pl-font-lg:    16px;
  --pl-font-xl:    20px;

  /* \u2500\u2500 \u5B57\u91CD \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
  --pl-weight-normal:    400;
  --pl-weight-medium:    500;
  --pl-weight-semibold:  600;
  --pl-weight-bold:      700;

  /* \u2500\u2500 \u5B57\u4F53\u65CF \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
  --pl-font-sans:  -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans CJK SC', 'Noto Sans SC', 'Source Han Sans SC', 'Helvetica Neue', Arial, sans-serif;
  --pl-font-mono:  'SF Mono', 'Monaco', 'Inconsolata', 'Fira Mono', 'Droid Sans Mono', 'Source Code Pro', monospace;

  /* \u2500\u2500 \u95F4\u8DDD\u5C42\u7EA7 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
  --pl-space-xxs:  2px;
  --pl-space-xs:   4px;
  --pl-space-sm:   8px;
  --pl-space-md:   12px;
  --pl-space-lg:   16px;
  --pl-space-xl:   24px;

  /* \u2500\u2500 \u5706\u89D2 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
  --pl-radius-sm:   4px;
  --pl-radius-md:   8px;
  --pl-radius-lg:   12px;
  --pl-radius-full: 9999px;

  /* \u2500\u2500 \u9634\u5F71 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
  --pl-shadow-sm:  0 1px 2px 0 rgba(0, 0, 0, 0.05);
  --pl-shadow-md:  0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);
  --pl-shadow-lg:  0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1);

  /* \u2500\u2500 \u8FC7\u6E21\u65F6\u95F4 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
  --pl-transition-fast:   150ms ease;
  --pl-transition-normal: 250ms ease;
  --pl-transition-slow:   350ms ease;

  /* \u2500\u2500 Semantic color tokens (light mode only) \u2500\u2500 */
  --pl-color-bg:            #ffffff;
  --pl-color-surface:       #f9fafb;
  --pl-color-text:          #1f2937;
  --pl-color-text-secondary:#6b7280;
  --pl-color-border:        #e5e7eb;
  --pl-color-shadow:        rgba(0, 0, 0, 0.05);

  /* \u2500\u2500 Z-index \u5C42\u7EA7\uFF08Shadow DOM \u5185\u90E8\uFF09 \u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
  --pl-z-base:     1;
  --pl-z-dropdown:  10;
  --pl-z-sticky:    20;
  --pl-z-modal:     30;
  --pl-z-tooltip:   40;
}
`,P0=`/**
 * Metric Bar Styles \u2014 injected into each metric bar's Shadow DOM
 *
 * \u6BCF\u4E2A Metric Bar \u5BBF\u4E3B\u5143\u7D20\u62E5\u6709\u72EC\u7ACB Shadow DOM\uFF0C
 * \u6837\u5F0F\u5B8C\u5168\u9694\u79BB\u4E8E PubMed \u9875\u9762\u3002
 *
 * Design Token \u4F9D\u8D56\uFF1A
 *   --pl-color-* / --pl-font-* / --pl-space-* / --pl-radius-*
 *   \u7531 tokens.css \u5728\u540C\u4E00 Shadow DOM \u5185\u901A\u8FC7 :host \u5B9A\u4E49
 */

/* \u2500\u2500 \u5BBF\u4E3B\u5143\u7D20\uFF08PubMed DOM \u4E2D\u7684 div\uFF09 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
:host {
  display: inline-flex;
  align-items: center;
  max-width: 100%;
  margin: 4px 0 5px;
  font: inherit;
}

:host([data-pl-layout="compact"]) {
  font-size: 13px;
}

/* \u2500\u2500 \u6307\u6807\u6761\u5BB9\u5668 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-metric-bar {
  display: inline-flex;
  align-items: center;
  gap: 0;
  max-width: min(100%, calc(100vw - 32px));
  overflow: hidden;
  border: 1px solid var(--pl-metric-border);
  border-radius: var(--pl-radius-sm);
  background: var(--pl-metric-bg);
  box-shadow: var(--pl-shadow-sm);
  font: inherit;
  line-height: 1;
}

/* \u2500\u2500 \u5355\u884C\u5206\u6BB5\u57FA\u7840\u6837\u5F0F \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-metric-cell {
  display: inline-flex;
  align-items: center;
  flex: 0 0 auto;
  min-height: 1.45em;
  padding: 0 0.48em;
  border-right: 1px solid color-mix(in srgb, var(--pl-metric-border), transparent 35%);
  color: var(--pl-metric-text);
  font: inherit;
  font-weight: var(--pl-weight-semibold);
  line-height: 1;
  white-space: nowrap;
}

:host([data-pl-layout="compact"]) .pl-metric-cell {
  min-height: 1.32em;
  padding: 0 0.34em;
}

.pl-metric-cell:last-child {
  border-right: 0;
}

.pl-metric-journal {
  flex: 1 1 auto;
  min-width: 0;
  max-width: min(var(--pl-metric-journal-max, 24ch), 100%);
  overflow: hidden;
  text-overflow: ellipsis;
  background: var(--pl-metric-journal-bg);
  cursor: help;
  white-space: nowrap;
}

:host([data-pl-layout="compact"]) .pl-metric-journal {
  max-width: min(var(--pl-metric-journal-max, 24ch), 100%);
}

.pl-metric-if,
.pl-metric-date {
  background: var(--pl-metric-soft-bg);
}

.pl-metric-oa {
  background: #dcfce7;
  color: #166534;
}

.pl-metric-type {
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  background: rgba(255, 255, 255, 0.58);
  color: var(--pl-color-gray-700);
}

/* \u2500\u2500 JCR \u5206\u533A badges (Q1 \u2192 Q4) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-metric-q1 {
  background-color: #b91c1c;
  color: #ffffff;
}

.pl-metric-q2 {
  background-color: #15803d;
  color: #ffffff;
}

.pl-metric-q3 {
  background-color: #b45309;
  color: #ffffff;
}

.pl-metric-q4 {
  background-color: #475569;
  color: #ffffff;
}

/* \u2500\u2500 \u4E2D\u79D1\u9662\u5206\u533A badges (1\u533A \u2192 4\u533A) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-metric-cas-1 {
  background-color: rgba(185, 28, 28, 0.1);
  color: #7f1d1d;
}

.pl-metric-cas-2 {
  background-color: rgba(21, 128, 61, 0.1);
  color: #14532d;
}

.pl-metric-cas-3 {
  background-color: rgba(180, 83, 9, 0.11);
  color: #78350f;
}

.pl-metric-cas-4 {
  background-color: rgba(71, 85, 105, 0.1);
  color: #334155;
}

.pl-metric-emerging {
  background: rgba(71, 85, 105, 0.1);
  color: #334155;
}

.pl-metric-emerging-1 {
  background-color: rgba(185, 28, 28, 0.1);
  color: #7f1d1d;
}

.pl-metric-emerging-2 {
  background-color: rgba(21, 128, 61, 0.1);
  color: #14532d;
}

.pl-metric-emerging-3 {
  background-color: rgba(180, 83, 9, 0.11);
  color: #78350f;
}

.pl-metric-emerging-4 {
  background-color: rgba(71, 85, 105, 0.1);
  color: #334155;
}

.pl-metric-bar--q1 {
  --pl-metric-bg: #fff7ed;
  --pl-metric-soft-bg: #ffedd5;
  --pl-metric-journal-bg: #fed7aa;
  --pl-metric-border: #fdba74;
  --pl-metric-text: #7c2d12;
}

.pl-metric-bar--q2 {
  --pl-metric-bg: #f0fdf4;
  --pl-metric-soft-bg: #dcfce7;
  --pl-metric-journal-bg: #bbf7d0;
  --pl-metric-border: #86efac;
  --pl-metric-text: #14532d;
}

.pl-metric-bar--q3 {
  --pl-metric-bg: #fffbeb;
  --pl-metric-soft-bg: #fef3c7;
  --pl-metric-journal-bg: #fde68a;
  --pl-metric-border: #fcd34d;
  --pl-metric-text: #78350f;
}

.pl-metric-bar--q4 {
  --pl-metric-bg: #f8fafc;
  --pl-metric-soft-bg: #e2e8f0;
  --pl-metric-journal-bg: #cbd5e1;
  --pl-metric-border: #94a3b8;
  --pl-metric-text: #1e293b;
}

@media (max-width: 760px) {
  .pl-metric-cell {
    padding: 0 0.36em;
  }
}

/* \u2500\u2500 Warning badges \u5BB9\u5668 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-metric-warnings {
  gap: 2px;
  padding: 0 4px;
  background: rgba(255, 255, 255, 0.45);
  flex-shrink: 0;
}

/* \u2500\u2500 Shimmer / Skeleton \u9AA8\u67B6\u6001 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-metric-shimmer {
  display: inline-flex;
  align-items: center;
  gap: var(--pl-space-xs);
  padding: 2px 0;
  margin-top: 2px;
  height: 20px;
}

.pl-shimmer-bar {
  display: inline-block;
  height: 16px;
  border-radius: var(--pl-radius-sm);
  background: linear-gradient(
    90deg,
    var(--pl-color-gray-100) 25%,
    var(--pl-color-gray-200) 50%,
    var(--pl-color-gray-100) 75%
  );
  background-size: 200% 100%;
  animation: pl-shimmer 1.5s ease-in-out infinite;
}

.pl-shimmer-bar--if {
  width: 60px;
}

.pl-shimmer-bar--q {
  width: 28px;
}

@keyframes pl-shimmer {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}
`;function wd(r){const e=document.createDocumentFragment();return r.casWarning&&e.appendChild(as("\u26A0","#C53030","\u4E2D\u79D1\u9662\u9884\u8B66\u671F\u520A",I0(r))),r.wosStatus==="delisted"?e.appendChild(as("\u{1F6AB}","#C53030","\u5DF2\u4ECE Web of Science \u79FB\u9664",t=>{ai(t,"\u8BE5\u671F\u520A\u5DF2\u4ECE Clarivate Web of Science \u79FB\u9664\uFF0C\u4E0D\u518D\u83B7\u5F97\u5F71\u54CD\u56E0\u5B50\u3002")})):r.wosStatus==="on_hold"&&e.appendChild(as("\u23F8","#C05621","Web of Science \u6682\u505C\u6536\u5F55",t=>{ai(t,"\u8BE5\u671F\u520A\u88AB Clarivate \u6682\u505C\u6536\u5F55\uFF0C\u5F71\u54CD\u56E0\u5B50\u53EF\u80FD\u6682\u505C\u66F4\u65B0\u3002")})),e}function Td(r){if(r.querySelector(".pl-warn-badge-style"))return;const e=document.createElement("style");e.className="pl-warn-badge-style",e.textContent=M0,r.appendChild(e)}function B0(){if(document.getElementById("pl-warn-popover-global-style"))return;const r=document.createElement("style");r.id="pl-warn-popover-global-style",r.textContent=q0,document.head.appendChild(r)}function I0(r){const e=r.casWarningYears?.map(String).join("\u3001")||"\u672A\u77E5";return t=>{ai(t,"\u8BE5\u671F\u520A\u88AB\u5217\u5165\u4E2D\u79D1\u9662\u56FD\u9645\u671F\u520A\u9884\u8B66\u540D\u5355\u3002"),t.append(document.createElement("br"));const n=document.createElement("b");n.textContent="\u9884\u8B66\u5E74\u4EFD\uFF1A",t.append(n,e,document.createElement("br")),ai(t,"\u88AB\u9884\u8B66\u671F\u520A\u53EF\u80FD\u5F71\u54CD\u804C\u79F0\u8BC4\u5BA1\u53CA\u79D1\u7814\u7ECF\u8D39\u8BA4\u53EF\uFF0C\u6295\u7A3F\u9700\u8C28\u614E\u8BC4\u4F30\u3002")}}function ai(r,e){r.append(document.createTextNode(e))}let te=null;function pn(){te&&(te.popover.classList.remove("pl-warn-popover--visible"),te.trigger.setAttribute("aria-expanded","false"),te.popover.remove(),te=null)}function Ed(r,e){const t=e.getBoundingClientRect(),n=220,a=r.offsetHeight||120;let i=t.top-a-6,o=t.left+t.width/2-n/2;i<4&&(i=t.bottom+6);const s=4;o<s&&(o=s),o+n>window.innerWidth-s&&(o=window.innerWidth-s-n),r.style.top=`${i}px`,r.style.left=`${o}px`}function Fd(r,e){pn(),B0(),document.body.appendChild(r),Ed(r,e),requestAnimationFrame(()=>r.classList.add("pl-warn-popover--visible")),e.setAttribute("aria-expanded","true"),te={popover:r,trigger:e}}function as(r,e,t,n){const a=document.createElement("button");a.type="button",a.className="pl-warn-badge",a.style.color=e,a.setAttribute("aria-label",t),a.setAttribute("aria-haspopup","dialog"),a.setAttribute("aria-expanded","false"),a.textContent=r;let i=null;function o(){if(!i){i=document.createElement("span"),i.className="pl-warn-popover",i.setAttribute("role","tooltip");const l=document.createElement("b");l.className="pl-warn-popover-title",l.style.color=e,l.textContent=`${r} ${t}`;const c=document.createElement("div");c.className="pl-warn-popover-body",n(c),i.append(l,c)}return i}a.addEventListener("click",l=>{l.stopPropagation(),te&&te.trigger===a?pn():Fd(o(),a)}),a.addEventListener("keydown",l=>{l.key==="Escape"&&(pn(),a.focus())}),a.addEventListener("mouseenter",()=>{(!te||te.trigger===a)&&Fd(o(),a)}),a.addEventListener("mouseleave",()=>{te?.trigger===a&&setTimeout(()=>{te?.trigger===a&&!a.matches(":focus-within")&&pn()},200)});const s=new MutationObserver(()=>{document.contains(a)||(te?.trigger===a&&pn(),s.disconnect(),i=null)});return s.observe(a.parentNode||document.body,{childList:!0,subtree:!0}),a}document.addEventListener("click",r=>{te&&!te.trigger.contains(r.target)&&!te.popover.contains(r.target)&&pn()}),document.addEventListener("keydown",r=>{r.key==="Escape"&&te&&pn()});const Dd=()=>{te&&Ed(te.popover,te.trigger)};window.addEventListener("scroll",Dd,{passive:!0}),window.addEventListener("resize",Dd,{passive:!0});const M0=`
.pl-warn-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: 11px;
  line-height: 1;
  cursor: pointer;
  position: relative;
  user-select: none;
  transition: transform 0.15s ease;
  padding: 0 1px;
  background: none;
  border: none;
  font-family: inherit;
}
.pl-warn-badge:hover {
  transform: scale(1.25);
}
.pl-warn-badge:focus-visible {
  outline: 2px solid currentColor;
  outline-offset: 1px;
  border-radius: 2px;
}
`,q0=`
.pl-warn-popover {
  position: fixed;
  width: 220px;
  padding: 10px 12px;
  border-radius: 6px;
  background: #ffffff;
  border: 1px solid #e2e8f0;
  box-shadow: 0 4px 12px rgba(0,0,0,0.12), 0 1px 3px rgba(0,0,0,0.08);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans CJK SC', 'Noto Sans SC', 'Source Han Sans SC', 'Helvetica Neue', Arial, sans-serif;
  font-size: 12px;
  line-height: 1.5;
  color: #334155;
  z-index: 2147483647;
  pointer-events: none;
  opacity: 0;
  transform: translateY(3px);
  transition: opacity 0.15s ease, transform 0.15s ease;
}
.pl-warn-popover--visible {
  opacity: 1;
  transform: translateY(0);
  pointer-events: auto;
}
.pl-warn-popover-title {
  display: block;
  font-size: 12.5px;
  font-weight: 600;
  margin-bottom: 6px;
}
.pl-warn-popover-body {
  font-weight: 400;
  color: #475569;
}
.pl-warn-popover-body b {
  color: #334155;
  font-weight: 500;
}
`,ii=["jcr","cas","emerging"],_d=new Set(["","undefined","null","none","n/a","na","-","--","?"]);function hn(r){const e=String(r??"").trim();if(_d.has(e.toLowerCase()))return null;const t=e.match(/[1-4]/)?.[0];return t?{value:t,label:`${t}\u533A`}:null}function j0(r){return hn(r)?.value}function Lt(r){const t=String(r??"").trim().toUpperCase().match(/Q[1-4]/);return t?{value:t[0],label:`JCR ${t[0]}`}:null}function zn(r,e){const t=String(e??"").trim();if(t)return t;const n=Number(r);return Number.isFinite(n)?n.toFixed(1):null}function Jn(r,e){const t=String(r??"").trim();if(_d.has(t.toLowerCase()))return null;const n=t.match(/[1-4]/)?.[0];if(!n)return null;const a=e===!0||String(e??"").trim().toUpperCase()==="TOP";return{value:n,label:`\u65B0\u9510${n}\u533A${n==="1"&&a?"\uFF08TOP\uFF09":""}`}}function is(r){const e=String(r??"").trim();return e==="jcr"?["jcr"]:e==="cas"?["cas"]:[...ii]}function os(r,e=ii){if(!Array.isArray(r))return[...e];const t=new Set(ii),n=[];for(const a of r){const i=String(a??"").trim().toLowerCase();t.has(i)&&!n.includes(i)&&n.push(i)}return n}function Rt(r){return Array.isArray(r?.quartileSources)?os(r?.quartileSources):r&&"quartileSource"in r?is(r.quartileSource):[...ii]}function ss(r,e){return Rt(e).includes(r)}function Vn(r,e){const t=Rt(e);return Number.isFinite(r.impactFactor)||Number.isFinite(r.sjr)&&!!r.sjrQuartile||r.openAccess===!0||r.openAccessDiamond===!0||r.casWarning===!0||!!r.wosStatus||t.includes("jcr")&&!!Lt(r.jcrQuartile)||t.includes("cas")&&!!hn(r.casQuartile)||t.includes("emerging")&&!!Jn(r.emergingQuartile)}const Ve=340,Pt=180,ce={top:24,right:16,bottom:30,left:42},$0=3,O0=5,oi='-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", "Noto Sans SC", "Source Han Sans SC", "Helvetica Neue", Arial, sans-serif';function Xe(r,e){return getComputedStyle(document.documentElement).getPropertyValue(r).trim()||e}function si(r,e,t={}){const n=r.getContext("2d");if(!n)return;const a=window.devicePixelRatio||1;if(r.width=Ve*a,r.height=Pt*a,r.style.width=`${Ve}px`,r.style.height=`${Pt}px`,n.scale(a,a),!e||e.length===0){U0(n);return}const i=Ve-ce.left-ce.right,o=Pt-ce.top-ce.bottom,s=e.map(N=>N.year),l=e.map(N=>N.if),c=Math.min(...s),u=Math.max(...s),d=Math.ceil(Math.max(...l)*1.15),p=N=>ce.left+(N-c)/(u-c||1)*i,h=N=>ce.top+o-N/(d||1)*o,f=Xe("--pl-color-primary","#2563eb"),y=Xe("--pl-color-text-secondary","#6b7280"),x=Xe("--pl-color-border","#e5e7eb"),T=Xe("--pl-color-bg","#ffffff"),E=Xe("--pl-color-primary","#2563eb"),w=Xe("--pl-color-gray-800","#1f2937"),v=Xe("--pl-color-white","#ffffff");n.clearRect(0,0,Ve,Pt);const g=4;n.strokeStyle=x,n.lineWidth=.5,n.font=`10px ${oi}`,n.fillStyle=y,n.textAlign="right",n.textBaseline="middle";for(let N=0;N<=g;N++){const S=d/g*N,_=h(S);n.beginPath(),n.moveTo(ce.left,_),n.lineTo(Ve-ce.right,_),n.stroke(),n.fillText(S.toFixed(S>=100?0:1),ce.left-4,_)}n.textAlign="center",n.textBaseline="top";const C=V0(n,s,i);for(const N of C){const S=p(e[N].year);n.fillText(String(e[N].year),S,Pt-ce.bottom+6)}n.strokeStyle=f,n.lineWidth=2,n.lineJoin="round",n.lineCap="round",n.beginPath();for(let N=0;N<e.length;N++){const S=p(e[N].year),_=h(e[N].if);N===0?n.moveTo(S,_):n.lineTo(S,_)}n.stroke();for(const N of e){const S=p(N.year),_=h(N.if);n.beginPath(),n.arc(S,_,$0,0,Math.PI*2),n.fillStyle=E,n.fill(),n.strokeStyle=T,n.lineWidth=1.5,n.stroke()}t.showPointValueLabels&&z0(n,e.map((N,S)=>{const _={index:S,value:N.if,x:p(N.year),y:h(N.if)};return N.ifLabel&&(_.label=N.ifLabel),_}),y,T);const L={data:e,minYear:c,maxYear:u,maxIF:d,xScale:p,yScale:h,tooltipBg:w,tooltipText:v,textColor:y,bgColor:T,showPointValueLabels:!!t.showPointValueLabels},$=r._trendHandler;$&&(r.removeEventListener("mousemove",$),r.removeEventListener("mouseleave",$));const k=J0(r,L);r._trendHandler=k,r.addEventListener("mousemove",k),r.addEventListener("mouseleave",k)}function U0(r){const e=Xe("--pl-color-text-secondary","#6b7280");r.clearRect(0,0,Ve,Pt),r.font=`13px ${oi}`,r.fillStyle=e,r.textAlign="center",r.textBaseline="middle",r.fillText("\u6682\u65E0\u5386\u5E74 IF \u6570\u636E",Ve/2,Pt/2)}function kd(r){return r>=10?r.toFixed(1):r.toFixed(2).replace(/\.?0+$/,"")}function H0(r){return r.ifLabel??kd(r.if)}function z0(r,e,t,n){r.save(),r.font=`10px ${oi}`,r.textAlign="center",r.textBaseline="middle";const a=[];for(const i of e){const o=i.label??kd(i.value),s=r.measureText(o).width;let l=i.x;l-s/2<ce.left&&(l=ce.left+s/2),l+s/2>Ve-ce.right&&(l=Ve-ce.right-s/2);const c=i.index%2===1||i.y-ce.top<14,u=[c?i.y+13:i.y-11,c?i.y-11:i.y+13,c?i.y+24:i.y-23].map(h=>Math.max(ce.top+7,Math.min(Pt-ce.bottom-7,h)));let d=u[0],p=!1;for(const h of u){const f={left:l-s/2-2,right:l+s/2+2,top:h-7,bottom:h+7};if(!a.some(y=>f.left<y.right&&f.right>y.left&&f.top<y.bottom&&f.bottom>y.top)){d=h,a.push(f),p=!0;break}}p||a.push({left:l-s/2-2,right:l+s/2+2,top:d-7,bottom:d+7}),r.strokeStyle=n,r.lineWidth=3,r.strokeText(o,l,d),r.fillStyle=t,r.fillText(o,l,d)}r.restore()}function J0(r,e){let t=-1;return n=>{if(!r.getContext("2d"))return;const i=r.getBoundingClientRect(),o=n.clientX-i.left,s=n.clientY-i.top;if(n.type==="mouseleave"){t=-1,si(r,e.data,{showPointValueLabels:e.showPointValueLabels});return}let l=-1,c=1/0;for(let w=0;w<e.data.length;w++){const v=e.xScale(e.data[w].year),g=e.yScale(e.data[w].if),C=Math.hypot(o-v,s-g);C<c&&(c=C,l=w)}if(c>30||l<0){t!==-1&&(t=-1,si(r,e.data,{showPointValueLabels:e.showPointValueLabels}));return}if(l===t)return;t=l,si(r,e.data,{showPointValueLabels:e.showPointValueLabels});const u=r.getContext("2d");if(!u)return;u.save();const d=e.data[l],p=e.xScale(d.year),h=e.yScale(d.if);u.beginPath(),u.arc(p,h,O0,0,Math.PI*2),u.fillStyle=Xe("--pl-color-primary","#2563eb"),u.fill(),u.strokeStyle=Xe("--pl-color-bg","#ffffff"),u.lineWidth=2,u.stroke();const f=`${d.year}: IF ${H0(d)}`;u.font=`11px ${oi}`;const y=u.measureText(f).width+12,x=20;let T=p-y/2,E=h-x-8;E<2&&(E=h+10),T<2&&(T=2),T+y>Ve-2&&(T=Ve-y-2),u.fillStyle=e.tooltipBg,u.beginPath(),u.roundRect(T,E,y,x,3),u.fill(),u.fillStyle=e.tooltipText,u.textAlign="center",u.textBaseline="middle",u.fillText(f,T+y/2,E+x/2),u.restore()}}function V0(r,e,t){if(e.length<=2)return e.map((s,l)=>l);const n=e.reduce((s,l)=>Math.max(s,r.measureText(String(l)).width),0),a=Math.max(2,Math.floor(t/Math.max(1,n+12)));if(e.length<=a)return e.map((s,l)=>l);const i=Math.max(1,Math.ceil((e.length-1)/Math.max(1,a-1))),o=new Set([0,e.length-1]);for(let s=i;s<e.length-1;s+=i)o.add(s);return Array.from(o).sort((s,l)=>s-l)}const W0="paperlens-journal-trend-popover",Nd="paperlens-journal-trend-popover-style",Ld="data-paperlens-trend-hover-bound";let ls=null,li=null,Rd;function G0(r){Rd=r?[...r]:void 0}function Wn(r,e){if(!e.journalName||r.getAttribute(Ld)==="1")return;r.setAttribute(Ld,"1");let t=null,n=!1,a=0;const i=()=>{t&&(clearTimeout(t),t=null)},o=l=>{n=!0;const c=++a;i(),t=setTimeout(()=>{Z0(r,e,()=>n&&c===a)},l)},s=()=>{n=!1,a++,i(),Id()};r.addEventListener("mouseenter",()=>{o(e.delayMs??280)}),r.addEventListener("mouseleave",s),r.addEventListener("focus",()=>{o(0)}),r.addEventListener("blur",s)}async function Z0(r,e,t){let n;try{n=await Promise.resolve(e.getTrendData())}catch{n=[]}if(!t())return;const a=await Y0(e,n);if(a.data.length<2&&!e.journal||!t()||!r.isConnected)return;ci(),rA(),Md();const i=document.createElement("div");i.id=W0,i.className="paperlens-journal-trend-popover",i.setAttribute("role","dialog"),i.setAttribute("aria-label",`${e.journalName} \u671F\u520A\u8BE6\u60C5`),i.appendChild(K0(e,a)),document.body.appendChild(i),ls=i,nA(i,r);const o=i.querySelector(".paperlens-journal-trend-canvas");o&&a.data.length>=2&&requestAnimationFrame(()=>si(o,a.data,{showPointValueLabels:!0})),i.addEventListener("mouseenter",ci),i.addEventListener("mouseleave",Id)}async function Y0(r,e){if(e.length>=2||!r.getSJRTrendData)return{metric:"IF",data:e};try{const n=(await Promise.resolve(r.getSJRTrendData())).filter(a=>Number.isFinite(a.year)&&Number.isFinite(a.sjr)).map(a=>({year:a.year,if:a.sjr}));if(n.length>=2)return{metric:"SJR",data:n}}catch{}return{metric:"IF",data:e}}function K0(r,e){const t=document.createElement("div");t.className="paperlens-journal-preview";const n=r.journal,a=e.data,i=a[0],o=a[a.length-1],s=document.createElement("div");s.className="paperlens-journal-trend-header";const l=document.createElement("div");l.className="paperlens-journal-title-wrap";const c=document.createElement("div");c.className="paperlens-journal-trend-title",c.textContent=n?.journalName??r.journalName,l.appendChild(c);const u=document.createElement("div");u.className="paperlens-journal-preview-subtitle",u.textContent=[n?.issn?.length?`ISSN ${n.issn.filter(p=>p&&p!=="N/A").slice(0,2).join(", ")}`:"",n?.country].filter(Boolean).join(" \xB7 "),u.textContent&&l.appendChild(u);const d=document.createElement("div");if(d.className="paperlens-journal-trend-range",d.textContent=i&&o?`${i.year}-${o.year} ${e.metric}`:"\u671F\u520A\u8BE6\u60C5",s.append(l,d),t.appendChild(s),n){t.appendChild(Q0(n,r));const p=X0(n);p&&t.appendChild(p);const h=eA(n);h&&t.appendChild(h);const f=tA(n);f&&t.appendChild(f)}if(a.length>=2){const p=document.createElement("div");p.className="paperlens-journal-chart-block";const h=document.createElement("canvas");h.className="paperlens-journal-trend-canvas",p.appendChild(h),t.appendChild(p)}return t}function Q0(r,e){const t=document.createElement("div");t.className="paperlens-journal-preview-tags";const n=Rt({quartileSources:Rd??e.quartileSources});Number.isFinite(r.impactFactor)&&Jr(t,`IF ${zn(r.impactFactor,r.impactFactorLabel)}`,"if");const a=Lt(r.jcrQuartile);a&&ss("jcr",{quartileSources:n})&&Jr(t,a.label,Pd(a.value));const i=hn(r.casQuartile);i&&ss("cas",{quartileSources:n})&&Jr(t,`\u4E2D\u79D1\u9662${i.label}`,"cas");const o=Jn(r.emergingQuartile,r.emergingTop);return o&&ss("emerging",{quartileSources:n})&&Jr(t,o.label,`emerging-${o.value}`),r.sjrQuartile&&Jr(t,`SJR ${r.sjrQuartile}`,Pd(r.sjrQuartile)),t}function X0(r){const e=[];if(r.openAccess!==void 0&&e.push(["OA",r.openAccess?"\u5F00\u653E\u83B7\u53D6":"\u975E\u5F00\u653E\u83B7\u53D6"]),r.openAccessDiamond&&e.push(["Diamond OA","\u662F"]),Number.isFinite(r.sjr)&&e.push(["SJR",Bd(r.sjr,3)]),Number.isFinite(r.sjrHIndex)&&e.push(["H-index",String(Math.round(r.sjrHIndex??0))]),Number.isFinite(r.citationsPerDoc)&&e.push(["Cite/Doc",Bd(r.citationsPerDoc,1)]),Number.isFinite(r.totalDocs2025)&&e.push(["2025 \u53D1\u6587",String(Math.round(r.totalDocs2025??0))]),e.length===0)return null;const t=document.createElement("div");t.className="paperlens-journal-fact-grid";for(const[n,a]of e.slice(0,6)){const i=document.createElement("div");i.className="paperlens-journal-fact";const o=document.createElement("span");o.className="paperlens-journal-fact-label",o.textContent=n;const s=document.createElement("span");s.className="paperlens-journal-fact-value",s.textContent=a,i.append(o,s),t.appendChild(i)}return t}function eA(r){const e=[...r.scimagoCategories??[],...r.category??[]].filter((a,i,o)=>a&&o.indexOf(a)===i);if(e.length===0)return null;const t=document.createElement("div");t.className="paperlens-journal-category-row";const n=document.createElement("span");n.className="paperlens-journal-category-label",n.textContent="\u5B66\u79D1",t.appendChild(n);for(const a of e.slice(0,3)){const i=document.createElement("span");i.className="paperlens-journal-category-chip",i.textContent=a,t.appendChild(i)}return t}function tA(r){const e=[];if(r.casWarning){const n=r.casWarningYears?.length?`\uFF08${r.casWarningYears.join(", ")}\uFF09`:"";e.push(`\u4E2D\u79D1\u9662\u9884\u8B66${n}`)}if(r.wosStatus==="delisted"?e.push(`WoS \u5DF2\u79FB\u9664${r.wosStatusDate?`\uFF08${r.wosStatusDate}\uFF09`:""}`):r.wosStatus==="on_hold"&&e.push(`WoS \u6682\u505C\u6536\u5F55${r.wosStatusDate?`\uFF08${r.wosStatusDate}\uFF09`:""}`),e.length===0)return null;const t=document.createElement("div");return t.className="paperlens-journal-warning-row",t.textContent=e.join(" \xB7 "),t}function Jr(r,e,t){const n=document.createElement("span");n.className=`paperlens-journal-preview-tag paperlens-journal-preview-tag--${t}`,n.textContent=e,r.appendChild(n)}function Pd(r){const e=r?.toLowerCase();return e&&/^q[1-4]$/.test(e)?e:"neutral"}function Bd(r,e){return Number.isFinite(r)?Number(r).toFixed(e):"N/A"}function nA(r,e){const n=e.getBoundingClientRect(),a=r.getBoundingClientRect(),i=n.bottom+10,o=n.top-a.height-10,l=i+a.height<=window.innerHeight-10?i:Math.max(10,o),c=n.left+n.width/2-a.width/2,u=Math.min(Math.max(10,c),Math.max(10,window.innerWidth-a.width-10));r.style.top=`${l}px`,r.style.left=`${u}px`}function Id(){ci(),li=setTimeout(Md,180)}function ci(){li&&(clearTimeout(li),li=null)}function Md(){ci(),ls?.remove(),ls=null}function rA(){if(document.getElementById(Nd))return;const r=document.createElement("style");r.id=Nd,r.textContent=`
    .paperlens-journal-trend-popover {
      position: fixed;
      z-index: 2147483647;
      width: min(430px, calc(100vw - 20px));
      padding: 12px;
      box-sizing: border-box;
      border: 1px solid #d8dee8;
      border-radius: 8px;
      background: #fff;
      box-shadow: 0 12px 28px rgba(15, 23, 42, 0.16);
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", "Noto Sans SC", "Source Han Sans SC", "Helvetica Neue", Arial, sans-serif;
      color: #1f2937;
    }
    .paperlens-journal-preview {
      display: flex;
      flex-direction: column;
      gap: 9px;
      min-width: 0;
    }
    .paperlens-journal-trend-header {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      gap: 10px;
    }
    .paperlens-journal-title-wrap {
      min-width: 0;
    }
    .paperlens-journal-trend-title {
      min-width: 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size: 13px;
      font-weight: 700;
    }
    .paperlens-journal-preview-subtitle {
      margin-top: 2px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size: 11px;
      line-height: 1.35;
      color: #64748b;
    }
    .paperlens-journal-trend-range {
      flex: 0 0 auto;
      font-size: 11px;
      color: #64748b;
    }
    .paperlens-journal-preview-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 5px;
    }
    .paperlens-journal-preview-tag {
      display: inline-flex;
      align-items: center;
      min-height: 20px;
      padding: 2px 7px;
      border: 1px solid #d8dee8;
      border-radius: 4px;
      background: #f8fafc;
      color: #334155;
      font-size: 11px;
      font-weight: 700;
      line-height: 1.2;
      white-space: nowrap;
    }
    .paperlens-journal-preview-tag--if {
      border-color: #fdba74;
      background: #ffedd5;
      color: #7c2d12;
    }
    .paperlens-journal-preview-tag--cas {
      border-color: #c4b5fd;
      background: #ede9fe;
      color: #5b21b6;
    }
    .paperlens-journal-preview-tag--emerging-1 {
      border-color: #fecaca;
      background: #fee2e2;
      color: #7f1d1d;
    }
    .paperlens-journal-preview-tag--emerging-2 {
      border-color: #bbf7d0;
      background: #dcfce7;
      color: #14532d;
    }
    .paperlens-journal-preview-tag--emerging-3 {
      border-color: #fde68a;
      background: #fef3c7;
      color: #78350f;
    }
    .paperlens-journal-preview-tag--emerging-4 {
      border-color: #cbd5e1;
      background: #e2e8f0;
      color: #334155;
    }
    .paperlens-journal-preview-tag--q1 {
      border-color: #b91c1c;
      background: #b91c1c;
      color: #fff;
    }
    .paperlens-journal-preview-tag--q2 {
      border-color: #15803d;
      background: #15803d;
      color: #fff;
    }
    .paperlens-journal-preview-tag--q3 {
      border-color: #b45309;
      background: #b45309;
      color: #fff;
    }
    .paperlens-journal-preview-tag--q4 {
      border-color: #475569;
      background: #475569;
      color: #fff;
    }
    .paperlens-journal-fact-grid {
      display: grid;
      grid-template-columns: repeat(3, minmax(0, 1fr));
      gap: 6px;
    }
    .paperlens-journal-fact {
      min-width: 0;
      padding: 6px 7px;
      border: 1px solid #e2e8f0;
      border-radius: 6px;
      background: #f8fafc;
    }
    .paperlens-journal-fact-label,
    .paperlens-journal-fact-value {
      display: block;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .paperlens-journal-fact-label {
      color: #64748b;
      font-size: 10px;
      font-weight: 600;
    }
    .paperlens-journal-fact-value {
      margin-top: 2px;
      color: #1f2937;
      font-size: 12px;
      font-weight: 700;
    }
    .paperlens-journal-category-row {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 5px;
    }
    .paperlens-journal-category-label {
      color: #64748b;
      font-size: 11px;
      font-weight: 700;
    }
    .paperlens-journal-category-chip {
      max-width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      padding: 2px 6px;
      border-radius: 999px;
      background: #eff6ff;
      color: #1d4ed8;
      font-size: 10px;
      font-weight: 600;
    }
    .paperlens-journal-warning-row {
      padding: 6px 8px;
      border: 1px solid #fecaca;
      border-radius: 6px;
      background: #fff1f2;
      color: #991b1b;
      font-size: 11px;
      font-weight: 700;
      line-height: 1.4;
    }
    .paperlens-journal-chart-block {
      padding-top: 3px;
      border-top: 1px solid #edf2f7;
    }
    .paperlens-journal-trend-canvas {
      display: block;
    }
  `,document.head.appendChild(r)}const Vr=new Map,Wr=new Map;let cs=null,Gr=null,us=null,Zr=null,ds=null,Yr=null;function Bt(r){return un(r).toLowerCase()}function fn(r){return Bt(r).replace(/[^a-z0-9]/g,"")}function ps(r){return`exact:${r.replace(/\s+/g," ").trim().toLowerCase()}`}function ui(...r){const e=new Set,t=[];for(const n of r){const a=n?.trim();if(!a)continue;const i=fn(a)||Bt(a);e.has(i)||(e.add(i),t.push(a))}return t}async function hs(r){let e=[];for(const t of r){const n=await uA(t);if(n.length>=2)return n;n.length>e.length&&(e=n)}return e}async function fs(r){let e=[];for(const t of r){const n=await dA(t);if(n.length>=2)return n;n.length>e.length&&(e=n)}return e}function Gn(r,e,t){if(!e)return;const n=r.get(e)??[];n.push(t),r.set(e,n)}function aA(r){if(!r?.length)return[];const e=new Map;for(const t of r){if(!Number.isFinite(t.year)||!Number.isFinite(t.if)||t.year<2010)continue;const n={year:t.year,if:t.if};t.ifLabel&&(n.ifLabel=t.ifLabel),e.set(t.year,n)}return Array.from(e.values()).sort((t,n)=>t.year-n.year)}function qd(r,e){const t=ps(e),n=Bt(e),a=fn(e);return aA(r.get(t)??r.get(n)??r.get(a))}function ms(r,e,t){!e||r.has(e)||r.set(e,t)}function iA(r){if(!r?.length)return[];const e=new Map;for(const t of r)!Number.isFinite(t.year)||t.sjr===null||t.sjr===void 0||e.set(t.year,{year:t.year,sjr:t.sjr,sjrQuartile:t.sjrQuartile??void 0});return Array.from(e.values()).sort((t,n)=>t.year-n.year)}function oA(r,e){const t=Bt(e),n=fn(e);return iA(r.get(t)??r.get(n))}async function sA(){return cs||Gr||(Gr=(async()=>{try{const r=await Mr("/data/journal-history.json"),e=new Map;for(const t of r.journals??[]){const n=ps(t.name),a=Bt(t.name),i=fn(t.name);for(const o of t.history??[]){const s=Number(o.if),l=Number(o.year);if(!Number.isFinite(s)||!Number.isFinite(l))continue;const c={year:l,if:s};o.ifLabel&&(c.ifLabel=o.ifLabel),Gn(e,n,c),Gn(e,a,c),i!==a&&Gn(e,i,c)}}return cs=e,e}catch{return new Map}finally{Gr=null}})(),Gr)}async function lA(){return us||Zr||(Zr=(async()=>{try{const r=await Mr("/data/jcr-history-raw.json"),e=new Map;for(const[t,n]of Object.entries(r)){const a=Number(t);if(!(!Number.isFinite(a)||a<2010))for(const i of n??[]){if(!i.name)continue;const o=Number(i.jif);if(!Number.isFinite(o))continue;const s=ps(i.name),l=Bt(i.name),c=fn(i.name),u={year:a,if:o};i.jifLabel&&(u.ifLabel=i.jifLabel),Gn(e,s,u),Gn(e,l,u),c!==l&&Gn(e,c,u)}}return us=e,e}catch{return new Map}finally{Zr=null}})(),Zr)}async function cA(){return ds||Yr||(Yr=(async()=>{try{const r=await Mr("/data/journal-history-sjr.json"),e=new Map;for(const[t,n]of Object.entries(r.sjrHistory)){const a=n.map(i=>({year:i.year,sjr:i.sjr,sjrQuartile:i.sjrQuartile}));ms(e,t,a),ms(e,Bt(t),a),ms(e,fn(t),a)}return ds=e,e}catch{return new Map}finally{Yr=null}})(),Yr)}async function uA(r){const e=Bt(r);if(Vr.has(e))return Vr.get(e);const t=await sA(),n=qd(t,r);if(n.length>0)return Vr.set(e,n),n;const a=await lA(),i=qd(a,r);return i.length>0?Vr.set(e,i):Vr.delete(e),i}async function dA(r){const e=fn(r);if(Wr.has(e))return Wr.get(e);try{const t=await cA(),n=oA(t,r);return n.length>0?Wr.set(e,n):Wr.delete(e),n}catch{return Wr.delete(e),[]}}const pA=ve+`
`+P0,bs="data-paperlens-enhanced",hA="paperlens-metric-host",fA="paperlens-shimmer-host",mA=15e3;function bA(r){const e=Array.from(r.trim()).length||10;return Math.min(Math.max(e+2,14),56)}function jd(r){const e=document.createElement("div");e.className=r;const t=e.attachShadow({mode:"open"}),n=document.createElement("style");return n.textContent=pA,t.appendChild(n),{host:e,shadow:t}}function $d(r=!1){const{host:e,shadow:t}=jd(fA);r||(e.style.visibility="hidden");const n=document.createElement("div");n.className="pl-metric-shimmer";const a=document.createElement("span");a.className="pl-shimmer-bar pl-shimmer-bar--if";const i=document.createElement("span");i.className="pl-shimmer-bar pl-shimmer-bar--q";const o=document.createElement("span");return o.className="pl-shimmer-bar pl-shimmer-bar--q",n.append(a,i,o),t.appendChild(n),e}function gs(r,e={}){const{host:t,shadow:n}=jd(hA);e.layout&&e.layout!=="default"&&(t.dataset.plLayout=e.layout),(r.casWarning||r.wosStatus)&&Td(n),Number.isFinite(r.impactFactor)&&(t.dataset.plIf=String(r.impactFactor));const a=Rt({quartileSources:e.quartileSources}),i=a.includes("jcr"),o=a.includes("cas"),s=a.includes("emerging"),l=Lt(r.jcrQuartile),c=l?.value;c&&(t.dataset.plJcr=c);const u=hn(r.casQuartile);u&&(t.dataset.plCas=u.value);const d=Jn(r.emergingQuartile,r.emergingTop);d&&(t.dataset.plEmerging=d.value);const p=c??r.sjrQuartile??"Q4",h=Number.isFinite(r.impactFactor)?r.impactFactor:void 0,f=zn(h,r.impactFactorLabel),y=h!==void 0,x=Number.isFinite(r.sjr),T=r.openAccess===!0,E=document.createElement("div");E.className=`pl-metric-bar pl-metric-bar--${p.toLowerCase()}`,E.title=r.journalName;const w=e.paper?.journal||r.journalName,v=document.createElement("span");if(v.className="pl-metric-cell pl-metric-journal",v.style.setProperty("--pl-metric-journal-max",`${bA(w)}ch`),v.textContent=w,v.title=`${w} \xB7 \u60AC\u505C\u67E5\u770B IF \u8D8B\u52BF`,E.appendChild(v),ys(v,r,a,e.showScimagoSJR),r.casWarning||r.wosStatus){const g=document.createElement("span");g.className="pl-metric-cell pl-metric-warnings",g.appendChild(wd(r)),E.appendChild(g)}if(y){const g=document.createElement("span");g.className="pl-metric-cell pl-metric-if",g.textContent=`IF ${f}`,g.title="\u60AC\u505C\u67E5\u770B IF \u8D8B\u52BF",E.appendChild(g),ys(g,r,a,e.showScimagoSJR)}else if(x){const g=document.createElement("span");g.className="pl-metric-cell pl-metric-if",g.textContent=`SJR ${r.sjr?.toFixed(2)}`,g.title="SCImago Journal Rank",E.appendChild(g),ys(g,r,a,e.showScimagoSJR)}if(T){t.dataset.plOpenAccess="true";const g=document.createElement("span");g.className="pl-metric-cell pl-metric-oa",g.textContent=r.openAccessDiamond?"Diamond OA":"OA",g.title=r.openAccessDiamond?"Diamond Open Access \u671F\u520A":"Open Access \u671F\u520A",E.appendChild(g)}if(l&&c){const g=`pl-metric-${c.toLowerCase()}`,C=document.createElement("span");C.className=`pl-metric-cell pl-metric-jcr ${g}`,C.textContent=l.label,C.title="JCR \u5206\u533A",C.setAttribute("data-pl-jcr-quartile",""),i||(C.style.display="none"),E.appendChild(C)}else if(!c&&r.sjrQuartile){const g=`pl-metric-${r.sjrQuartile.toLowerCase()}`,C=document.createElement("span");C.className=`pl-metric-cell pl-metric-jcr ${g}`,C.textContent=`SJR ${r.sjrQuartile}`,C.title="SCImago \u5206\u533A",E.appendChild(C)}if(u){const g=document.createElement("span");g.className=`pl-metric-cell pl-metric-cas-${u.value}`,g.textContent=`\u4E2D\u79D1\u9662${u.label}`,g.title="\u4E2D\u79D1\u9662\u5206\u533A",g.setAttribute("data-pl-cas-quartile",""),o||(g.style.display="none"),E.appendChild(g)}if(d){const g=document.createElement("span");g.className=`pl-metric-cell pl-metric-emerging pl-metric-emerging-${d.value}`,g.textContent=d.label,g.title="\u65B0\u9510\u671F\u520A\u5206\u533A",g.setAttribute("data-pl-emerging-quartile",""),s||(g.style.display="none"),E.appendChild(g)}if(e.paper?.publicationDate){const g=document.createElement("span");g.className="pl-metric-cell pl-metric-date",g.textContent=e.paper.publicationDate,g.title="\u53D1\u8868\u65E5\u671F",E.appendChild(g)}if(e.paper?.articleType){const g=document.createElement("span");g.className="pl-metric-cell pl-metric-type",g.textContent=e.paper.articleType,E.appendChild(g)}return n.appendChild(E),t}function di(r){return r.hasAttribute(bs)}function Zn(r){r.setAttribute(bs,"")}function pi(r){r.removeAttribute(bs)}const Kr=new Map;function ys(r,e,t,n){(e.normalizedName||e.journalName)&&Wn(r,{journalName:e.journalName,journal:e,getTrendData:async()=>(await Od(e,!1)).trendData,...n===!1?{}:{getSJRTrendData:async()=>(await Od(e,!0)).sjrTrendData},quartileSources:t,delayMs:280})}function Od(r,e){const n=`${(r.normalizedName||r.journalName).toLowerCase()}::${e?"with-sjr":"if-only"}`,a=Kr.get(n);if(a)return a;const i=H({type:"GET_JOURNAL_TREND_DATA",payload:{normalizedName:r.normalizedName,journalName:r.journalName,includeSJR:e}},mA).then(async o=>{if(o?.success===!1&&gA(o.error))return Kr.delete(n),{trendData:[],sjrTrendData:[]};let s=o?.success&&Array.isArray(o.data?.trendData)?o.data.trendData:[],l=o?.success&&Array.isArray(o.data?.sjrTrendData)?o.data.sjrTrendData:[];if(s.length<2||e&&l.length<2){const c=await Ud(r,e);s.length<2&&(s=c.trendData),e&&l.length<2&&(l=c.sjrTrendData)}return s.length<2&&l.length<2&&Kr.delete(n),{trendData:s,sjrTrendData:l}}).catch(()=>(Kr.delete(n),Ud(r,e)));return Kr.set(n,i),i}function gA(r){return/请先登录|当前账户暂不能使用|Pro\s*永久版权益|账户状态已切换|未授权|NOT_AUTHENTICATED|SESSION_CHANGED|PLAN_REQUIRED/i.test(r||"")}async function Ud(r,e){const t=ui(r.normalizedName,r.journalName);if(t.length===0)return{trendData:[],sjrTrendData:[]};const n=await hs(t),a=e?await fs(t):[];return{trendData:n,sjrTrendData:a}}let Hd=null,zd=null,Jd=null,Vd=null,hi=null;function yA(){const r=globalThis;return(r.browser?.runtime??r.chrome?.runtime)?.getURL?.("data")??"data"}async function xA(){return hi||(hi=(async()=>{try{const r=yA(),[e,t,n,a]=await Promise.allSettled([fetch(`${r}/pku-core-journals.json`).then(i=>i.json()),fetch(`${r}/cscd-journals.json`).then(i=>i.json()),fetch(`${r}/cssci-journals.json`).then(i=>i.json()),fetch(`${r}/cas-warning-all.json`).then(i=>i.json())]);e.status==="fulfilled"&&e.value?.journals&&(Hd=new Set(e.value.journals.map(i=>Qr(i?.name)).filter(Boolean))),t.status==="fulfilled"&&t.value?.journals&&(zd=new Map(t.value.journals.flatMap(i=>{const o=Qr(i?.name);return o&&i?.library_type?[[o,i.library_type]]:[]}))),n.status==="fulfilled"&&n.value?.journals&&(Jd=new Map(n.value.journals.flatMap(i=>{const o=Qr(i?.name);return o?[[o,i.is_core?"\u6838\u5FC3":"\u6269\u5C55"]]:[]}))),a.status==="fulfilled"&&a.value?.journals&&(Vd=new Set(a.value.journals.map(i=>Qr(i?.name)).filter(Boolean)))}catch(r){console.warn("[ChineseMetrics] Failed to load data:",r)}})(),hi)}function Qr(r){return(r??"").toLowerCase().replace(/^期刊[:：]/,"").replace(/[《》〈〉“”"'‘’【】\[\]{}]/g,"").replace(/[\s·•.。．、，,;；:：|｜/\\（）()\u00A0\u3000-]/g,"")}async function AA(r){await xA();const e=Qr(r);return e?{pkuCore:Hd?.has(e)??!1,cscd:zd?.get(e)??void 0,cssci:Jd?.get(e)??void 0,casWarning:Vd?.has(e)??!1}:{pkuCore:!1,casWarning:!1}}const Yn={pku:{bg:"#e8f4fd",color:"#1976d2",label:"\u5317\u5927\u6838\u5FC3"},cscdCore:{bg:"#e8f5e9",color:"#2e7d32",label:"CSCD\u6838\u5FC3"},cscdExt:{bg:"#f1f8e9",color:"#558b2f",label:"CSCD\u6269\u5C55"},cssciCore:{bg:"#fce4ec",color:"#c62828",label:"CSSCI\u6838\u5FC3"},cssciExt:{bg:"#f3e5f5",color:"#6a1b9a",label:"CSSCI\u6269\u5C55"},warning:{bg:"#fff3e0",color:"#e65100",label:"\u26A0\uFE0F\u9884\u8B66"}};function Kn(r,e="500"){const t=document.createElement("span");return t.style.display="inline-block",t.style.padding="1px 6px",t.style.borderRadius="3px",t.style.fontSize="11px",t.style.background=r.bg,t.style.color=r.color,t.style.marginRight="4px",t.style.fontWeight=e,t.textContent=r.label,t}function CA(r){const e=[];return r.pkuCore&&e.push(Kn(Yn.pku)),r.cscd==="\u6838\u5FC3\u5E93"?e.push(Kn(Yn.cscdCore)):r.cscd==="\u6269\u5C55\u5E93"&&e.push(Kn(Yn.cscdExt)),r.cssci==="\u6838\u5FC3"?e.push(Kn(Yn.cssciCore)):r.cssci==="\u6269\u5C55"&&e.push(Kn(Yn.cssciExt)),r.casWarning&&e.push(Kn(Yn.warning,"600")),e}let Qn=null,Xn=null,fi=null;function vA(){const r=globalThis;return(r.browser?.runtime??r.chrome?.runtime)?.getURL?.("data")??"data"}async function SA(){return fi||(fi=(async()=>{try{const r=vA(),t=await(await fetch(`${r}/ccf-journals.json`)).json();Qn=new Map,Xn=new Map;for(const n of t.journals??[]){const a={ccfClass:n.ccf_class,type:"journal",domain:n.domain,abbreviation:n.abbreviation,fullName:n.full_name},i=Xr(n.abbreviation??n.full_name??"");i&&Qn.set(i,a),n.full_name&&Qn.set(Xr(n.full_name),a)}for(const n of t.conferences??[]){const a={ccfClass:n.ccf_class,type:"conference",domain:n.domain,abbreviation:n.abbreviation,fullName:n.full_name},i=Xr(n.abbreviation??n.full_name??"");i&&Xn.set(i,a),n.full_name&&Xn.set(Xr(n.full_name),a)}}catch(r){console.warn("[CCFBadge] Failed to load data:",r)}})(),fi)}function Xr(r){return r.toLowerCase().replace(/[\s.\-']/g,"")}async function wA(r,e){if(await SA(),!Qn||!Xn)return null;const t=Xr(r);return t?e==="conference"?Xn.get(t)??null:e==="journal"?Qn.get(t)??null:Qn.get(t)??Xn.get(t)??null:null}const TA={A:{bg:"#ffebee",color:"#c62828",label:"CCF-A"},B:{bg:"#fff3e0",color:"#e65100",label:"CCF-B"},C:{bg:"#e3f2fd",color:"#1565c0",label:"CCF-C"}};function EA(r){if(!r.ccfClass)return null;const e=TA[r.ccfClass];if(!e)return null;const t=r.type==="conference"?"\u{1F4C5}":"\u{1F4F0}",n=document.createElement("span");return n.style.display="inline-block",n.style.padding="1px 6px",n.style.borderRadius="3px",n.style.fontSize="11px",n.style.background=e.bg,n.style.color=e.color,n.style.marginRight="4px",n.style.fontWeight="600",n.textContent=`${t} ${e.label}`,n}const FA=`/**
 * Extra Download Button Styles \u2014 injected into each button's Shadow DOM
 *
 * Design Token \u4F9D\u8D56\uFF1A
 *   --pl-color-* / --pl-font-* / --pl-space-* / --pl-radius-*
 *   \u7531 tokens.css \u5728\u540C\u4E00 Shadow DOM \u5185\u901A\u8FC7 :host \u5B9A\u4E49
 */

:host {
  display: inline-flex;
  align-items: center;
  gap: var(--pl-space-xs);
  padding: 0;
  margin: 0;
  vertical-align: middle;
}

/* \u2500\u2500 \u6309\u94AE\u5BB9\u5668 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-extra-dl-bar {
  display: inline-flex;
  align-items: center;
  gap: var(--pl-space-xs);
  font-family: var(--pl-font-sans);
  font-size: 13px;
  line-height: 1;
}

/* \u2500\u2500 \u53EF\u70B9\u51FB\u7684\u4E0B\u8F7D\u6309\u94AE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-extra-dl-btn {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  min-height: 28px;
  padding: 0 11px;
  border: 1px solid #bfdbfe;
  border-radius: 7px;
  font-size: 13px;
  font-weight: var(--pl-weight-semibold);
  line-height: 1;
  white-space: nowrap;
  background-color: #eff6ff;
  color: #1d4ed8;
  text-decoration: none;
  cursor: pointer;
  box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
  transition: background-color var(--pl-transition-fast),
              border-color var(--pl-transition-fast),
              box-shadow var(--pl-transition-fast),
              color var(--pl-transition-fast),
              transform var(--pl-transition-fast);
}

.pl-extra-dl-btn:hover {
  border-color: #93c5fd;
  background-color: #dbeafe;
  box-shadow: 0 2px 6px rgba(37, 99, 235, 0.1);
}

.pl-extra-dl-btn:active {
  transform: scale(0.96);
}

.pl-extra-dl-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 14px;
  height: 14px;
  flex-shrink: 0;
}

/* \u2500\u2500 \u7F6E\u7070\u72B6\u6001\uFF08\u65E0 DOI\uFF09 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-extra-dl-btn--disabled {
  border-color: #e5e7eb;
  background-color: #f8fafc;
  color: #94a3b8;
  cursor: not-allowed;
  pointer-events: auto;
  position: relative;
}

.pl-extra-dl-btn--disabled:hover {
  border-color: #e5e7eb;
  background-color: #f1f5f9;
  box-shadow: none;
}

/* \u2500\u2500 \u65E0 DOI \u7684 Tooltip \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-extra-dl-tooltip {
  display: none;
  position: absolute;
  bottom: calc(100% + 4px);
  left: 50%;
  transform: translateX(-50%);
  padding: 4px 8px;
  border-radius: var(--pl-radius-sm);
  background-color: var(--pl-color-gray-800);
  color: var(--pl-color-white);
  font-size: var(--pl-font-xs);
  font-weight: var(--pl-weight-normal);
  white-space: nowrap;
  z-index: var(--pl-z-tooltip);
  box-shadow: var(--pl-shadow-md);
  pointer-events: none;
}

.pl-extra-dl-tooltip::after {
  content: '';
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  border: 4px solid transparent;
  border-top-color: var(--pl-color-gray-800);
}

.pl-extra-dl-btn--disabled:hover .pl-extra-dl-tooltip {
  display: block;
}
`,DA=`/**
 * PaperLens Toast Notification Styles
 *
 * Plain DOM \u2014 NOT inside Shadow DOM.
 * Appended to document.body for maximum z-index stacking.
 * Uses --pl-* tokens via inline fallbacks for dark mode compatibility.
 */

/* \u2500\u2500 Container \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-toast-container {
  position: fixed;
  top: 72px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 2147483647;
  display: flex;
  flex-direction: column-reverse;
  align-items: center;
  gap: 8px;
  width: min(480px, calc(100vw - 32px));
  pointer-events: none;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans CJK SC', 'Noto Sans SC', 'Source Han Sans SC', 'Helvetica Neue', Arial, sans-serif;
}

/* \u2500\u2500 Individual Toast \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-toast {
  pointer-events: auto;
  display: flex;
  align-items: center;
  gap: 8px;
  width: fit-content;
  min-width: min(240px, 100%);
  max-width: 100%;
  padding: 12px 16px;
  border-radius: 10px;
  font-size: 14px;
  line-height: 1.4;
  color: #fff;
  -webkit-backdrop-filter: blur(8px);
  backdrop-filter: blur(8px);
  box-shadow: 0 14px 36px rgba(15, 23, 42, 0.2);
  cursor: pointer;
  user-select: none;
  word-break: break-word;
  opacity: 0;
  transform: translateY(-14px) scale(0.98);
  animation: pl-toast-in 300ms ease forwards;
}

.pl-toast--closing {
  animation: pl-toast-out 250ms ease forwards;
}

/* \u2500\u2500 Type Variants \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-toast--success {
  background: rgba(16, 185, 129, 0.92);
}
.pl-toast--error {
  background: rgba(239, 68, 68, 0.92);
}
.pl-toast--info {
  background: rgba(59, 130, 246, 0.92);
}

/* \u2500\u2500 Icon \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-toast-icon {
  flex-shrink: 0;
  font-size: 16px;
  line-height: 1;
}

/* \u2500\u2500 Message \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-toast-message {
  flex: 1;
}

/* \u2500\u2500 Animations (GPU-accelerated) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
@keyframes pl-toast-in {
  from {
    opacity: 0;
    transform: translateY(-14px) scale(0.98);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

@keyframes pl-toast-out {
  from {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
  to {
    opacity: 0;
    transform: translateY(-10px) scale(0.98);
  }
}

/* \u2500\u2500 Dark Mode \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
@media (prefers-color-scheme: dark) {
  .pl-toast {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);
  }
  .pl-toast--success {
    background: rgba(52, 211, 153, 0.88);
    color: #064e3b;
  }
  .pl-toast--error {
    background: rgba(248, 113, 113, 0.88);
    color: #7f1d1d;
  }
  .pl-toast--info {
    background: rgba(96, 165, 250, 0.88);
    color: #1e3a5f;
  }
}
`,_A={success:"\u2713",error:"\u2715",info:"\u2139"};let xs=!1;function kA(){if(xs||typeof document>"u")return;if(document.getElementById("paperlens-toast-styles")){xs=!0;return}const e=document.createElement("style");e.id="paperlens-toast-styles",e.textContent=DA,document.head.appendChild(e),xs=!0}class er{static instance;container=null;constructor(){}static getInstance(){return er.instance||(er.instance=new er),er.instance}ensureContainer(){if(this.container&&this.container.parentNode)return this.container;kA();const e=document.createElement("div");return e.className="pl-toast-container",document.body.appendChild(e),this.container=e,e}show(e){const t=this.ensureContainer(),n=e.duration??3e3,a=document.createElement("div");a.className=`pl-toast pl-toast--${e.type}`;const i=document.createElement("span");i.className="pl-toast-icon",i.textContent=_A[e.type];const o=document.createElement("span");o.className="pl-toast-message",o.textContent=e.message,a.append(i,o),a.addEventListener("click",()=>{this.dismiss(a)}),t.appendChild(a);const s=setTimeout(()=>{this.dismiss(a)},n);a.dataset.timer=String(s)}dismiss(e){e.dataset.dismissed||(e.dataset.dismissed="true",e.dataset.timer&&clearTimeout(Number(e.dataset.timer)),e.classList.add("pl-toast--closing"),e.addEventListener("animationend",()=>{e.remove(),this.container&&this.container.childNodes.length===0&&(this.container.remove(),this.container=null)},{once:!0}))}success(e,t){this.show({type:"success",message:e,duration:t})}error(e,t){this.show({type:"error",message:e,duration:t})}info(e,t){this.show({type:"info",message:e,duration:t})}}const D=er.getInstance(),Wd=ve+`
`+FA,As="paperlens-extra-download-host",NA="data-pl-doi",Gd="data-pl-oa",Zd="http://www.w3.org/2000/svg";function Yd(r,e,t,n,a={}){if(t&&(a.openAccessPdfUrl||a.pmcid))return null;const i=document.createElement("div");i.className=As,i.setAttribute("data-paperlens-fulltext","extra-download"),r&&i.setAttribute(NA,r),i.setAttribute(Gd,t?"true":"false");const o=i.attachShadow({mode:"open"}),s=document.createElement("style");s.textContent=Wd,o.appendChild(s);const l=document.createElement("div");l.className="pl-extra-dl-bar";const c=t||a.journalOpenAccess===!0;if(e||!!(c&&r))if(r){const d=document.createElement("a");d.className="pl-extra-dl-btn",d.href=c?IA(r):PA(e??"",r),d.target="_blank",d.rel="noopener noreferrer",d.title=c?"\u901A\u8FC7 DOI \u6253\u5F00\u5F00\u653E\u83B7\u53D6\u5168\u6587":"\u901A\u8FC7\u81EA\u5B9A\u4E49\u6E90\u4E0B\u8F7D\u5168\u6587",Cs(d,{doi:r,title:n,fallbackDomain:e,pmid:a.pmid,nativeFullTextUrl:a.nativeFullTextUrl,openAccessPdfUrl:a.openAccessPdfUrl,pmcid:a.pmcid,journalOpenAccess:a.journalOpenAccess},c?"\u5F00\u653E\u83B7\u53D6\u9875\u9762":"\u5907\u7528\u5168\u6587\u4E0B\u8F7D");const p=document.createElement("span");p.className="pl-extra-dl-icon",p.appendChild(ea());const h=document.createElement("span");h.textContent="\u5168\u6587\u4E0B\u8F7D",d.append(p,h),l.appendChild(d)}else if(n&&e){const d=document.createElement("a");d.className="pl-extra-dl-btn",d.href=BA(e,n),d.target="_blank",d.rel="noopener noreferrer",d.title="\u901A\u8FC7\u8BBA\u6587\u6807\u9898\u641C\u7D22\u4E0B\u8F7D\u5168\u6587",Cs(d,{title:n,fallbackDomain:e,pmid:a.pmid,nativeFullTextUrl:a.nativeFullTextUrl,openAccessPdfUrl:a.openAccessPdfUrl,pmcid:a.pmcid,journalOpenAccess:a.journalOpenAccess},"\u5907\u7528\u5168\u6587\u641C\u7D22");const p=document.createElement("span");p.className="pl-extra-dl-icon",p.appendChild(ea());const h=document.createElement("span");h.textContent="\u5168\u6587\u4E0B\u8F7D",d.append(p,h),l.appendChild(d)}else{const d=document.createElement("button");d.className="pl-extra-dl-btn pl-extra-dl-btn--disabled",d.type="button",d.disabled=!0,d.title="\u8BE5\u8BBA\u6587\u65E0 DOI\uFF0C\u65E0\u6CD5\u8DF3\u8F6C";const p=document.createElement("span");p.className="pl-extra-dl-icon",p.appendChild(ea());const h=document.createElement("span");h.textContent="\u5168\u6587\u4E0B\u8F7D",d.append(p,h),l.appendChild(d)}else{const d=document.createElement("button");d.className="pl-extra-dl-btn pl-extra-dl-btn--disabled",d.type="button",d.title="\u8BF7\u5728\u8BBE\u7F6E\u4E2D\u914D\u7F6E\u4E0B\u8F7D\u6E90",d.addEventListener("click",()=>{D.info("\u8BF7\u5728\u767B\u5F55\u540E\u7684\u8BBE\u7F6E\u4E2D\u914D\u7F6E\u4E0B\u8F7D\u6E90")});const p=document.createElement("span");p.className="pl-extra-dl-icon",p.appendChild(ea());const h=document.createElement("span");h.textContent="\u5168\u6587\u4E0B\u8F7D";const f=document.createElement("span");f.className="pl-extra-dl-tooltip",f.textContent="\u8BF7\u5728\u8BBE\u7F6E\u4E2D\u914D\u7F6E\u4E0B\u8F7D\u6E90",d.append(p,h,f),l.appendChild(d)}return o.appendChild(l),i}function LA(r,e="\u5168\u6587\u83B7\u53D6",t){const n=RA(r);if(!n)return null;const a=document.createElement("div");a.className=As,a.setAttribute("data-paperlens-fulltext","native");const i=a.attachShadow({mode:"open"}),o=document.createElement("style");o.textContent=Wd,i.appendChild(o);const s=document.createElement("div");s.className="pl-extra-dl-bar";const l=document.createElement("a");l.className="pl-extra-dl-btn",l.href=n,l.target="_blank",l.rel="noopener noreferrer",l.title="\u4F18\u5148\u6253\u5F00\u539F\u7AD9\u6216\u5F00\u653E\u83B7\u53D6\u5168\u6587";const c=!!(t?.doi||t?.openAccessPdfUrl||t?.pmcid||t?.journalOpenAccess);t&&c?Cs(l,{pmid:t.pmid,doi:t.doi,title:t.title,fallbackDomain:t.fallbackDomain,nativeFullTextUrl:t.nativeFullTextUrl??n,openAccessPdfUrl:t.openAccessPdfUrl,pmcid:t.pmcid,journalOpenAccess:t.journalOpenAccess}):l.addEventListener("click",p=>{p.stopPropagation()});const u=document.createElement("span");u.className="pl-extra-dl-icon",u.appendChild(ea());const d=document.createElement("span");return d.textContent=e,l.append(u,d),s.appendChild(l),i.appendChild(s),a}function mi(r){return document.createElementNS(Zd,r)}function ea(){const r=mi("svg");r.setAttribute("xmlns",Zd),r.setAttribute("width","14"),r.setAttribute("height","14"),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke","currentColor"),r.setAttribute("stroke-width","2"),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round");const e=mi("path");e.setAttribute("d","M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4");const t=mi("polyline");t.setAttribute("points","7 10 12 15 17 10");const n=mi("line");return n.setAttribute("x1","12"),n.setAttribute("y1","15"),n.setAttribute("x2","12"),n.setAttribute("y2","3"),r.append(e,t,n),r}function RA(r){try{const e=new URL(r,location.href);return e.protocol==="http:"||e.protocol==="https:"?e.href:null}catch{return null}}function PA(r,e){const t=Kd(r),n=e.replace(/^\/+/,"");return`${t}/${n}`}function BA(r,e){return`${Kd(r)}/search?q=${encodeURIComponent(e)}`}function IA(r){return`https://doi.org/${r.replace(/^\/+/,"")}`}function Cs(r,e,t="\u5907\u7528\u5168\u6587\u4E0B\u8F7D"){r.addEventListener("click",n=>{n.preventDefault(),n.stopPropagation(),qA(r.href,e,t)})}function MA(r){return r?.success===!1&&r.error==="No full text target found"}async function qA(r,e,t="\u5907\u7528\u5168\u6587\u4E0B\u8F7D"){const n=window.open("","_blank");try{D.info("\u6B63\u5728\u6838\u5BF9\u5F00\u653E\u83B7\u53D6\u5168\u6587...");const a=await H({type:"RESOLVE_FULLTEXT_DOWNLOAD",payload:e},12e3);if(a?.success===!1&&!MA(a)){n?.close(),D.error(a.error||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528\u5168\u6587\u4E0B\u8F7D");return}const i=a?.success&&a.data?.url?a.data.url:r,o=a?.success&&a.data?.isOpenAccess?a.data.label:t;jA(n,i),D.success(`\u5DF2\u6253\u5F00${o}`)}catch(a){n?.close(),D.error(a instanceof Error&&a.message==="runtime message timed out"?"\u5728\u7EBF\u6743\u9650\u6821\u9A8C\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5":"\u5728\u7EBF\u6743\u9650\u6821\u9A8C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5")}}function jA(r,e){if(r&&!r.closed){r.opener=null,r.location.href=e;return}window.open(e,"_blank","noopener,noreferrer")}function Kd(r){const e=r.trim().replace(/\/+$/,"");return e?/^https?:\/\//i.test(e)?e:`https://${e}`:""}function $A(r,e){document.querySelectorAll(`.${As}`).forEach(n=>{if(n.getAttribute("data-paperlens-fulltext")==="native"){n.style.display="";return}const a=n.getAttribute(Gd)==="true";n.style.display=r&&(a||e)?"":"none"})}const bi="paperlens_library";Promise.resolve();async function vs(){try{const r=await I.storage.local.get(bi);return r[bi]&&Array.isArray(r[bi])?r[bi]:[]}catch(r){return console.error("[Library] Failed to read library:",r),[]}}function OA(r){return r.pmid||r.sourceId||r.doi||""}function ta(r){const e=r?.trim()??"";return/^10\.\d{4,9}\//i.test(e)?e.toLowerCase():e}async function gi(r){if(!r)return!1;const e=await vs(),t=ta(r);return e.some(n=>ta(OA(n))===t||ta(n.pmid)===t||ta(n.doi)===t||ta(n.sourceId)===t)}const Qd="paperlens_auth_tokens";async function Xd(){const r=await UA();return r?!!r.refresh_token:!1}async function UA(){try{const e=(await I.storage.local.get(Qd))[Qd];return!e?.access_token||!e?.refresh_token?null:e}catch(r){return console.error("[TokenManager] Failed to load tokens:",r),null}}const HA=15e3;function zA(r){return{...r,authors:r.authors?[...r.authors]:void 0,keywords:r.keywords?[...r.keywords]:void 0,meshTerms:r.meshTerms?[...r.meshTerms]:void 0,publicationTypes:r.publicationTypes?[...r.publicationTypes]:void 0,affiliations:r.affiliations?[...r.affiliations]:void 0}}function JA(r){return!r.pmid||!r.issn||!r.publisher||r.citationCount==null}async function VA(r){const e=zA(r);if(!JA(e))return e;try{const t=await H({type:"ENRICH_LIBRARY_PAPER",payload:{paper:e}},HA);if(t?.success&&t.data)return t.data;t?.error&&console.warn("[PaperLens] Library metadata enrichment failed:",t.error)}catch(t){console.warn("[PaperLens] Library metadata enrichment request failed:",t)}return e}const WA=ve+`
`+`/**
 * Save Button Styles \u2014 injected into each save button's Shadow DOM
 *
 * \u8BBE\u8BA1\u89C4\u8303\uFF1A
 * - \u672A\u6536\u85CF\uFF1A\u6587\u5B57\u6536\u85CF\uFF0Chover \u63D0\u793A\u300C\u6536\u85CF\u6B64\u8BBA\u6587\u300D
 * - \u5DF2\u6536\u85CF\uFF1A\u6587\u5B57\u5DF2\u6536\u85CF\uFF0Chover \u63D0\u793A\u300C\u53D6\u6D88\u6536\u85CF\u300D
 * - \u70B9\u51FB\u5207\u6362\u72B6\u6001\uFF0C\u5373\u65F6\u66F4\u65B0 UI
 *
 * Design Token \u4F9D\u8D56\uFF1A
 *   --pl-color-* / --pl-font-* / --pl-space-* / --pl-radius-*
 *   \u7531 tokens.css \u5728\u540C\u4E00 Shadow DOM \u5185\u901A\u8FC7 :host \u5B9A\u4E49
 */

:host {
  display: inline-flex;
  align-items: center;
  vertical-align: middle;
  cursor: pointer;
  user-select: none;
}

/* \u2500\u2500 \u6309\u94AE\u5BB9\u5668 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-save-btn {
  position: relative;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  min-height: 28px;
  padding: 0 11px;
  border: 1px solid #d5dbe7;
  border-radius: 7px;
  font-family: var(--pl-font-sans);
  font-size: 13px;
  font-weight: var(--pl-weight-semibold);
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  transition: background-color var(--pl-transition-fast),
              border-color var(--pl-transition-fast),
              box-shadow var(--pl-transition-fast),
              color var(--pl-transition-fast),
              transform var(--pl-transition-fast);
  outline: none;
  background-color: #ffffff;
  box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
}

/* \u2500\u2500 \u672A\u6536\u85CF\u72B6\u6001 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-save-btn--unsaved {
  color: #334155;
}

.pl-save-btn--unsaved:hover {
  color: #1d4ed8;
  border-color: #93c5fd;
  background-color: #eff6ff;
  box-shadow: 0 2px 6px rgba(37, 99, 235, 0.1);
}

.pl-save-btn--unsaved:active {
  transform: scale(0.92);
}

/* \u2500\u2500 \u5DF2\u6536\u85CF\u72B6\u6001 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-save-btn--saved {
  color: #9a3412;
  border-color: #fdba74;
  background-color: #fff7ed;
}

.pl-save-btn--saved:hover {
  color: #b91c1c;
  border-color: #fecaca;
  background-color: #fff1f2;
}

.pl-save-btn--saved:active {
  transform: scale(0.92);
}

/* \u6536\u85CF\u52A8\u753B \u2014 \u653E\u5927\u540E\u56DE\u5F39 */
@keyframes pl-save-bounce {
  0% { transform: scale(1); }
  30% { transform: scale(1.35); }
  60% { transform: scale(0.9); }
  100% { transform: scale(1); }
}

.pl-save-label--animate {
  animation: pl-save-bounce 0.35s ease-out;
}

/* \u2500\u2500 \u63D0\u793A\u6587\u5B57 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-save-label {
  font-size: 13px;
  line-height: 1;
}

/* \u2500\u2500 Tooltip \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-save-tooltip {
  display: none;
  position: absolute;
  bottom: calc(100% + 4px);
  left: 50%;
  transform: translateX(-50%);
  padding: 4px 8px;
  border-radius: var(--pl-radius-sm);
  background-color: var(--pl-color-gray-800);
  color: var(--pl-color-white);
  font-size: var(--pl-font-xs);
  font-weight: var(--pl-weight-normal);
  white-space: nowrap;
  z-index: var(--pl-z-tooltip);
  box-shadow: var(--pl-shadow-md);
  pointer-events: none;
}

.pl-save-tooltip::after {
  content: '';
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  border: 4px solid transparent;
  border-top-color: var(--pl-color-gray-800);
}

.pl-save-btn:hover .pl-save-tooltip {
  display: block;
}
`,GA=2e4,ep="paperlens-save-host";function ZA(){const r=document.createElement("div");r.className=ep,r.dataset.pmid="";const e=r.attachShadow({mode:"open"}),t=document.createElement("style");return t.textContent=WA,e.appendChild(t),{host:r,shadow:e}}function Ss(r,e=!1){const{host:t,shadow:n}=ZA();rp(t,XA(r));const a=document.createElement("button");a.type="button",a.className=e?"pl-save-btn pl-save-btn--saved":"pl-save-btn pl-save-btn--unsaved";const i=document.createElement("span");i.className="pl-save-label",i.textContent=Ts(e);const o=document.createElement("span");return o.className="pl-save-tooltip",o.textContent=e?"\u53D6\u6D88\u6536\u85CF":"\u6536\u85CF\u6B64\u8BBA\u6587",a.append(i,o),n.appendChild(a),a.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),YA(t,a,i,r)}),t}async function YA(r,e,t,n){const a=r.dataset.pmid||np(n);if(e.classList.contains("pl-save-btn--saved")){const o=Array.from(ws(r));await QA(o),ra(r,!1),ap(r,!1),D.success("\u5DF2\u4ECE\u6587\u732E\u5E93\u79FB\u9664"),r.dispatchEvent(new CustomEvent("paperlens:unsaved",{bubbles:!0,detail:{pmid:a,ids:o}}))}else{if(!await Xd()){D.info("\u8BF7\u5148\u767B\u5F55\u540E\u518D\u6536\u85CF\u8BBA\u6587",4e3);return}try{const s=tC(n),l=await VA(s),c=eC(l,n.alternateIds);rp(r,c);const u=(await Promise.all(c.map(d=>gi(d)))).some(Boolean);await KA(l),ra(r,!0),ap(r,!0),t.classList.add("pl-save-label--animate"),t.addEventListener("animationend",()=>{t.classList.remove("pl-save-label--animate")},{once:!0}),u?D.info("\u8BE5\u8BBA\u6587\u5DF2\u5728\u6587\u732E\u5E93\u4E2D"):D.success("\u5DF2\u4FDD\u5B58\u5230\u6587\u732E\u5E93"),r.dispatchEvent(new CustomEvent("paperlens:saved",{bubbles:!0,detail:{pmid:c[0]??a,ids:c}}))}catch{D.error("\u4FDD\u5B58\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5")}}}async function tp(r){try{const e=await H(r,GA);if(e?.success===!0)return;throw new Error(e?.error||"Background library mutation failed")}catch(e){throw e instanceof Error?e:new Error("Background library mutation failed")}}async function KA(r){await tp({type:"ADD_LIBRARY_PAPER",payload:{paper:r}})}async function QA(r){await tp({type:"REMOVE_LIBRARY_PAPERS",payload:{ids:r}})}function np(r){return r.pmid||r.sourceId||r.doi||""}function XA(r){return Array.from(new Set([np(r),r.pmid,r.sourceId,r.doi,na(r.doi),...r.alternateIds??[],...(r.alternateIds??[]).map(na)].filter(Boolean)))}function eC(r,e=[]){return Array.from(new Set([r.pmid,r.sourceId,r.doi,na(r.doi),...e,...e.map(na)].filter(Boolean)))}function ws(r){const e=[r.dataset.pmid,...r.dataset.paperlensIds?.split("	")??[]].filter(t=>!!t);return new Set(e.flatMap(t=>[t,na(t)]).filter(Boolean))}function na(r){const e=r?.trim()??"";return/^10\.\d{4,9}\//i.test(e)?e.toLowerCase():e}function rp(r,e){r.dataset.pmid=e[0]??"",r.dataset.paperlensIds=e.join("	")}function tC(r){return{sourceId:r.sourceId,source:r.source,pmid:r.pmid,doi:r.doi,title:r.title,journal:r.journal,impactFactor:r.impactFactor,jcrQuartile:r.jcrQuartile,casQuartile:r.casQuartile,year:r.year,citationCount:r.citationCount,url:r.url,language:r.language,authors:r.authors?[...r.authors]:void 0,abstract:r.abstract,keywords:r.keywords?[...r.keywords]:void 0,meshTerms:r.meshTerms?[...r.meshTerms]:void 0,publicationTypes:r.publicationTypes?[...r.publicationTypes]:void 0,volume:r.volume,issue:r.issue,pages:r.pages,publisher:r.publisher,issn:r.issn,pmcid:r.pmcid,pdfUrl:r.pdfUrl,oaUrl:r.oaUrl,sourceUrl:r.sourceUrl||r.url,affiliations:r.affiliations?[...r.affiliations]:void 0,savedAt:Date.now()}}function Ts(r){return r?"\u5DF2\u6536\u85CF":"\u6536\u85CF"}function ap(r,e){const t=ws(r);t.size!==0&&r.ownerDocument.querySelectorAll(`.${ep}`).forEach(n=>{if(n===r)return;const a=ws(n);Array.from(t).some(i=>a.has(i))&&ra(n,e)})}function ra(r,e){const t=r.shadowRoot;if(!t)return;const n=t.querySelector(".pl-save-btn"),a=t.querySelector(".pl-save-label"),i=t.querySelector(".pl-save-tooltip");!n||!a||!i||(e?(n.className="pl-save-btn pl-save-btn--saved",a.textContent=Ts(!0),i.textContent="\u53D6\u6D88\u6536\u85CF"):(n.className="pl-save-btn pl-save-btn--unsaved",a.textContent=Ts(!1),i.textContent="\u6536\u85CF\u6B64\u8BBA\u6587"))}function Es(r,e,t){const n=new Blob([r],{type:t}),a=URL.createObjectURL(n),i=document.createElement("a");i.href=a,i.download=e,i.style.display="none",document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(a)}const Fs={ris:"application/x-research-info-systems",bibtex:"application/x-bibtex",medline:"text/plain",csv:"text/csv;charset=utf-8"},ip={ris:".ris",bibtex:".bib",medline:".nbib",csv:".csv"},Ds=Object.freeze(Object.defineProperty({__proto__:null,EXPORT_EXTENSIONS:ip,EXPORT_MIME_TYPES:Fs,downloadFile:Es},Symbol.toStringTag,{value:"Module"})),Le="pubmed.query_optimizer",It="PubMed \u68C0\u7D22\u8BCD\u4F18\u5316",tr="pubmed.advanced_filter",op="PubMed \u9AD8\u7EA7\u7B5B\u9009",nr="pubmed.full_result_analysis",sp="PubMed \u5168\u91CF\u7ED3\u679C\u5206\u6790",rr="ai.translate",_s="AI \u7FFB\u8BD1",aa="ai.summarize",lp="AI \u603B\u7ED3",et="ai.deep_interpretation",ar="AI \u89E3\u8BFB",Mt="export.zotero",cp="Zotero \u5BFC\u51FA",pe="paperlens:entitlement-ui-sync",up={ris:"export.ris",bibtex:"export.bibtex",medline:"export.nbib",csv:"export.csv"},nC={ris:"RIS \u5BFC\u51FA",bibtex:"BibTeX \u5BFC\u51FA",medline:"MEDLINE/NBIB \u5BFC\u51FA",csv:"CSV \u5BFC\u51FA"},rC=new Set(Object.values(up)),mn="paperlens_entitlement_snapshot",bn="paperlens_entitlement_ui_denied",aC=1800*1e3,ks=25e3,yi="\u6743\u76CA\u6821\u9A8C\u8D85\u65F6\uFF0C\u8BF7\u5237\u65B0\u9875\u9762\u540E\u91CD\u8BD5",dp=[Le,tr,nr,rr,aa,et,Mt];let xi=null,Ns=!1,Ls=null,gn=null;const qt=new Map;let ir="",ia="";function Rs(r){return r===Le?It:r===tr?op:r===nr?sp:r===rr?_s:r===aa?lp:r===et?ar:r===Mt?cp:r}function oa(r){if(typeof document>"u")return;const e=document.defaultView?.CustomEvent??(typeof CustomEvent=="function"?CustomEvent:null);e&&document.dispatchEvent(new e(pe,{detail:r}))}function Ps(r){return r?.features?JSON.stringify({plan:r.plan,status:r.status,expires_at:r.expires_at??null,core_status:r.core_entitlement?.status??null,core_plan:r.core_entitlement?.plan??null,core_lifetime:r.core_entitlement?.lifetime??null,ai_status:r.ai_entitlement?.status??null,ai_active:r.ai_entitlement?.active??null,features:r.features,limits:r.limits}):""}function Bs(r){const e=r?.server_time;return typeof e=="string"?e.slice(0,7):""}function pp(r){if(!r)return!1;const e=r.core_entitlement;if(e?.plan==="pro"&&e.lifetime&&e.status!=="expired"&&e.status!=="cancelled")return!0;const t=e?.expires_at??r.expires_at;if(t){const n=Date.parse(t);if(Number.isFinite(n)&&n<=Date.now())return!1}return e?.plan==="pro"&&e.status==="active"?!0:r.plan==="pro"&&r.status==="active"}function Is(r){return r===rr||r===aa||r===et}function hp(r){return rC.has(r)}function fp(r){return r===Le||r===tr||r===nr||r===Mt||hp(r)||Is(r)}function iC(r){return r===Le||r===tr||r===nr}function Ms(r){return r==="plugin.chrome"||r==="metrics.basic"||r==="metrics.warning_tags"||r==="fulltext.open_access"||r.startsWith("sites.")}function mp(r){return iC(r)||Is(r)||hp(r)||r===Mt||Ms(r)}function oC(r,e){return Object.prototype.hasOwnProperty.call(r.features??{},e)}function bp(r){const e=r?.server_time;if(typeof e!="string")return!1;const t=Date.parse(e);return Number.isFinite(t)?Math.abs(Date.now()-t)<=aC:!1}function sa(r,e){return r?oC(r,e)?r.features?.[e]===!0:(fp(e)||Ms(e))&&pp(r)?!0:r.features?.[e]===!0:!1}function gp(r,e,t){return(fp(e)||Ms(e))&&r&&!pp(r)?`${t} \u662F Pro \u6C38\u4E45\u7248\u6743\u76CA\uFF0C${td()}`:`\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528${t}`}function sC(r){if(!r||typeof r!="object")return{};const e={};for(const[t,n]of Object.entries(r)){if(!n||typeof n!="object")continue;const a=n;e[t]={snapshotSignature:typeof a.snapshotSignature=="string"?a.snapshotSignature:"",quotaPeriodKey:typeof a.quotaPeriodKey=="string"?a.quotaPeriodKey:void 0,quotaDenied:typeof a.quotaDenied=="boolean"?a.quotaDenied:void 0,aiServiceDenied:typeof a.aiServiceDenied=="boolean"?a.aiServiceDenied:void 0,featureLabel:typeof a.featureLabel=="string"?a.featureLabel:void 0,error:typeof a.error=="string"?a.error:void 0,createdAt:typeof a.createdAt=="number"?a.createdAt:Date.now()}}return e}function yp(r){qt.clear();for(const[e,t]of Object.entries(sC(r)))qt.set(e,t)}function lC(){return Object.fromEntries(qt.entries())}async function xp(){try{const r=lC();if(Object.keys(r).length===0){await I.storage.local.remove(bn);return}await I.storage.local.set({[bn]:r})}catch{}}async function cC(){try{const r=await I.storage.local.get(bn);yp(r[bn])}catch{qt.clear()}}async function Ai(){try{return(await I.storage.local.get(mn))[mn]??null}catch{return null}}async function uC(){if(!ir)try{const r=await Ai();r&&(ir=Ps(r),ia=Bs(r))}catch{}}function Ap(r){const e=Cp(r.error),t=vp(r.error);qt.set(r.featureKey,{snapshotSignature:ir,quotaPeriodKey:e?ia:void 0,quotaDenied:e,aiServiceDenied:t,featureLabel:r.featureLabel,error:r.error,createdAt:Date.now()}),xp()}function Cp(r){return/本月.*次数已用完|次数已用完|QUOTA_EXCEEDED/i.test(r||"")}function vp(r){return/AI\s*服务包|ai_monthly|AI_SERVICE_INACTIVE/i.test(r||"")}function Sp(r,e){return e.quotaDenied===!0||e.aiServiceDenied===!0?!0:Is(r)}function Ci(r){return r instanceof Error&&r.message==="runtime message timed out"}function dC(){const r=globalThis.chrome?.runtime;return r?.sendMessage?r:null}function pC(){const r=I.runtime;return r?.sendMessage?r:null}function wp(r,e){return new Promise((t,n)=>{try{const a=r.sendMessage?.(e,i=>{const o=r.lastError?.message;if(o){n(new Error(o));return}if(typeof i>"u"){n(new Error("empty runtime response"));return}t(i)});a&&typeof a.then=="function"&&a.then(i=>{if(typeof i>"u"){n(new Error("empty runtime response"));return}t(i)}).catch(n)}catch(a){n(a)}})}function Tp(r){const e=I.runtime;return e?.sendMessage?e.sendMessage(r).then(t=>{if(typeof t>"u")throw new Error("empty runtime response");return t}):Promise.reject(new Error("runtime messaging is unavailable"))}function hC(r){return r.length===0?Promise.reject(new Error("runtime messaging is unavailable")):r.length===1?r[0]:new Promise((e,t)=>{let n=0;const a=[];for(const i of r)i.then(e).catch(o=>{if(n+=1,a.push(o),n===r.length){const s=a.find(Boolean);t(s instanceof Error?s:new Error("runtime messaging failed"))}})})}function fC(r){if(!qr())return Tp(r);const e=ad(r)?r:id(r),t=[],n=dC();n&&t.push(wp(n,e));const a=pC();return a&&t.push(wp(a,e)),I.runtime?.sendMessage&&t.push(Tp(e)),hC(t)}function Ep(r,e=ks){return new Promise((t,n)=>{const a=setTimeout(()=>n(new Error("runtime message timed out")),e);fC(r).then(i=>{clearTimeout(a),t(i)}).catch(i=>{clearTimeout(a),n(i)})})}function qs(r){qt.delete(r)&&xp()}function jt(r){const e=r?.features;if(!e){ir="",ia="";for(const i of dp){const o=Rs(i),s=qt.get(i);oa({featureKey:i,featureLabel:o,allowed:!1,error:s?.error||`\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528${o}`,source:"snapshot"})}return}const t=Ps(r),n=Bs(r);ir=t,ia=n;const a=new Set([...dp,...Object.keys(e)]);for(const i of a){const o=sa(r,i),s=Rs(i),l=qt.get(i),c=!!(l?.quotaDenied&&l.quotaPeriodKey&&n&&l.quotaPeriodKey!==n),u=l?Sp(i,l):!1,d=o&&!!l&&u&&l?.snapshotSignature===t&&!c;o&&l&&(!u||l.snapshotSignature!==t||c)&&qs(i),oa({featureKey:i,featureLabel:s,allowed:d?!1:o,error:d?l?.error||gp(r,i,s):o?void 0:gp(r,i,s),source:"snapshot"})}}function yn(r,e=Rs(r)){qs(r),oa({featureKey:r,featureLabel:e,allowed:!0,source:"online-allowed"})}function xn(){if(typeof document>"u")return;if(Ns&&Ls===document){js();return}const r=I.storage?.onChanged;gn&&r?.removeListener&&r.removeListener(gn),r?.addListener&&(gn=(e,t)=>{if(!(t&&t!=="local"))if(Object.prototype.hasOwnProperty.call(e,bn)&&yp(e[bn]?.newValue),Object.prototype.hasOwnProperty.call(e,mn)){const n=e[mn]?.newValue;jt(n??null)}else Object.prototype.hasOwnProperty.call(e,bn)&&js({refreshIfMissing:!1})},r.addListener(gn),Ns=!0,Ls=document,window.addEventListener("pagehide",()=>{gn&&r.removeListener&&r.removeListener(gn),gn=null,Ns=!1,Ls=null},{once:!0})),js()}async function js(r={}){try{await cC();const e=await I.storage.local.get(mn),t=Object.prototype.hasOwnProperty.call(e,mn),n=e[mn]??null;if(t&&jt(n),r.refreshIfMissing!==!1){const a=await $s();if(a.snapshot){jt(a.snapshot);return}const i=await Ai();jt(i);return}if(!t){jt(null);return}}catch{}}async function $s(){return xi||(xi=Ep({type:"REFRESH_ENTITLEMENTS"},ks).then(r=>({snapshot:r?.success&&r.data?r.data:null,timedOut:!1,error:r?.success===!1?r.error:void 0})).catch(r=>({snapshot:null,timedOut:Ci(r),error:Ci(r)?yi:void 0})).finally(()=>{xi=null})),xi}async function $t(r,e={}){let t=null,n=!1;await uC();const a=ir,i=ia,o=Cp(r.error);Ap(r);try{if(t=(await $s()).snapshot,t){const l=Ps(t),c=Bs(t),u=!!(o&&i&&c&&i!==c),d=Sp(r.featureKey,{quotaDenied:o,aiServiceDenied:vp(r.error)});n=sa(t,r.featureKey)&&(d?l!==a||u:!0),jt(t)}else{const l=await Ai();e.allowCachedRuntimeFallback===!0&&!o&&mp(r.featureKey)&&bp(l)&&sa(l,r.featureKey)&&(t=l,n=!0),jt(l)}}catch{}finally{n?(qs(r.featureKey),oa({featureKey:r.featureKey,featureLabel:r.featureLabel,allowed:!0,source:"snapshot"})):(Ap(r),oa({...r,allowed:!1,source:"online-denied"}))}return n}async function Fp(r,e){if(!mp(r))return null;const t=await Ai();return!bp(t)||!sa(t,r)?null:(jt(t),yn(r,e),{allowed:!0})}async function We(r,e,t={}){const n=await Fp(r,e);if(n)return n;try{const a=await Ep({type:"CHECK_ENTITLEMENT",payload:{featureKey:r,featureLabel:e}},ks);if(a?.success===!0&&a.data?.allowed===!0)return t.syncUiAfterDenied===!0&&yn(r,e),{allowed:!0};const i=a?.error||`\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528${e}`,o=t.syncUiAfterDenied===!0?await $t({featureKey:r,featureLabel:e,error:i}):!1;return{allowed:o,error:o?void 0:i,syncedAllowed:o}}catch(a){const i=Ci(a),o=i?yi:"\u8BF7\u5148\u767B\u5F55\u8D26\u6237\uFF0C\u6216\u7A0D\u540E\u91CD\u8BD5",s=t.syncUiAfterDenied===!0&&!i?await $t({featureKey:r,featureLabel:e,error:o},{allowCachedRuntimeFallback:!0}):!1;return{allowed:s,error:s?void 0:o,syncedAllowed:s,transient:i&&!s}}}async function Dp(){const r=await Fp(Le,It);return r||$s().then(async e=>{const t=e.snapshot;if(sa(t,Le))return yn(Le,It),{allowed:!0};const n=e.timedOut?yi:t?`${It} \u662F Pro \u6C38\u4E45\u7248\u6743\u76CA\uFF0C${td()}`:e.error||"\u8BF7\u5148\u767B\u5F55\u8D26\u6237\uFF0C\u6216\u7A0D\u540E\u91CD\u8BD5";if(e.timedOut)return{allowed:!1,error:n,syncedAllowed:!1,transient:!0};const a=await $t({featureKey:Le,featureLabel:It,error:n});return{allowed:a,error:a?void 0:n,syncedAllowed:a}}).catch(async e=>{const t=Ci(e),n=t?yi:"\u8BF7\u5148\u767B\u5F55\u8D26\u6237\uFF0C\u6216\u7A0D\u540E\u91CD\u8BD5";if(t)return{allowed:!1,error:n,syncedAllowed:!1,transient:!0};const a=await $t({featureKey:Le,featureLabel:It,error:n});return{allowed:a,error:a?void 0:n,syncedAllowed:a}})}function Os(){return We(tr,op,{syncUiAfterDenied:!0})}function _p(){return We(nr,sp,{syncUiAfterDenied:!0})}function mC(r){return up[r]}function bC(r){return nC[r]}function lt(r){return We(mC(r),bC(r),{syncUiAfterDenied:!0})}function or(){return We(Mt,cp,{syncUiAfterDenied:!0})}const gC=ve+`
`+`/**
 * Export Button Styles \u2014 injected into each export button's Shadow DOM
 *
 * \u8BBE\u8BA1\u89C4\u8303\uFF1A
 * - \u5C0F\u5DE7\u7D27\u51D1\u7684\u5BFC\u51FA\u6309\u94AE\uFF0C\u4E0E metric-bar \u98CE\u683C\u4E00\u81F4
 * - \u4E0B\u62C9\u83DC\u5355\u4F7F\u7528 Shadow DOM \u9694\u79BB
 * - \u4F7F\u7528 --pl-* design tokens
 */

:host {
  display: inline-flex;
  align-items: center;
  vertical-align: middle;
  position: relative;
  user-select: none;
}

/* \u2500\u2500 \u6309\u94AE\u5BB9\u5668 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-export-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  min-height: 28px;
  padding: 0 11px;
  border: 1px solid #d5dbe7;
  border-radius: 7px;
  background-color: #ffffff;
  font-family: var(--pl-font-sans);
  font-size: 13px;
  font-weight: var(--pl-weight-semibold);
  color: #334155;
  cursor: pointer;
  white-space: nowrap;
  height: 28px;
  line-height: 1;
  box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
  transition: all var(--pl-transition-fast);
}

.pl-export-btn:hover {
  border-color: #93c5fd;
  color: #1d4ed8;
  background-color: #eff6ff;
  box-shadow: 0 2px 6px rgba(37, 99, 235, 0.1);
}

.pl-export-btn:active {
  transform: scale(0.95);
}

.pl-export-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* \u2500\u2500 \u6279\u91CF\u5BFC\u51FA\u6309\u94AE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-export-btn--batch {
  padding: 4px 10px;
  height: 28px;
}

.pl-export-label {
  font-size: 13px;
  line-height: 1;
}

/* \u2500\u2500 Tooltip \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-export-tooltip {
  display: none;
  position: absolute;
  bottom: calc(100% + 4px);
  left: 50%;
  transform: translateX(-50%);
  padding: 4px 8px;
  border-radius: var(--pl-radius-sm);
  background-color: var(--pl-color-gray-800);
  color: var(--pl-color-white);
  font-size: var(--pl-font-xs);
  font-weight: var(--pl-weight-normal);
  white-space: nowrap;
  z-index: var(--pl-z-tooltip);
  box-shadow: var(--pl-shadow-md);
  pointer-events: none;
}

.pl-export-tooltip::after {
  content: '';
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  border: 4px solid transparent;
  border-top-color: var(--pl-color-gray-800);
}

.pl-export-btn:hover .pl-export-tooltip {
  display: block;
}

/* \u2500\u2500 \u4E0B\u62C9\u83DC\u5355 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-export-dropdown {
  display: none;
  position: absolute;
  top: calc(100% + 4px);
  left: 50%;
  transform: translateX(-50%);
  min-width: 160px;
  background-color: var(--pl-color-white);
  border: 1px solid var(--pl-color-gray-200);
  border-radius: var(--pl-radius-md);
  box-shadow: var(--pl-shadow-lg);
  z-index: var(--pl-z-dropdown);
  padding: var(--pl-space-xs) 0;
  overflow: hidden;
}

/* \u2500\u2500 \u4E0B\u62C9\u83DC\u5355\u9009\u9879 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-export-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 6px 12px;
  border: none;
  background: none;
  font-family: var(--pl-font-sans);
  font-size: var(--pl-font-xs);
  cursor: pointer;
  transition: background-color var(--pl-transition-fast);
  text-align: left;
}

.pl-export-option:hover {
  background-color: var(--pl-color-primary-light);
}

.pl-export-option:disabled {
  cursor: not-allowed;
  opacity: 0.55;
}

.pl-export-option:disabled:hover {
  background: none;
}

.pl-export-option-name {
  font-weight: var(--pl-weight-semibold);
  color: var(--pl-color-gray-800);
}

.pl-export-option-desc {
  font-weight: var(--pl-weight-normal);
  color: var(--pl-color-gray-400);
  margin-left: 8px;
}
`,yC=45e3,xC="paperlens-export-host";function AC(r){return!(r instanceof Error)||!r.message?"\u5BFC\u51FA\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5":r.message==="runtime message timed out"?"\u5BFC\u51FA\u5931\u8D25\uFF1A\u540E\u53F0\u54CD\u5E94\u8D85\u65F6":`\u5BFC\u51FA\u5931\u8D25\uFF1A${r.message}`}const CC=[{value:"ris",label:"RIS",desc:"EndNote / Zotero"},{value:"bibtex",label:"BibTeX",desc:"LaTeX"},{value:"medline",label:"NBIB",desc:"MEDLINE / EndNote"},{value:"csv",label:"CSV",desc:"Excel"}];function kp(){const r=document.createElement("div");r.className=xC;const e=r.attachShadow({mode:"open"}),t=document.createElement("style");return t.textContent=gC,e.appendChild(t),{host:r,shadow:e}}function vC(r){return r==="ris"||r==="bibtex"||r==="medline"||r==="csv"}async function Np(r){const e=await lt(r);return e.allowed?!0:(D.error(e.error||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528\u8BE5\u5BFC\u51FA\u683C\u5F0F"),!1)}async function Lp(r){const e=Array.from(r.querySelectorAll(".pl-export-option[data-export-format]"));await Promise.all(e.map(async t=>{const n=t.dataset.exportFormat;if(!vC(n))return;const a=await lt(n),i=t.querySelector(".pl-export-option-desc"),o=t.dataset.defaultDesc||i?.textContent||"";if(a.allowed){t.disabled=!1,t.title="",t.classList.remove("pl-export-option--locked"),t.removeAttribute("aria-disabled"),i&&(i.textContent=o);return}t.disabled=!0,t.title=a.error||"\u8BE5\u5BFC\u51FA\u683C\u5F0F\u6682\u4E0D\u53EF\u7528",t.classList.add("pl-export-option--locked"),t.setAttribute("aria-disabled","true"),i&&(i.textContent="Pro")}))}function Rp(r,e){const t=document.createElement("button");t.type="button",t.className="pl-export-option",t.dataset.exportFormat=r.value,t.dataset.defaultDesc=r.desc;const n=document.createElement("span");n.className="pl-export-option-name",n.textContent=r.label;const a=document.createElement("span");return a.className="pl-export-option-desc",a.textContent=r.desc,t.append(n,a),t.addEventListener("click",async()=>{await e()}),t}function SC(r){const{host:e,shadow:t}=kp(),n=document.createElement("button");n.type="button",n.className="pl-export-btn",n.setAttribute("aria-label","\u5BFC\u51FA\u6587\u732E");const a=document.createElement("span");a.className="pl-export-label",a.textContent="\u5BFC\u51FA",n.appendChild(a);const i=wC(r);return i.classList.add("pl-export-dropdown"),i.style.display="none",t.append(n,i),n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation();const s=i.style.display!=="none";Pp(),s||(i.style.display="block",Lp(i))}),document.addEventListener("click",o=>{e.contains(o.target)||(i.style.display="none")}),e}function wC(r){const e=document.createElement("div");for(const t of CC){const n=Rp(t,async()=>{e.style.display="none",await TC([r],t.value)});e.appendChild(n)}return e}function Pp(){document.querySelectorAll(Bn).forEach(r=>{const e=r.shadowRoot;if(e){const t=e.querySelector(".pl-export-dropdown");t instanceof HTMLElement&&(t.style.display="none")}})}async function TC(r,e){if(!await Np(e))return;const t={type:"EXPORT_PUBMED_RECORDS",payload:{pmids:r,format:e}};let n;try{D.info("\u6B63\u5728\u5BFC\u51FA..."),n=await H(t,yC)}catch(u){D.error(AC(u));return}if(!n?.success||!n.data){D.error(n?.error?`\u5BFC\u51FA\u5931\u8D25\uFF1A${n.error}`:"\u5BFC\u51FA\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5");return}const{downloadFile:a,EXPORT_MIME_TYPES:i,EXPORT_EXTENSIONS:o}=await Promise.resolve().then(()=>Ds),s=o[e]??".txt",l=i[e]??"text/plain",c=r.length===1?`PMID${r[0]}${s}`:`pubmed_export_${new Date().toISOString().slice(0,10)}${s}`;a(n.data,c,l),D.success(`\u5DF2\u5BFC\u51FA ${r.length} \u7BC7\u6587\u732E`)}const EC=[{value:"ris",label:"RIS",desc:"EndNote / Zotero"},{value:"bibtex",label:"BibTeX",desc:"LaTeX"},{value:"csv",label:"CSV",desc:"Excel"}];function FC(r){const e=[],t=r.citationType??"article",n=t==="inproceedings"?"CONF":t==="incollection"?"CHAP":t==="book"?"BOOK":t==="misc"?"GEN":"JOUR";if(e.push(`TY  - ${n}`),e.push(`TI  - ${r.title}`),r.authors)for(const a of r.authors)e.push(`AU  - ${a}`);if(r.journal&&e.push(`JO  - ${r.journal}`),r.journal&&e.push(`T2  - ${r.journal}`),r.publicationDate&&e.push(`DA  - ${r.publicationDate}`),r.year&&e.push(`PY  - ${r.year}`),r.volume&&e.push(`VL  - ${r.volume}`),r.issue&&e.push(`IS  - ${r.issue}`),r.pages){const{startPage:a,endPage:i}=DC(r.pages);e.push(`SP  - ${a}`),i&&e.push(`EP  - ${i}`)}return r.doi&&e.push(`DO  - ${r.doi}`),r.issn&&e.push(`SN  - ${r.issn}`),r.url&&e.push(`UR  - ${r.url}`),r.abstract&&e.push(`AB  - ${r.abstract}`),e.push("ER  -"),e.join(`
`)}function DC(r){const e=r.trim();if(!e)return{startPage:r};const n=e.replace(/[–—]/g,"-").split(/\s*-\s*/).map(a=>a.trim()).filter(Boolean);return n.length>=2?{startPage:n[0],endPage:n[n.length-1]}:{startPage:e}}function _C(r){const e=r.citationType??"article",n=(r.authors?.[0]?.split(" ").pop()??"unknown").toLowerCase().replace(/[^a-z]/g,"")+(r.year??""),a=[];if(a.push(`  title = {${Ot(r.title)}}`),r.authors?.length&&a.push(`  author = {${r.authors.map(Ot).join(" and ")}}`),r.journal){const i=e==="inproceedings"||e==="incollection"?"booktitle":e==="misc"?"howpublished":"journal";a.push(`  ${i} = {${Ot(r.journal)}}`)}return r.volume&&a.push(`  volume = {${Ot(r.volume)}}`),r.issue&&a.push(`  number = {${Ot(r.issue)}}`),r.pages&&a.push(`  pages = {${Ot(r.pages.replace(/-/g,"--"))}}`),r.year&&a.push(`  year = {${r.year}}`),r.doi&&a.push(`  doi = {${r.doi}}`),r.issn&&a.push(`  issn = {${Ot(r.issn)}}`),r.url&&a.push(`  url = {${r.url}}`),r.abstract&&a.push(`  abstract = {${Ot(r.abstract)}}`),`@${e}{${n},
${a.join(`,
`)}
}`}function Ot(r){return r.replace(/\\/g,"\\\\").replace(/\{/g,"\\{").replace(/\}/g,"\\}")}function kC(r){return`"Title","Authors","Journal","PublicationDate","Year","Volume","Issue","Pages","DOI","ISSN","URL"
`+[r.title,(r.authors??[]).join("; "),r.journal??"",r.publicationDate??"",r.year?.toString()??"",r.volume??"",r.issue??"",r.pages??"",r.doi??"",r.issn??"",r.url??""].map(t=>`"${t.replace(/"/g,'""')}"`).join(",")}function NC(r,e){if(e==="ris")return r.nativeExportUrls?.ris;if(e==="bibtex")return r.nativeExportUrls?.bibtex}function Bp(r,e){const t=ip[e]??".txt";return`${r.title.slice(0,40).replace(/[^a-zA-Z0-9]/g,"_")}${t}`}async function LC(r,e){if(!await Np(e))return;const t=NC(r,e);if(t){try{const i=await fetch(t);if(i.ok){const o=await i.text(),s=Fs[e]??"text/plain";Es(o,Bp(r,e),s),D.success("\u5DF2\u5BFC\u51FA\u6587\u732E");return}}catch{}window.open(t,"_blank","noopener,noreferrer"),D.success("\u5DF2\u6253\u5F00\u539F\u7AD9\u5BFC\u51FA");return}let n;switch(e){case"ris":n=FC(r);break;case"bibtex":n=_C(r);break;case"csv":n=kC(r);break}const a=Fs[e]??"text/plain";Es(n,Bp(r,e),a),D.success("\u5DF2\u5BFC\u51FA\u6587\u732E")}function RC(r){const{host:e,shadow:t}=kp(),n=document.createElement("button");n.type="button",n.className="pl-export-btn",n.setAttribute("aria-label","\u5BFC\u51FA\u6587\u732E");const a=document.createElement("span");a.className="pl-export-label",a.textContent="\u5BFC\u51FA",n.appendChild(a);const i=document.createElement("div");i.className="pl-export-dropdown",i.style.display="none";for(const o of EC){const s=Rp(o,()=>{i.style.display="none",LC(r,o.value)});i.appendChild(s)}return t.append(n,i),n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation();const s=i.style.display!=="none";Pp(),s||(i.style.display="block",Lp(i))}),document.addEventListener("click",o=>{e.contains(o.target)||(i.style.display="none")}),e}function Us(r){const e={itemType:PC(r),title:r.title,creators:IC(r),abstractNote:r.abstract||void 0,date:MC(r),DOI:r.doi||void 0,url:r.url||(r.pmid?`https://pubmed.ncbi.nlm.nih.gov/${r.pmid}/`:void 0),extra:qC(r),publicationTitle:r.journal||void 0,volume:r.volume||void 0,issue:r.issue||void 0,pages:r.pages||void 0,ISSN:r.issn||void 0,tags:(r.tags||[]).map(t=>({tag:t})),attachments:[],notes:[],seeAlso:[],complete:!0,libraryCatalog:BC(r),accessDate:new Date().toISOString().slice(0,10)};return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function PC(r){switch(r.citationType){case"inproceedings":return"conferencePaper";case"incollection":return"bookSection";case"book":return"book";case"misc":return"webpage";default:return"journalArticle"}}function BC(r){if(r.pmid)return"PubMed";if(r.source)switch(r.source){case"sciencedirect":return"ScienceDirect";case"springerlink":return"SpringerLink";case"wiley":return"Wiley Online Library";case"sage-journals":return"Sage Journals";case"nature":return"Nature";case"science-org":return"Science.org";default:return r.source}}function IC(r){return r.s2Authors&&r.s2Authors.length>0?r.s2Authors.map(e=>{if(e.firstName&&e.lastName)return{creatorType:"author",firstName:e.firstName,lastName:e.lastName};const t=(e.name||"").trim();return t?Ip(t):null}).filter(e=>e!==null):r.authors&&r.authors.length>0?r.authors.map(e=>Ip(e)).filter(Boolean):[]}function Ip(r){const e=r.trim();if(!e)return{creatorType:"author",name:e};if(e.includes(",")){const i=e.split(",").map(o=>o.trim());if(i.length>=2&&i[0]&&i[1])return{creatorType:"author",lastName:i[0],firstName:i[1]}}const t=e.split(/\s+/);if(t.length===1)return{creatorType:"author",name:e};const n=t[t.length-1];return{creatorType:"author",firstName:t.slice(0,-1).join(" "),lastName:n}}function MC(r){if(r.publicationDate)return r.publicationDate;if(r.year)return String(r.year)}function qC(r){const e=[];return r.pmid&&e.push(`PMID: ${r.pmid}`),r.pmcid&&e.push(`PMCID: ${r.pmcid}`),e.length>0?e.join(`
`):void 0}const jC=`:host {
  position: fixed;
  inset: 0;
  z-index: 2147483647;
  display: block;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", "Noto Sans SC", "Source Han Sans SC", "Helvetica Neue", Arial, sans-serif;
}

.zotero-modal-frame {
  position: fixed;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  box-sizing: border-box;
}

.zotero-modal-backdrop {
  position: absolute;
  inset: 0;
  padding: 0;
  border: 0;
  background: rgba(15, 23, 42, 0.42);
  cursor: default;
}

.zotero-modal {
  position: relative;
  z-index: 1;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
  width: 420px;
  max-width: min(420px, calc(100vw - 40px));
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.zotero-modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid #e5e7eb;
}

.zotero-modal-title {
  font-size: 16px;
  font-weight: 700;
  color: #111827;
  margin: 0;
}

.zotero-modal-close {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  background: none;
  cursor: pointer;
  border-radius: 6px;
  color: #6b7280;
  font-size: 18px;
  line-height: 1;
}

.zotero-modal-close:hover {
  background: #f3f4f6;
  color: #111827;
}

.zotero-modal-body {
  flex: 1;
  overflow-y: auto;
  padding: 16px 20px;
}

.zotero-modal-label {
  font-size: 13px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 10px;
}

.zotero-collection-list {
  list-style: none;
  margin: 0;
  padding: 0;
}

.zotero-collection-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
  color: #374151;
  transition: background 0.15s;
}

.zotero-collection-item:hover {
  background: #f3f4f6;
}

.zotero-collection-item--selected {
  background: #eff6ff;
  color: #1d4ed8;
  font-weight: 600;
}

.zotero-collection-item--selected:hover {
  background: #dbeafe;
}

.zotero-collection-icon {
  font-size: 14px;
  flex-shrink: 0;
}

.zotero-collection-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.zotero-collection-check {
  color: #3b82f6;
  font-size: 14px;
  flex-shrink: 0;
  display: none;
}

.zotero-collection-item--selected .zotero-collection-check {
  display: inline;
}

.zotero-collection-item[data-zotero-level="0"] {
  font-weight: 650;
}

.zotero-collection-item[data-zotero-level="1"],
.zotero-collection-item[data-zotero-level="2"],
.zotero-collection-item[data-zotero-level="3"],
.zotero-collection-item[data-zotero-level="4"],
.zotero-collection-item[data-zotero-level="5"],
.zotero-collection-item[data-zotero-level="6"],
.zotero-collection-item[data-zotero-level="7"],
.zotero-collection-item[data-zotero-level="8"] {
  position: relative;
}

.zotero-collection-item[data-zotero-level="1"]::before,
.zotero-collection-item[data-zotero-level="2"]::before,
.zotero-collection-item[data-zotero-level="3"]::before,
.zotero-collection-item[data-zotero-level="4"]::before,
.zotero-collection-item[data-zotero-level="5"]::before,
.zotero-collection-item[data-zotero-level="6"]::before,
.zotero-collection-item[data-zotero-level="7"]::before,
.zotero-collection-item[data-zotero-level="8"]::before {
  content: '';
  width: 8px;
  height: 1px;
  background: #cbd5e1;
  border-radius: 999px;
  flex: 0 0 8px;
  margin-left: -4px;
}

.zotero-collection-empty {
  text-align: center;
  padding: 24px;
  color: #9ca3af;
  font-size: 13px;
}

.zotero-modal-loading {
  text-align: center;
  padding: 24px;
  color: #6b7280;
  font-size: 13px;
}

.zotero-modal-loading-spinner {
  display: inline-block;
  width: 20px;
  height: 20px;
  border: 2px solid #e5e7eb;
  border-top-color: #3b82f6;
  border-radius: 50%;
  animation: zotero-spin 0.6s linear infinite;
  margin-bottom: 8px;
}

@keyframes zotero-spin {
  to { transform: rotate(360deg); }
}

.zotero-modal-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 20px;
  border-top: 1px solid #e5e7eb;
}

.zotero-remember-check {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #6b7280;
  cursor: pointer;
}

.zotero-remember-check input {
  cursor: pointer;
  accent-color: #3b82f6;
}

.zotero-modal-actions {
  display: flex;
  gap: 8px;
}

.zotero-btn {
  padding: 7px 16px;
  border: none;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.15s;
}

.zotero-btn--cancel {
  background: #f3f4f6;
  color: #374151;
}

.zotero-btn--cancel:hover {
  background: #e5e7eb;
}

.zotero-btn--confirm {
  background: #3b82f6;
  color: #ffffff;
}

.zotero-btn--confirm:hover {
  background: #2563eb;
}

.zotero-btn--confirm:disabled {
  background: #93c5fd;
  cursor: not-allowed;
}
`,$C=45e3;function Hs(r){let e=!1;const t=document.createElement("div");t.className="zotero-modal-overlay-wrapper";const n=t.attachShadow({mode:"open"}),a=document.createElement("style");a.textContent=jC,n.appendChild(a);const i=document.createElement("div");i.className="zotero-modal-frame";const o=document.createElement("button");o.className="zotero-modal-backdrop",o.type="button",o.setAttribute("aria-label","\u5173\u95ED Zotero \u4FDD\u5B58\u4F4D\u7F6E\u9009\u62E9");const s=document.createElement("div");s.className="zotero-modal";const l=document.createElement("div");l.className="zotero-modal-header";const c=document.createElement("h3");c.className="zotero-modal-title",c.textContent="\u4FDD\u5B58\u5230 Zotero";const u=document.createElement("button");u.className="zotero-modal-close",u.textContent="\u2715",u.type="button",l.append(c,u);const d=document.createElement("div");d.className="zotero-modal-body";const p=document.createElement("div");p.className="zotero-modal-label",p.textContent="\u9009\u62E9 Zotero \u4FDD\u5B58\u4F4D\u7F6E:";const h=document.createElement("div");h.innerHTML=`
    <div class="zotero-modal-loading">
      <div class="zotero-modal-loading-spinner"></div>
      <div>\u6B63\u5728\u8BFB\u53D6 Zotero \u4FDD\u5B58\u4F4D\u7F6E...</div>
    </div>
  `,d.append(p,h);const f=document.createElement("div");f.className="zotero-modal-footer";const y=document.createElement("label");y.className="zotero-remember-check";const x=document.createElement("input");x.type="checkbox",x.checked=!0;const T=document.createElement("span");T.textContent="\u8BB0\u4F4F\u672C\u6B21\u9009\u62E9",y.append(x,T);const E=document.createElement("div");E.className="zotero-modal-actions";const w=document.createElement("button");w.className="zotero-btn zotero-btn--cancel",w.type="button",w.textContent="\u53D6\u6D88";const v=document.createElement("button");v.className="zotero-btn zotero-btn--confirm",v.type="button",v.textContent="\u786E\u8BA4\u4FDD\u5B58",v.disabled=!1,E.append(w,v),f.append(y,E),s.append(l,d,f),i.append(o,s),n.appendChild(i);let g=r.defaultCollectionKey||"",C=r.defaultCollectionName||(r.defaultCollectionKey?"\u672A\u77E5\u6587\u4EF6\u5939":"\u6211\u7684\u8D44\u6599\u5E93");function L(S,_,P,R,M){const Q=document.createElement("li");Q.className="zotero-collection-item";const se=Math.max(0,Math.min(P,8));Q.dataset.zoteroLevel=String(se),Q.style.paddingLeft=`${12+se*20}px`,R&&Q.classList.add("zotero-collection-item--selected");const at=document.createElement("span");at.className="zotero-collection-icon",at.textContent=S.startsWith("L")?"\u{1F4DA}":"\u{1F4C1}";const fe=document.createElement("span");fe.className="zotero-collection-name",fe.textContent=_;const X=document.createElement("span");return X.className="zotero-collection-check",X.textContent="\u2713",Q.append(at,fe,X),Q.addEventListener("click",xt=>{xt.stopPropagation(),h.querySelectorAll(".zotero-collection-item--selected").forEach(Oe=>Oe.classList.remove("zotero-collection-item--selected")),Q.classList.add("zotero-collection-item--selected"),M()}),Q}function $(S){h.innerHTML="";const _=document.createElement("ul");_.className="zotero-collection-list";const P=L("","Zotero \u5F53\u524D\u5E93/\u5F53\u524D\u6587\u4EF6\u5939",0,!0,()=>{g="",C="Zotero \u5F53\u524D\u5E93",v.disabled=!1});if(_.appendChild(P),S){const R=document.createElement("li");R.className="zotero-collection-empty",R.textContent=`\u65E0\u6CD5\u8BFB\u53D6 Zotero \u4FDD\u5B58\u4F4D\u7F6E\uFF0C\u53EF\u76F4\u63A5\u4FDD\u5B58\u5230\u5F53\u524D\u5E93\u3002${S}`,_.appendChild(R)}g="",C="Zotero \u5F53\u524D\u5E93",v.disabled=!1,x.checked=!1,x.disabled=!0,h.appendChild(_)}function k(S){h.innerHTML="";const _=document.createElement("ul");_.className="zotero-collection-list";const P=S[0],R=!!(g&&S.some(M=>M.id===g));if((!g||!R)&&P&&(g=P.id,C=P.name),S.length===0){$("Zotero \u672A\u8FD4\u56DE\u53EF\u4FDD\u5B58\u4F4D\u7F6E\u3002");return}for(const M of S)_.appendChild(L(M.id,M.name,M.level||0,M.id===g,()=>{g=M.id,C=M.name,v.disabled=!1}));h.appendChild(_)}function N(){e||(e=!0,t.remove())}return u.addEventListener("click",()=>{r.onCancel?.(),N()}),w.addEventListener("click",()=>{r.onCancel?.(),N()}),v.addEventListener("click",()=>{r.onConfirm(g,C,x.checked),N()}),o.addEventListener("click",()=>{r.onCancel?.(),N()}),(async()=>{try{const S=await H({type:"ZOTERO_FETCH_COLLECTIONS"},$C);if(!S?.success){const _=S?.error||"\u8BF7\u786E\u8BA4 Zotero \u5DF2\u5F00\u542F\u672C\u5730\u8FDE\u63A5\u3002";$(_.includes("FEATURE_NOT_ENTITLED")?"\u5F53\u524D\u8D26\u53F7\u6682\u672A\u5F00\u901A Zotero \u5BFC\u51FA\u6743\u9650\u3002":_);return}k(S.data||[])}catch(S){$(S instanceof Error&&S.message==="runtime message timed out"?"\u8BFB\u53D6\u4FDD\u5B58\u4F4D\u7F6E\u8D85\u65F6\uFF0C\u53EF\u76F4\u63A5\u4FDD\u5B58\u5230 Zotero \u5F53\u524D\u5E93\u3002":"\u8BF7\u786E\u8BA4 Zotero \u5DF2\u5F00\u542F\u672C\u5730\u8FDE\u63A5\u3002")}})(),document.body.appendChild(t),N}const OC=`.pl-zotero-btn {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  height: 28px;
  min-height: 28px;
  padding: 0 11px;
  border: 1px solid #d5dbe7;
  border-radius: 7px;
  background: #ffffff;
  color: #334155;
  font-size: 13px;
  font-weight: 650;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", "Noto Sans SC", "Source Han Sans SC", "Helvetica Neue", Arial, sans-serif;
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
  transition: background 0.15s, border-color 0.15s, box-shadow 0.15s, color 0.15s, transform 0.15s;
}

.pl-zotero-btn:hover {
  background: #f8fafc;
  border-color: #94a3b8;
  box-shadow: 0 2px 6px rgba(15, 23, 42, 0.08);
}

.pl-zotero-btn:active {
  background: #f1f5f9;
  transform: scale(0.96);
}

.pl-zotero-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pl-zotero-btn--saving {
  opacity: 0.7;
  pointer-events: none;
}

.pl-zotero-btn-icon {
  font-size: 13px;
  line-height: 1;
}

.pl-zotero-btn-label {
  line-height: 1;
}
`,UC="paperlens-zotero-host",zs="paperlens_zotero_last_collection",Js="paperlens_zotero_last_collection_name",Mp=35e3,qp=45e3;function HC(r){return new Promise(e=>setTimeout(e,r))}function vi(r,e,t="Zotero \u68C0\u6D4B\u8D85\u65F6"){return r instanceof Error?r.message==="runtime message timed out"?t:r.message?`${e}\uFF1A${r.message}`:e:e}async function jp(){try{const r=await I.storage.local.get([zs,Js]);return{key:r[zs]||"",name:r[Js]||""}}catch{return{key:"",name:""}}}async function $p(r,e){try{await I.storage.local.set({[zs]:r,[Js]:e})}catch{}}function Op(r,e,t){r.disabled=!0,r.title=t,r.setAttribute("aria-disabled","true"),e.textContent="Zotero Pro"}function Up(r,e){r.dataset.busy!=="true"&&(r.disabled=!1),r.title="",r.removeAttribute("aria-disabled"),e.textContent="Zotero"}async function Vs(r,e){const t=await or();if(t.allowed){Up(r,e);return}if(t.transient){r.disabled=!1,r.title=t.error||"",r.removeAttribute("aria-disabled"),e.textContent="Zotero";return}Op(r,e,t.error||"Zotero \u5BFC\u51FA\u662F Pro \u6C38\u4E45\u7248\u6743\u76CA")}function zC(r,e){xn();const t=n=>{const a=n.detail;if(a?.featureKey===Mt){if(a.allowed===!0){Up(r,e);return}Op(r,e,a.error||"Zotero \u5BFC\u51FA\u662F Pro \u6C38\u4E45\u7248\u6743\u76CA")}};document.addEventListener(pe,t),window.addEventListener("pagehide",()=>{document.removeEventListener(pe,t)},{once:!0})}async function Hp(){const r=await or();return r.allowed?!0:(D.error(r.error||"Zotero \u5BFC\u51FA\u662F Pro \u6C38\u4E45\u7248\u6743\u76CA"),!1)}function zp(r){return/(?:Zotero 导出|Pro|永久版权益|开通|当前账户暂不能使用|请先登录|账户状态已切换|NOT_AUTHENTICATED|SESSION_CHANGED|FEATURE_|PLAN_REQUIRED)/i.test(r||"")}function Jp(r){const e=document.createElement("div");e.className=UC;const t=e.attachShadow({mode:"open"}),n=document.createElement("style");n.textContent=OC,t.appendChild(n);const a=document.createElement("button");a.type="button",a.className="pl-zotero-btn",a.setAttribute("aria-label","\u4FDD\u5B58\u5230 Zotero");const i=document.createElement("span");i.className="pl-zotero-btn-icon",i.textContent="\u{1F4DA}";const o=document.createElement("span");return o.className="pl-zotero-btn-label",o.textContent="Zotero",a.append(i,o),t.appendChild(a),Vs(a,o),zC(a,o),a.addEventListener("click",async s=>{if(s.preventDefault(),s.stopPropagation(),!await Hp()){await Vs(a,o);return}a.classList.add("pl-zotero-btn--saving"),a.dataset.busy="true",o.textContent="\u68C0\u6D4B\u4E2D...",D.info("\u6B63\u5728\u8FDE\u63A5 Zotero...");try{let l;try{l=await H({type:"ZOTERO_PING"},Mp)}catch(u){l={success:!1,error:vi(u,"Zotero \u68C0\u6D4B\u5931\u8D25")}}if(!l?.success||!l?.data){if(zp(l?.error)){D.error(l?.error||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528 Zotero \u5BFC\u51FA"),await Vs(a,o),a.classList.remove("pl-zotero-btn--saving"),delete a.dataset.busy;return}D.info(`\u672A\u68C0\u6D4B\u5230 Zotero ping\uFF0C\u5C06\u76F4\u63A5\u5C1D\u8BD5\u4FDD\u5B58${l?.error?`\uFF1A${l.error}`:""}`)}const c=await jp();o.textContent="Zotero",a.classList.remove("pl-zotero-btn--saving"),delete a.dataset.busy,Hs({defaultCollectionKey:c.key,defaultCollectionName:c.name,onConfirm:async(u,d,p)=>{let h=r.paper;if(r.beforeSave){D.info("\u6B63\u5728\u8865\u5168\u5143\u6570\u636E...");try{h=await r.beforeSave({...r.paper,authors:r.paper.authors?[...r.paper.authors]:void 0,s2Authors:r.paper.s2Authors?r.paper.s2Authors.map(x=>({...x})):void 0,tags:r.paper.tags?[...r.paper.tags]:void 0})}catch(x){console.warn("[PaperLens] Zotero beforeSave failed, falling back to page metadata:",x),D.info("\u5143\u6570\u636E\u8865\u5168\u5931\u8D25\uFF0C\u7EE7\u7EED\u4F7F\u7528\u9875\u9762\u6570\u636E\u4FDD\u5B58"),h=r.paper}}const f=Us(h),y=u?[u]:void 0;D.info("\u6B63\u5728\u4FDD\u5B58\u5230 Zotero...");try{const x=await H({type:"ZOTERO_SAVE_ITEMS",payload:{items:[f],collections:y}},qp);x?.success?(x.warning?D.info(x.warning):D.success(`\u5DF2\u4FDD\u5B58\u5230 Zotero${d?` \u2192 ${d}`:""}`),p&&u&&await $p(u,d)):D.error(`\u4FDD\u5B58\u5931\u8D25\uFF1A${x?.error||x?.message||"\u672A\u77E5\u9519\u8BEF"}`)}catch(x){D.error(vi(x,"\u4FDD\u5B58\u5230 Zotero \u5931\u8D25","\u4FDD\u5B58\u5230 Zotero \u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5"))}}})}catch(l){D.error(vi(l,"\u65E0\u6CD5\u8FDE\u63A5 Zotero")),o.textContent="Zotero",a.classList.remove("pl-zotero-btn--saving"),delete a.dataset.busy}}),e}async function JC(r){if(!await Hp())return;D.info("\u6B63\u5728\u8FDE\u63A5 Zotero...");let e;try{e=await H({type:"ZOTERO_PING"},Mp)}catch(n){e={success:!1,error:vi(n,"Zotero \u68C0\u6D4B\u5931\u8D25")}}if(!e?.success||!e?.data){if(zp(e?.error)){D.error(e?.error||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528 Zotero \u5BFC\u51FA");return}D.info(`\u672A\u68C0\u6D4B\u5230 Zotero ping\uFF0C\u5C06\u76F4\u63A5\u5C1D\u8BD5\u4FDD\u5B58${e?.error?`\uFF1A${e.error}`:""}`)}const t=await jp();Hs({defaultCollectionKey:t.key,defaultCollectionName:t.name,onConfirm:async(n,a,i)=>{const o=r.map(Us),s=n?[n]:void 0;let l=0,c=0;D.info(`\u6B63\u5728\u4FDD\u5B58 ${o.length} \u7BC7\u5230 Zotero...`);for(let u=0;u<o.length;u++){try{(await H({type:"ZOTERO_SAVE_ITEMS",payload:{items:[o[u]],collections:s}},qp))?.success?l++:c++}catch{c++}u<o.length-1&&await HC(300)}c===0?D.success(`${l} \u7BC7\u5DF2\u4FDD\u5B58\u5230 Zotero${a?` \u2192 ${a}`:""}`):D.info(`\u5DF2\u4FDD\u5B58 ${l}/${l+c} \u7BC7\uFF0C${c} \u7BC7\u5931\u8D25`),i&&n&&await $p(n,a)}})}const VC=`/* AI Translate component styles */

:host,
.pl-translate-wrapper {
  display: inline-flex;
  align-items: center;
  flex: 0 0 auto;
  margin-top: 0;
  max-width: 100%;
  line-height: 1;
  vertical-align: middle;
}

:host(.pl-translate-wrapper--article-page),
.pl-translate-wrapper--article-page {
  display: inline-flex;
  align-items: center;
  flex: 0 0 auto;
  margin: 0;
  max-width: 100%;
  line-height: 1;
  vertical-align: middle;
}

/* \u2500\u2500 Button \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */

.pl-translate-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  height: 28px;
  min-height: 28px;
  padding: 0 11px;
  border: 1px solid #d5dbe7;
  border-radius: 7px;
  background: #ffffff;
  color: #334155;
  font-size: 13px;
  font-weight: 650;
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  transition: background-color 0.15s, border-color 0.15s, box-shadow 0.15s, color 0.15s, transform 0.15s;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans CJK SC', 'Noto Sans SC', 'Source Han Sans SC', 'Helvetica Neue', Arial, sans-serif;
  box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
  appearance: none;
}

.pl-translate-wrapper--article-page .pl-translate-btn {
  background: #ffffff;
  color: #334155;
  font-size: 13px;
  padding: 0 11px;
}

.pl-translate-btn:hover:not(:disabled) {
  color: #2563eb;
  background: #eff6ff;
  border-color: #93c5fd;
  box-shadow: 0 2px 6px rgba(37, 99, 235, 0.1);
}

.pl-translate-wrapper--article-page .pl-translate-btn:hover:not(:disabled) {
  color: #1d4ed8;
  background: #dbeafe;
}

.pl-translate-btn:disabled {
  opacity: 0.7;
  cursor: wait;
}

.pl-translate-btn--deep:hover:not(:disabled) {
  color: #6d28d9;
  border-color: #c4b5fd;
  background: #f5f3ff;
}

.pl-translate-wrapper--article-page .pl-translate-btn--deep:hover:not(:disabled) {
  color: #6d28d9;
  background: #ede9fe;
}

/* \u2500\u2500 Drawer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */

.pl-translate-drawer {
  all: initial;
  position: fixed;
  top: 0;
  right: 0;
  z-index: 2147483647;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  width: 420px;
  max-width: min(420px, 92vw);
  height: 100vh;
  border-left: 1px solid #e5e7eb;
  background: #ffffff;
  box-shadow: -4px 0 18px rgba(15, 23, 42, 0.12);
  color: #1f2937;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans CJK SC', 'Noto Sans SC', 'Source Han Sans SC', 'Helvetica Neue', Arial, sans-serif !important;
  transform: translateX(100%);
  animation: pl-translate-drawer-in 220ms ease-out forwards;
}

.pl-translate-drawer *,
.pl-translate-drawer *::before,
.pl-translate-drawer *::after {
  box-sizing: border-box;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans CJK SC', 'Noto Sans SC', 'Source Han Sans SC', 'Helvetica Neue', Arial, sans-serif !important;
}

.pl-translate-drawer--closing {
  animation: pl-translate-drawer-out 180ms ease-in forwards;
}

@keyframes pl-translate-drawer-in {
  from { transform: translateX(100%); }
  to { transform: translateX(0); }
}

@keyframes pl-translate-drawer-out {
  from { transform: translateX(0); }
  to { transform: translateX(100%); }
}

.pl-translate-drawer-header {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  border-bottom: 1px solid #e5e7eb;
  flex-shrink: 0;
}

.pl-translate-drawer-title-wrap {
  flex: 1;
  min-width: 0;
}

.pl-translate-drawer-title {
  display: block;
  margin: 0 !important;
  padding: 0 !important;
  color: #111827 !important;
  font-size: 15px !important;
  font-style: normal !important;
  font-weight: 650 !important;
  line-height: 1.35 !important;
  letter-spacing: 0 !important;
  text-transform: none !important;
}

.pl-translate-drawer-meta {
  margin-top: 3px !important;
  color: #6b7280 !important;
  font-size: 11px !important;
  font-style: normal !important;
  font-weight: 500 !important;
  line-height: 1.3 !important;
  letter-spacing: 0 !important;
  text-transform: none !important;
}

.pl-translate-drawer-actions {
  display: inline-flex;
  align-items: center;
  gap: 9px;
  flex-shrink: 0;
}

.pl-translate-drawer-pdf {
  all: unset;
  box-sizing: border-box;
  display: inline-flex !important;
  align-items: center;
  justify-content: center;
  height: 28px !important;
  padding: 0 10px !important;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  background: #ffffff;
  color: #374151;
  font-size: 12px !important;
  font-weight: 650 !important;
  line-height: 1 !important;
  cursor: pointer !important;
}

.pl-translate-drawer-pdf:hover {
  border-color: #2563eb;
  background: #eff6ff;
  color: #1d4ed8;
}

.pl-translate-drawer-close {
  all: unset;
  box-sizing: border-box;
  display: inline-flex !important;
  align-items: center;
  justify-content: center;
  width: 34px !important;
  height: 34px !important;
  min-width: 34px !important;
  min-height: 34px !important;
  border: 1px solid transparent !important;
  border-radius: 10px !important;
  background: transparent !important;
  color: #64748b !important;
  line-height: 1 !important;
  cursor: pointer !important;
  box-shadow: none !important;
  transition: background-color 0.15s, border-color 0.15s, color 0.15s, transform 0.15s;
}

.pl-translate-drawer-close:hover {
  border-color: #e2e8f0 !important;
  background: #f1f5f9 !important;
  color: #0f172a !important;
}

.pl-translate-drawer-close:active {
  transform: scale(0.96);
}

.pl-translate-drawer-close:focus-visible {
  outline: 2px solid #93c5fd !important;
  outline-offset: 2px !important;
}

.pl-translate-drawer-close-icon {
  display: inline-flex !important;
  align-items: center;
  justify-content: center;
  width: 20px !important;
  height: 20px !important;
  color: inherit !important;
  font-family: Arial, Helvetica, sans-serif !important;
  font-size: 24px !important;
  font-style: normal !important;
  font-weight: 300 !important;
  line-height: 18px !important;
  transform: translateY(-1px);
  pointer-events: none !important;
  text-align: center;
}

.pl-translate-drawer-body {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  padding: 16px;
}

.pl-translate-source-title {
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f3f4f6;
  color: #374151;
  font-size: 13px;
  font-weight: 600;
  line-height: 1.45;
}

.pl-translate-paper-meta {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 6px 10px;
  margin: -2px 0 14px;
  padding: 10px 12px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  background: #f9fafb;
}

.pl-translate-paper-meta-item {
  min-width: 0;
  font-size: 12px;
  line-height: 1.45;
}

.pl-translate-paper-meta-label {
  display: inline-block;
  margin-right: 6px;
  color: #6b7280;
  font-weight: 650;
}

.pl-translate-paper-meta-value {
  color: #374151;
  overflow-wrap: anywhere;
  text-decoration: none;
}

a.pl-translate-paper-meta-value:hover {
  color: #005ea8;
  text-decoration: underline;
}

.pl-translate-drawer-loading {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 16px;
  color: #4b5563;
  font-size: 13px;
}

.pl-translate-spinner {
  width: 14px;
  height: 14px;
  border: 2px solid #d1d5db;
  border-top-color: #2563eb;
  border-radius: 999px;
  animation: pl-translate-spin 700ms linear infinite;
}

@keyframes pl-translate-spin {
  to { transform: rotate(360deg); }
}

.pl-translate-drawer .pl-translate-result {
  margin-top: 0;
}

.pl-translate-drawer-error {
  padding: 10px 12px;
  border-radius: 4px;
  background: #fef2f2;
}

/* \u2500\u2500 Result Panel \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */

.pl-translate-result {
  margin-top: 8px;
  padding: 0;
  background: transparent;
  font-size: 13px;
  line-height: 1.6;
  animation: pl-translate-fade-in 0.3s ease;
}

.pl-translate-provider-badge {
  display: inline-flex;
  align-items: center;
  margin-bottom: 12px;
  padding: 3px 8px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  color: #4b5563;
  background: #f9fafb;
  font-size: 12px;
  line-height: 1.4;
}

.pl-translate-language-notice {
  margin: 12px 0 0;
  padding: 10px 12px;
  border: 1px solid #fed7aa;
  border-radius: 7px;
  background: #fff7ed;
  color: #9a3412;
  font-size: 12px;
  font-weight: 600;
  line-height: 1.55;
}

@keyframes pl-translate-fade-in {
  from { opacity: 0; transform: translateY(-4px); }
  to { opacity: 1; transform: translateY(0); }
}

.pl-translate-section {
  margin-bottom: 14px;
}

.pl-translate-section-label {
  color: #6b7280;
  font-size: 12px;
  font-weight: 700;
  letter-spacing: 0;
  margin-bottom: 6px;
}

.pl-translate-title-zh {
  font-size: 15px;
  font-weight: 600;
  color: #111827;
  line-height: 1.55;
}

.pl-translate-abstract-zh {
  font-size: 13px;
  color: #374151;
  line-height: 1.75;
  white-space: pre-wrap;
}

.pl-translate-abstract-original {
  font-size: 13px;
  color: #4b5563;
  line-height: 1.75;
  white-space: pre-wrap;
}

/* \u2500\u2500 Keywords \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */

.pl-translate-keywords {
  margin: 2px 0 14px;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
}

.pl-translate-keywords-label {
  margin-right: 2px;
  color: #6b7280;
  font-size: 12px;
  font-weight: 650;
}

.pl-translate-keyword-tag {
  display: inline-block;
  background: #eef2ff;
  color: #3730a3;
  font-size: 11px;
  padding: 2px 8px;
  border-radius: 4px;
  font-weight: 500;
}

/* \u2500\u2500 Interpretation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */

.pl-translate-interpretation {
  margin-top: 4px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  background: #ffffff;
  overflow: hidden;
}

.pl-translate-interp-header {
  padding: 9px 11px;
  border-bottom: 1px solid #e5e7eb;
  background: #f9fafb;
  color: #374151;
  font-size: 13px;
  font-weight: 650;
}

.pl-translate-framework-item {
  display: grid;
  grid-template-columns: 86px minmax(0, 1fr);
  gap: 10px;
  padding: 9px 11px;
  border-bottom: 1px solid #f3f4f6;
}

.pl-translate-framework-item:last-child {
  border-bottom: 0;
}

.pl-translate-framework-label {
  color: #4b5563;
  font-size: 12px;
  font-weight: 650;
  line-height: 1.55;
}

.pl-translate-framework-text {
  color: #374151;
  font-size: 13px;
  line-height: 1.65;
}

/* \u2500\u2500 Error \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */

.pl-translate-error {
  margin-top: 6px;
  font-size: 12px;
  color: #dc2626;
  animation: pl-translate-fade-in 0.3s ease;
}

/* \u2500\u2500 Dark Mode \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */

@media (prefers-color-scheme: dark) {
  .pl-translate-btn:hover:not(:disabled) {
    color: #60a5fa;
    background: rgba(37, 99, 235, 0.15);
  }

  .pl-translate-btn--deep:hover:not(:disabled) {
    color: #a78bfa;
    background: rgba(124, 58, 237, 0.15);
  }

  .pl-translate-title-zh {
    color: #93c5fd;
  }

  .pl-translate-abstract-zh {
    color: #d1d5db;
  }

  .pl-translate-abstract-original {
    color: #d1d5db;
  }

  .pl-translate-keyword-tag {
    background: rgba(96, 165, 250, 0.2);
    color: #93c5fd;
  }

  .pl-translate-interpretation {
    border-color: #374151;
    background: rgba(255, 255, 255, 0.03);
  }

  .pl-translate-interp-header {
    border-bottom-color: #374151;
    background: rgba(255, 255, 255, 0.04);
    color: #d1d5db;
  }

  .pl-translate-framework-item {
    border-bottom-color: #374151;
  }

  .pl-translate-framework-label {
    color: #9ca3af;
  }

  .pl-translate-framework-text {
    color: #d1d5db;
  }

  .pl-translate-paper-meta {
    border-color: #374151;
    background: rgba(255, 255, 255, 0.03);
  }

  .pl-translate-paper-meta-value { color: #d1d5db; }


  .pl-translate-error {
    color: #f87171;
  }
}

/* PubMed explicit dark mode */
body.dark-mode .pl-translate-btn:hover:not(:disabled) {
  color: #60a5fa;
  background: rgba(37, 99, 235, 0.15);
}

body.dark-mode .pl-translate-title-zh { color: #93c5fd; }
body.dark-mode .pl-translate-abstract-zh { color: #d1d5db; }
body.dark-mode .pl-translate-abstract-original { color: #d1d5db; }
body.dark-mode .pl-translate-keyword-tag {
  background: rgba(96, 165, 250, 0.2);
  color: #93c5fd;
}
body.dark-mode .pl-translate-interpretation {
  border-color: #374151;
  background: rgba(255, 255, 255, 0.03);
}
body.dark-mode .pl-translate-interp-header {
  border-bottom-color: #374151;
  background: rgba(255, 255, 255, 0.04);
  color: #d1d5db;
}
body.dark-mode .pl-translate-framework-item { border-bottom-color: #374151; }
body.dark-mode .pl-translate-framework-label { color: #9ca3af; }
body.dark-mode .pl-translate-framework-text { color: #d1d5db; }
body.dark-mode .pl-translate-error { color: #f87171; }
`,Ge="deep",Vp="AI \u89E3\u8BFB",Wp="\u67E5\u770B\u7FFB\u8BD1\u3001\u5173\u952E\u8BCD\u548C\u7ED3\u6784\u5316\u89E3\u8BFB",Gp="\u89E3\u8BFB\u4E2D\u2026",WC="\u6B63\u5728\u751F\u6210\u89E3\u8BFB\u2026",Ws="zh-CN",GC="AI \u8FD4\u56DE\u7684\u89E3\u8BFB\u6B63\u6587\u4E0D\u662F\u4E2D\u6587\uFF0C\u5DF2\u9690\u85CF\u82F1\u6587\u5185\u5BB9\u3002\u8BF7\u91CD\u65B0\u70B9\u51FB AI \u89E3\u8BFB\u751F\u6210\u4E2D\u6587\u7248\u672C\u3002",Gs=15e4,ZC=15e3;let Re=null,Zs=0,Ys=0;const Ut=new Set;let Ks=!1,An=null,he="";function Qs(r){return{...r,targetLanguage:Ws,target_language:Ws,locale:Ws}}function Xs(r,e,t,n={}){const{wrapper:a,button:i}=Zp();return i.addEventListener("click",()=>{nv(i,a,r,e,t,Ge,n)}),a}function YC(r){const{wrapper:e,button:t}=Zp();return t.addEventListener("click",()=>{rv(t,e,r)}),e}async function KC(r){Yp();const e=rl(),t=Kp(r),n=Qp(r);Se({pmid:r.pmid,paperTitle:r.title,paperMeta:t,status:"loading"});try{const a=await H({type:"ARTICLE_AI_REQUEST",payload:Qs(r)},Gs);if(ct(e))return;if(!a?.success){const o=a?.error==="NOT_AUTHENTICATED"?"\u8BF7\u5148\u767B\u5F55 PaperLens \u8D26\u6237":a?.error||"\u89E3\u8BFB\u5931\u8D25";if(await nl(Ge,o),ct(e))return;Se({pmid:r.pmid,paperId:n,paperTitle:r.title,paperMeta:t,mode:Ge,status:"error",error:o});return}const i=a.data;if(he){Se({pmid:r.pmid,paperId:n,paperTitle:r.title,paperMeta:t,mode:Ge,status:"error",error:he});return}yn(et,ar),Se({pmid:r.pmid,paperId:n,paperTitle:r.title,paperMeta:t,mode:Ge,status:"success",data:i,cached:i.cached})}catch{if(ct(e))return;Se({pmid:r.pmid,paperTitle:r.title,paperMeta:t,status:"error",error:"\u7F51\u7EDC\u9519\u8BEF\uFF0C\u8BF7\u91CD\u8BD5"})}}function Zp(){const r=document.createElement("div");r.className="pl-translate-wrapper";const e=r.attachShadow({mode:"open"}),t=document.createElement("style");t.textContent=VC;const n=document.createElement("button");return n.type="button",n.className="pl-translate-btn pl-translate-btn--deep",n.textContent=Vp,n.title=Wp,e.append(t,n),QC(n),{wrapper:r,button:n}}function QC(r){An&&An!==document&&(Ut.clear(),he=""),Ut.add(r),Yp(),he&&sr(r,he)}function Yp(){xn(),!(Ks&&An===document)&&(An?.removeEventListener(pe,el),Ks=!0,An=document,document.addEventListener(pe,el),window.addEventListener("pagehide",()=>{An?.removeEventListener(pe,el),Ut.clear(),Ks=!1,An=null},{once:!0}))}function XC(){if(he)for(const r of Array.from(Ut))sr(r,he)}function el(r){const e=r.detail;if(e?.featureKey===et){if(e.allowed===!0){tv();return}ev(e.error||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528 AI \u89E3\u8BFB"),XC()}}function ev(r){he=r;for(const e of Array.from(Ut)){const t=e.getRootNode(),n="host"in t?t.host:null;if(!(e.isConnected||!!(n&&typeof n=="object"&&"isConnected"in n&&n.isConnected))){Ut.delete(e);continue}sr(e,r)}}function sr(r,e){r.disabled=!0,r.title=e,r.textContent="AI \u89E3\u8BFB Pro",r.setAttribute("aria-disabled","true")}function tv(){if(he){he="";for(const r of Array.from(Ut)){const e=r.getRootNode(),t="host"in e?e.host:null;if(!(r.isConnected||!!(t&&typeof t=="object"&&"isConnected"in t&&t.isConnected))){Ut.delete(r);continue}r.disabled=!1,r.title=Wp,r.textContent=Vp,r.removeAttribute("aria-disabled")}}}function tl(r){return/AI 服务暂未配置|请联系管理员/.test(r)||/需要先(?:在 Popup 设置中)?配置自定义模型接口|接口在当前服务器上未部署|切换自定义模型/.test(r)?!1:/(?:Pro|永久版权益|开通|当前账户暂不能使用|请先登录|账户状态已切换|AI 服务包|本月.*次数已用完|次数已用完|QUOTA_EXCEEDED|NOT_AUTHENTICATED|SESSION_CHANGED|REMOTE_CHECK_FAILED)/i.test(r)}async function nl(r,e){return tl(e)?$t({featureKey:et,featureLabel:ar,error:e}):!1}async function nv(r,e,t,n,a,i,o){if(r.disabled)return;const s=rl();r.disabled=!0;const l=r.textContent;r.textContent=Gp,Se({pmid:t,paperTitle:n,paperMeta:o,status:"loading"});const c=e.querySelector(".pl-translate-result");c&&c.remove();const u=e.querySelector(".pl-translate-error");u&&u.remove();try{const d=await ov(t,a,o),p=await H({type:"TRANSLATE_REQUEST",payload:Qs({pmid:t,title:n,abstract:d,mode:i})},Gs);if(ct(s)){Ze(r,l);return}if(!p?.success){const f=p?.error==="NOT_AUTHENTICATED"?"\u8BF7\u5148\u767B\u5F55 PaperLens \u8D26\u6237":p?.error||"\u89E3\u8BFB\u5931\u8D25",y=await nl(i,f);if(ct(s)||(Se({pmid:t,paperTitle:n,paperMeta:o,mode:i,status:"error",error:f}),tl(f)&&!y))return;Ze(r,l);return}const h=p.data;if(i===Ge&&he){sr(r,he);return}yn(i===Ge?et:rr,i===Ge?ar:_s),Se({pmid:t,paperTitle:n,paperMeta:o,mode:i,status:"success",data:h,cached:h.cached}),r.textContent=h.cached?"\u2705 \u5DF2\u89E3\u8BFB\uFF08\u7F13\u5B58\uFF09":"\u2705 \u89E3\u8BFB\u5B8C\u6210",setTimeout(()=>{Ze(r,l)},3e3)}catch{if(ct(s)){Ze(r,l);return}Se({pmid:t,paperTitle:n,paperMeta:o,status:"error",error:"\u7F51\u7EDC\u9519\u8BEF\uFF0C\u8BF7\u91CD\u8BD5"}),Ze(r,l)}}async function rv(r,e,t){if(r.disabled)return;const n=rl();r.disabled=!0;const a=r.textContent;r.textContent=Gp;const i=Kp(t),o=Qp(t);if(!av(t)){Se({pmid:t.pmid,paperTitle:t.title,paperMeta:i,status:"error",error:"\u672A\u53EF\u9760\u8BFB\u53D6\u5230\u6458\u8981\u3002\u8BF7\u5212\u9009\u6458\u8981\u6B63\u6587\u540E\uFF0C\u70B9\u51FB\u6D6E\u52A8\u5DE5\u5177\u680F\u91CC\u7684\u201C\u6458\u8981\u89E3\u8BFB\u201D\u3002"}),Ze(r,a);return}Se({pmid:t.pmid,paperTitle:t.title,paperMeta:i,status:"loading"}),e.querySelector(".pl-translate-result")?.remove(),e.querySelector(".pl-translate-error")?.remove();try{const s=await H({type:"ARTICLE_AI_REQUEST",payload:Qs(t)},Gs);if(ct(n)){Ze(r,a);return}if(!s?.success){const c=s?.error==="NOT_AUTHENTICATED"?"\u8BF7\u5148\u767B\u5F55 PaperLens \u8D26\u6237":s?.error||"\u89E3\u8BFB\u5931\u8D25",u=await nl(Ge,c);if(ct(n)||(Se({pmid:t.pmid,paperId:o,paperTitle:t.title,paperMeta:i,mode:Ge,status:"error",error:c}),tl(c)&&!u))return;Ze(r,a);return}const l=s.data;if(he){sr(r,he);return}yn(et,ar),Se({pmid:t.pmid,paperId:o,paperTitle:t.title,paperMeta:i,mode:Ge,status:"success",data:l,cached:l.cached}),r.textContent=l.cached?"\u2705 \u5DF2\u89E3\u8BFB\uFF08\u7F13\u5B58\uFF09":"\u2705 \u89E3\u8BFB\u5B8C\u6210",setTimeout(()=>{Ze(r,a)},3e3)}catch{if(ct(n)){Ze(r,a);return}Se({pmid:t.pmid,paperTitle:t.title,paperMeta:i,status:"error",error:"\u7F51\u7EDC\u9519\u8BEF\uFF0C\u8BF7\u91CD\u8BD5"}),Ze(r,a)}}function Kp(r){return{journal:r.journal,authors:r.authors,doi:r.doi,publicationDate:r.publication_date,source:r.source,sourceUrl:r.source_url}}function Qp(r){return r.paper_id??r.pmid??r.doi??r.source_url}function av(r){const e=r.abstract?.trim();if(!e||e.length<50)return!1;const t=r.title?.trim();return t?Xp(e)!==Xp(t):!0}function Xp(r){return r.normalize("NFKC").toLowerCase().replace(/[^a-z0-9\u3400-\u9fff]+/g,"")}function rl(){return Ys=Zs,++Zs}function iv(){Ys=Zs}function ct(r){return r<=Ys}function Ze(r,e){if(he){sr(r,he);return}r.textContent=e,r.disabled=!1}async function ov(r,e,t){const n=e.trim();return t.hasFullAbstract&&n?n:sv(r,n)}async function sv(r,e){try{const t=await H({type:"GET_PAPER_SUMMARY",payload:{pmid:r}},ZC),n=t?.data;if(t?.success&&typeof n?.abstract=="string"&&n.abstract.trim())return n.abstract.trim()}catch{}return e}function Se(r){const e=lv();e.classList.remove("pl-translate-drawer--closing"),uv(e,r)}function lv(){return Re?.isConnected&&Re.ownerDocument===document||(Re=document.createElement("aside"),Re.className="pl-translate-drawer",Re.setAttribute("role","dialog"),Re.setAttribute("aria-modal","false"),document.body.appendChild(Re)),Re}function cv(){if(iv(),!Re)return;const r=Re;r.classList.add("pl-translate-drawer--closing"),r.addEventListener("animationend",()=>{r.remove(),Re===r&&(Re=null)},{once:!0})}function uv(r,e){r.textContent="";const t=document.createElement("div");t.className="pl-translate-drawer-header";const n=document.createElement("div");n.className="pl-translate-drawer-title-wrap";const a=document.createElement("h2");a.className="pl-translate-drawer-title",a.textContent="AI \u89E3\u8BFB";const i=document.createElement("div");i.className="pl-translate-drawer-meta",i.textContent=e.pmid?`PMID: ${e.pmid}`:e.paperMeta?.journal||e.paperMeta?.source||"\u5F53\u524D\u6587\u7AE0",n.append(a,i);const o=document.createElement("div");if(o.className="pl-translate-drawer-actions",e.status==="success"&&e.data){const u=document.createElement("button");u.type="button",u.className="pl-translate-drawer-pdf",u.textContent="\u5BFC\u51FA PDF",u.addEventListener("click",()=>xv(e)),o.appendChild(u)}const s=document.createElement("button");s.type="button",s.className="pl-translate-drawer-close",s.setAttribute("aria-label","\u5173\u95ED"),s.appendChild(yv()),s.addEventListener("click",cv),o.appendChild(s),t.append(n,o),r.appendChild(t);const l=document.createElement("div");l.className="pl-translate-drawer-body";const c=document.createElement("div");if(c.className="pl-translate-source-title",c.textContent=e.paperTitle,l.appendChild(c),l.appendChild(gv(e.pmid,e.paperMeta)),e.status==="loading"){const u=document.createElement("div");u.className="pl-translate-drawer-loading";const d=document.createElement("span");d.className="pl-translate-spinner";const p=document.createElement("span");p.textContent=WC,u.append(d,p),l.appendChild(u)}else if(e.status==="error"){const u=document.createElement("div");u.className="pl-translate-error pl-translate-drawer-error",u.textContent=`\u26A0\uFE0F ${e.error||"\u8BF7\u6C42\u5931\u8D25"}`,l.appendChild(u)}else e.data&&l.appendChild(dv(e.data));r.appendChild(l)}function dv(r){const e=document.createElement("div");e.className="pl-translate-result";const t=fv(r),n=pv(r.aiProvider,r.aiModel,r.aiFallbackUsed);n&&e.appendChild(n),Si(e,oe(r.title_zh),"pl-translate-title-zh","\u6807\u9898\u7FFB\u8BD1"),Si(e,r.original_summary,"pl-translate-abstract-original","\u539F\u6587\u6458\u8981");const a=oe(r.abstract_zh),i=oe(r.summary_zh);if(Si(e,a??i,"pl-translate-abstract-zh","\u4E2D\u6587\u6458\u8981"),eh(i,a)&&Si(e,i,"pl-translate-summary-zh","\u4E2D\u6587\u6982\u8981"),r.keywords?.length){const o=document.createElement("div");o.className="pl-translate-keywords";const s=document.createElement("span");s.className="pl-translate-keywords-label",s.textContent="\u5173\u952E\u8BCD",o.appendChild(s);for(const l of r.keywords){const c=document.createElement("span");c.className="pl-translate-keyword-tag",c.textContent=l,o.appendChild(c)}e.appendChild(o)}if(r.interpretation){const o=r.interpretation,s=document.createElement("div");s.className="pl-translate-interpretation";const l=document.createElement("div");l.className="pl-translate-interp-header",l.textContent="\u89E3\u8BFB\u6846\u67B6",s.appendChild(l);const c=[{label:"\u4E00\u53E5\u8BDD\u7ED3\u8BBA",value:oe(o.one_sentence_summary)},{label:"\u7814\u7A76\u95EE\u9898",value:oe(o.research_question??o.background)},{label:"\u7814\u7A76\u65B9\u6CD5",value:oe(o.methods)},{label:"\u5173\u952E\u53D1\u73B0",value:oe(o.key_findings??o.core_findings)},{label:"\u5C40\u9650",value:oe(o.limitations)},{label:"\u4EF7\u503C\u610F\u4E49",value:oe(o.significance??o.clinical_significance)}];let u=0;for(const d of c)d.value&&(s.appendChild(bv(d.label,d.value)),u+=1);u>0&&e.appendChild(s)}return t&&e.appendChild(mv()),e}function pv(r,e,t){if(!r)return null;const n=document.createElement("div");n.className="pl-translate-provider-badge";const a=r==="custom"?"\u81EA\u5B9A\u4E49\u6A21\u578B":"PaperLens AI \u6A21\u578B";return n.textContent=`\u6765\u6E90\uFF1A${a}`,n}function Si(r,e,t,n){if(!e)return;const a=document.createElement("section");if(a.className="pl-translate-section",n){const o=document.createElement("div");o.className="pl-translate-section-label",o.textContent=n,a.appendChild(o)}const i=document.createElement("div");i.className=t,i.textContent=e,a.appendChild(i),r.appendChild(a)}function eh(r,e){return r?e?th(r)!==th(e):!0:!1}function th(r){return r.normalize("NFKC").replace(/\s+/g,"").trim()}function hv(r){return/[\u3400-\u9fff]/.test(r)}function nh(r){const e=r?.trim();if(!e||hv(e))return!1;const t=e.match(/[A-Za-z]/g)?.length??0,n=e.match(/[A-Za-z]{2,}/g)?.length??0;return t>=24&&n>=4}function oe(r){if(r?.trim())return nh(r)?void 0:r}function fv(r){const e=r.interpretation;return[r.title_zh,r.abstract_zh,r.summary_zh,...e?[e.one_sentence_summary,e.research_question,e.background,e.methods,e.key_findings,e.core_findings,e.limitations,e.significance,e.clinical_significance]:[]].some(nh)}function mv(){const r=document.createElement("div");return r.className="pl-translate-language-notice",r.textContent=GC,r}function bv(r,e){const t=document.createElement("div");t.className="pl-translate-framework-item";const n=document.createElement("div");n.className="pl-translate-framework-label",n.textContent=r;const a=document.createElement("div");return a.className="pl-translate-framework-text",a.textContent=e,t.append(n,a),t}function gv(r,e){const t=document.createElement("div");t.className="pl-translate-paper-meta";const n=[{label:"\u671F\u520A",value:e?.journal},{label:"\u4F5C\u8005",value:rh(e?.authors)},{label:"PMID",value:r,href:r?`https://pubmed.ncbi.nlm.nih.gov/${r}/`:void 0},{label:"DOI",value:e?.doi,href:e?.doi?`https://doi.org/${e.doi}`:void 0},{label:"\u53D1\u8868\u65E5\u671F",value:e?.publicationDate},{label:"\u6587\u7AE0\u7C7B\u578B",value:e?.articleType},{label:"\u6765\u6E90",value:e?.source}];for(const a of n){if(!a.value)continue;const i=document.createElement("div");i.className="pl-translate-paper-meta-item";const o=document.createElement("span");o.className="pl-translate-paper-meta-label",o.textContent=a.label;const s=a.href?document.createElement("a"):document.createElement("span");s.className="pl-translate-paper-meta-value",s.textContent=a.value,s instanceof HTMLAnchorElement&&a.href&&(s.href=a.href,s.target="_blank",s.rel="noopener noreferrer"),i.append(o,s),t.appendChild(i)}return t}function rh(r){return r?.length?r.length<=4?r.join(", "):`${r.slice(0,4).join(", ")} \u7B49 ${r.length} \u4F4D\u4F5C\u8005`:""}function yv(){const r=document.createElement("span");return r.className="pl-translate-drawer-close-icon",r.setAttribute("aria-hidden","true"),r.textContent="\xD7",r}function xv(r){if(!r.data)return;const e=URL.createObjectURL(new Blob([Av(r)],{type:"text/html;charset=utf-8"})),t=window.open(e,"_blank");if(!t){URL.revokeObjectURL(e);return}t.opener=null,t.addEventListener("load",()=>{URL.revokeObjectURL(e),t.focus(),t.print()},{once:!0})}function Av(r){const e=r.data;if(!e)return"";const t=e.interpretation,n=oe(e.title_zh),a=oe(e.abstract_zh),i=oe(e.summary_zh),o=[["\u671F\u520A",r.paperMeta?.journal],["\u4F5C\u8005",rh(r.paperMeta?.authors)],["PMID",r.pmid],["DOI",r.paperMeta?.doi],["\u53D1\u8868\u65E5\u671F",r.paperMeta?.publicationDate],["\u6587\u7AE0\u7C7B\u578B",r.paperMeta?.articleType],["\u6765\u6E90",r.paperMeta?.source]].filter(l=>!!l[1]),s=t?[["\u4E00\u53E5\u8BDD\u7ED3\u8BBA",oe(t.one_sentence_summary)],["\u7814\u7A76\u95EE\u9898",oe(t.research_question??t.background)],["\u7814\u7A76\u65B9\u6CD5",oe(t.methods)],["\u5173\u952E\u53D1\u73B0",oe(t.key_findings??t.core_findings)],["\u5C40\u9650",oe(t.limitations)],["\u4EF7\u503C\u610F\u4E49",oe(t.significance??t.clinical_significance)]].filter(l=>!!l[1]):[];return`<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>${Pe("AI \u89E3\u8BFB")} - ${Pe(r.paperTitle)}</title>
  <style>
    body { margin: 28px; color: #111827; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", "Noto Sans SC", "Source Han Sans SC", "Helvetica Neue", Arial, sans-serif; line-height: 1.65; }
    h1 { margin: 0 0 8px; font-size: 22px; line-height: 1.35; }
    h2 { margin: 22px 0 10px; font-size: 16px; border-bottom: 1px solid #e5e7eb; padding-bottom: 6px; }
    .source-title { margin: 0 0 12px; color: #374151; font-size: 14px; font-weight: 600; }
    .meta { display: grid; grid-template-columns: 90px 1fr; gap: 6px 12px; margin: 12px 0 18px; font-size: 12px; color: #374151; }
    .meta b { color: #6b7280; }
    .abstract { white-space: pre-wrap; }
    .interp { display: grid; grid-template-columns: 92px 1fr; gap: 8px 12px; }
    .interp b { color: #374151; }
    ol { padding-left: 22px; }
    li { margin-bottom: 10px; }
    a { color: #005ea8; text-decoration: none; }
    @page { margin: 18mm; }
  </style>
</head>
<body>
  <h1>${Pe("AI \u89E3\u8BFB")}</h1>
  <div class="source-title">${Pe(r.paperTitle)}</div>
  ${o.length?`<div class="meta">${o.map(([l,c])=>`<b>${Pe(l)}</b><span>${Pe(c)}</span>`).join("")}</div>`:""}
  <h2>\u6807\u9898\u7FFB\u8BD1</h2>
  <p>${Pe(n||"")}</p>
  ${e.original_summary?`<h2>\u539F\u6587\u6458\u8981</h2><p class="abstract">${Pe(e.original_summary)}</p>`:""}
  <h2>\u4E2D\u6587\u6458\u8981</h2>
  <p class="abstract">${Pe(a||i||"")}</p>
  ${eh(i,a)?`<h2>\u4E2D\u6587\u6982\u8981</h2><p class="abstract">${Pe(i)}</p>`:""}
  ${e.keywords?.length?`<h2>\u5173\u952E\u8BCD</h2><p>${e.keywords.map(Pe).join("\uFF0C")}</p>`:""}
  ${s.length?`<h2>\u89E3\u8BFB\u6846\u67B6</h2><div class="interp">${s.map(([l,c])=>`<b>${Pe(l)}</b><span>${Pe(c)}</span>`).join("")}</div>`:""}
</body>
</html>`}function Pe(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const Cv=9,vv="1.3.1",Ht=`https://${["sci","hub.ru"].join("-")}/`,ut={appVersion:vv,schemaVersion:Cv,showImpactFactor:!0,showCitations:!0,showOpenAccess:!0,showReferences:!1,showExtraDownload:!0,pubmedApiKey:"",extraDownloadUrl:Ht,quartileSources:["jcr","cas","emerging"],showScimagoSJR:!0,aiProviderMode:"auto",aiFallbackToPaperLens:!1,aiRequestTimeoutMs:6e4},la="paperlens_settings",wi="paperlens_pubmed_api_key",al=["show","Sci","hub"].join(""),il=["sci","hub","Domain"].join("");function Sv(r,e){return{...r,quartileSources:os(r.quartileSources,is(r.quartileSource))}}async function ol(){try{const e=(await I.storage.local.get(wi))[wi];return typeof e=="string"?e:""}catch{return""}}async function wv(r){const e=r.trim();e?await I.storage.local.set({[wi]:e}):await I.storage.local.remove(wi)}async function Tv(r){if(!("pubmedApiKey"in r))return r;const e={...r},t=typeof e.pubmedApiKey=="string"?e.pubmedApiKey.trim():"";delete e.pubmedApiKey;const n=await ol();return t&&!n&&await wv(t),await I.storage.sync.set({[la]:e}),e}function ah(r){const{pubmedApiKey:e,...t}=r;return t}function Ev(r){const e={...r};let t=!1;return al in e&&("showExtraDownload"in e||(e.showExtraDownload=e[al]),delete e[al],t=!0),il in e&&("extraDownloadUrl"in e||(e.extraDownloadUrl=e[il]),delete e[il],t=!0),t&&I.storage.sync.set({[la]:ah(e)}),e}function Fv(r){const e={...r};let t=!1;if(!Array.isArray(e.quartileSources))e.quartileSources=is(e.quartileSource),t=!0;else{const n=os(e.quartileSources,[]);JSON.stringify(n)!==JSON.stringify(e.quartileSources)&&(e.quartileSources=n,t=!0)}return"quartileSource"in e&&(delete e.quartileSource,t=!0),t&&I.storage.sync.set({[la]:ah(e)}),e}async function we(){try{let e=(await I.storage.sync.get(la))[la];if(e){e=Ev(e),e=Fv(e),e=await Tv(e);const n=await ol();return Sv({...ut,...e,pubmedApiKey:n},e)}const t=await ol();return{...ut,pubmedApiKey:t}}catch(r){return console.error("[Settings] Failed to get settings:",r),{...ut}}}function sl(r,e){switch(r.position){case"after":r.element.after(e);break;case"before":r.element.before(e);break;case"prepend":r.element.prepend(e);break;case"append":r.element.appendChild(e);break;default:r.element.after(e)}}async function Dv(r){try{const e=await H({type:"ENRICH_ZOTERO_PAPER",payload:{paper:r}},1e4);if(e?.success&&e.data)return e.data;e?.error&&console.warn("[PaperLens] Zotero CrossRef enrich failed:",e.error)}catch(e){console.warn("[PaperLens] Zotero CrossRef enrich request failed:",e)}return r}const Ti="data-paperlens-article-id",ll="data-paperlens-article-signature",ih=[_t,".paperlens-extra-tags",eu,xo,In,".paperlens-action-row",Pn,Bn].join(","),_v={pubmed:"sites.pubmed","google-scholar":"sites.google_scholar","baidu-scholar":"sites.baidu_scholar","semantic-scholar":"sites.semantic_scholar",cnki:"sites.cnki",wanfang:"sites.wanfang",wos:"sites.webofscience","ieee-xplore":"sites.ieee_acm","acm-dl":"sites.acm_dl",jstor:"sites.jstor",mdpi:"sites.mdpi","science-org":"sites.science_org","publisher-network":"sites.publisher_sites",nature:"sites.publisher_sites",springerlink:"sites.publisher_sites",sciencedirect:"sites.publisher_sites",wiley:"sites.publisher_sites",lww:"sites.publisher_sites",lancet:"sites.publisher_sites",bmj:"sites.publisher_sites",nejm:"sites.publisher_sites","jama-network":"sites.publisher_sites","sage-journals":"sites.publisher_sites","taylor-francis":"sites.publisher_sites","oxford-academic":"sites.publisher_sites","cambridge-core":"sites.publisher_sites","cell-com":"sites.publisher_sites",plos:"sites.publisher_sites",openreview:"sites.preprints",dblp:"sites.preprints"},kv='13px/1.35 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","Noto Sans CJK SC","Noto Sans SC","Source Han Sans SC","Helvetica Neue",Arial,sans-serif',cl='14px/1.45 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","Noto Sans CJK SC","Noto Sans SC","Source Han Sans SC","Helvetica Neue",Arial,sans-serif';async function Ei(r){if(typeof I?.runtime?.sendMessage!="function")return{pluginAllowed:!0,siteAllowed:!0,metricsBasic:!0,warningTags:!0,fulltextOpenAccess:!0};const e=_v[r.id],[t,n,a,i,o]=await Promise.all([We("plugin.chrome","Chrome \u6269\u5C55"),e?We(e,r.name):Promise.resolve({allowed:!0}),We("metrics.basic","\u57FA\u7840\u671F\u520A\u6307\u6807"),We("metrics.warning_tags","\u9884\u8B66\u4E0E\u4E2D\u6587\u6807\u7B7E"),We("fulltext.open_access","\u5F00\u653E\u83B7\u53D6\u5168\u6587")]);return{pluginAllowed:t.allowed,siteAllowed:n.allowed,metricsBasic:a.allowed,warningTags:i.allowed,fulltextOpenAccess:o.allowed}}function Fi(r,e){return e.pluginAllowed&&e.siteAllowed?!0:(console.warn(`[PaperLens] Enhancement disabled by server entitlement for ${r.id}`),!1)}function Nv(r,e){const t=e.getRootNode();return t.nodeType===11&&"host"in t?t:r}function tt(r,e){return!!r.querySelector(e)}function oh(r){r.querySelectorAll(ih).forEach(e=>e.remove())}function sh(r){if(r.pmid)return r.pmid;if(r.sourceId)return r.sourceId;if(r.doi)return r.doi;const e=`${r.source??"article"}|${r.url??""}|${r.title}`;let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return`${r.source??"article"}:${Math.abs(t).toString(36)}`}function Lv(r,e){return Array.from(new Set([e,r.pmid,r.sourceId,r.doi].filter(Boolean)))}function lh(r){const e=r?.trim()??"";return/^10\.\d{4,9}\//i.test(e)?e.toLowerCase():e}function ch(r){const e=new Set;for(const t of r)for(const n of[t.pmid,t.sourceId,t.doi]){const a=n?.trim();if(!a)continue;e.add(a);const i=lh(a);i&&e.add(i)}return e}function uh(r){let e=0;for(let t=0;t<r.length;t++)e=(e<<5)-e+r.charCodeAt(t)|0;return Math.abs(e).toString(36)}function dh(r,e){return uh([e,r.title,r.journalName,r.doi,r.year,r.url,r.abstractSnippet,r.articleTypes?.join("|"),r.authors?.join("|")].filter(Boolean).join("||"))}function ph(r,e,t){return r.id==="baidu-scholar"&&e.hostElement?hh(e.hostElement,t):dh(e,t)}function lr(r){return(r??"").replace(/\s+/g," ").trim()}function ul(r){const e=r?.trim();if(!e)return"";try{return new URL(e,location.href).href}catch{return e}}const Rv=/\b10\.\d{4,9}\/[-._;()/:<>+\[\]A-Z0-9]+/i;function hh(r,e){const t=r.querySelector('.sc_title a, h3 a, .result-title a, a[data-click*="title"]'),n=Array.from(r.querySelectorAll(".sc_author, .sc_source, .sc_time, .sc_type, .result-meta, [data-paperlens-meta]")).map(o=>lr(o.textContent??"")).filter(Boolean).join("|"),i=lr(r.textContent??"").match(Rv)?.[0]??"";return uh([e,lr(t?.textContent??""),ul(t?.getAttribute("href")??t?.href??""),n,lr(i)].join("||"))}function Pv(r,e,t){const n=r.hostElement;if(!n?.isConnected)return!1;const a=n.getAttribute(Ti);if(a&&a!==e)return!1;const i=n.querySelector('.sc_title a, h3 a, .result-title a, a[data-click*="title"]'),o=lr(i?.textContent??"");if(o&&o!==lr(r.title))return!1;const s=ul(i?.getAttribute("href")??i?.href??""),l=ul(r.url);return s&&l&&s!==l?!1:hh(n,e)===t}function Bv(r,e,t,n){const a=r.getAttribute(ll),i=!!e.querySelector(ih);a!==n&&(a||i)&&oh(e),r.getAttribute(Ti)!==t&&r.setAttribute(Ti,t),a!==n&&r.setAttribute(ll,n)}function Iv(r,e,t,n){if(!e.hostElement?.isConnected)return!1;if(r.id==="baidu-scholar")return Pv(e,t,n);let a;if(r.isSearchPage())a=r.parseSearchResults().find(o=>o.hostElement===e.hostElement);else if(r.isArticlePage()){if(a=r.parseArticlePage(),a?.hostElement!==e.hostElement)return!1}else return!0;if(!a)return!1;const i=sh(a);return i===t&&ph(r,a,i)===n}function zt(r,e,t,n,a){return Iv(r,e,n,a)?!1:(oh(t),e.hostElement?.removeAttribute(Ti),e.hostElement?.removeAttribute(ll),!0)}function Mv(r){const e=r.match(/[A-Za-z]/g)?.length??0,t=r.match(/[\u3400-\u9fff]/g)?.length??0;return e>=12&&e>t}function qv(r,e){return e.showExtraDownload===!1||!(e.extraDownloadUrl??Ht)?!1:r.source==="cnki"||r.source==="wanfang"||r.source==="baidu-scholar"?r.doi?!0:r.source==="baidu-scholar"?!1:Mv(r.title)&&fh(r):!0}function fh(r){if(!r.articleTypes||r.articleTypes.length===0)return!0;const e=r.articleTypes.join(" ").toLowerCase();return!/(conference|proceedings|proceeding paper|meeting abstract|preprint|book review|book|chapter|thesis|dissertation|patent|newspaper|会议|学位|硕士|博士|专利|报纸|图书|章节|预印本)/i.test(e)}async function jv(r){const e=[r.journalName,...r.journalCandidates??[]].map(n=>n?.trim()).filter(n=>!!n),t=new Set;for(const n of e){const a=n.toLowerCase();if(t.has(a))continue;t.add(a);const i=await zr(n,r.issn);if(i)return{match:i,journalName:i.journal.journalName}}if(r.issn){const n=await zr("",r.issn);if(n)return{match:n,journalName:n.journal.journalName}}return{match:null,journalName:r.journalName}}async function $v(r,e){const t=mh(r),n=[e,r.journalName,...r.journalCandidates??[]].map(i=>i?.trim()).filter(i=>!!i),a=new Set;for(const i of n){const o=i.toLowerCase();if(a.has(o))continue;a.add(o);const s=await wA(i,t);if(s)return s}return null}function mh(r){if(r.citationType==="inproceedings")return"conference";if(r.citationType==="article")return"journal";const e=r.articleTypes?.join(" ").toLowerCase()??"";if(/conference|proceedings|会议/.test(e))return"conference";if(/journal|期刊/.test(e))return"journal"}function Ov(r,e){return e?!0:mh(r)==="conference"}function Uv(r){return r.isArticlePage()||r.id==="springerlink"||r.id==="nature"||r.id==="wanfang"||r.id==="cell-com"||r.id==="jstor"||r.id==="lancet"||r.id==="bmj"}function Hv(r,e){return!r.isArticlePage()||e.position!=="after"?!1:r.id==="publisher-network"?!0:/^(a|span|strong|em|b|i|small|sup|sub)$/i.test(e.element.tagName)}function zv(r,e){if(e.id==="publisher-network"){r.style.cssText=["display:block","flex:0 0 100%","grid-column:1 / -1","align-self:stretch","justify-self:stretch","box-sizing:border-box","width:100%","min-width:0","max-width:100%",`font:${cl}`,"margin:6px 0 0","clear:both"].join(";")+";";return}r.style.cssText="display:block;width:max-content;max-width:100%;margin:6px 0 0;"}function Jv(r){return r.id==="baidu-scholar"||r.id==="science-org"&&r.isArticlePage()?"compact":"default"}function Vv(r,e){e.isArticlePage()&&(r.style.font=e.id==="publisher-network"?cl:kv)}function Wv(r,e){const t=r.sourceId??"";return t.startsWith("pnas:")?"PNAS":t.startsWith("acs:")?e:t.startsWith("csh-perspectives:")?"Cold Spring Harbor Perspectives":t.startsWith("genes-dev:")?"Genes & Development":r.journalName||e}function Gv(r,e,t){return r.id==="publisher-network"?Wv(e,t):r.id==="science-org"&&r.isArticlePage()?t||e.journalName:e.journalName||t}function Zv(r){return r.id==="publisher-network"&&r.isArticlePage()?["display:flex","flex:0 0 100%","grid-column:1 / -1","align-items:center","justify-content:flex-start","flex-wrap:wrap","gap:8px","box-sizing:border-box","width:100%","min-width:0","max-width:100%",`font:${cl}`,"margin:6px 0 0","clear:both"].join(";")+";":Uv(r)?"display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin:8px 0 0;":"display:inline-flex;flex-wrap:wrap;align-items:center;gap:8px;margin-left:8px;"}const Yv=/^(?:在线阅读|查看全文|下载全文|下载|全文快报|引用|收藏|评审材料|导出)$/,Kv=/(?:被引(?:量)?|下载(?:量)?|浏览(?:量)?|阅读(?:量)?|引证)[:：]?\d+/,bh=[".reference",".org",".abstract",".record-title",".title-row",".meta-row",".abstract-row",".keyword-row",".wf-search-card__meta",".wf-search-card__abstract"].join(", ");function dl(r){return(r??"").replace(/\s+/g,"").trim()}function Qv(r){return dl(r).replace(/^(?:AI)?(?:free)?/i,"").replace(/(?:AI)?(?:free)?$/i,"")}function gh(r){return r.matches(bh)}function yh(r){const e=Qv(r.textContent??"");return!e||e.length>20?!1:Yv.test(e)}function pl(r){if(!r)return!1;const e=dl(r.textContent??"");return!!e&&Kv.test(e)}function Xv(r){const e=dl(r.textContent??"");return e?/^[|/·•\-—丨]+$/.test(e):!0}function xh(r){return gh(r)||!!r.querySelector(bh)}function Di(r,e){const t=Array.from(r.children);return t.length===0?!1:t.every(n=>e.some(a=>n===a||n.contains(a))||pl(n)||Xv(n))}function Ah(r,e){let t=r;for(;t.parentElement&&t.parentElement!==e;){const n=t.parentElement;if(gh(n))return n;if(xh(n))break;if(Di(n,[t])){t=n;continue}if(yh(n)&&n.children.length<=3){t=n;continue}if(n.matches(".wf-list-button, .btn-read, .btn-download, .lnk-view, .lnk-download, .list-button-quote, a, button")){t=n;continue}break}return t}function hl(r){if(r.length===0)return null;if(r.length===1)return r[0]?.parentElement??null;const t=(n=>{const a=[];let i=n;for(;i;)a.push(i),i=i.parentElement;return a})(r[0]);for(const n of t)if(r.every(a=>n.contains(a)))return n;return null}function eS(r){const e=r.hostElement,t=e.querySelector(".wf-search-card__actions, .action-row, .item-btnpanel, .btnpanel");if(t)return t;const n=Array.from(e.querySelectorAll(".wf-list-button, .btn-read, .btn-download, .lnk-view, .lnk-download, .list-button-quote, a, button, span, div")).filter(s=>yh(s));if(n.length===0)return null;const a=n[0]?.parentElement;if(a&&n.every(s=>s.parentElement===a))return Di(a,n)?pl(a.nextElementSibling)&&a.parentElement&&a.parentElement!==e&&Di(a.parentElement,n)?a.parentElement:a:Ah(n.at(-1)??a,e);const i=hl(n);if(i&&i!==e&&!xh(i))return pl(i.nextElementSibling)&&i.parentElement&&i.parentElement!==e&&Di(i.parentElement,n)?i.parentElement:i;const o=n.at(-1);return o?Ah(o,e):null}function tS(r,e){return r.id==="wanfang"&&r.isSearchPage()?eS(e):r.id==="jstor"&&r.isSearchPage()?aS(e):r.id==="cell-com"&&r.isSearchPage()?cS(e):null}const nS=/^(?:read online|download|save(?: to workspace)?|cite|this content is not available for download)$/i;function rS(r){return(r??"").replace(/\s+/g," ").trim()}function Ch(r){const e=rS(r.textContent??"");return!e||e.length>48?!1:nS.test(e)}function aS(r){const e=r.hostElement,t=e.querySelector('.actions, .result-actions, .search-result__actions, .item-actions, [data-testid*="actions"], [class*="actions"]');if(t&&Array.from(t.querySelectorAll("button, a, span, div, li")).some(o=>Ch(o)))return t;const n=Array.from(e.querySelectorAll("button, a, span, div, li")).filter(o=>Ch(o));if(n.length===0)return null;const a=n[0]?.parentElement;if(a&&n.every(o=>o.parentElement===a)&&a!==e)return a;const i=hl(n);return i&&i!==e?i:null}const iS=/^(?:download(?:\s+pdf)?|export\s+citation|request\s+permissions|get\s+access)$/i,oS=/^[|/·•\-—]+$/,vh=[".abstract",".issue-item__abstract",".summary",".meta",".publication_meta",".issue-item__title",".art_title"].join(", ");function fl(r){return(r??"").replace(/\s+/g," ").trim()}function ml(r){const e=fl(r.textContent??"");return!e||e.length>40?!1:iS.test(e)}function sS(r){const e=fl(r.textContent??"");return!e||oS.test(e)}function lS(r){const e=fl(r.textContent??"");return!!e&&(/^doi\b/i.test(e)||/doi\.org\//i.test(e))}function Sh(r){return Array.from(r.querySelectorAll("a, button, span, div")).filter(e=>ml(e)).length}function ca(r){return r.matches(vh)||!!r.querySelector(vh)}function wh(r){if(ca(r))return!1;const e=Array.from(r.children);return e.length===0?!1:e.every(t=>ml(t)||sS(t)||lS(t)||Sh(t)>0)}function Th(r,e){let t=r;for(;t.parentElement&&t.parentElement!==e;){const n=t.parentElement;if(ca(n))break;if(n.children.length===1||wh(n)){t=n;continue}break}return t}function cS(r){const e=r.hostElement,t=Array.from(e.querySelectorAll("a, button, span, div")).filter(l=>ml(l));if(t.length===0)return null;const n=Array.from(new Set(t.map(l=>Th(l,e)).filter(l=>l!==e))),a=e.querySelector(".article-tools, .issue-item__buttons, .toolbar, .action-bar, .search-result__actions, .issue-item__detail, .issue-item__detail-actions, .article-links");if(a&&!ca(a))return n.filter(c=>!a.contains(c)).at(-1)??a;if(a){const l=Array.from(a.querySelectorAll("div, span, ul, ol")).find(c=>wh(c)&&Sh(c)>0);if(l)return l}const i=t[0]?.parentElement;if(i&&t.every(l=>l.parentElement===i)&&!ca(i))return i;if(n.length>0)return n.at(-1)??null;const o=hl(t);if(o&&o!==e&&!ca(o))return o;const s=t.at(-1);return s?Th(s,e):null}async function _i(r,e,t,n,a){if(!e.hostElement)return"skipped";const i=sh(e),o=ph(r,e,i),s=r.getMetricBarAnchor(e.hostElement),l=Nv(e.hostElement,s.element);Bv(e.hostElement,l,i,o);let c=null;const u=n.metricsBasic&&fh(e),d=e.journalName||e.journalCandidates?.[0]||"",p=u?jv(e):Promise.resolve({match:null,journalName:e.journalName}),h=Lv(e,i),f=tS(r,e),y=!!f;let x=l.querySelector(".paperlens-action-row");const T=()=>x||(x=document.createElement("div"),x.className="paperlens-action-row",x.style.cssText=Zv(r),f?f.after(x):c?c.after(x):sl(s,x),x),E=await p;if(zt(r,e,l,i,o))return"stale";const w=E.journalName||e.journalName,v=E.match?.journal,g=n.fulltextOpenAccess?e.nativeFullTextUrl:void 0,C=n.fulltextOpenAccess&&qv(e,t),L={pmid:e.pmid,doi:e.doi,title:e.title,fallbackDomain:t.extraDownloadUrl??Ht,nativeFullTextUrl:g,journalOpenAccess:!!v?.openAccess},$=tt(l,'[data-paperlens-fulltext="native"]')||tt(l,'[data-paperlens-fulltext="extra-download"]'),k=!$&&g?LA(g,"\u5168\u6587\u83B7\u53D6",L):!$&&C?Yd(e.doi,t.extraDownloadUrl??Ht,!!v?.openAccess,e.title,L):null;if(k&&(k.style.cssText="display:inline-flex;align-items:center;",T().appendChild(k)),zt(r,e,l,i,o))return"stale";if(e.title&&!tt(l,xo)){const R=Jp({paper:{pmid:e.pmid??"",title:e.title,authors:e.authors,abstract:e.abstractSnippet,publicationDate:e.publicationDate,year:e.year,doi:e.doi,journal:d,volume:e.volume,issue:e.issue,pages:e.pages,issn:e.issn,url:e.url,citationType:e.citationType,source:e.source},beforeSave:e.doi?void 0:Dv});R.style.cssText="display:inline-flex;align-items:center;",T().appendChild(R)}if(zt(r,e,l,i,o))return"stale";if(e.title&&(!tt(l,Pn)||!tt(l,Bn))){if(!tt(l,Pn)){const R=a?h.some(se=>a.has(se)||a.has(lh(se))):(await Promise.all(h.map(se=>gi(se)))).some(Boolean);if(zt(r,e,l,i,o)||zt(r,e,l,i,o))return"stale";const M=v,Q=Ss({sourceId:e.sourceId??(e.pmid||e.doi?void 0:i),alternateIds:h,source:e.source,pmid:e.pmid,doi:e.doi,title:e.title,journal:d,impactFactor:M?.impactFactor,jcrQuartile:M?.jcrQuartile,casQuartile:M?.casQuartile?String(M.casQuartile).replace("\u533A",""):void 0,year:e.year,url:e.url,language:["\u4E2D\u56FD\u77E5\u7F51","\u4E07\u65B9\u6570\u636E","\u767E\u5EA6\u5B66\u672F","cnki","wanfang","baidu-scholar"].includes(e.source??"")?"zh":void 0,authors:e.authors,abstract:e.abstractSnippet,publicationTypes:e.articleTypes,volume:e.volume,issue:e.issue,pages:e.pages,issn:e.issn,pdfUrl:e.nativeFullTextUrl,oaUrl:e.nativeFullTextUrl,sourceUrl:e.url},R);Q.style.cssText="display:inline-flex;align-items:center;",T().appendChild(Q)}if(!tt(l,Bn)){const R=RC({title:e.title,journal:d,publicationDate:e.publicationDate,year:e.year,doi:e.doi,url:e.url,authors:e.authors,abstract:e.abstractSnippet,volume:e.volume,issue:e.issue,pages:e.pages,issn:e.issn,citationType:e.citationType,nativeExportUrls:e.nativeExportUrls});R.style.cssText="display:inline-flex;align-items:center;",T().appendChild(R)}}if(e.title&&!tt(l,In)){const R=YC({paper_id:i,pmid:e.pmid,doi:e.doi,title:e.title,abstract:e.abstractSnippet,journal:d,authors:e.authors,year:e.year,publication_date:e.publicationDate,source:e.source,source_url:e.url??location.href});R.style.cssText="display:inline-flex;align-items:center;",T().appendChild(R)}if(zt(r,e,l,i,o))return"stale";if(u&&(w||e.issn)&&!tt(l,_t)){const R=E.match;if(R&&Vn(R.journal,{quartileSources:t.quartileSources})){const M=gs(R.journal,{layout:Jv(r),quartileSources:t.quartileSources,showScimagoSJR:t.showScimagoSJR,paper:{journal:Gv(r,e,R.journal.journalName)}});Hv(r,s)&&zv(M,r),Vv(M,r),x&&!y?x.before(M):sl(s,M),c=M}}const N=n.warningTags&&u&&w?CA(await AA(w)):[];if(zt(r,e,l,i,o))return"stale";const S=n.warningTags&&Ov(e,u)?await $v(e,w):null;if(zt(r,e,l,i,o))return"stale";const _=S?EA(S):null,P=[...N,..._?[_]:[]];if(P.length&&!tt(l,".paperlens-extra-tags")){const R=document.createElement("span");R.className="paperlens-extra-tags",R.append(...P),R.style.cssText="display:inline-flex;align-items:center;gap:2px;margin-left:4px;",c?c.after(R):x&&!y?x.before(R):sl(s,R),c=R}return"enhanced"}async function bl(r){let e=r.parseSearchResults();if(e.length===0)return console.log(`[PaperLens] No articles found by ${r.id} adapter`),0;console.log(`[PaperLens] Enhancing ${e.length} articles on ${r.name}`);const t=await Ei(r);if(!Fi(r,t))return 0;await Hn().catch(()=>{});let n;try{n=await we()}catch(s){console.warn("[PaperLens] getSettings failed, using defaults:",s),n={extraDownloadUrl:Ht}}let a;try{a=ch(await vs())}catch(s){console.warn("[PaperLens] Failed to preload library ids for multi-site enhancement:",s)}let i=0,o=!1;for(let s=0;s<5;s++){o=!1;for(const l of e)try{const c=await _i(r,l,n,t,a);c==="enhanced"&&i++,c==="stale"&&(o=!0)}catch(c){console.warn(`[PaperLens] Failed to enhance article "${l.title?.slice(0,40)}":`,c)}if(!o)break;if(e=r.parseSearchResults(),r.id==="baidu-scholar"&&e.length>0)for(let l=0;l<2&&e.length>0;l++)await Promise.resolve(),e=r.parseSearchResults();if(e.length===0)break}return console.log(`[PaperLens] Enhanced ${i}/${e.length} articles`),i}async function J(r){const e=r.parseArticlePage();if(!e)return console.log(`[PaperLens] No detail article found by ${r.id} adapter`),0;const t=await Ei(r);if(!Fi(r,t))return 0;await Hn().catch(i=>console.warn("[PaperLens] loadJournals failed:",i));let n;try{n=await we()}catch{n={extraDownloadUrl:Ht}}let a;try{a=ch(await vs())}catch(i){console.warn("[PaperLens] Failed to preload library ids for detail-page enhancement:",i)}return await _i(r,e,n,t,a),console.log(`[PaperLens] Enhanced article page on ${r.name}`),1}async function uS(r){const e=r,t=e.parseCitationLibrary();if(t.length===0)return console.log("[PaperLens] No articles found in citation library"),0;console.log(`[PaperLens] Enhancing ${t.length} citation library articles`);const n=await Ei(r);if(!Fi(r,n))return 0;await Hn().catch(l=>console.warn("[PaperLens] loadJournals failed:",l));let a;try{a=await we()}catch{a={extraDownloadUrl:Ht}}const i=l=>e.getCitationLibraryAnchor(l);let o=0;for(const l of t)if(l.hostElement&&!l.hostElement.hasAttribute("data-pl-enhanced"))try{const c=r.getMetricBarAnchor.bind(r);r.getMetricBarAnchor=i;try{await _i(r,l,a,n)}finally{r.getMetricBarAnchor=c}l.hostElement.setAttribute("data-pl-enhanced","true"),o++}catch(c){console.warn(`[PaperLens] Failed to enhance library article "${l.title?.slice(0,40)}"`,c)}const s=document.getElementById("gsc_a_b");if(s){let l=null;const c=new MutationObserver(()=>{l&&clearTimeout(l),l=setTimeout(async()=>{const u=e.parseCitationLibrary(),d=await Ei(r);if(!Fi(r,d))return;const p=r.getMetricBarAnchor.bind(r);r.getMetricBarAnchor=i;try{for(const h of u)if(h.hostElement&&!h.hostElement.hasAttribute("data-pl-enhanced"))try{await _i(r,h,a,d),h.hostElement.setAttribute("data-pl-enhanced","true")}catch(f){console.warn("[PaperLens] dynamic enhance failed:",f)}}finally{r.getMetricBarAnchor=p}},300)});c.observe(s,{childList:!0,subtree:!0}),document.addEventListener("visibilitychange",()=>{document.hidden?c.disconnect():c.observe(s,{childList:!0,subtree:!0})})}return console.log(`[PaperLens] Enhanced ${o}/${t.length} library articles`),o}const dS=`/**
 * PaperLens Shadow DOM \u5185\u90E8\u6837\u5F0F
 *
 * \u6B64\u6587\u4EF6\u4E2D\u7684\u6240\u6709\u6837\u5F0F\u4EC5\u4F5C\u7528\u4E8E Shadow DOM \u5185\u90E8\u3002
 * Shadow DOM \u7684\u6837\u5F0F\u9694\u79BB\u673A\u5236\u786E\u4FDD\uFF1A
 *   1. PubMed \u9875\u9762\u7684 CSS \u9009\u62E9\u5668\u65E0\u6CD5\u5339\u914D Shadow DOM \u5185\u90E8\u5143\u7D20
 *   2. Shadow DOM \u5185\u90E8\u7684\u6837\u5F0F\u4E0D\u4F1A\u6CC4\u6F0F\u5230 PubMed \u9875\u9762
 *   3. \u5373\u4F7F PubMed \u4F7F\u7528\u4E86\u4E0E\u6211\u4EEC\u76F8\u540C\u7684 class \u540D\uFF0C\u4E5F\u4E0D\u4F1A\u51B2\u7A81
 *
 * \u6280\u672F\u539F\u7406\uFF1A
 *   - Shadow DOM \u4E3A\u5185\u90E8\u5143\u7D20\u521B\u5EFA\u4E86\u4E00\u4E2A\u72EC\u7ACB\u7684 CSS \u4F5C\u7528\u57DF
 *   - \u5916\u90E8\u6837\u5F0F\u8868\u4E2D :root / body \u7B49\u9009\u62E9\u5668\u65E0\u6CD5\u7A7F\u900F Shadow boundary
 *   - \u5185\u90E8\u5B9A\u4E49\u7684\u6837\u5F0F\u4E5F\u4E0D\u4F1A\u5F71\u54CD document \u4E2D\u7684\u5143\u7D20
 *   - \u552F\u4E00\u4F8B\u5916\uFF1ACSS Custom Properties (inherit) \u53EF\u4ECE\u5916\u90E8\u7EE7\u627F\uFF0C
 *     \u4F46\u6211\u4EEC\u5728 :host \u4E0A\u663E\u5F0F\u5B9A\u4E49\u4E86\u6240\u6709 --pl-* \u53D8\u91CF\uFF0C\u8986\u76D6\u4E86\u7EE7\u627F
 */

/* \u2500\u2500 Design Tokens \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
/* tokens.css \u7531 content script \u5728 JS \u4E2D\u62FC\u63A5\uFF0C\u4E0D\u901A\u8FC7 @import */

/* \u2500\u2500 \u5BB9\u5668\u5E03\u5C40\uFF08\u5BBF\u4E3B\u5143\u7D20\uFF09 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
:host {
  all: initial;
  display: block;
  color: inherit;
  font: inherit;
  position: fixed;
  top: 0;
  right: 0;
  z-index: 2147483647; /* 32-bit signed max \u2014 \u786E\u4FDD\u5728\u6700\u9876\u5C42 */
  pointer-events: none;
  font-family: var(--pl-font-sans);
  color: var(--pl-color-text);
  line-height: 1.5;
}

/* \u2500\u2500 \u5185\u90E8\u5BB9\u5668 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-container {
  box-sizing: border-box;
  pointer-events: auto;
  margin: var(--pl-space-sm);
}

/* \u2500\u2500 \u6D4B\u8BD5 Badge \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-badge {
  display: inline-flex;
  align-items: center;
  gap: var(--pl-space-xs);
  background-color: var(--pl-color-primary);
  color: var(--pl-color-white);
  padding: var(--pl-space-xs) var(--pl-space-md);
  border-radius: var(--pl-radius-full);
  font-family: var(--pl-font-sans);
  font-size: var(--pl-font-sm);
  font-weight: var(--pl-weight-medium);
  line-height: 1.4;
  box-shadow: var(--pl-shadow-md);
  cursor: default;
  user-select: none;
  white-space: nowrap;
  opacity: 1;
  transition: opacity var(--pl-transition-normal);
}

.pl-badge:hover {
  background-color: var(--pl-color-primary-hover);
  box-shadow: var(--pl-shadow-lg);
}

.pl-badge--faded {
  opacity: 0.6;
}

/* \u2500\u2500 Utility Classes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */

/* \u6392\u7248 */
.pl-text-xs   { font-size: var(--pl-font-xs); }
.pl-text-sm   { font-size: var(--pl-font-sm); }
.pl-text-base { font-size: var(--pl-font-base); }
.pl-text-lg   { font-size: var(--pl-font-lg); }
.pl-text-xl   { font-size: var(--pl-font-xl); }

.pl-font-normal   { font-weight: var(--pl-weight-normal); }
.pl-font-medium   { font-weight: var(--pl-weight-medium); }
.pl-font-semibold { font-weight: var(--pl-weight-semibold); }
.pl-font-bold     { font-weight: var(--pl-weight-bold); }

/* \u5E03\u5C40 */
.pl-flex          { display: flex; }
.pl-flex-center   { display: flex; align-items: center; justify-content: center; }
.pl-flex-col      { display: flex; flex-direction: column; }
.pl-items-center  { display: flex; align-items: center; }
.pl-gap-xs        { gap: var(--pl-space-xs); }
.pl-gap-sm        { gap: var(--pl-space-sm); }
.pl-gap-md        { gap: var(--pl-space-md); }

/* \u95F4\u8DDD */
.pl-m-0   { margin: 0; }
.pl-p-0   { padding: 0; }
.pl-p-xs  { padding: var(--pl-space-xs); }
.pl-p-sm  { padding: var(--pl-space-sm); }
.pl-p-md  { padding: var(--pl-space-md); }
.pl-p-lg  { padding: var(--pl-space-lg); }

/* \u76D2\u6A21\u578B\u91CD\u7F6E\uFF08\u6240\u6709\u5185\u90E8\u5143\u7D20\uFF09 */
.pl-badge *,
.pl-container * {
  box-sizing: border-box;
}

/* \u989C\u8272\u5DE5\u5177 */
.pl-text-primary  { color: var(--pl-color-primary); }
.pl-text-white    { color: var(--pl-color-white); }
.pl-text-gray-500 { color: var(--pl-color-gray-500); }
.pl-bg-primary    { background-color: var(--pl-color-primary); }
.pl-bg-white      { background-color: var(--pl-color-white); }

/* \u5706\u89D2 */
.pl-rounded-sm   { border-radius: var(--pl-radius-sm); }
.pl-rounded-md   { border-radius: var(--pl-radius-md); }
.pl-rounded-lg   { border-radius: var(--pl-radius-lg); }
.pl-rounded-full { border-radius: var(--pl-radius-full); }

/* \u9634\u5F71 */
.pl-shadow-sm { box-shadow: var(--pl-shadow-sm); }
.pl-shadow-md { box-shadow: var(--pl-shadow-md); }
.pl-shadow-lg { box-shadow: var(--pl-shadow-lg); }
`,pS=`/**
 * Citation Badge Styles \u2014 injected into each citation badge's Shadow DOM
 *
 * Design Token \u4F9D\u8D56\uFF1A
 *   --pl-color-* / --pl-font-* / --pl-space-* / --pl-radius-*
 *   \u7531 tokens.css \u5728\u540C\u4E00 Shadow DOM \u5185\u901A\u8FC7 :host \u5B9A\u4E49
 */

:host {
  display: inline-flex;
  align-items: center;
  gap: var(--pl-space-xs);
  padding: 0;
  margin: 0;
  vertical-align: middle;
}

/* \u2500\u2500 \u6307\u6807\u884C\u5BB9\u5668\uFF08\u4E0E metric-bar \u540C\u884C\uFF09 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-citation-bar {
  display: inline-flex;
  align-items: center;
  gap: var(--pl-space-xs);
  font-family: var(--pl-font-sans);
  font-size: var(--pl-font-xs);
  line-height: 1;
}

/* \u2500\u2500 \u5F15\u7528\u6570 Badge \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-citation-badge {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  min-height: 24px;
  padding: 0 8px;
  border-radius: var(--pl-radius-sm);
  font-size: 12px;
  font-weight: var(--pl-weight-semibold);
  line-height: 1;
  white-space: nowrap;
  border: 0;
  background-color: var(--pl-color-gray-100);
  color: var(--pl-color-gray-700);
  font-family: var(--pl-font-sans);
  cursor: default;
  position: relative;
}

.pl-citation-badge:hover {
  background-color: var(--pl-color-gray-200);
}

.pl-citation-badge--clickable {
  cursor: pointer;
}

.pl-citation-badge--clickable:hover {
  color: var(--pl-color-primary);
}

.pl-citation-icon {
  font-size: 12px;
  opacity: 0.82;
}

/* \u2500\u2500 OA Badge \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-oa-badge {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  min-height: 24px;
  padding: 0 8px;
  border-radius: var(--pl-radius-sm);
  font-size: 12px;
  font-weight: var(--pl-weight-semibold);
  line-height: 1;
  white-space: nowrap;
  background-color: var(--pl-color-success-light);
  color: var(--pl-color-success);
  text-decoration: none;
  cursor: pointer;
  transition: background-color var(--pl-transition-fast);
}

.pl-oa-badge:hover {
  background-color: var(--pl-color-success-light);
}

.pl-oa-badge:active {
  background-color: var(--pl-color-success);
  color: var(--pl-color-bg);
}

.pl-oa-icon {
  font-size: 10px;
  letter-spacing: 0;
}

/* \u2500\u2500 OA Badge: \u72B6\u6001 2 \u2014 OA \u4F46\u65E0 PDF \u94FE\u63A5\uFF08\u7070\u8272\u4E0D\u53EF\u70B9\u51FB\uFF09 \u2500\u2500 */
.pl-oa-badge--no-pdf {
  background-color: var(--pl-color-gray-100);
  color: var(--pl-color-gray-500);
  cursor: default;
  pointer-events: auto; /* allow hover for tooltip */
}

.pl-oa-badge--no-pdf:hover {
  background-color: var(--pl-color-gray-200);
}
`;class $e{static currentDrawer=null;static register(e){$e.currentDrawer&&$e.currentDrawer.close(),$e.currentDrawer=e}static unregister(e){$e.currentDrawer===e&&($e.currentDrawer=null)}static getCurrent(){return $e.currentDrawer}}const hS=`/**
 * Citation Drawer Styles \u2014 injected into Shadow DOM
 *
 * \u53F3\u4FA7\u6ED1\u51FA\u62BD\u5C49\u9762\u677F\uFF0C\u663E\u793A\u5F15\u7528\u6587\u732E\u5217\u8868\u3002
 * \u4F7F\u7528 --pl-* design tokens
 */

:host {
  display: inline-flex;
  align-items: center;
  vertical-align: middle;
}

/* \u2500\u2500 \u89E6\u53D1\u6309\u94AE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-panel-trigger {
  display: inline-flex;
  align-items: center;
  gap: var(--pl-space-xs);
  min-height: 24px;
  padding: 0 8px;
  border: 1px solid var(--pl-color-gray-200);
  border-radius: var(--pl-radius-sm);
  background-color: var(--pl-color-gray-100);
  color: var(--pl-color-gray-700);
  font-family: var(--pl-font-sans);
  font-size: 12px;
  font-weight: var(--pl-weight-medium);
  line-height: 1;
  cursor: pointer;
  transition: background-color var(--pl-transition-fast);
  white-space: nowrap;
}

.pl-panel-trigger:hover {
  background-color: var(--pl-color-gray-200);
}

.pl-panel-trigger:active {
  background-color: var(--pl-color-gray-300);
}

.pl-trigger-icon {
  font-size: 12px;
  transition: transform var(--pl-transition-fast);
}

.pl-trigger-spinner {
  display: inline-block;
  width: 10px;
  height: 10px;
  border: 2px solid var(--pl-color-gray-300);
  border-top-color: var(--pl-color-gray-600);
  border-radius: 50%;
  animation: pl-spin 0.6s linear infinite;
}

@keyframes pl-spin {
  to { transform: rotate(360deg); }
}

/* \u2500\u2500 \u62BD\u5C49\u5BBF\u4E3B\u5BB9\u5668 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
:host(.pl-drawer) {
  position: fixed;
  top: 0;
  right: 0;
  width: 420px;
  max-width: min(420px, 92vw);
  height: 100vh;
  z-index: 999999;
  background: var(--pl-color-bg, #ffffff);
  border-left: 1px solid var(--pl-color-gray-200, #e5e7eb);
  box-shadow: -4px 0 16px var(--pl-color-shadow, rgba(0, 0, 0, 0.08));
  display: flex;
  flex-direction: column;
  font-family: var(--pl-font-sans, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans CJK SC', 'Noto Sans SC', 'Source Han Sans SC', 'Helvetica Neue', Arial, sans-serif);
  will-change: transform;
  transform: translateX(100%);
  animation: pl-drawer-slide-in 300ms ease-out forwards;
}

:host(.pl-drawer--closing) {
  animation: pl-drawer-slide-out 250ms ease-in forwards;
}

@keyframes pl-drawer-slide-in {
  from { transform: translateX(100%); }
  to   { transform: translateX(0); }
}

@keyframes pl-drawer-slide-out {
  from { transform: translateX(0); }
  to   { transform: translateX(100%); }
}

/* \u2500\u2500 \u6807\u9898\u680F\uFF08\u56FA\u5B9A\u9876\u90E8\uFF09 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-drawer-header {
  display: flex;
  align-items: flex-start;
  gap: var(--pl-space-sm, 8px);
  padding: var(--pl-space-lg, 16px);
  border-bottom: 1px solid var(--pl-color-gray-200, #e5e7eb);
  flex-shrink: 0;
}

.pl-drawer-title {
  flex: 1;
  font-size: var(--pl-font-sm, 12px);
  font-weight: var(--pl-weight-semibold, 600);
  color: var(--pl-color-gray-900, #111827);
  line-height: 1.4;
  margin: 0;
  padding-right: var(--pl-space-xs, 4px);
}

.pl-drawer-count {
  display: inline-block;
  font-size: 10px;
  font-weight: var(--pl-weight-medium, 500);
  color: var(--pl-color-gray-500, #6b7280);
  white-space: nowrap;
  flex-shrink: 0;
  padding-top: 2px;
}

.pl-drawer-close {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  border: 1px solid var(--pl-color-gray-200, #e5e7eb);
  border-radius: 999px;
  background: var(--pl-color-white, #ffffff);
  color: var(--pl-color-gray-600, #4b5563);
  line-height: 1;
  cursor: pointer;
  flex-shrink: 0;
  box-shadow: 0 1px 2px rgba(15, 23, 42, 0.06);
  transition: all var(--pl-transition-fast, 150ms ease);
}

.pl-drawer-close:hover {
  border-color: var(--pl-color-gray-300, #d1d5db);
  background-color: var(--pl-color-gray-50, #f9fafb);
  color: var(--pl-color-gray-900, #111827);
}

.pl-drawer-close svg {
  width: 16px;
  height: 16px;
  fill: none;
  stroke: currentColor;
  stroke-width: 2;
  stroke-linecap: round;
}

/* \u2500\u2500 \u5206\u9875\u5DE5\u5177\u6761 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-drawer-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--pl-space-sm, 8px);
  padding: 10px var(--pl-space-lg, 16px);
  border-bottom: 1px solid var(--pl-color-gray-100, #f3f4f6);
  background: var(--pl-color-gray-50, #f9fafb);
  flex-shrink: 0;
  flex-wrap: wrap;
}

.pl-drawer-range {
  min-width: 92px;
  font-size: 11px;
  font-weight: var(--pl-weight-semibold, 600);
  color: var(--pl-color-gray-700, #374151);
  white-space: nowrap;
}

.pl-drawer-controls {
  display: inline-flex;
  align-items: center;
  justify-content: flex-end;
  gap: 6px;
  flex-wrap: wrap;
}

.pl-drawer-selection {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  font-size: 10px;
  color: var(--pl-color-gray-600, #4b5563);
  white-space: nowrap;
}

.pl-drawer-select-page {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
}

.pl-drawer-select-page input,
.pl-ref-select {
  width: 13px;
  height: 13px;
  margin: 0;
  accent-color: var(--pl-color-primary, #2563eb);
  cursor: pointer;
}

.pl-drawer-select-page input:disabled {
  cursor: not-allowed;
}

.pl-drawer-selected-count {
  font-weight: var(--pl-weight-semibold, 600);
  color: var(--pl-color-gray-700, #374151);
}

.pl-drawer-page-size {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-size: 10px;
  color: var(--pl-color-gray-500, #6b7280);
  white-space: nowrap;
}

.pl-drawer-page-size select {
  height: 24px;
  border: 1px solid var(--pl-color-gray-200, #e5e7eb);
  border-radius: var(--pl-radius-sm, 4px);
  background: var(--pl-color-bg, #ffffff);
  color: var(--pl-color-gray-700, #374151);
  font-size: 11px;
}

.pl-drawer-tool-btn {
  height: 24px;
  padding: 0 7px;
  border: 1px solid var(--pl-color-gray-200, #e5e7eb);
  border-radius: var(--pl-radius-sm, 4px);
  background: var(--pl-color-bg, #ffffff);
  color: var(--pl-color-gray-700, #374151);
  font-size: 11px;
  font-weight: var(--pl-weight-medium, 500);
  cursor: pointer;
  white-space: nowrap;
}

.pl-drawer-tool-btn:hover:not(:disabled) {
  background: var(--pl-color-gray-100, #f3f4f6);
}

.pl-drawer-tool-btn:disabled,
.pl-drawer-page-size select:disabled {
  opacity: 0.45;
  cursor: not-allowed;
}

/* \u2500\u2500 \u5BFC\u51FA\u4E0B\u62C9\u83DC\u5355 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-drawer-export-wrap {
  position: relative;
  display: inline-block;
}

.pl-drawer-export-dropdown {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 4px;
  background: var(--pl-color-bg, #ffffff);
  border: 1px solid var(--pl-color-gray-200, #e5e7eb);
  border-radius: var(--pl-radius-sm, 4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  z-index: 1000000;
  min-width: 180px;
  overflow: hidden;
}

.pl-drawer-export-group {
  padding: 7px 10px 3px;
  font-size: 10px;
  font-weight: var(--pl-weight-semibold, 600);
  color: var(--pl-color-gray-500, #6b7280);
  background: var(--pl-color-gray-50, #f9fafb);
}

.pl-drawer-export-divider {
  height: 1px;
  background: var(--pl-color-gray-100, #f3f4f6);
}

.pl-drawer-export-option {
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 6px 10px;
  border: none;
  background: transparent;
  text-align: left;
  cursor: pointer;
  font-family: var(--pl-font-sans);
  transition: background-color 0.12s ease;
}

.pl-drawer-export-option:hover {
  background-color: var(--pl-color-gray-50, #f9fafb);
}

.pl-drawer-export-option:disabled {
  cursor: not-allowed;
  opacity: 0.45;
}

.pl-drawer-export-option:disabled:hover {
  background: transparent;
}

.pl-drawer-export-name {
  font-size: 11px;
  font-weight: var(--pl-weight-semibold, 600);
  color: var(--pl-color-gray-800, #1f2937);
}

.pl-drawer-export-desc {
  font-size: 9px;
  color: var(--pl-color-gray-500, #6b7280);
}

/* \u2500\u2500 \u5F15\u7528\u5217\u8868\uFF08\u53EF\u6EDA\u52A8\uFF09 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-drawer-list {
  flex: 1;
  overflow-y: auto;
  margin: 0;
  padding: 0;
  list-style: none;
}

.pl-drawer-list::-webkit-scrollbar {
  width: 4px;
}

.pl-drawer-list::-webkit-scrollbar-track {
  background: transparent;
}

.pl-drawer-list::-webkit-scrollbar-thumb {
  background: var(--pl-color-gray-300, #d1d5db);
  border-radius: 2px;
}

/* \u2500\u2500 \u5355\u6761\u5F15\u7528\u6587\u732E \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-drawer-item {
  display: flex;
  flex-direction: column;
  gap: 2px;
  padding: var(--pl-space-sm, 8px) var(--pl-space-lg, 16px);
  border-bottom: 1px solid var(--pl-color-gray-100, #f3f4f6);
  transition: background-color var(--pl-transition-fast, 150ms ease);
}

.pl-drawer-item:hover {
  background-color: var(--pl-color-gray-50, #f9fafb);
}

.pl-drawer-item:last-child {
  border-bottom: none;
}

.pl-drawer-item-head {
  display: grid;
  grid-template-columns: 14px 28px minmax(0, 1fr);
  gap: 8px;
  align-items: start;
}

.pl-ref-select {
  align-self: start;
  margin-top: 3px;
}

.pl-ref-index {
  display: inline-flex;
  align-items: center;
  justify-content: flex-end;
  padding-top: 2px;
  font-size: 10px;
  font-variant-numeric: tabular-nums;
  color: var(--pl-color-gray-400, #9ca3af);
}

.pl-ref-title {
  min-width: 0;
  font-size: var(--pl-font-xs, 11px);
  font-weight: var(--pl-weight-medium, 500);
  color: var(--pl-color-primary, #2563eb);
  text-decoration: none;
  line-height: 1.5;
  cursor: pointer;
}

.pl-ref-title:hover {
  text-decoration: underline;
}

.pl-ref-meta {
  display: inline-flex;
  align-items: center;
  gap: var(--pl-space-xs, 4px);
  padding-left: 58px;
  font-size: 10px;
  color: var(--pl-color-gray-500, #6b7280);
  line-height: 1.3;
  flex-wrap: wrap;
}

.pl-ref-journal {
  font-style: italic;
}

.pl-ref-citations {
  color: var(--pl-color-gray-600, #4b5563);
  font-weight: var(--pl-weight-medium, 500);
}

/* \u2500\u2500 \u52A0\u8F7D\u72B6\u6001 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-drawer-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1;
  padding: var(--pl-space-xl, 24px);
}

.pl-drawer-spinner {
  display: inline-block;
  width: 20px;
  height: 20px;
  border: 2px solid var(--pl-color-gray-200, #e5e7eb);
  border-top-color: var(--pl-color-primary, #2563eb);
  border-radius: 50%;
  animation: pl-spin 0.6s linear infinite;
}

/* \u2500\u2500 \u9519\u8BEF\u72B6\u6001 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-drawer-error {
  padding: var(--pl-space-lg, 16px);
  font-size: var(--pl-font-xs, 11px);
  color: var(--pl-color-error, #ef4444);
  text-align: center;
}

.pl-drawer-empty {
  padding: var(--pl-space-xl, 24px) var(--pl-space-lg, 16px);
  font-size: var(--pl-font-xs, 11px);
  color: var(--pl-color-gray-500, #6b7280);
  text-align: center;
}

/* \u2500\u2500 \u5E95\u90E8\u63D0\u793A \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-drawer-footer {
  padding: var(--pl-space-sm, 8px) var(--pl-space-lg, 16px);
  font-size: 10px;
  color: var(--pl-color-gray-400, #9ca3af);
  font-style: italic;
  text-align: center;
  border-top: 1px solid var(--pl-color-gray-100, #f3f4f6);
  flex-shrink: 0;
}
`;function gl(r){return r.replace(/([&%$#_{}])/g,"\\$1")}const fS=ve+`
`+hS,mS=80,bS=50,gS=[20,50,100],yS=[{format:"ris",label:"RIS",desc:"EndNote / Zotero"},{format:"bibtex",label:"BibTeX",desc:"LaTeX"},{format:"medline",label:"NBIB",desc:"MEDLINE / EndNote"},{format:"csv",label:"CSV",desc:"Excel"}];function xS(r,e){return r?r.length>e?r.slice(0,e)+"\u2026":r:"Untitled"}function Jt(r){return r.toLocaleString("en-US")}function Eh(r){return r?`https://pubmed.ncbi.nlm.nih.gov/${r}/`:null}function Fh(r){return r?`https://doi.org/${r}`:null}function AS(r){return r?`https://www.semanticscholar.org/paper/${encodeURIComponent(r)}`:null}function CS(r){const e=Eh(r.externalIds?.PubMed);if(e)return{url:e,source:"PubMed"};const t=Fh(r.externalIds?.DOI);if(t)return{url:t,source:"DOI"};const n=AS(r.paperId);return n?{url:n,source:"Semantic Scholar"}:null}function vS(r,e,t){if(Array.isArray(r))return{papers:r,offset:e,limit:t};if(!r||typeof r!="object")return null;const n=r;if(Array.isArray(n.papers)&&typeof n.total=="number"){const i=n.papers.map(TS),o=n.papers.length,s=e+i.length<o?e+i.length:void 0;return{papers:i,total:o,offset:e,limit:t,next:s}}const a=r;return Array.isArray(a.papers)?{papers:a.papers,total:typeof a.total=="number"?a.total:void 0,offset:typeof a.offset=="number"?a.offset:e,limit:typeof a.limit=="number"?a.limit:t,next:typeof a.next=="number"?a.next:void 0}:null}function SS(r){const e=r==null?"":String(r);return/[",\n\r]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function wS(r){return r.replace(/[^a-z0-9_-]+/gi,"-").replace(/^-+|-+$/g,"").slice(0,80)||"paper"}function TS(r){return{paperId:r.s2PaperId??r.pmid??r.doi??"",title:r.title,citationCount:r.citationCount??0,influentialCitationCount:0,isOpenAccess:r.isOpenAccess??!1,openAccessPdf:r.openAccessPdf?{url:r.openAccessPdf}:void 0,year:r.year,venue:r.venue,externalIds:{PubMed:r.pmid,DOI:r.doi},authors:r.authors?r.authors.split(",").map(e=>({name:e.trim()})):void 0}}function ki(r){return r.paperId?`s2:${r.paperId}`:r.externalIds?.PubMed?`pmid:${r.externalIds.PubMed}`:r.externalIds?.DOI?`doi:${r.externalIds.DOI}`:`paper:${r.title??"untitled"}:${r.year??""}`}class Ye{constructor(e){this.opts=e,this.total=e.count>0?e.count:void 0}opts;static instance=null;drawer=null;shadow=null;isOpen=!1;escHandler=null;currentOffset=0;pageSize=bS;total;nextOffset;currentPapers=[];selectedPapers=new Map;requestSeq=0;static open(e){Ye.instance?.isOpen&&Ye.instance.close(),Ye.instance=new Ye(e),Ye.instance.doOpen()}static closeCurrent(){Ye.instance?.isOpen&&Ye.instance.close()}doOpen(){$e.register(this),this.drawer=document.createElement("div"),this.drawer.className="pl-drawer",document.body.appendChild(this.drawer),this.shadow=this.drawer.attachShadow({mode:"open"});const e=document.createElement("style");e.textContent=fS,this.shadow.appendChild(e),this.renderHeader(),this.renderToolbar(),this.renderLoading(),this.escHandler=t=>{t.key==="Escape"&&this.close()},document.addEventListener("keydown",this.escHandler),this.isOpen=!0,this.loadPapers(0)}close(){if(!this.isOpen)return;$e.unregister(this),this.escHandler&&(document.removeEventListener("keydown",this.escHandler),this.escHandler=null),this.drawer&&this.drawer.classList.add("pl-drawer--closing");const e=this.drawer;setTimeout(()=>{e?.remove()},250),this.isOpen=!1,this.drawer=null,this.shadow=null,Ye.instance===this&&(Ye.instance=null)}renderHeader(){if(!this.shadow)return;const e=document.createElement("div");e.className="pl-drawer-header";const t=document.createElement("h3");t.className="pl-drawer-title",t.textContent=this.opts.mode==="citations"?"\u88AB\u5F15\u8BE6\u60C5":this.opts.paperTitle??"\u5F15\u7528\u6587\u732E";const n=document.createElement("span");n.className="pl-drawer-count",n.textContent=this.opts.mode==="citations"?`${Jt(this.opts.count)} \u6B21\u88AB\u5F15`:`${Jt(this.opts.count)} \u7BC7\u5F15\u7528\u6587\u732E`;const a=document.createElement("button");a.className="pl-drawer-close",a.type="button",a.setAttribute("aria-label","\u5173\u95ED"),a.innerHTML='<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M6.75 6.75l10.5 10.5M17.25 6.75l-10.5 10.5"/></svg>',a.addEventListener("click",()=>this.close()),e.append(t,n,a),this.shadow.appendChild(e)}renderToolbar(){if(!this.shadow)return;const e=document.createElement("div");e.className="pl-drawer-toolbar",e.setAttribute("data-role","toolbar");const t=document.createElement("span");t.className="pl-drawer-range",t.setAttribute("data-role","range"),t.textContent="\u52A0\u8F7D\u4E2D...";const n=document.createElement("div");n.className="pl-drawer-selection";const a=document.createElement("label");a.className="pl-drawer-select-page";const i=document.createElement("input");i.type="checkbox",i.setAttribute("data-role","select-page"),i.addEventListener("change",()=>{this.setCurrentPageSelected(i.checked)});const o=document.createElement("span");o.textContent="\u672C\u9875\u5168\u9009",a.append(i,o);const s=document.createElement("span");s.className="pl-drawer-selected-count",s.setAttribute("data-role","selected-count"),s.textContent="\u5DF2\u9009 0",n.append(a,s);const l=document.createElement("div");l.className="pl-drawer-controls";const c=document.createElement("label");c.className="pl-drawer-page-size",c.textContent="\u6BCF\u9875";const u=document.createElement("select");u.setAttribute("data-role","page-size");for(const g of gS){const C=document.createElement("option");C.value=String(g),C.textContent=String(g),C.selected=g===this.pageSize,u.appendChild(C)}u.addEventListener("change",()=>{this.pageSize=Number(u.value),this.loadPapers(0)}),c.appendChild(u);const d=document.createElement("button");d.className="pl-drawer-tool-btn",d.type="button",d.textContent="\u4E0A\u4E00\u9875",d.setAttribute("data-role","prev"),d.addEventListener("click",()=>{this.loadPapers(Math.max(0,this.currentOffset-this.pageSize))});const p=document.createElement("button");p.className="pl-drawer-tool-btn",p.type="button",p.textContent="\u4E0B\u4E00\u9875",p.setAttribute("data-role","next"),p.addEventListener("click",()=>{typeof this.nextOffset=="number"&&this.loadPapers(this.nextOffset)});const h=document.createElement("div");h.className="pl-drawer-export-wrap",h.setAttribute("data-role","export");const f=document.createElement("button");f.className="pl-drawer-tool-btn",f.type="button",f.textContent="\u5BFC\u51FA \u25BE";const y=document.createElement("div");y.className="pl-drawer-export-dropdown",y.style.display="none";const x=(g,C)=>{const L=document.createElement("div");L.className="pl-drawer-export-group",L.textContent=g,y.appendChild(L);for(const $ of yS){const k=document.createElement("button");k.type="button",k.className="pl-drawer-export-option",k.dataset.exportScope=C,k.dataset.exportFormat=$.format,k.dataset.defaultDesc=$.desc;const N=document.createElement("span");N.className="pl-drawer-export-name",N.textContent=$.label;const S=document.createElement("span");S.className="pl-drawer-export-desc",S.textContent=$.desc,k.append(N,S),k.addEventListener("click",()=>{y.style.display="none",this.exportPapers($.format,C)}),y.appendChild(k)}};x("\u9009\u4E2D\u6587\u732E","selected");const T=document.createElement("div");T.className="pl-drawer-export-divider",y.appendChild(T),x("\u5F53\u524D\u9875\u5168\u90E8","page");const E=document.createElement("button");E.type="button",E.className="pl-drawer-export-option pl-drawer-clear-selection",E.setAttribute("data-role","clear-selection");const w=document.createElement("span");w.className="pl-drawer-export-name",w.textContent="\u6E05\u7A7A\u9009\u62E9";const v=document.createElement("span");v.className="pl-drawer-export-desc",v.textContent="\u4FDD\u7559\u5F53\u524D\u9875",E.append(w,v),E.addEventListener("click",()=>{y.style.display="none",this.clearSelection()}),y.appendChild(E);for(const g of y.querySelectorAll(".pl-drawer-export-option"))g.addEventListener("click",C=>C.stopPropagation());f.addEventListener("click",g=>{g.stopPropagation();const C=y.style.display!=="none";y.style.display=C?"none":"block",C||this.refreshExportAccess(y)}),document.addEventListener("click",g=>{h.contains(g.target)||(y.style.display="none")}),h.append(f,y),l.append(c,d,p,h),e.append(t,n,l),this.shadow.appendChild(e),this.updateToolbar(!0)}renderLoading(){if(!this.shadow)return;const e=document.createElement("div");e.className="pl-drawer-loading",e.setAttribute("data-role","loading");const t=document.createElement("span");t.className="pl-drawer-spinner",e.appendChild(t),this.shadow.appendChild(e)}clearDynamicContent(){this.shadow&&this.shadow.querySelectorAll('[data-role="loading"], [data-role="list"], [data-role="empty"], [data-role="error"], [data-role="footer"]').forEach(e=>e.remove())}updateToolbar(e=!1){if(!this.shadow)return;const t=this.shadow.querySelector('[data-role="range"]'),n=this.shadow.querySelector('[data-role="prev"]'),a=this.shadow.querySelector('[data-role="next"]'),i=this.shadow.querySelector('[data-role="export"] button'),o=this.shadow.querySelector('[data-role="page-size"]'),s=this.shadow.querySelector('[data-role="select-page"]'),l=this.shadow.querySelector('[data-role="selected-count"]'),c=this.shadow.querySelectorAll('[data-export-scope="selected"]'),u=this.shadow.querySelectorAll('[data-export-scope="page"]'),d=this.shadow.querySelector('[data-role="clear-selection"]');if(t)if(e)t.textContent="\u52A0\u8F7D\u4E2D...";else if(this.currentPapers.length===0)t.textContent=typeof this.total=="number"?`0 / ${Jt(this.total)}`:"0";else{const p=this.currentOffset+1,h=this.currentOffset+this.currentPapers.length,f=typeof this.total=="number"?` / ${Jt(this.total)}`:"";t.textContent=`${Jt(p)}-${Jt(h)}${f}`}if(n&&(n.disabled=e||this.currentOffset<=0),a&&(a.disabled=e||typeof this.nextOffset!="number"),i&&(i.disabled=e||this.currentPapers.length===0&&this.selectedPapers.size===0),o&&(o.disabled=e),l&&(l.textContent=`\u5DF2\u9009 ${Jt(this.selectedPapers.size)}`),s){const p=this.getCurrentPageSelectedCount();s.disabled=e||this.currentPapers.length===0,s.checked=this.currentPapers.length>0&&p===this.currentPapers.length,s.indeterminate=p>0&&p<this.currentPapers.length}c.forEach(p=>{p.disabled=e||this.selectedPapers.size===0}),u.forEach(p=>{p.disabled=e||this.currentPapers.length===0}),d&&(d.disabled=e||this.selectedPapers.size===0)}getCurrentPageSelectedCount(){return this.currentPapers.reduce((e,t)=>e+(this.selectedPapers.has(ki(t))?1:0),0)}setCurrentPageSelected(e){for(const t of this.currentPapers){const n=ki(t);e?this.selectedPapers.set(n,t):this.selectedPapers.delete(n)}this.syncCurrentPageCheckboxes(),this.updateToolbar(!1)}setPaperSelected(e,t){const n=ki(e);t?this.selectedPapers.set(n,e):this.selectedPapers.delete(n),this.updateToolbar(!1)}clearSelection(){this.selectedPapers.clear(),this.syncCurrentPageCheckboxes(),this.updateToolbar(!1)}syncCurrentPageCheckboxes(){this.shadow&&this.shadow.querySelectorAll('[data-role="paper-select"]').forEach(e=>{const t=e.dataset.paperKey;e.checked=!!(t&&this.selectedPapers.has(t))})}async loadPapers(e=this.currentOffset){if(!this.shadow)return;const t=++this.requestSeq,n=Math.max(0,Math.floor(e||0));this.currentOffset=n,this.currentPapers=[],this.nextOffset=void 0,this.clearDynamicContent(),this.updateToolbar(!0),this.renderLoading();try{const a=await this.opts.sendToBackground(this.opts.mode==="citations"?"GET_CITATIONS":"GET_REFERENCES",{paperId:this.opts.paperId,pmid:this.opts.pmid??"",offset:String(n),limit:String(this.pageSize)});if(!this.isOpen||t!==this.requestSeq)return;if(this.clearDynamicContent(),a.success){const i=vS(a.data,n,this.pageSize);if(i){this.renderPapers(i);return}this.renderError("Unexpected paper list response")}else this.renderError(a.error??"Failed to load papers")}catch{if(!this.isOpen||t!==this.requestSeq)return;this.clearDynamicContent(),this.renderError("Network error")}}renderPapers(e){if(!this.shadow)return;if(this.currentOffset=e.offset,this.nextOffset=e.next,typeof e.total=="number"&&(this.total=e.total),e.papers.length===0){this.currentPapers=[],this.updateToolbar(!1),this.renderEmpty((this.total??0)>0);return}const t=[...e.papers];this.currentPapers=t,this.updateToolbar(!1);const n=document.createElement("ul");n.className="pl-drawer-list",n.setAttribute("data-role","list");for(let a=0;a<t.length;a++){const i=t[a],o=document.createElement("li");o.className="pl-drawer-item";const s=CS(i),l=s?document.createElement("a"):document.createElement("span");l.className="pl-ref-title",l.textContent=xS(i.title??"",mS),s&&l instanceof HTMLAnchorElement&&(l.href=s.url,l.target="_blank",l.rel="noopener noreferrer",l.title=`\u6253\u5F00 ${s.source}`);const c=document.createElement("div");c.className="pl-drawer-item-head";const u=ki(i),d=document.createElement("input");d.className="pl-ref-select",d.type="checkbox",d.checked=this.selectedPapers.has(u),d.dataset.paperKey=u,d.setAttribute("data-role","paper-select"),d.setAttribute("aria-label",`\u9009\u62E9\u6587\u732E ${e.offset+a+1}`),d.addEventListener("change",()=>{this.setPaperSelected(i,d.checked)});const p=document.createElement("span");p.className="pl-ref-index",p.textContent=String(e.offset+a+1),c.append(d,p,l);const h=document.createElement("span");h.className="pl-ref-meta";const f=[],y=i.journal?.name||i.venue||"";y&&f.push(y),i.year&&f.push(String(i.year));const x=f.length>0?f.join(", "):"";if(x){const T=document.createElement("span");T.className="pl-ref-journal",T.textContent=x,h.appendChild(T)}if(typeof i.citationCount=="number"){const T=document.createElement("span");T.className="pl-ref-citations",T.textContent=`\u88AB\u5F15 ${Jt(i.citationCount)}`,h.appendChild(T)}o.appendChild(c),o.appendChild(h),n.appendChild(o)}this.shadow.appendChild(n),this.renderFooter()}renderEmpty(e=!1){if(!this.shadow)return;const t=document.createElement("div");t.className="pl-drawer-empty",t.setAttribute("data-role","empty"),e?t.textContent=this.opts.mode==="citations"?"Semantic Scholar \u6709\u88AB\u5F15\u8BA1\u6570\uFF0C\u4F46\u6682\u672A\u8FD4\u56DE\u53EF\u5C55\u793A\u7684\u88AB\u5F15\u6587\u732E\u5217\u8868":"Semantic Scholar \u6709\u5F15\u7528\u8BA1\u6570\uFF0C\u4F46\u6682\u672A\u8FD4\u56DE\u53EF\u5C55\u793A\u7684\u5F15\u7528\u6587\u732E\u5217\u8868":t.textContent=this.opts.mode==="citations"?"\u6682\u65E0\u88AB\u5F15\u8BB0\u5F55":"\u6682\u65E0\u5F15\u7528\u6587\u732E",this.shadow.appendChild(t)}renderFooter(){if(!this.shadow)return;const e=document.createElement("div");e.className="pl-drawer-footer",e.setAttribute("data-role","footer"),e.textContent="\u53EF\u52FE\u9009\u6587\u732E\u540E\u5BFC\u51FA\uFF1B\u7FFB\u9875\u9009\u62E9\u4F1A\u4FDD\u7559\u5230\u62BD\u5C49\u5173\u95ED\u3002",this.shadow.appendChild(e)}renderError(e){if(!this.shadow)return;this.currentPapers=[],this.nextOffset=void 0,this.updateToolbar(!1);const t=document.createElement("div");t.className="pl-drawer-error",t.setAttribute("data-role","error"),t.textContent=`\u26A0 ${e}`,this.shadow.appendChild(t)}async exportPapers(e="csv",t="page"){const n=await lt(e);if(!n.allowed){D.error(n.error||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528\u8BE5\u5BFC\u51FA\u683C\u5F0F");return}const a=t==="selected"?Array.from(this.selectedPapers.values()):this.currentPapers;if(a.length===0)return;const i=t==="selected"?0:this.currentOffset,o=this.buildExport(a,i,e),s={ris:"application/x-research-info-systems",bibtex:"application/x-bibtex",medline:"text/plain",csv:"text/csv;charset=utf-8"},l={ris:".ris",bibtex:".bib",medline:".nbib",csv:".csv"},c=e==="csv"?`\uFEFF${o}`:o,u=new Blob([c],{type:s[e]||"text/plain"}),d=URL.createObjectURL(u),p=document.createElement("a"),h=this.opts.mode==="citations"?"citations":"references",f=t==="selected"?`selected-${a.length}`:`${this.currentOffset+1}-${this.currentOffset+a.length}`;p.href=d,p.download=`paperlens-${h}-${wS(this.opts.paperId)}-${f}${l[e]||".txt"}`,p.style.display="none",document.body.appendChild(p),p.click(),p.remove(),window.setTimeout(()=>URL.revokeObjectURL(d),1e3)}async refreshExportAccess(e){const t=Array.from(e.querySelectorAll(".pl-drawer-export-option[data-export-format]"));await Promise.all(t.map(async n=>{const a=n.dataset.exportFormat;if(!a)return;const i=await lt(a),o=n.querySelector(".pl-drawer-export-desc"),s=n.dataset.defaultDesc||o?.textContent||"";if(i.allowed){n.disabled=!1,n.title="",n.removeAttribute("aria-disabled"),o&&(o.textContent=s);return}n.disabled=!0,n.title=i.error||"\u8BE5\u5BFC\u51FA\u683C\u5F0F\u6682\u4E0D\u53EF\u7528",n.setAttribute("aria-disabled","true"),o&&(o.textContent="Pro")}))}buildExport(e,t,n){switch(n){case"ris":return this.buildRis(e);case"bibtex":return this.buildBibtex(e);case"medline":return this.buildMedline(e);default:return this.buildCsv(e,t)}}buildRis(e){const t=[];for(const n of e){const a=[];if(a.push("TY  - JOUR"),a.push(`TI  - ${n.title??""}`),n.authors)for(const i of n.authors)a.push(`AU  - ${i.name}`);a.push(`JO  - ${n.journal?.name||n.venue||""}`),n.year&&a.push(`YR  - ${n.year}`),n.journal?.volume&&a.push(`VL  - ${n.journal.volume}`),n.journal?.pages&&a.push(`SP  - ${n.journal.pages}`),n.externalIds?.DOI&&a.push(`DO  - ${n.externalIds.DOI}`),n.abstract&&a.push(`AB  - ${n.abstract}`),a.push("ER  - "),t.push(a.join(`
`))}return t.join(`
`)}buildBibtex(e){const t=[];for(const n of e){const a=[],i=n.externalIds?.PubMed?`PMID${n.externalIds.PubMed}`:n.paperId??"unknown";a.push(`@article{${i},`),a.push(`  title = {${gl(n.title??"")}},`),n.authors&&n.authors.length>0&&a.push(`  author = {${n.authors.map(o=>gl(o.name)).join(" and ")}},`),a.push(`  journal = {${gl(n.journal?.name||n.venue||"")}},`),n.year&&a.push(`  year = {${n.year}},`),n.journal?.volume&&a.push(`  volume = {${n.journal.volume}},`),n.journal?.pages&&a.push(`  pages = {${n.journal.pages.replace("-","--")}},`),n.externalIds?.DOI&&a.push(`  doi = {${n.externalIds.DOI}},`),a.push("}"),t.push(a.join(`
`))}return t.join(`

`)}buildMedline(e){const t=[];for(const n of e){const a=[];if(a.push(`PMID- ${n.externalIds?.PubMed??n.paperId??""}`),a.push(`TI  - ${n.title??""}`),n.authors)for(const o of n.authors)a.push(`AU  - ${o.name}`);a.push(`JT  - ${n.journal?.name||n.venue||""}`);const i=[];n.year&&i.push(String(n.year)),n.journal?.volume&&i.push(n.journal.volume),i.length>0&&a.push(`DP  - ${i.join(";")}`),n.externalIds?.DOI&&a.push(`AID - ${n.externalIds.DOI} [doi]`),n.abstract&&a.push(`AB  - ${n.abstract}`),a.push(""),t.push(a.join(`
`))}return t.join(`
`)}buildCsv(e,t){const n=[["No","Title","Year","Journal","Citation Count","PMID","DOI","Semantic Scholar ID","PubMed URL","DOI URL"]];return e.forEach((a,i)=>{const o=a.externalIds?.PubMed,s=a.externalIds?.DOI;n.push([String(t+i+1),a.title??"",a.year?String(a.year):"",a.journal?.name||a.venue||"",typeof a.citationCount=="number"?String(a.citationCount):"",o??"",s??"",a.paperId??"",Eh(o)??"",Fh(s)??""])}),n.map(a=>a.map(SS).join(",")).join(`
`)}}function ES(r){Ye.open({mode:"citations",paperId:r.paperId,pmid:r.pmid,count:r.citationCount,paperTitle:r.paperTitle,sendToBackground:r.sendToBackground})}const FS=ve+`
`+pS,DS="paperlens-citation-host";function _S(r){return r.toLocaleString("en-US")}function kS(){const r=document.createElement("div");r.className=DS;const e=r.attachShadow({mode:"open"}),t=document.createElement("style");return t.textContent=FS,e.appendChild(t),{host:r,shadow:e}}function Dh(r,e={}){const{host:t,shadow:n}=kS();t.dataset.plCitations=String(r.citationCount);const a=document.createElement("div");a.className="pl-citation-bar";const o=!!(e.paperId&&e.sendToBackground)?document.createElement("button"):document.createElement("span");o.className="pl-citation-badge",o instanceof HTMLButtonElement&&(o.type="button",o.classList.add("pl-citation-badge--clickable"),o.title="\u67E5\u770B\u88AB\u5F15\u8BE6\u60C5",o.setAttribute("aria-label","\u67E5\u770B\u88AB\u5F15\u8BE6\u60C5"),o.addEventListener("click",()=>{ES({paperId:e.paperId,pmid:e.pmid,citationCount:r.citationCount,paperTitle:e.paperTitle,sendToBackground:e.sendToBackground})}));const s=document.createElement("span");s.className="pl-citation-icon",s.textContent="\u88AB\u5F15";const l=document.createElement("span");if(l.className="pl-citation-count",l.textContent=_S(r.citationCount),o.append(s,l),a.appendChild(o),r.isOpenAccess)if(r.openAccessPdf?.url){const c=document.createElement("a");c.className="pl-oa-badge",c.setAttribute("data-pl-oa-badge",""),c.href=r.openAccessPdf.url,c.target="_blank",c.rel="noopener noreferrer",c.title="Open Access \u2014 \u70B9\u51FB\u4E0B\u8F7D PDF";const u=document.createElement("span");u.className="pl-oa-icon",u.textContent="PDF";const d=document.createElement("span");d.textContent="OA",c.append(u,d),a.appendChild(c),t.setAttribute("data-pl-oa-badge","")}else{const c=document.createElement("span");c.className="pl-oa-badge pl-oa-badge--no-pdf",c.setAttribute("data-pl-oa-badge",""),c.title="\u5F00\u653E\u83B7\u53D6\uFF0C\u4F46\u672A\u627E\u5230\u76F4\u63A5 PDF \u94FE\u63A5";const u=document.createElement("span");u.className="pl-oa-icon",u.textContent="OA",c.appendChild(u),a.appendChild(c),t.setAttribute("data-pl-oa-badge","")}return n.appendChild(a),t}function _h(r){return r!=null&&typeof r.citationCount=="number"}const NS=ve+`
`+`/**
 * Paper Preview Drawer Styles \u2014 injected into Shadow DOM
 *
 * \u53F3\u4FA7\u6ED1\u51FA\u9884\u89C8\u9762\u677F\uFF0C\u663E\u793A\u8BBA\u6587\u8BE6\u60C5\uFF08\u6458\u8981\u3001\u4F5C\u8005\u3001\u5173\u952E\u8BCD\u3001MeSH Terms \u7B49\uFF09\u3002
 * \u5BBD\u5EA6 420px\uFF0C\u4F7F\u7528 --pl-* design tokens\u3002
 */

/* \u2500\u2500 \u62BD\u5C49\u5BBF\u4E3B\u5BB9\u5668 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
:host(.pl-preview-drawer) {
  position: fixed;
  top: 0;
  right: 0;
  width: 420px;
  height: 100vh;
  z-index: 999999;
  background: #ffffff;
  border-left: 1px solid var(--pl-color-gray-200, #e5e7eb);
  box-shadow: -4px 0 16px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  font-family: var(--pl-font-sans, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans CJK SC', 'Noto Sans SC', 'Source Han Sans SC', 'Helvetica Neue', Arial, sans-serif);
  will-change: transform;
  transform: translateX(100%);
  animation: pl-preview-slide-in 300ms ease-out forwards;
}

:host(.pl-preview-drawer--closing) {
  animation: pl-preview-slide-out 250ms ease-in forwards;
}

@keyframes pl-preview-slide-in {
  from { transform: translateX(100%); }
  to   { transform: translateX(0); }
}

@keyframes pl-preview-slide-out {
  from { transform: translateX(0); }
  to   { transform: translateX(100%); }
}

/* \u2500\u2500 \u6807\u9898\u680F \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-preview-header {
  display: flex;
  align-items: flex-start;
  padding: var(--pl-space-lg, 16px);
  border-bottom: 1px solid var(--pl-color-gray-200, #e5e7eb);
  flex-shrink: 0;
  gap: var(--pl-space-sm, 8px);
}

.pl-preview-close {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  border: 1px solid var(--pl-color-gray-200, #e5e7eb);
  border-radius: 999px;
  background: var(--pl-color-white, #ffffff);
  color: var(--pl-color-gray-600, #4b5563);
  line-height: 1;
  cursor: pointer;
  flex-shrink: 0;
  box-shadow: 0 1px 2px rgba(15, 23, 42, 0.06);
  transition: all var(--pl-transition-fast, 150ms ease);
}

.pl-preview-close:hover {
  border-color: var(--pl-color-gray-300, #d1d5db);
  background-color: var(--pl-color-gray-50, #f9fafb);
  color: var(--pl-color-gray-900, #111827);
}

.pl-preview-close svg {
  width: 16px;
  height: 16px;
  fill: none;
  stroke: currentColor;
  stroke-width: 2;
  stroke-linecap: round;
}

/* \u2500\u2500 \u5185\u5BB9\u533A\uFF08\u53EF\u6EDA\u52A8\uFF09 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-preview-content {
  flex: 1;
  overflow-y: auto;
  padding: var(--pl-space-lg, 16px);
}

.pl-preview-content::-webkit-scrollbar {
  width: 4px;
}

.pl-preview-content::-webkit-scrollbar-track {
  background: transparent;
}

.pl-preview-content::-webkit-scrollbar-thumb {
  background: var(--pl-color-gray-300, #d1d5db);
  border-radius: 2px;
}

/* \u2500\u2500 \u6807\u9898\u533A \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-preview-title {
  font-size: var(--pl-font-lg, 16px);
  font-weight: var(--pl-weight-bold, 700);
  color: var(--pl-color-gray-900, #111827);
  line-height: 1.4;
  margin: 0 0 var(--pl-space-sm, 8px);
}

.pl-preview-authors {
  font-size: var(--pl-font-sm, 12px);
  color: var(--pl-color-gray-600, #4b5563);
  line-height: 1.4;
  margin: 0 0 var(--pl-space-xs, 4px);
}

.pl-preview-journal {
  font-size: var(--pl-font-sm, 12px);
  color: var(--pl-color-gray-500, #6b7280);
  font-style: italic;
  line-height: 1.4;
  margin: 0 0 var(--pl-space-md, 12px);
}

.pl-preview-notice {
  padding: var(--pl-space-sm, 8px) var(--pl-space-md, 12px);
  margin: 0 0 var(--pl-space-md, 12px);
  border: 1px solid var(--pl-color-warning-light, #fef3c7);
  border-radius: var(--pl-radius-md, 6px);
  background: var(--pl-color-warning-light, #fef3c7);
  color: var(--pl-color-gray-700, #374151);
  font-size: var(--pl-font-xs, 11px);
  line-height: 1.5;
}

/* \u2500\u2500 \u6807\u8BC6\u884C\uFF08DOI / PMID / PMCID\uFF09 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-preview-ids {
  display: flex;
  flex-direction: column;
  gap: var(--pl-space-xs, 4px);
  margin-bottom: var(--pl-space-lg, 16px);
}

.pl-preview-id-row {
  display: flex;
  align-items: center;
  gap: var(--pl-space-xs, 4px);
  font-size: var(--pl-font-xs, 11px);
  color: var(--pl-color-gray-700, #374151);
}

.pl-preview-id-label {
  font-weight: var(--pl-weight-semibold, 600);
  min-width: 44px;
}

.pl-preview-id-value {
  font-family: var(--pl-font-mono, monospace);
  word-break: break-all;
}

.pl-preview-id-value a {
  color: var(--pl-color-primary, #2563eb);
  text-decoration: none;
}

.pl-preview-id-value a:hover {
  text-decoration: underline;
}

.pl-preview-copy-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 22px;
  height: 22px;
  border: none;
  border-radius: var(--pl-radius-sm, 4px);
  background: transparent;
  color: var(--pl-color-gray-400, #9ca3af);
  font-size: 12px;
  cursor: pointer;
  flex-shrink: 0;
  transition: background-color var(--pl-transition-fast, 150ms ease),
              color var(--pl-transition-fast, 150ms ease);
}

.pl-preview-copy-btn:hover {
  background-color: var(--pl-color-gray-100, #f3f4f6);
  color: var(--pl-color-gray-700, #374151);
}

.pl-preview-copy-btn--copied {
  color: var(--pl-color-success, #10b981);
}

/* \u2500\u2500 \u5206\u533A\u6807\u9898 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-preview-section {
  margin-bottom: var(--pl-space-lg, 16px);
}

.pl-preview-section-title {
  font-size: var(--pl-font-xs, 11px);
  font-weight: var(--pl-weight-semibold, 600);
  color: var(--pl-color-gray-500, #6b7280);
  text-transform: uppercase;
  letter-spacing: 0.05em;
  border-bottom: 1px solid var(--pl-color-gray-200, #e5e7eb);
  padding-bottom: var(--pl-space-xs, 4px);
  margin: 0 0 var(--pl-space-sm, 8px);
}

/* \u2500\u2500 \u6458\u8981\u533A \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-preview-abstract {
  font-size: var(--pl-font-sm, 12px);
  color: var(--pl-color-gray-800, #1f2937);
  line-height: 1.6;
  white-space: pre-line;
}

.pl-preview-abstract-label {
  font-weight: var(--pl-weight-semibold, 600);
  color: var(--pl-color-primary, #2563eb);
  margin-top: var(--pl-space-sm, 8px);
  margin-bottom: var(--pl-space-xs, 4px);
  font-size: var(--pl-font-sm, 12px);
}

.pl-preview-abstract-text {
  margin: 0;
  line-height: 1.6;
}

/* \u2500\u2500 \u6807\u7B7E\u5217\u8868\uFF08Keywords / MeSH Terms\uFF09 \u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-preview-tags {
  display: flex;
  flex-wrap: wrap;
  gap: var(--pl-space-xs, 4px);
}

.pl-preview-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: var(--pl-radius-full, 9999px);
  background-color: var(--pl-color-gray-100, #f3f4f6);
  color: var(--pl-color-gray-700, #374151);
  font-size: 10px;
  font-weight: var(--pl-weight-medium, 500);
  line-height: 1.5;
}

/* \u2500\u2500 \u5E95\u90E8\u64CD\u4F5C\u680F \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-preview-actions {
  display: flex;
  align-items: center;
  gap: var(--pl-space-sm, 8px);
  padding: var(--pl-space-md, 12px) var(--pl-space-lg, 16px);
  border-top: 1px solid var(--pl-color-gray-200, #e5e7eb);
  flex-shrink: 0;
}

.pl-preview-action-btn {
  display: inline-flex;
  align-items: center;
  gap: var(--pl-space-xs, 4px);
  padding: 6px 12px;
  border: 1px solid var(--pl-color-gray-200, #e5e7eb);
  border-radius: var(--pl-radius-md, 8px);
  background: var(--pl-color-white, #ffffff);
  color: var(--pl-color-gray-700, #374151);
  font-family: var(--pl-font-sans, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans CJK SC', 'Noto Sans SC', 'Source Han Sans SC', 'Helvetica Neue', Arial, sans-serif);
  font-size: var(--pl-font-xs, 11px);
  font-weight: var(--pl-weight-medium, 500);
  cursor: pointer;
  transition: background-color var(--pl-transition-fast, 150ms ease),
              border-color var(--pl-transition-fast, 150ms ease);
  white-space: nowrap;
}

.pl-preview-action-btn:hover {
  background-color: var(--pl-color-gray-50, #f9fafb);
  border-color: var(--pl-color-gray-300, #d1d5db);
}

.pl-preview-action-btn--primary {
  background-color: var(--pl-color-primary, #2563eb);
  color: #ffffff;
  border-color: var(--pl-color-primary, #2563eb);
}

.pl-preview-action-btn--primary:hover {
  background-color: var(--pl-color-primary-hover, #1d4ed8);
}

/* \u2500\u2500 Skeleton \u52A0\u8F7D\u52A8\u753B \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-preview-skeleton {
  padding: var(--pl-space-lg, 16px);
}

.pl-preview-skeleton-line {
  height: 12px;
  border-radius: var(--pl-radius-sm, 4px);
  background: linear-gradient(90deg, var(--pl-color-gray-100, #f3f4f6) 25%, var(--pl-color-gray-200, #e5e7eb) 50%, var(--pl-color-gray-100, #f3f4f6) 75%);
  background-size: 200% 100%;
  animation: pl-preview-skeleton-shimmer 1.5s infinite;
  margin-bottom: var(--pl-space-sm, 8px);
}

.pl-preview-skeleton-line--title {
  height: 18px;
  width: 85%;
}

.pl-preview-skeleton-line--subtitle {
  width: 60%;
}

.pl-preview-skeleton-line--id {
  width: 45%;
}

.pl-preview-skeleton-line--text {
  width: 100%;
}

.pl-preview-skeleton-line--short {
  width: 70%;
}

@keyframes pl-preview-skeleton-shimmer {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

/* \u2500\u2500 \u9519\u8BEF\u72B6\u6001 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-preview-error {
  padding: var(--pl-space-xl, 24px) var(--pl-space-lg, 16px);
  font-size: var(--pl-font-sm, 12px);
  color: var(--pl-color-error, #ef4444);
  text-align: center;
}
`;function LS(r,e){navigator.clipboard.writeText(r).then(()=>{D.success("\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F");const t=e.textContent??"";e.textContent="\u2713",e.classList.add("pl-preview-copy-btn--copied"),setTimeout(()=>{e.textContent=t,e.classList.remove("pl-preview-copy-btn--copied")},1500)}).catch(()=>{D.error("\u590D\u5236\u5931\u8D25")})}class dt{constructor(e,t,n,a){this.paperTitle=t,this.pmid=e,this.fallbackAbstract=n,this.sendToBackground=a}paperTitle;static instance=null;overlay=null;drawer=null;shadow=null;isOpen=!1;escHandler=null;pmid;fallbackAbstract;sendToBackground;static async open(e,t,n,a){const i=$e.getCurrent();i&&i.close(),dt.instance=new dt(e,t,n,a),dt.instance.doOpen()}static closeCurrent(){dt.instance?.isOpen&&dt.instance.close()}doOpen(){$e.register(this),this.drawer=document.createElement("div"),this.drawer.className="pl-preview-drawer",document.body.appendChild(this.drawer),this.shadow=this.drawer.attachShadow({mode:"open"});const e=document.createElement("style");e.textContent=NS,this.shadow.appendChild(e),this.renderHeader(),this.renderSkeleton(),this.escHandler=t=>{t.key==="Escape"&&this.close()},document.addEventListener("keydown",this.escHandler),this.isOpen=!0,this.loadDetail()}close(){if(!this.isOpen)return;$e.unregister(this),this.escHandler&&(document.removeEventListener("keydown",this.escHandler),this.escHandler=null),this.overlay&&this.overlay.classList.add("pl-preview-overlay--closing"),this.drawer&&this.drawer.classList.add("pl-preview-drawer--closing");const e=this.overlay,t=this.drawer;setTimeout(()=>{e?.remove(),t?.remove()},250),this.isOpen=!1,this.overlay=null,this.drawer=null,this.shadow=null,dt.instance===this&&(dt.instance=null)}renderHeader(){if(!this.shadow)return;const e=document.createElement("div");e.className="pl-preview-header";const t=document.createElement("div");t.style.flex="1";const n=document.createElement("button");n.className="pl-preview-close",n.type="button",n.setAttribute("aria-label","\u5173\u95ED"),n.innerHTML='<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M6.75 6.75l10.5 10.5M17.25 6.75l-10.5 10.5"/></svg>',n.addEventListener("click",()=>this.close()),e.append(t,n),this.shadow.appendChild(e)}renderSkeleton(){if(!this.shadow)return;const e=document.createElement("div");e.className="pl-preview-skeleton",e.setAttribute("data-role","loading"),e.innerHTML=`
      <div class="pl-preview-skeleton-line pl-preview-skeleton-line--title"></div>
      <div class="pl-preview-skeleton-line pl-preview-skeleton-line--subtitle"></div>
      <div class="pl-preview-skeleton-line pl-preview-skeleton-line--subtitle"></div>
      <div class="pl-preview-skeleton-line pl-preview-skeleton-line--id"></div>
      <div class="pl-preview-skeleton-line pl-preview-skeleton-line--id"></div>
      <div style="margin-top: 16px;"></div>
      <div class="pl-preview-skeleton-line pl-preview-skeleton-line--text"></div>
      <div class="pl-preview-skeleton-line pl-preview-skeleton-line--text"></div>
      <div class="pl-preview-skeleton-line pl-preview-skeleton-line--text"></div>
      <div class="pl-preview-skeleton-line pl-preview-skeleton-line--short"></div>
    `,this.shadow.appendChild(e)}async loadDetail(){if(this.shadow)try{const e=await this.sendToBackground("GET_PAPER_SUMMARY",{pmid:this.pmid});if(!this.isOpen)return;this.shadow.querySelector('[data-role="loading"]')?.remove(),e.success&&e.data?this.renderDetail(e.data):this.fallbackAbstract?this.renderFallbackDetail(e.error??"PubMed detail temporarily unavailable"):this.renderError(e.error??"Failed to load paper detail")}catch{if(!this.isOpen)return;this.shadow.querySelector('[data-role="loading"]')?.remove(),this.fallbackAbstract?this.renderFallbackDetail("Network error"):this.renderError("Network error")}}renderDetail(e){if(!this.shadow)return;const t=document.createElement("div");t.className="pl-preview-content";const n=document.createElement("h2");if(n.className="pl-preview-title",n.textContent=e.title||this.paperTitle,t.appendChild(n),e.authors?.length){const o=document.createElement("p");o.className="pl-preview-authors",o.textContent=e.authors.join(", "),t.appendChild(o)}const a=[];if(e.journal&&a.push(e.journal),e.year&&a.push(String(e.year)),e.volume&&a.push(`Vol ${e.volume}`),e.issue&&a.push(`Issue ${e.issue}`),e.pages&&a.push(e.pages),a.length>0){const o=document.createElement("p");o.className="pl-preview-journal",o.textContent=a.join("; "),t.appendChild(o)}const i=document.createElement("div");if(i.className="pl-preview-ids",e.doi&&i.appendChild(this.createIdRow("DOI",e.doi,`https://doi.org/${e.doi}`)),i.appendChild(this.createIdRow("PMID",e.pmid,`https://pubmed.ncbi.nlm.nih.gov/${e.pmid}/`)),e.pmcid&&i.appendChild(this.createIdRow("PMCID",e.pmcid)),t.appendChild(i),e.abstract||e.abstractSections?.length){const o=document.createElement("div");o.className="pl-preview-section";const s=document.createElement("div");s.className="pl-preview-section-title",s.textContent="Abstract",o.appendChild(s);const l=document.createElement("div");if(l.className="pl-preview-abstract",e.abstractSections?.length)for(const c of e.abstractSections){const u=document.createElement("div");u.className="pl-preview-abstract-label",u.textContent=c.label;const d=document.createElement("p");d.className="pl-preview-abstract-text",d.textContent=c.text,l.append(u,d)}else if(e.abstract){const c=document.createElement("p");c.className="pl-preview-abstract-text",c.textContent=e.abstract,l.appendChild(c)}o.appendChild(l),t.appendChild(o)}e.keywords?.length&&t.appendChild(this.createTagSection("Keywords",e.keywords)),e.meshTerms?.length&&t.appendChild(this.createTagSection("MeSH Terms",e.meshTerms)),this.shadow.appendChild(t),this.renderActions(e)}renderFallbackDetail(e){if(!this.shadow)return;const t=document.createElement("div");t.className="pl-preview-content";const n=document.createElement("h2");n.className="pl-preview-title",n.textContent=this.paperTitle,t.appendChild(n);const a=document.createElement("div");a.className="pl-preview-notice",a.textContent=`\u5B8C\u6574\u6458\u8981\u6682\u65F6\u65E0\u6CD5\u83B7\u53D6\uFF0C\u4EE5\u4E0B\u663E\u793A PubMed \u641C\u7D22\u7ED3\u679C\u4E2D\u7684\u6458\u8981\u7247\u6BB5\u3002${e}`,t.appendChild(a);const i=document.createElement("div");i.className="pl-preview-section";const o=document.createElement("div");o.className="pl-preview-section-title",o.textContent="Abstract Snippet",i.appendChild(o);const s=document.createElement("div");s.className="pl-preview-abstract";const l=document.createElement("p");l.className="pl-preview-abstract-text",l.textContent=this.fallbackAbstract??"",s.appendChild(l),i.appendChild(s),t.appendChild(i),this.shadow.appendChild(t)}createIdRow(e,t,n){const a=document.createElement("div");a.className="pl-preview-id-row";const i=document.createElement("span");i.className="pl-preview-id-label",i.textContent=`${e}:`;const o=document.createElement("span");if(o.className="pl-preview-id-value",n){const l=document.createElement("a");l.href=n,l.target="_blank",l.rel="noopener noreferrer",l.textContent=t,o.appendChild(l)}else o.textContent=t;const s=document.createElement("button");return s.className="pl-preview-copy-btn",s.type="button",s.textContent="\u{1F4CB}",s.title="Copy",s.addEventListener("click",()=>LS(t,s)),a.append(i,o,s),a}createTagSection(e,t){const n=document.createElement("div");n.className="pl-preview-section";const a=document.createElement("div");a.className="pl-preview-section-title",a.textContent=e,n.appendChild(a);const i=document.createElement("div");i.className="pl-preview-tags";for(const o of t){const s=document.createElement("span");s.className="pl-preview-tag",s.textContent=o,i.appendChild(s)}return n.appendChild(i),n}renderActions(e){if(!this.shadow)return;const t=document.createElement("div");t.className="pl-preview-actions";const n=document.createElement("button");n.className="pl-preview-action-btn",n.type="button",n.innerHTML="\u2B50 Save",n.addEventListener("click",()=>{this.sendToBackground("SAVE_PAPER",{pmid:e.pmid}).catch(o=>{console.warn("[PaperLens] Save paper failed:",o)}),n.innerHTML="\u2705 Saved",n.disabled=!0});const a=document.createElement("button");a.className="pl-preview-action-btn",a.type="button",a.innerHTML="\u{1F4E5} Export \u25BE",a.addEventListener("click",async()=>{const o=await lt("ris");if(!o.allowed){D.error(o.error||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528 RIS \u5BFC\u51FA");return}this.sendToBackground("EXPORT_PUBMED_RECORDS",{pmids:e.pmid,format:"ris"}).then(s=>{if(s.success&&typeof s.data=="string"){const l=new Blob([s.data],{type:"application/x-research-info-systems"}),c=URL.createObjectURL(l),u=document.createElement("a");u.href=c,u.download=`${e.pmid}.ris`,u.click(),URL.revokeObjectURL(c)}}).catch(s=>{console.warn("[PaperLens] Export failed:",s)})});const i=document.createElement("a");i.className="pl-preview-action-btn pl-preview-action-btn--primary",i.href=`https://pubmed.ncbi.nlm.nih.gov/${e.pmid}/`,i.target="_blank",i.rel="noopener noreferrer",i.textContent="\u{1F517} PubMed",t.append(n,a,i),this.shadow.appendChild(t)}renderError(e){if(!this.shadow)return;const t=document.createElement("div");t.className="pl-preview-error",t.textContent=`\u26A0 ${e}`,this.shadow.appendChild(t)}}async function RS(r){await dt.open(r.pmid,r.paperTitle,r.fallbackAbstract,r.sendToBackground)}const PS=ve+`
`+`/**
 * Abstract Button Styles \u2014 compact inline action for PubMed result rows.
 */

:host {
  display: inline-flex;
  align-items: center;
  vertical-align: middle;
}

.pl-abstract-btn {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  min-height: 28px;
  padding: 0 11px;
  border: 1px solid #d5dbe7;
  border-radius: 7px;
  background: #ffffff;
  color: #334155;
  font-family: var(--pl-font-sans);
  font-size: 13px;
  font-weight: var(--pl-weight-semibold);
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
  transition:
    border-color var(--pl-transition-fast),
    background-color var(--pl-transition-fast),
    box-shadow var(--pl-transition-fast),
    color var(--pl-transition-fast);
}

.pl-abstract-btn:hover {
  border-color: #93c5fd;
  background: #eff6ff;
  color: #1d4ed8;
  box-shadow: 0 2px 6px rgba(37, 99, 235, 0.1);
}

.pl-abstract-icon {
  font-size: 12px;
  line-height: 1;
}
`,BS="paperlens-abstract-host";function IS(){const r=document.createElement("div");r.className=BS,r.dataset.pmid="";const e=r.attachShadow({mode:"open"}),t=document.createElement("style");return t.textContent=PS,e.appendChild(t),{host:r,shadow:e}}function MS(r){const{host:e,shadow:t}=IS();e.dataset.pmid=r.pmid;const n=document.createElement("button");n.type="button",n.className="pl-abstract-btn",n.setAttribute("aria-label","\u67E5\u770B\u6458\u8981");const a=document.createElement("span");a.className="pl-abstract-icon",a.textContent="\u25A3";const i=document.createElement("span");return i.textContent="Abstract",n.append(a,i),t.appendChild(n),n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),RS({pmid:r.pmid,paperTitle:r.paperTitle,fallbackAbstract:r.fallbackAbstract,sendToBackground:r.sendToBackground})}),e}class Be{static instance;selectedPmids=new Map;listeners=new Set;constructor(){}static getInstance(){return Be.instance||(Be.instance=new Be),Be.instance}toggle(e,t){this.selectedPmids.has(e)?this.selectedPmids.delete(e):this.selectedPmids.set(e,t),this.notify()}selectAll(e){if(e.length!==0){for(const t of e)t.PMID&&this.selectedPmids.set(t.PMID,t);this.notify()}}deselectAll(){this.selectedPmids.size!==0&&(this.selectedPmids.clear(),this.notify())}isSelected(e){return this.selectedPmids.has(e)}getSelected(){return new Map(this.selectedPmids)}getCount(){return this.selectedPmids.size}getSelectedPmids(){return Array.from(this.selectedPmids.keys())}onChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(){for(const e of this.listeners)e()}}const qS=ve+`
`+`/**
 * Checkbox Styles \u2014 injected into each checkbox's Shadow DOM
 *
 * \u81EA\u5B9A\u4E49\u590D\u9009\u6846\u6837\u5F0F\uFF1A
 * - 16x16px \u5706\u89D2\u65B9\u5F62
 * - \u672A\u9009\u4E2D\uFF1A\u7070\u8272\u8FB9\u6846\uFF0C\u767D\u8272\u80CC\u666F
 * - \u9009\u4E2D\uFF1A--pl-color-primary \u586B\u5145\uFF0C\u767D\u8272 \u2713
 * - hover \u5FAE\u53CD\u9988
 */

:host {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  flex-shrink: 0;
  cursor: pointer;
  user-select: none;
  vertical-align: middle;
}

/* \u2500\u2500 \u590D\u9009\u6846\u6309\u94AE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-checkbox {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
  border: 1.5px solid var(--pl-color-gray-300);
  border-radius: var(--pl-radius-sm);
  background-color: var(--pl-color-white);
  cursor: pointer;
  padding: 0;
  margin: 0;
  transition: all var(--pl-transition-fast);
  position: relative;
  outline: none;
}

.pl-checkbox:hover {
  border-color: var(--pl-color-primary);
  background-color: var(--pl-color-primary-light);
}

.pl-checkbox:focus-visible {
  box-shadow: 0 0 0 2px var(--pl-color-primary-light);
}

/* \u2500\u2500 \u9009\u4E2D\u72B6\u6001 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-checkbox[data-pl-checked="true"] {
  background-color: var(--pl-color-primary);
  border-color: var(--pl-color-primary);
}

.pl-checkbox[data-pl-checked="true"]:hover {
  background-color: var(--pl-color-primary-hover);
  border-color: var(--pl-color-primary-hover);
}

/* \u2500\u2500 \u2713 \u56FE\u6807 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-checkbox-icon {
  font-size: 11px;
  font-weight: var(--pl-weight-bold);
  line-height: 1;
  color: transparent;
  transition: color var(--pl-transition-fast);
  pointer-events: none;
}

.pl-checkbox[data-pl-checked="true"] .pl-checkbox-icon {
  color: var(--pl-color-white);
}
`,kh="paperlens-checkbox-host",yl="data-pl-checked";function jS(r,e){const t=document.createElement("div");t.className=kh,t.dataset.pmid=r;const n=t.attachShadow({mode:"open"}),a=document.createElement("style");a.textContent=qS,n.appendChild(a);const i=document.createElement("button");i.type="button",i.className="pl-checkbox",i.setAttribute("role","checkbox"),i.setAttribute("aria-checked","false"),i.setAttribute("aria-label","\u9009\u62E9\u6B64\u8BBA\u6587"),i.setAttribute(yl,"false");const o=document.createElement("span");return o.className="pl-checkbox-icon",o.textContent="\u2713",i.appendChild(o),n.appendChild(i),i.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation();const l=Be.getInstance();l.toggle(r,e);const c=l.isSelected(r);i.setAttribute("aria-checked",String(c)),i.setAttribute(yl,String(c))}),t}function xl(r,e){const t=r.shadowRoot;if(!t)return;const n=t.querySelector(".pl-checkbox");n&&(n.setAttribute("aria-checked",String(e)),n.setAttribute(yl,String(e)))}function Al(){return kh}const ee=new Map,$S=300,OS=8e3,US=45e3;function Nh(r){const e=String(r??"").trim().replace("\u533A","");if(e==="1"||e==="2"||e==="3"||e==="4")return Number(e)}function Lh(r){const e=String(r??"").trim().toUpperCase();return e==="Q1"||e==="Q2"||e==="Q3"||e==="Q4"?e:void 0}function HS(r){const e=r.match(/[A-Za-z]/g)?.length??0,t=r.match(/[\u3400-\u9fff]/g)?.length??0;return e>=12&&e>t}function Rh(r){return r.extraDownloadUrl?.trim()||Ht}function zS(r,e){return e.showExtraDownload===!1||!Rh(e)?!1:!!r.DOI||HS(r.title)}async function Ph(){const r=await We("metrics.basic","\u57FA\u7840\u671F\u520A\u6307\u6807");return r.allowed||console.warn("[PaperLens] PubMed metrics disabled by entitlement:",r.error),r.allowed}const Bh="paperlens-action-row",pt={abstract:10,citationCount:20,download:35,save:40,export:55,zotero:56,translate:60};function Ni(r,e){const t=r.article.querySelector(Nt);if(t){t.after(e);return}r.citation.before(e)}function JS(r){return r.querySelector(So)??r.querySelector(Wa)??r.querySelector(vo)}function cr(r){const e=r.querySelector(`.${Bh}`);if(e instanceof HTMLElement)return e;const t=JS(r);if(!t)return null;const n=document.createElement("div");return n.className=Bh,n.style.display="flex",n.style.flexWrap="wrap",n.style.alignItems="center",n.style.gap="8px",n.style.marginTop="8px",n.style.maxWidth="100%",t.after(n),n}function ht(r,e,t){e.style.order=String(t),r.appendChild(e)}function VS(r,e,t){const n=document.createElement("button");return n.type="button",n.disabled=!0,n.className=t,n.textContent=r,n.title=e,n.style.display="inline-flex",n.style.alignItems="center",n.style.minHeight="28px",n.style.padding="0 11px",n.style.border="1px solid #e5e7eb",n.style.borderRadius="7px",n.style.background="#f8fafc",n.style.color="#94a3b8",n.style.font='650 13px/1 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", "Noto Sans SC", "Source Han Sans SC", "Helvetica Neue", Arial, sans-serif',n.style.whiteSpace="nowrap",n.style.cursor="not-allowed",n}function WS(r){r.querySelectorAll(".paperlens-citation-placeholder").forEach(e=>e.remove())}function Ih(r,e){!r.querySelector(kt)&&!r.querySelector(".paperlens-citation-placeholder")&&ht(e,VS("\u88AB\u5F15 \u2014","\u6682\u65E0\u88AB\u5F15\u6570\u636E","paperlens-citation-placeholder"),pt.citationCount)}function Cl(r){return Array.from(r.values()).map(e=>({pmid:e.pmid,doi:e.paper.DOI}))}function Mh(r,e){if(!r.has(e))return e;let t=2,n=`${e}:${t}`;for(;r.has(n);)t++,n=`${e}:${t}`;return n}function GS(r){const e=new Set(r.map(n=>n.pmid)),t=document.querySelectorAll(`${ke} ${ie}`);for(const n of t){if(!di(n))continue;const i=n.querySelector(Nt)?.getAttribute(sn);if(!i||!e.has(i))continue;const o=cr(n);o&&Ih(n,o)}}function vl(){const r=document.querySelectorAll(`${ke} ${ie}`);for(const e of r){if(e.dataset.plTitleIntercepted)continue;const t=e.querySelector(Nt);if(!t)continue;const n=t.getAttribute(sn);n&&(e.dataset.plTitleIntercepted="true",t.addEventListener("click",a=>{const i=a;if(i.button===0&&!i.shiftKey&&!i.ctrlKey&&!i.metaKey&&!i.altKey){i.preventDefault(),i.stopPropagation();const o=t.getAttribute("href")??`https://pubmed.ncbi.nlm.nih.gov/${n}/`;window.open(o,"_blank","noopener")}}))}}function ZS(){const r=document.querySelectorAll(`${ke} ${ie}`);let e=0;for(const t of r)if(!di(t))try{const n=Za(t);if(!n.PMID){Zn(t);continue}const a=t.querySelector(Wa);if(!a){Zn(t);continue}ee.set(Mh(ee,n.PMID),{pmid:n.PMID,journal:n.journal,article:t,citation:a,shimmerHost:null,paper:n}),Zn(t),e++}catch{}return console.log(`[PaperLens] Collected ${e} pending entries`),e}function YS(){for(const r of ee.values())if(!r.shimmerHost){const e=$d(!0);Ni(r,e),r.shimmerHost=e}}function KS(){return ee.size}async function QS(){if(ee.size===0)return 0;if(!await Ph()){for(const o of ee.values())o.shimmerHost?.remove();return Sl(ee),wl(ee),Tl(ee),(await we().catch(()=>ut)).showCitations&&El(Cl(ee)),ee.clear(),0}const e=[];for(const i of ee.values())i.journal&&e.push({id:i.pmid,journal:i.journal});const t=await ri(e),n=await we().catch(()=>ut);let a=0;for(const i of ee.values()){const o=t.get(i.pmid);if(o){i.paper.impactFactor=o.journal.impactFactor,i.paper.jcrQuartile=Lh(o.journal.jcrQuartile),i.paper.journalOpenAccess=o.journal.openAccess===!0;const s=Nh(o.journal.casQuartile);if(s&&(i.paper.casQuartile=s),!Vn(o.journal,{quartileSources:n.quartileSources})){i.shimmerHost?.remove(),pi(i.article);continue}const l=gs(o.journal,{paper:i.paper,quartileSources:n.quartileSources,showScimagoSJR:n.showScimagoSJR});i.shimmerHost?i.shimmerHost.replaceWith(l):Ni(i,l),a++}else i.shimmerHost?.remove()}return ee.size>0&&(Sl(ee),wl(ee),Tl(ee)),a>0&&El(Cl(ee)),XS(),ee.clear(),a>0&&vl(),console.log(`[PaperLens] Rendered ${a} metric bars`),a}function qh(){return async(r,e)=>{try{const t=await H({type:r,payload:e},US);return t||{success:!1,error:"No response from background"}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Message send failed"}}}}function Sl(r){const e=qh();for(const t of r.values()){const n=t.pmid;if(t.article.querySelector(wb))continue;const a=cr(t.article);a&&ht(a,MS({pmid:n,paperTitle:t.paper.title,fallbackAbstract:t.paper.abstractSnippet,sendToBackground:e}),pt.abstract)}}function jh(r){Sl(r)}function wl(r){const e=Array.from(r.entries());(async()=>{try{const t=e.map(([,o])=>o.pmid);if(t.length===0)return;const n=await Promise.all(t.map(async o=>({pmid:o,saved:await gi(o)}))),a=new Map(n.map(({pmid:o,saved:s})=>[o,s])),i=await we().catch(()=>({...ut}));for(const[,o]of e){const s=o.pmid;if(!o.article.querySelector(`.${Al().split(" ").join(".")}`)){const c=jS(s,o.paper),u=o.article.querySelector("div.docsum-wrap");u?u.insertBefore(c,u.firstChild):o.article.insertBefore(c,o.article.firstChild),Be.getInstance().isSelected(s)&&xl(c,!0)}const l=cr(o.article);if(l&&!o.article.querySelector(eu)&&zS(o.paper,i)){const c=Yd(o.paper.DOI,Rh(i),!!(o.paper.isOpenAccess||o.paper.journalOpenAccess),o.paper.title,{pmid:s,openAccessPdfUrl:o.paper.openAccessPdf,journalOpenAccess:o.paper.journalOpenAccess});c&&ht(l,c,pt.download)}if(!o.article.querySelector(Pn)){const c=o.paper,u={source:"PubMed",pmid:s,doi:c.DOI,title:c.title,journal:c.journal,impactFactor:c.impactFactor,jcrQuartile:c.jcrQuartile,casQuartile:c.casQuartile?String(c.casQuartile):void 0,year:c.year,citationCount:c.citationCount,url:`https://pubmed.ncbi.nlm.nih.gov/${encodeURIComponent(s)}/`,authors:c.authors,abstract:c.abstractSnippet,publicationTypes:c.articleType?[c.articleType]:void 0,oaUrl:c.openAccessPdf,sourceUrl:`https://pubmed.ncbi.nlm.nih.gov/${encodeURIComponent(s)}/`},d=a.get(s)??!1,p=Ss(u,d);l?ht(l,p,pt.save):o.citation.after(p)}if(!o.article.querySelector(Bn)){const c=SC(s);l?ht(l,c,pt.export):o.citation.after(c)}if(!o.article.querySelector(xo)){const c=o.paper,u={paper:{pmid:s,title:c.title,authors:c.authors,doi:c.DOI,journal:c.journal,year:c.year,publicationDate:c.publicationDate,abstract:c.abstractSnippet}},d=Jp(u);l?ht(l,d,pt.zotero):o.citation.after(d)}}console.log(`[PaperLens] Save buttons injected for ${t.length} papers`)}catch(t){console.warn("[PaperLens] Failed to inject save buttons:",t)}})()}function $h(r){wl(r)}function Tl(r){for(const e of r.values()){const t=e.pmid;if(e.article.querySelector(In))continue;const n=cr(e.article);if(!n)continue;const a=Xs(t,e.paper.title,e.paper.abstractSnippet||"",{journal:e.paper.journal,authors:e.paper.authors,doi:e.paper.DOI,publicationDate:e.paper.publicationDate,articleType:e.paper.articleType});ht(n,a,pt.translate)}}function XS(){const r=document.querySelectorAll("article.full-docsum");for(const e of r){if(e.querySelector(In))continue;const t=Za(e),n=t.PMID;if(!n)continue;const a=cr(e);if(!a)continue;const i=t.title,o=t.abstractSnippet||"";if(!i)continue;const s=Xs(n,i,o,{journal:t.journal,authors:t.authors,doi:t.DOI,publicationDate:t.publicationDate,articleType:t.articleType});ht(a,s,pt.translate)}}function Oh(r){Tl(r)}function El(r){(async()=>{try{GS(r);const e=await ew(r,OS)??{},t=new Map(r.map(i=>[i.pmid,i.doi])),n=new Set(r.map(i=>i.pmid)),a=document.querySelectorAll(`${ke} ${ie}`);for(const i of a){if(!di(i))continue;const s=i.querySelector(Nt)?.getAttribute(sn);if(!s||!n.has(s))continue;const l=cr(i);if(!l)continue;const c=t.get(s),u=e[s]??(c?e[c]:void 0);if(!_h(u)){Ih(i,l);continue}WS(i);const d=qh();if(!i.querySelector(kt)){const p=Dh(u,{paperId:u.paperId,pmid:u.externalIds?.PubMed,paperTitle:u.title??void 0,sendToBackground:d});ht(l,p,pt.citationCount)}}console.log(`[PaperLens] Citation badges rendered for ${Object.keys(e).length} papers`),document.dispatchEvent(new CustomEvent("paperlens:data-updated"))}catch(e){console.warn("[PaperLens] S2 citation query failed (graceful degradation):",e)}})()}async function ew(r,e){const t=Array.from(new Set(r.map(o=>o.pmid).filter(Boolean))),n=Array.from(new Set(r.map(o=>o.doi).filter(o=>!!o))),a={type:"GET_BATCH_PAPER_DATA",payload:{pmids:t,...n.length?{dois:n}:{}}},i=await H(a,e).catch(()=>null);return!i||!i.success||!i.data?null:i.data}function Uh(r){El(r)}function tw(){for(const r of ee.values())r.shimmerHost?.remove(),pi(r.article);ee.clear(),console.warn("[PaperLens] Cleaned up all pending entries after error")}async function Fl(r){const e=new Map;for(const a of r)if(!di(a))try{const i=Za(a);if(!i.PMID){Zn(a);continue}const o=a.querySelector(Wa)??a.querySelector(vo);if(!o){Zn(a);continue}e.set(Mh(e,i.PMID),{pmid:i.PMID,journal:i.journal,article:a,citation:o,shimmerHost:null,paper:i}),Zn(a)}catch{}if(e.size===0)return 0;if(!await Ph())return jh(e),$h(e),Oh(e),(await we().catch(()=>ut)).showCitations&&Uh(Cl(e)),vl(),0;const t=setTimeout(()=>{for(const a of e.values())if(!a.shimmerHost){const i=$d(!0);Ni(a,i),a.shimmerHost=i}},$S),n=[];for(const a of e.values())a.journal&&n.push({id:a.pmid,journal:a.journal});try{const a=await ri(n),i=await we().catch(()=>ut);let o=0;for(const s of e.values()){const l=a.get(s.pmid);if(l){s.paper.impactFactor=l.journal.impactFactor,s.paper.jcrQuartile=Lh(l.journal.jcrQuartile),s.paper.journalOpenAccess=l.journal.openAccess===!0;const c=Nh(l.journal.casQuartile);if(c&&(s.paper.casQuartile=c),!Vn(l.journal,{quartileSources:i.quartileSources})){s.shimmerHost?.remove(),pi(s.article);continue}const u=gs(l.journal,{paper:s.paper,quartileSources:i.quartileSources,showScimagoSJR:i.showScimagoSJR});s.shimmerHost?s.shimmerHost.replaceWith(u):Ni(s,u),o++}else s.shimmerHost?.remove()}if(jh(e),$h(e),Oh(e),vl(),o>0){console.log(`[PaperLens] Enhanced ${o} new articles`);const s=[];for(const l of e.values())a.has(l.pmid)&&s.push({pmid:l.pmid,doi:l.paper.DOI});s.length>0&&Uh(s)}return o}catch(a){for(const i of e.values())i.shimmerHost?.remove(),pi(i.article);throw console.warn("[PaperLens] Failed to enhance new articles, cleaned up:",a),a}finally{clearTimeout(t)}}const nw={sortField:"default",oaOnly:!1,jcrQuartiles:[],casQuartiles:[],ifMin:void 0,ifMax:void 0,journalQuery:void 0};function Hh(){return{...nw}}let ur=null;function rw(r){ur||(ur=r.map(e=>({element:e,position:{parent:e.parentElement,nextSibling:e.nextElementSibling}})))}function aw(r){const e=r.querySelector(_t);if(!e)return;const t=e.dataset.plIf;if(t!==void 0){const i=parseFloat(t);if(!isNaN(i))return i}if(!e.shadowRoot)return;const n=e.shadowRoot.querySelector(".pl-metric-if");if(!n?.textContent)return;const a=n.textContent.match(/IF:\s*([\d.]+)/);return a?parseFloat(a[1]):void 0}function iw(r){const e=r.querySelector(_t),t=e?.dataset.plJcr;if(t)return t;if(e?.shadowRoot)for(const n of["q1","q2","q3","q4"]){const a=e.shadowRoot.querySelector(`.pl-metric-${n}`);if(a?.textContent)return a.textContent.trim().toUpperCase()}}function ow(r){const e=r.querySelector(_t),t=e?.dataset.plCas;if(t)return t;if(e?.shadowRoot)for(const n of["1","2","3","4"]){const a=e.shadowRoot.querySelector(`.pl-metric-cas-${n}`);if(a?.textContent)return a.textContent.trim().replace("\u533A","")}}function sw(r){const e=r.querySelector(kt),t=e?.dataset.plCitations;if(t!==void 0){const i=parseInt(t.replace(/,/g,""),10);if(!isNaN(i))return i}if(!e?.shadowRoot)return;const n=e.shadowRoot.querySelector(".pl-citation-count");if(!n?.textContent)return;const a=n.textContent.match(/([\d,]+)/);return a?parseInt(a[1].replace(/,/g,""),10):void 0}function lw(r){const e=r.querySelector(kt);return e?.shadowRoot?e.shadowRoot.querySelector(".pl-oa-badge")!==null:!1}function cw(r){const t=r.querySelector(Db)?.dataset.plArticleType?.trim();if(t)return t;const n=r.querySelector(Va)?.textContent?.trim();return Ga(n??null)??void 0}function uw(r){return r.querySelector(Nt)?.getAttribute(sn)??""}function dw(r){const e=r.querySelector(kr);if(!e?.textContent)return;const t=e.textContent.match(/\b(\d{4})\b/);if(t?.[1]){const n=parseInt(t[1],10);if(n>=1800&&n<=2100)return n}}function pw(){const r=document.querySelectorAll(`${ke} ${ie}`),e=[];for(const t of r){const n=uw(t);if(!n)continue;let a;const i=t.querySelector("span.docsum-journal-citation.full-journal-citation");i?.textContent&&(a=i.textContent.split(".")[0]?.trim()||void 0),e.push({element:t,pmid:n,year:dw(t),impactFactor:aw(t),citationCount:sw(t),isOpenAccess:lw(t),jcrQuartile:iw(t),casQuartile:ow(t),journal:a,articleType:cw(t)})}return e}function hw(r,e,t){const n=[...r],a=t==="desc"?-1:1;return n.sort((i,o)=>{let s,l;switch(e){case"impactFactor":s=i.impactFactor,l=o.impactFactor;break;case"citationCount":s=i.citationCount,l=o.citationCount;break;case"year":s=i.year,l=o.year;break;default:return 0}return s===void 0&&l===void 0?0:s===void 0?1:l===void 0?-1:(s-l)*a}),n}function Dl(r){switch(r){case"impactFactor":case"impactFactor-desc":return{field:"impactFactor",direction:"desc"};case"impactFactor-asc":return{field:"impactFactor",direction:"asc"};case"citationCount":case"citationCount-desc":return{field:"citationCount",direction:"desc"};case"citationCount-asc":return{field:"citationCount",direction:"asc"};case"year-desc":return{field:"year",direction:"desc"};case"year-asc":return{field:"year",direction:"asc"};default:return null}}function fw(r,e){return e?r.filter(t=>t.isOpenAccess===!0):r}function mw(r,e){return e.length===0?r:r.filter(t=>t.jcrQuartile!==void 0&&e.includes(t.jcrQuartile))}function bw(r,e){return e.length===0?r:r.filter(t=>t.casQuartile!==void 0&&e.includes(t.casQuartile))}function gw(r,e,t){return e===void 0&&t===void 0?r:r.filter(n=>!(n.year===void 0||e!==void 0&&n.year<e||t!==void 0&&n.year>t))}function zh(r){return r.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]/g,"")}const yw=new Set(["a","an","and","de","for","in","of","the"]);function Jh(r){return r.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function xw(r,e){return r===e?!0:r.length<3||e.length<3?!1:e.startsWith(r)||r.startsWith(e)}function Vh(r,e){if(!e||!e.trim())return!0;if(!r)return!1;const t=e.trim(),n=t.toLowerCase(),a=zh(t),i=r.toLowerCase(),o=zh(r);if(!a||i.includes(n)||o.includes(a))return!0;const s=Jh(n),l=Jh(i);if(s.length===0||l.length===0)return!1;const c=l.map(p=>p[0]).join("");if(a.length>=2&&c.startsWith(a))return!0;const u=s.filter(p=>!yw.has(p));return(u.length>0?u:s).every(p=>l.some(h=>xw(p,h)))}function Aw(r,e){return!e||!e.trim()?r:r.filter(t=>Vh(t.journal,e))}function Cw(r,e,t){return e===void 0&&t===void 0?r:r.filter(n=>!(n.impactFactor===void 0||e!==void 0&&n.impactFactor<e||t!==void 0&&n.impactFactor>t))}function vw(r){const e=document.querySelector(Ja);if(!e)return{total:0,visible:0};const t=e.querySelector(ke)??e,n=Array.from(document.querySelectorAll(`${ke} ${ie}`));if(n.length===0)return{total:0,visible:0};rw(n);let a=pw();const i=a.length;a=fw(a,r.oaOnly),a=mw(a,r.jcrQuartiles),a=bw(a,r.casQuartiles),a=gw(a,r.yearMin,r.yearMax),a=Cw(a,r.ifMin,r.ifMax),a=Aw(a,r.journalQuery);const o=Dl(r.sortField);o&&(a=hw(a,o.field,o.direction));const s=a.length,l=new Set(a.map(u=>u.element)),c=a.map(u=>u.element);for(const u of c)t.appendChild(u);for(const u of n)l.has(u)?u.style.display="":u.style.display="none";return{total:i,visible:s}}function _l(){if(ur){for(let r=ur.length-1;r>=0;r--){const{element:e,position:t}=ur[r],{parent:n,nextSibling:a}=t;e.style.display="",a&&a.parentElement?n.insertBefore(e,a):n.appendChild(e)}ur=null}}function kl(r){return r.sortField==="default"&&!r.oaOnly&&r.jcrQuartiles.length===0&&r.casQuartiles.length===0&&r.yearMin===void 0&&r.yearMax===void 0&&r.ifMin===void 0&&r.ifMax===void 0&&r.journalQuery===void 0}const ue="paperlens-global-results-root",Wh="paperlens-global-results-style",Sw=200,Gh=2e3,Zh=80,ww=6e4,Tw="PubMed \u5168\u91CF\u7ED3\u679C\u5206\u6790",Yh=45e3;let re=null,Nl=0,Li=null;function Ew(){return re!==null}function Fw(r){const e=r.publicationTypes?.length?r.publicationTypes:r.articleType?[r.articleType]:void 0;return{pmid:r.pmid,year:r.year,jcrQuartile:r.jcrQuartile,casQuartile:r.casQuartile,articleTypes:e}}function Dw(){return re?Ri(re):null}function Ri(r){const e=Vt(r);return{scope:"global",sourceTotal:r.sourceTotal,analyzed:dr(r),visible:e.length,done:r.done,loading:r.loading,records:e.map(Fw)}}async function _w(r,e={}){const t=of();if(!t)return{scope:"global",sourceTotal:0,analyzed:0,visible:0,done:!0,loading:!1,records:[]};const n={requestId:0,term:t,pubmedSort:sf(),state:r,sourceTotal:0,nextStart:0,records:[],loading:!0,done:!1},a=()=>{e.onUpdate?.(Ri(n))},i=()=>{if(e.signal?.aborted)throw new DOMException("Analysis aborted","AbortError")};a();try{for(;!n.done;){i();const o=await Xh(n);i(),n.sourceTotal=o.count,n.nextStart=o.retstart+o.pmids.length,n.done=o.pmids.length===0||n.nextStart>=o.count;const s=await ef(o.papers,n.state);i(),n.records.push(...s),n.loading=!n.done,a(),n.done||await af(Zh)}}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return n.loading=!1,a(),Ri(n);throw o}return n.loading=!1,a(),Ri(n)}function Pi(){Nl++,Ll(),re=null,document.getElementById(ue)?.remove(),Rl(!1)}function kw(){Nl++,Ll();const r=re!==null;re=null,document.getElementById(ue)?.remove(),Rl(!1),r&&console.log("[PaperLens] Global filter cancelled by user")}async function Nw(r){const e=of(),t=++Nl;return e?(re={requestId:t,term:e,pubmedSort:sf(),state:r,sourceTotal:0,nextStart:0,records:[],loading:!1,done:!1},zw(),Rl(!0),Ii(re,[]),Lw(t),await Kh(t)):(Pi(),{sourceTotal:0,analyzed:0,visible:0,done:!0,loading:!1})}async function Kh(r,e){if(!await Bi(r))return Cn();const t=re?dr(re):0;let n=await Qh(r);for(;Hw(r,n,t);){if(await af(Zh),!await Bi(r))return Cn();n=await Qh(r)}return n}async function Qh(r=re?.requestId??0){const e=re;if(!e||e.requestId!==r||!await Bi(r))return Cn();if(e.loading)return ua(e,Vt(e).length);if(e.done){const t=Vt(e);return Ii(e,t),ua(e,t.length)}e.loading=!0,Pl(e,Vt(e).length),Ii(e,Vt(e));try{const t=await Xh(e);if(re?.requestId!==r)return Cn();e.sourceTotal=t.count,e.nextStart=t.retstart+t.pmids.length,e.done=t.pmids.length===0||e.nextStart>=t.count;const n=await ef(t.papers,e.state);if(re?.requestId!==r)return Cn();e.records.push(...n);const a=Vt(e);e.loading=!1,Ii(e,a),Pl(e,a.length);const i=Ow();return i.length>0&&Fl(i),ua(e,a.length)}catch(t){return re?.requestId!==r?Cn():(e.loading=!1,e.done=!0,Bw(t),Pl(e,Vt(e).length),ua(e,Vt(e).length))}}function Lw(r){Ll(),Li=window.setInterval(()=>{Bi(r)},ww)}function Ll(){Li!==null&&(window.clearInterval(Li),Li=null)}async function Bi(r=re?.requestId??0){const e=re;if(!e||e.requestId!==r)return!1;const[t,n]=await Promise.all([_p(),Os()]);if(t.allowed&&n.allowed)return!0;if(re?.requestId===r){Pi();const a=n.allowed?t.error||`${Tw}\u5F53\u524D\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5237\u65B0\u8D26\u6237\u6743\u9650\u540E\u91CD\u8BD5`:n.error||"PubMed \u9AD8\u7EA7\u7B5B\u9009\u5F53\u524D\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5237\u65B0\u8D26\u6237\u6743\u9650\u540E\u91CD\u8BD5";document.dispatchEvent(new CustomEvent("paperlens:global-filter-denied",{detail:{message:a}}))}return!1}async function Xh(r){const e={term:r.term,retstart:r.nextStart,retmax:Sw,sort:r.pubmedSort},t=await H({type:"SEARCH_PUBMED_RESULTS",payload:e},Yh);if(!t?.success||!t.data)throw new Error(t?.error??"PubMed global search failed");return t.data}async function ef(r,e){const t=await ri(r.map(i=>({id:i.pmid,journal:i.journal}))),a=Dl(e.sortField)?.field==="citationCount"?await Rw(r):new Map;return r.map(i=>{const o=t.get(i.pmid),s=a.get(i.pmid),l=!!i.pmcid||!!s?.isOpenAccess,c=Lt(o?.journal.jcrQuartile);return{...i,impactFactor:o?.journal.impactFactor,citationCount:s?.citationCount,isOpenAccess:l,jcrQuartile:c?.value,casQuartile:o?j0(o.journal.casQuartile):void 0,journalMatch:o}})}async function Rw(r){const e=r.map(n=>n.pmid).filter(Boolean),t=r.map(n=>n.doi).filter(n=>!!n);if(e.length===0&&t.length===0)return new Map;try{const n=await H({type:"GET_BATCH_PAPER_DATA",payload:{pmids:e,dois:t}},Yh);if(!n?.success||!n.data)return new Map;const a=new Map;for(const i of r){const o=n.data[i.pmid],s=i.doi?n.data[i.doi]:void 0,l=o??s;l&&a.set(i.pmid,{citationCount:l.citationCount,isOpenAccess:l.isOpenAccess})}return a}catch{return new Map}}function Vt(r){let e=[...r.records];const{state:t}=r;return t.oaOnly&&(e=e.filter(n=>n.isOpenAccess===!0)),t.jcrQuartiles.length>0&&(e=e.filter(n=>n.jcrQuartile!==void 0&&t.jcrQuartiles.includes(n.jcrQuartile))),t.casQuartiles.length>0&&(e=e.filter(n=>n.casQuartile!==void 0&&t.casQuartiles.includes(n.casQuartile))),(t.yearMin!==void 0||t.yearMax!==void 0)&&(e=e.filter(n=>!(n.year===void 0||t.yearMin!==void 0&&n.year<t.yearMin||t.yearMax!==void 0&&n.year>t.yearMax))),(t.ifMin!==void 0||t.ifMax!==void 0)&&(e=e.filter(n=>!(n.impactFactor===void 0||t.ifMin!==void 0&&n.impactFactor<t.ifMin||t.ifMax!==void 0&&n.impactFactor>t.ifMax))),t.journalQuery!==void 0&&(e=e.filter(n=>Vh(n.journal,t.journalQuery))),Pw(e,t)}function Pw(r,e){const t=Dl(e.sortField);if(!t)return r;const n=t.direction==="desc"?-1:1;return[...r].sort((a,i)=>{const o=tf(a,t.field),s=tf(i,t.field);return o===void 0&&s===void 0?0:o===void 0?1:s===void 0?-1:(o-s)*n})}function tf(r,e){if(e==="impactFactor")return r.impactFactor;if(e==="citationCount")return r.citationCount;if(e==="year")return r.year}function Ii(r,e){const t=nf();if(!t)return;t.replaceChildren();const n=document.createElement("div");n.className="paperlens-global-status";const a=document.createElement("div");a.className="paperlens-global-status-text",a.textContent=Uw(r,e.length);const i=document.createElement("div");i.className="paperlens-global-status-actions";const o=document.createElement("button");o.type="button",o.className="paperlens-global-load-more",o.textContent=r.done?"\u5DF2\u5B8C\u6210":r.loading?"\u5206\u6790\u4E2D...":"\u7EE7\u7EED\u5206\u6790\u66F4\u591A",o.disabled=r.done||r.loading,o.addEventListener("click",()=>{Kh(r.requestId)}),i.appendChild(o),n.append(a,i),t.appendChild(n);const s=document.createElement("div");s.className="search-results-chunks paperlens-global-chunks";const l=document.createElement("div");l.className="search-results-chunk results-chunk paperlens-global-chunk",l.dataset.pageNumber="1",l.dataset.resultsAmount=String(r.sourceTotal),l.dataset.chunkIds=e.map(c=>c.pmid).join(","),e.length===0?l.appendChild(Iw(r)):e.forEach((c,u)=>{l.appendChild(Mw(c,u+1))}),s.appendChild(l),t.appendChild(s)}function Bw(r){const e=nf();if(!e)return;e.replaceChildren();const t=document.createElement("div");t.className="paperlens-global-status paperlens-global-status--error",t.textContent=r instanceof Error?`\u5168\u91CF\u7B5B\u9009\u5931\u8D25\uFF1A${r.message}`:"\u5168\u91CF\u7B5B\u9009\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",e.appendChild(t)}function Iw(r){const e=document.createElement("div");return e.className="paperlens-global-empty",r.loading?e.append(ft("pl-empty-icon","\u{1F50D}"),ft("pl-empty-title","\u6B63\u5728\u5206\u6790 PubMed \u5168\u91CF\u7ED3\u679C..."),ft("pl-empty-desc","\u9996\u6B21\u5206\u6790\u53EF\u80FD\u9700\u8981\u51E0\u79D2\uFF0C\u8BF7\u7A0D\u5019")):r.done?e.append(ft("pl-empty-icon","\u{1F4ED}"),ft("pl-empty-title","\u6CA1\u6709\u627E\u5230\u7B26\u5408\u6761\u4EF6\u7684\u6587\u732E"),ft("pl-empty-desc",`\u5DF2\u5206\u6790\u5168\u90E8 ${r.sourceTotal.toLocaleString()} \u6761\u7ED3\u679C\uFF0C\u5747\u4E0D\u7B26\u5408\u5F53\u524D\u7B5B\u9009\u6761\u4EF6\u3002\u5EFA\u8BAE\u653E\u5BBD\u7B5B\u9009\u6761\u4EF6\u540E\u91CD\u8BD5\u3002`)):e.append(ft("pl-empty-icon","\u{1F50D}"),ft("pl-empty-title","\u5F53\u524D\u6279\u6B21\u6CA1\u6709\u7B26\u5408\u6761\u4EF6\u7684\u6587\u732E"),ft("pl-empty-desc",`\u5DF2\u5206\u6790\u524D ${dr(r).toLocaleString()} \u6761\u3002\u6BCF\u8F6E\u6700\u591A\u81EA\u52A8\u5206\u6790 ${Gh.toLocaleString()} \u6761\uFF0C\u53EF\u4EE5\u70B9\u51FB\u4E0A\u65B9\u300C\u7EE7\u7EED\u5206\u6790\u66F4\u591A\u300D\u52A0\u8F7D\u4E0B\u4E00\u8F6E\u3002`)),e}function ft(r,e){const t=document.createElement("div");return t.className=r,t.textContent=e,t}function Mw(r,e){const t=document.createElement("article");t.className="full-docsum paperlens-global-docsum",t.dataset.relPos=String(e);const n=document.createElement("div");n.className=`item-selector-wrap selectors-and-actions${e===1?" first-selector":""}`;const a=document.createElement("label");a.className="search-result-position";const i=document.createElement("span");i.className="position-number",i.textContent=String(e),a.appendChild(i),n.appendChild(a);const o=document.createElement("div");o.className="docsum-wrap";const s=document.createElement("div");s.className="docsum-content";const l=document.createElement("a");l.className="docsum-title",l.href=`/${r.pmid}/`,l.dataset.articleId=r.pmid,l.textContent=r.title||`PMID ${r.pmid}`;const c=document.createElement("div");c.className="docsum-citation full-citation";const u=document.createElement("span");u.className="docsum-authors full-authors",u.textContent=jw(r.authors);const d=document.createElement("span");d.className="docsum-authors short-authors",d.textContent=$w(r.authors);const p=document.createElement("span");p.className="docsum-journal-citation full-journal-citation",p.textContent=qw(r);const h=document.createElement("span");h.className="docsum-journal-citation short-journal-citation",h.textContent=`${r.journal||"PubMed"}${r.year?`. ${r.year}.`:"."}`;const f=document.createElement("span");f.className="citation-part",f.append("PMID: ");const y=document.createElement("span");if(y.className="docsum-pmid",y.textContent=r.pmid,f.appendChild(y),c.append(u,d,p,h,f),r.pmcid){const x=document.createElement("span");x.className="free-resources spaced-citation-item citation-part",x.textContent="Free PMC article.",c.appendChild(x)}if(r.articleType){const x=document.createElement("span");x.className="publication-type spaced-citation-item citation-part",x.textContent=`${r.articleType}.`,c.appendChild(x)}if(s.append(l,c),r.abstractSnippet){const x=document.createElement("div");x.className="docsum-snippet",x.textContent=r.abstractSnippet,s.appendChild(x)}return o.appendChild(s),t.append(n,o),t}function qw(r){const e=[`${r.journal||"PubMed"}.`];return r.year&&e.push(`${r.year}.`),r.doi&&e.push(`doi: ${r.doi}.`),e.join(" ")}function jw(r){return r.length===0?"":`${r.join(", ")}.`}function $w(r){return r.length===0?"":r.length===1?`${r[0]}.`:`${r[0]}, et al.`}function nf(){const r=document.getElementById(ue);if(r instanceof HTMLElement)return r;const e=document.querySelector(lu),n=rf()??e?.firstElementChild??e;if(!e||!n)return null;const a=document.createElement("div");return a.id=ue,a.className="paperlens-global-results",n.before(a),a}function Ow(){const r=document.getElementById(ue);return r?Array.from(r.querySelectorAll(ie)):[]}function Rl(r){const e=rf();e instanceof HTMLElement&&(e.style.display=r?"none":"")}function rf(){return Array.from(document.querySelectorAll(Ja)).find(r=>!r.closest(`#${ue}`))??null}function Uw(r,e){const t=r.sourceTotal>0?r.sourceTotal:0,a=`\u5DF2\u5206\u6790 ${dr(r).toLocaleString()} / ${t.toLocaleString()}\uFF0C\u663E\u793A ${e.toLocaleString()}`;return r.loading?t>0?`\u5168\u91CF\u7B5B\u9009\u4E2D\uFF1A${a}`:"\u6B63\u5728\u8BFB\u53D6 PubMed \u5168\u91CF\u7ED3\u679C...":r.done?`\u5168\u91CF\u7B5B\u9009\u5B8C\u6210\uFF1A${a}`:`\u5168\u91CF\u7B5B\u9009\uFF1A${a}\uFF0C\u672C\u8F6E\u5DF2\u6682\u505C\uFF0C\u53EF\u7EE7\u7EED\u5206\u6790\u66F4\u591A`}function Pl(r,e){document.dispatchEvent(new CustomEvent("paperlens:global-filter-updated",{detail:ua(r,e)}))}function ua(r,e){return{sourceTotal:r.sourceTotal,analyzed:dr(r),visible:e,done:r.done,loading:r.loading}}function dr(r){return r.sourceTotal<=0?r.records.length:Math.min(Math.max(r.records.length,r.nextStart),r.sourceTotal)}function Hw(r,e,t){const n=re;return!n||n.requestId!==r||n.loading||n.done||e.done?!1:dr(n)-t<Gh}function af(r){return new Promise(e=>window.setTimeout(e,r))}function Cn(){return{sourceTotal:0,analyzed:0,visible:0,done:!0,loading:!1}}function of(){try{return new URL(window.location.href).searchParams.get("term")?.trim()??""}catch{return""}}function sf(){try{return new URL(window.location.href).searchParams.get("sort")?.trim()||void 0}catch{return}}function zw(){if(document.getElementById(Wh))return;const r=document.createElement("style");r.id=Wh,r.textContent=`
    #${ue}.paperlens-global-results {
      width: 100%;
      margin: 0 0 10px;
    }

    #${ue} .paperlens-global-status {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 12px;
      margin: 8px 0 10px;
      padding: 8px 10px;
      border: 1px solid #d8dee8;
      border-radius: 4px;
      background: #f8fafc;
      color: #4b5563;
      font-size: 14px;
      line-height: 1.4;
    }

    #${ue} .paperlens-global-status--error {
      border-color: #fecaca;
      background: #fef2f2;
      color: #991b1b;
    }

    #${ue} .paperlens-global-status-actions {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      flex-shrink: 0;
    }

    #${ue} .paperlens-global-load-more {
      min-height: 28px;
      padding: 4px 10px;
      border: 1px solid #b8c7dc;
      border-radius: 4px;
      background: #ffffff;
      color: #1f2937;
      font-size: 13px;
      font-weight: 600;
      cursor: pointer;
    }

    #${ue} .paperlens-global-load-more:disabled {
      cursor: default;
      opacity: 0.6;
    }

    #${ue} .paperlens-global-empty {
      padding: 40px 20px;
      text-align: center;
      color: #6b7280;
    }

    #${ue} .pl-empty-icon {
      font-size: 36px;
      margin-bottom: 12px;
      line-height: 1;
    }

    #${ue} .pl-empty-title {
      font-size: 15px;
      font-weight: 600;
      color: #374151;
      margin-bottom: 6px;
    }

    #${ue} .pl-empty-desc {
      font-size: 13px;
      color: #9ca3af;
      line-height: 1.5;
      max-width: 400px;
      margin: 0 auto;
    }

    #${ue} .paperlens-global-docsum {
      border-bottom: 1px solid #e5e7eb;
    }
  `,document.head.appendChild(r)}const lf=new Set(["chen","wang","zhang","li","liu","huang","zhao","wu","xu","sun","ma","zhu","hu","guo","he","lin","gao","luo","zheng","liang","song","xie","tang","han","feng","deng","cao","peng","zeng"]),Jw=new Set(["of","for","in","with","without","and","or","study","review","trial","analysis","cancer","medicine","genome","screening","therapy","detection","biomarker","risk","surgical","clinical","patient","treatment","diagnosis","prognosis","survival","meta-analysis","systematic","management","control","disease","effect","effects","result","results","new","england","journal","open","network","research","cell","nature","science","blood","bone","liver","heart","lung","brain","immune","public","international"]),Vw=/[0-9\/:=\[\]{}<>@#$%^&*\\]/,Ww=/^[A-Za-z\s,\-\'.]+$/,Gw=new Set(["new","england","journal","open","network","research","cell","nature","science","blood","bone","liver","heart","lung","brain","immune","public","international","scientific","reports","medical","clinical","surgical","international","national","global","world","university","college","school","institute","center","hospital","control","disease","effect","effects","result","results","outcome","outcomes"]),Zw=/\b(jr|sr|ii|iii|iv)\b/i;function Mi(r){return r.trim().replace(/\s+,/g,",").replace(/,\s*$/g,"").replace(/\s+/g," ")}function qi(r,e){const t=r.trim();if(!t)return null;const n=t.split(/\s+/);if(n.length<2||n.length>4||!Ww.test(t)||Vw.test(t)||n.length===2&&n.every(f=>f.replace(/[.,]/g,"").length===1&&/^[A-Za-z]$/.test(f.replace(/[.,]/g,"")))||n.map(f=>f.toLowerCase().replace(/[,'.]/g,"")).every(f=>Gw.has(f)))return null;const s=n.map(f=>f.toLowerCase().replace(/[,'.]/g,""));for(const f of s)if(Jw.has(f))return null;let l=0,c=null;const u=t.match(/^([A-Z][A-Za-z'\-.]+)\s+([A-Z]{1,4}|[A-Z](?:\.[A-Z]){0,3}\.?)$/);u&&(l+=.95,c="surname-initial");const d=t.match(/^([A-Za-z][A-Za-z'\-.]*(?:\s+(?:[A-Za-z][A-Za-z'\-.]*|jr|sr|ii|iii|iv))?),\s+([A-Za-z][A-Za-z'\-.]*(?:\s+[A-Za-z])?)$/i);if(!u&&d&&(l+=.92,c="inverted"),!c){const f=n.length;if(f===2||f===3)if(n.every(x=>/^[A-Za-z]/.test(x.replace(/[,'.]/g,""))))l+=.73,c="natural";else return null;else return null}const p=s[0],h=s[s.length-1];return(lf.has(p)||lf.has(h))&&(l+=n.length===2?.18:.08),e.hasJournalSibling&&(l+=.1),e.hitsConceptRule&&(l-=.2),l>=.9?{confidence:l,terms:cf(t,c),note:`"${t}" \u2192 detected as author name`}:l>=.8&&e.hasJournalSibling?{confidence:l,terms:cf(t,c),note:`"${t}" \u2192 detected as author name (medium confidence, supported by journal context)`}:null}function cf(r,e){const t=[],n=r.trim();switch(e){case"surname-initial":{t.push(n),n.endsWith(".")?t.push(n.slice(0,-1)):t.push(`${n}.`);break}case"inverted":{t.push(n);const a=n.split(/,\s*/);if(a.length===2){const i=Mi(a[0]),o=Mi(a[1]);if(t.push(`${i} ${o}`),o.length>=1){const s=o[0].toUpperCase();t.push(`${i} ${s}`),t.push(`${i} ${s}.`)}}break}case"natural":{t.push(n);const a=n.split(/\s+/);if(a.length===2){const[i,o]=a;t.push(`${o} ${i}`);const s=i[0].toUpperCase();t.push(`${o} ${s}`),t.push(`${o} ${s}.`)}else if(a.length===3)if(Zw.test(a[1])){const i=Mi(a[2]),o=Mi(`${a[0]} ${a[1]}`);t.push(`${o}, ${i}`),t.push(`${o} ${i}`),t.push(`${o} ${i[0].toUpperCase()}`),t.push(`${o} ${i[0].toUpperCase()}.`)}else{const i=a.slice(0,2).join(" "),o=a[2];t.push(`${o} ${i}`),t.push(`${o} ${i[0].toUpperCase()}`),t.push(`${o} ${i[0].toUpperCase()}.`)}break}default:t.push(n)}return Yw(t)}function Yw(r){return Array.from(new Set(r.filter(Boolean)))}const uf=new Map(Object.entries({nature:{canonical:"Nature",aliases:["Nat"]},science:{canonical:"Science",aliases:["Sci"]},cell:{canonical:"Cell",aliases:[]},"the lancet":{canonical:"The Lancet",aliases:["Lancet","Lanc"]},lancet:{canonical:"The Lancet",aliases:["Lanc"]},"new england journal of medicine":{canonical:"New England Journal of Medicine",aliases:["N Engl J Med","NEJM","N Engl J"]},nejm:{canonical:"New England Journal of Medicine",aliases:["N Engl J Med","New England Journal of Medicine"]},jama:{canonical:"JAMA",aliases:["JAMA","J Am Med Assoc","Journal of the American Medical Association"]},"journal of the american medical association":{canonical:"JAMA",aliases:["JAMA","J Am Med Assoc"]},bmj:{canonical:"BMJ",aliases:["BMJ","Br Med J","British Medical Journal"]},"british medical journal":{canonical:"BMJ",aliases:["BMJ","Br Med J"]},"nature medicine":{canonical:"Nature Medicine",aliases:["Nat Med"]},"nature genetics":{canonical:"Nature Genetics",aliases:["Nat Genet"]},"nature biotechnology":{canonical:"Nature Biotechnology",aliases:["Nat Biotechnol"]},"nature cell biology":{canonical:"Nature Cell Biology",aliases:["Nat Cell Biol"]},"nature immunology":{canonical:"Nature Immunology",aliases:["Nat Immunol"]},"nature neuroscience":{canonical:"Nature Neuroscience",aliases:["Nat Neurosci"]},"nature methods":{canonical:"Nature Methods",aliases:["Nat Methods"]},"nature reviews cancer":{canonical:"Nature Reviews Cancer",aliases:["Nat Rev Cancer"]},"nature reviews immunology":{canonical:"Nature Reviews Immunology",aliases:["Nat Rev Immunol"]},"nature reviews genetics":{canonical:"Nature Reviews Genetics",aliases:["Nat Rev Genet"]},"nature reviews molecular cell biology":{canonical:"Nature Reviews Molecular Cell Biology",aliases:["Nat Rev Mol Cell Biol"]},"nature reviews drug discovery":{canonical:"Nature Reviews Drug Discovery",aliases:["Nat Rev Drug Discov"]},"nature reviews clinical oncology":{canonical:"Nature Reviews Clinical Oncology",aliases:["Nat Rev Clin Oncol"]},"nature communications":{canonical:"Nature Communications",aliases:["Nat Commun"]},"nature structural and molecular biology":{canonical:"Nature Structural & Molecular Biology",aliases:["Nat Struct Mol Biol"]},"cancer discovery":{canonical:"Cancer Discovery",aliases:["Cancer Discov"]},"cancer cell":{canonical:"Cancer Cell",aliases:["Cancer Cell"]},"cancer research":{canonical:"Cancer Research",aliases:["Cancer Res"]},"journal of clinical oncology":{canonical:"Journal of Clinical Oncology",aliases:["J Clin Oncol","JCO"]},jco:{canonical:"Journal of Clinical Oncology",aliases:["J Clin Oncol","Journal of Clinical Oncology"]},"clinical cancer research":{canonical:"Clinical Cancer Research",aliases:["Clin Cancer Res"]},"the new england journal of medicine":{canonical:"New England Journal of Medicine",aliases:["N Engl J Med","NEJM"]},"genome medicine":{canonical:"Genome Medicine",aliases:["Genome Med"]},"genome biology":{canonical:"Genome Biology",aliases:["Genome Biol"]},"genome research":{canonical:"Genome Research",aliases:["Genome Res"]},"nature genomics":{canonical:"Nature Genomics",aliases:["Nat Genomics"]},"cell research":{canonical:"Cell Research",aliases:["Cell Res"]},"cell metabolism":{canonical:"Cell Metabolism",aliases:["Cell Metab"]},"cell stem cell":{canonical:"Cell Stem Cell",aliases:["Cell Stem Cell"]},"molecular cell":{canonical:"Molecular Cell",aliases:["Mol Cell"]},"developmental cell":{canonical:"Developmental Cell",aliases:["Dev Cell"]},immunity:{canonical:"Immunity",aliases:[]},neuron:{canonical:"Neuron",aliases:[]},"the embo journal":{canonical:"The EMBO Journal",aliases:["EMBO J"]},"embo journal":{canonical:"The EMBO Journal",aliases:["EMBO J"]},"embo reports":{canonical:"EMBO Reports",aliases:["EMBO Rep"]},"proceedings of the national academy of sciences":{canonical:"Proceedings of the National Academy of Sciences",aliases:["Proc Natl Acad Sci U S A","PNAS"]},pnas:{canonical:"Proceedings of the National Academy of Sciences",aliases:["Proc Natl Acad Sci U S A","Proceedings of the National Academy of Sciences"]},"science translational medicine":{canonical:"Science Translational Medicine",aliases:["Sci Transl Med"]},"science immunology":{canonical:"Science Immunology",aliases:["Sci Immunol"]},"science advances":{canonical:"Science Advances",aliases:["Sci Adv"]},"the journal of experimental medicine":{canonical:"The Journal of Experimental Medicine",aliases:["J Exp Med"]},"journal of experimental medicine":{canonical:"The Journal of Experimental Medicine",aliases:["J Exp Med"]},"the journal of clinical investigation":{canonical:"The Journal of Clinical Investigation",aliases:["J Clin Invest","JCI"]},"journal of clinical investigation":{canonical:"The Journal of Clinical Investigation",aliases:["J Clin Invest","JCI"]},jci:{canonical:"The Journal of Clinical Investigation",aliases:["J Clin Invest","The Journal of Clinical Investigation"]},"journal of the national cancer institute":{canonical:"Journal of the National Cancer Institute",aliases:["J Natl Cancer Inst","JNCI"]},jnci:{canonical:"Journal of the National Cancer Institute",aliases:["J Natl Cancer Inst","Journal of the National Cancer Institute"]},"annals of oncology":{canonical:"Annals of Oncology",aliases:["Ann Oncol"]},"the lancet oncology":{canonical:"The Lancet Oncology",aliases:["Lancet Oncol"]},"lancet oncology":{canonical:"The Lancet Oncology",aliases:["Lancet Oncol"]},"the lancet neurology":{canonical:"The Lancet Neurology",aliases:["Lancet Neurol"]},"the lancet infectious diseases":{canonical:"The Lancet Infectious Diseases",aliases:["Lancet Infect Dis"]},"the lancet respiratory medicine":{canonical:"The Lancet Respiratory Medicine",aliases:["Lancet Respir Med"]},"the lancet gastroenterology and hepatology":{canonical:"The Lancet Gastroenterology & Hepatology",aliases:["Lancet Gastroenterol Hepatol"]},"the lancet diabetes and endocrinology":{canonical:"The Lancet Diabetes & Endocrinology",aliases:["Lancet Diabetes Endocrinol"]},"the lancet psychiatry":{canonical:"The Lancet Psychiatry",aliases:["Lancet Psychiatry"]},"the lancet haematology":{canonical:"The Lancet Haematology",aliases:["Lancet Haematol"]},"the lancet global health":{canonical:"The Lancet Global Health",aliases:["Lancet Glob Health"]},"the lancet digital health":{canonical:"The Lancet Digital Health",aliases:["Lancet Digit Health"]},gastroenterology:{canonical:"Gastroenterology",aliases:["Gastroenterology"]},gut:{canonical:"Gut",aliases:["Gut"]},"the american journal of gastroenterology":{canonical:"The American Journal of Gastroenterology",aliases:["Am J Gastroenterol"]},"american journal of gastroenterology":{canonical:"The American Journal of Gastroenterology",aliases:["Am J Gastroenterol"]},"gut microbes":{canonical:"Gut Microbes",aliases:["Gut Microbes"]},microbiome:{canonical:"Microbiome",aliases:["Microbiome"]},"gastrointestinal endoscopy":{canonical:"Gastrointestinal Endoscopy",aliases:["Gastrointest Endosc"]},endoscopy:{canonical:"Endoscopy",aliases:["Endoscopy"]},"the american journal of human genetics":{canonical:"The American Journal of Human Genetics",aliases:["Am J Hum Genet","AJHG"]},"american journal of human genetics":{canonical:"The American Journal of Human Genetics",aliases:["Am J Hum Genet","AJHG"]},ajhg:{canonical:"The American Journal of Human Genetics",aliases:["Am J Hum Genet","The American Journal of Human Genetics"]},"american journal of pathology":{canonical:"The American Journal of Pathology",aliases:["Am J Pathol"]},"the journal of biological chemistry":{canonical:"The Journal of Biological Chemistry",aliases:["J Biol Chem","JBC"]},"journal of biological chemistry":{canonical:"The Journal of Biological Chemistry",aliases:["J Biol Chem","JBC"]},jbc:{canonical:"The Journal of Biological Chemistry",aliases:["J Biol Chem","The Journal of Biological Chemistry"]},"nature chemical biology":{canonical:"Nature Chemical Biology",aliases:["Nat Chem Biol"]},"nature chemistry":{canonical:"Nature Chemistry",aliases:["Nat Chem"]},"nature physics":{canonical:"Nature Physics",aliases:["Nat Phys"]},"nature materials":{canonical:"Nature Materials",aliases:["Nat Mater"]},"nature nanotechnology":{canonical:"Nature Nanotechnology",aliases:["Nat Nanotechnol"]},"nature photonics":{canonical:"Nature Photonics",aliases:["Nat Photonics"]},"nature ecology and evolution":{canonical:"Nature Ecology & Evolution",aliases:["Nat Ecol Evol"]},"nature climate change":{canonical:"Nature Climate Change",aliases:["Nat Clim Chang"]},"nature energy":{canonical:"Nature Energy",aliases:["Nat Energy"]},"nature food":{canonical:"Nature Food",aliases:["Nat Food"]},"nature aging":{canonical:"Nature Aging",aliases:["Nat Aging"]},"nature cancer":{canonical:"Nature Cancer",aliases:["Nat Cancer"]},"nature metabolism":{canonical:"Nature Metabolism",aliases:["Nat Metab"]},"nature microbiology":{canonical:"Nature Microbiology",aliases:["Nat Microbiol"]},"nature plants":{canonical:"Nature Plants",aliases:["Nat Plants"]},blood:{canonical:"Blood",aliases:["Blood"]},"the journal of immunology":{canonical:"The Journal of Immunology",aliases:["J Immunol"]},"journal of immunology":{canonical:"The Journal of Immunology",aliases:["J Immunol"]},immunology:{canonical:"Immunology",aliases:["Immunology"]},"frontiers in immunology":{canonical:"Frontiers in Immunology",aliases:["Front Immunol"]},"frontiers in oncology":{canonical:"Frontiers in Oncology",aliases:["Front Oncol"]},"frontiers in genetics":{canonical:"Frontiers in Genetics",aliases:["Front Genet"]},"frontiers in cell and developmental biology":{canonical:"Frontiers in Cell and Developmental Biology",aliases:["Front Cell Dev Biol"]},"frontiers in microbiology":{canonical:"Frontiers in Microbiology",aliases:["Front Microbiol"]},"frontiers in pharmacology":{canonical:"Frontiers in Pharmacology",aliases:["Front Pharmacol"]},"frontiers in neuroscience":{canonical:"Frontiers in Neuroscience",aliases:["Front Neurosci"]},"frontiers in medicine":{canonical:"Frontiers in Medicine",aliases:["Front Med"]},"frontiers in public health":{canonical:"Frontiers in Public Health",aliases:["Front Public Health"]},"frontiers in endocrinology":{canonical:"Frontiers in Endocrinology",aliases:["Front Endocrinol"]},"frontiers in nutrition":{canonical:"Frontiers in Nutrition",aliases:["Front Nutr"]},oncogene:{canonical:"Oncogene",aliases:["Oncogene"]},oncogenesis:{canonical:"Oncogenesis",aliases:["Oncogenesis"]},oncotarget:{canonical:"Oncotarget",aliases:["Oncotarget"]},cancers:{canonical:"Cancers",aliases:["Cancers (Basel)"]},"journal of pathology":{canonical:"The Journal of Pathology",aliases:["J Pathol"]},"the journal of pathology":{canonical:"The Journal of Pathology",aliases:["J Pathol"]},"modern pathology":{canonical:"Modern Pathology",aliases:["Mod Pathol"]},"laboratory investigation":{canonical:"Laboratory Investigation",aliases:["Lab Invest"]},"american journal of surgical pathology":{canonical:"The American Journal of Surgical Pathology",aliases:["Am J Surg Pathol"]},"the american journal of surgical pathology":{canonical:"The American Journal of Surgical Pathology",aliases:["Am J Surg Pathol"]},histopathology:{canonical:"Histopathology",aliases:["Histopathology"]},"virchows archiv":{canonical:"Virchows Archiv",aliases:["Virchows Arch"]},"human pathology":{canonical:"Human Pathology",aliases:["Hum Pathol"]},"nature medicine new york":{canonical:"Nature Medicine",aliases:["Nat Med"]},"plos medicine":{canonical:"PLOS Medicine",aliases:["PLoS Med"]},"plos biology":{canonical:"PLOS Biology",aliases:["PLoS Biol"]},"plos genetics":{canonical:"PLOS Genetics",aliases:["PLoS Genet"]},"plos computational biology":{canonical:"PLOS Computational Biology",aliases:["PLoS Comput Biol"]},"plos pathogens":{canonical:"PLOS Pathogens",aliases:["PLoS Pathog"]},"plos neglected tropical diseases":{canonical:"PLOS Neglected Tropical Diseases",aliases:["PLoS Negl Trop Dis"]},"plos one":{canonical:"PLOS ONE",aliases:["PLoS One","PLoS ONE"]},elife:{canonical:"eLife",aliases:["eLife"]},"bmj open":{canonical:"BMJ Open",aliases:["BMJ Open"]},"bmj medicine":{canonical:"BMJ Medicine",aliases:["BMJ Med"]},"bmj global health":{canonical:"BMJ Global Health",aliases:["BMJ Glob Health"]},"annals of internal medicine":{canonical:"Annals of Internal Medicine",aliases:["Ann Intern Med"]},"archives of internal medicine":{canonical:"Archives of Internal Medicine",aliases:["Arch Intern Med","JAMA Intern Med"]},"jama internal medicine":{canonical:"JAMA Internal Medicine",aliases:["JAMA Intern Med"]},"jama oncology":{canonical:"JAMA Oncology",aliases:["JAMA Oncol"]},"jama neurology":{canonical:"JAMA Neurology",aliases:["JAMA Neurol"]},"jama cardiology":{canonical:"JAMA Cardiology",aliases:["JAMA Cardiol"]},"jama surgery":{canonical:"JAMA Surgery",aliases:["JAMA Surg"]},"jama pediatrics":{canonical:"JAMA Pediatrics",aliases:["JAMA Pediatr"]},"jama ophthalmology":{canonical:"JAMA Ophthalmology",aliases:["JAMA Ophthalmol"]},circulation:{canonical:"Circulation",aliases:["Circulation"]},"journal of the american college of cardiology":{canonical:"Journal of the American College of Cardiology",aliases:["J Am Coll Cardiol","JACC"]},jacc:{canonical:"Journal of the American College of Cardiology",aliases:["J Am Coll Cardiol","Journal of the American College of Cardiology"]},"european heart journal":{canonical:"European Heart Journal",aliases:["Eur Heart J"]},"circulation research":{canonical:"Circulation Research",aliases:["Circ Res"]},"nature cardiovascular research":{canonical:"Nature Cardiovascular Research",aliases:["Nat Cardiovasc Res"]},"european respiratory journal":{canonical:"European Respiratory Journal",aliases:["Eur Respir J"]},"american journal of respiratory and critical care medicine":{canonical:"American Journal of Respiratory and Critical Care Medicine",aliases:["Am J Respir Crit Care Med"]},chest:{canonical:"Chest",aliases:["Chest"]},thorax:{canonical:"Thorax",aliases:["Thorax"]},diabetes:{canonical:"Diabetes",aliases:["Diabetes"]},diabetologia:{canonical:"Diabetologia",aliases:["Diabetologia"]},"the lancet planetary health":{canonical:"The Lancet Planetary Health",aliases:["Lancet Planet Health"]},stroke:{canonical:"Stroke",aliases:["Stroke"]},neurology:{canonical:"Neurology",aliases:["Neurology"]},brain:{canonical:"Brain",aliases:["Brain"]},"annals of neurology":{canonical:"Annals of Neurology",aliases:["Ann Neurol"]},"acta neuropathologica":{canonical:"Acta Neuropathologica",aliases:["Acta Neuropathol"]},"kidney international":{canonical:"Kidney International",aliases:["Kidney Int"]},"journal of the american society of nephrology":{canonical:"Journal of the American Society of Nephrology",aliases:["J Am Soc Nephrol","JASN"]},jasn:{canonical:"Journal of the American Society of Nephrology",aliases:["J Am Soc Nephrol","Journal of the American Society of Nephrology"]},hepatology:{canonical:"Hepatology",aliases:["Hepatology"]},"journal of hepatology":{canonical:"Journal of Hepatology",aliases:["J Hepatol"]},"american journal of transplantation":{canonical:"American Journal of Transplantation",aliases:["Am J Transplant","AJT"]},ajt:{canonical:"American Journal of Transplantation",aliases:["Am J Transplant"]},transplantation:{canonical:"Transplantation",aliases:["Transplantation"]},"arthritis and rheumatology":{canonical:"Arthritis & Rheumatology",aliases:["Arthritis Rheumatol","Arthritis Rheum"]},"annals of the rheumatic diseases":{canonical:"Annals of the Rheumatic Diseases",aliases:["Ann Rheum Dis"]},"journal of allergy and clinical immunology":{canonical:"Journal of Allergy and Clinical Immunology",aliases:["J Allergy Clin Immunol","JACI"]},jaci:{canonical:"Journal of Allergy and Clinical Immunology",aliases:["J Allergy Clin Immunol"]},"clinical infectious diseases":{canonical:"Clinical Infectious Diseases",aliases:["Clin Infect Dis"]},"the journal of infectious diseases":{canonical:"The Journal of Infectious Diseases",aliases:["J Infect Dis"]},"journal of virology":{canonical:"Journal of Virology",aliases:["J Virol"]},"infection and immunity":{canonical:"Infection and Immunity",aliases:["Infect Immun"]},microbiology:{canonical:"Microbiology",aliases:["Microbiology"]},mbio:{canonical:"mBio",aliases:["mBio"]},"cell host and microbe":{canonical:"Cell Host & Microbe",aliases:["Cell Host Microbe"]},"trends in microbiology":{canonical:"Trends in Microbiology",aliases:["Trends Microbiol"]},"molecular microbiology":{canonical:"Molecular Microbiology",aliases:["Mol Microbiol"]},"cell reports":{canonical:"Cell Reports",aliases:["Cell Rep"]},"cell reports medicine":{canonical:"Cell Reports Medicine",aliases:["Cell Rep Med"]},iscience:{canonical:"iScience",aliases:["iScience"]},"signal transduction and targeted therapy":{canonical:"Signal Transduction and Targeted Therapy",aliases:["Signal Transduct Target Ther"]},"cell discovery":{canonical:"Cell Discovery",aliases:["Cell Discov"]},"protein and cell":{canonical:"Protein & Cell",aliases:["Protein Cell"]},"national science review":{canonical:"National Science Review",aliases:["Natl Sci Rev","NSR"]},"science bulletin":{canonical:"Science Bulletin",aliases:["Sci Bull"]},"medical journal of australia":{canonical:"Medical Journal of Australia",aliases:["Med J Aust"]},"canadian medical association journal":{canonical:"Canadian Medical Association Journal",aliases:["CMAJ","Can Med Assoc J"]},cmaj:{canonical:"Canadian Medical Association Journal",aliases:["Can Med Assoc J","Canadian Medical Association Journal"]},"deutsches arzteblatt international":{canonical:"Deutsches Arzteblatt International",aliases:["Dtsch Arztebl Int"]},"bmc medicine":{canonical:"BMC Medicine",aliases:["BMC Med"]},"systematic reviews":{canonical:"Systematic Reviews",aliases:["Syst Rev"]},trials:{canonical:"Trials",aliases:["Trials"]},peerj:{canonical:"PeerJ",aliases:["PeerJ"]},"scientific reports":{canonical:"Scientific Reports",aliases:["Sci Rep"]},heliyon:{canonical:"Heliyon",aliases:["Heliyon"]},"communications biology":{canonical:"Communications Biology",aliases:["Commun Biol"]},"communications medicine":{canonical:"Communications Medicine",aliases:["Commun Med"]},"cell systems":{canonical:"Cell Systems",aliases:["Cell Syst"]},"molecular systems biology":{canonical:"Molecular Systems Biology",aliases:["Mol Syst Biol"]},"nature methods new york":{canonical:"Nature Methods",aliases:["Nat Methods"]},bioinformatics:{canonical:"Bioinformatics",aliases:["Bioinformatics"]},"briefings in bioinformatics":{canonical:"Briefings in Bioinformatics",aliases:["Brief Bioinform"]},"nucleic acids research":{canonical:"Nucleic Acids Research",aliases:["Nucleic Acids Res","NAR"]},nar:{canonical:"Nucleic Acids Research",aliases:["Nucleic Acids Res"]},"biochimica et biophysica acta":{canonical:"Biochimica et Biophysica Acta",aliases:["Biochim Biophys Acta","BBA"]},"journal of molecular biology":{canonical:"Journal of Molecular Biology",aliases:["J Mol Biol"]},"trends in biochemical sciences":{canonical:"Trends in Biochemical Sciences",aliases:["Trends Biochem Sci"]},"trends in cell biology":{canonical:"Trends in Cell Biology",aliases:["Trends Cell Biol"]},"trends in genetics":{canonical:"Trends in Genetics",aliases:["Trends Genet"]},"trends in molecular medicine":{canonical:"Trends in Molecular Medicine",aliases:["Trends Mol Med"]},"trends in pharmacological sciences":{canonical:"Trends in Pharmacological Sciences",aliases:["Trends Pharmacol Sci"]},"trends in cancer":{canonical:"Trends in Cancer",aliases:["Trends Cancer"]},"pharmacological reviews":{canonical:"Pharmacological Reviews",aliases:["Pharmacol Rev"]},"annual review of immunology":{canonical:"Annual Review of Immunology",aliases:["Annu Rev Immunol"]},"annual review of biochemistry":{canonical:"Annual Review of Biochemistry",aliases:["Annu Rev Biochem"]},"annual review of cell and developmental biology":{canonical:"Annual Review of Cell and Developmental Biology",aliases:["Annu Rev Cell Dev Biol"]},"annual review of genetics":{canonical:"Annual Review of Genetics",aliases:["Annu Rev Genet"]},"annual review of medicine":{canonical:"Annual Review of Medicine",aliases:["Annu Rev Med"]},"annual review of pathology":{canonical:"Annual Review of Pathology",aliases:["Annu Rev Pathol"]},"annual review of neuroscience":{canonical:"Annual Review of Neuroscience",aliases:["Annu Rev Neurosci"]},"annual review of pharmacology and toxicology":{canonical:"Annual Review of Pharmacology and Toxicology",aliases:["Annu Rev Pharmacol Toxicol"]},"current biology":{canonical:"Current Biology",aliases:["Curr Biol"]},genetics:{canonical:"Genetics",aliases:["Genetics"]},genomics:{canonical:"Genomics",aliases:["Genomics"]},"human molecular genetics":{canonical:"Human Molecular Genetics",aliases:["Hum Mol Genet"]},"human genetics":{canonical:"Human Genetics",aliases:["Hum Genet"]},"genetic epidemiology":{canonical:"Genetic Epidemiology",aliases:["Genet Epidemiol"]},"statistical genetics":{canonical:"Statistical Genetics",aliases:[]},bioethics:{canonical:"Bioethics",aliases:["Bioethics"]},"jama network open":{canonical:"JAMA Network Open",aliases:["JAMA Netw Open"]},"annals of surgery":{canonical:"Annals of Surgery",aliases:["Ann Surg"]},"clinical gastroenterology and hepatology":{canonical:"Clinical Gastroenterology and Hepatology",aliases:["Clin Gastroenterol Hepatol"]},"the lancet public health":{canonical:"The Lancet Public Health",aliases:["Lancet Public Health"]}}));function ji(r){const e=r.trim().toLowerCase();if(!e||e.length<2)return null;const t=uf.get(e);if(t)return{entry:t,confidence:.98};for(const[,n]of uf){if(n.canonical.toLowerCase()===e)return{entry:n,confidence:.98};if(n.aliases.some(a=>a.toLowerCase()===e))return{entry:n,confidence:.95}}return null}function Bl(r){return Kw([r.canonical,...r.aliases]).filter(Boolean)}function Kw(r){return Array.from(new Set(r.filter(Boolean)))}function Il(r){return/^10\.\d{4,}\/[^\s]+$/.test(r.trim())}function Ml(r){const t=r.trim().match(/^(?:PMID:\s*)?(\d{6,8})$/i);return t?{isValid:!0,pmid:t[1]}:{isValid:!1,pmid:null}}const ql=new Set(["head and neck cancer","quality of life","signs and symptoms","research and development"]),df=new Set(["a","an","and","are","as","at","be","by","for","from","in","into","is","of","on","or","that","the","their","this","to","use","using","via","with","without"]),Qw=new Set(["study","studies","analysis","method","methods","approach","approaches","factors","factor","effect","effects","result","results","data","review","reviews","report","reports","case","cases","cells","cell","tissue","tissues","sample","samples","patients","patient","group","groups","model","models","role","impact","association","relationship","correlation","evidence","finding","findings","outcome","outcomes","level","levels","type","types","form","forms","base","based","use","using","used","new","novel"]),Xw=new Set(["cell","cancer","diabetes"]),pf=[{key:"colorectal-cancer",label:"colorectal cancer",patterns:[/\bcrc\b/i,/\bcolorectal cancer\b/i,/\bcolorectal neoplasms?\b/i,/\bcolon cancer\b/i,/\brectal cancer\b/i],titleAbstractTerms:["colorectal cancer","CRC","colorectal neoplasms","colon cancer","rectal cancer"],meshTerms:["Colorectal Neoplasms"],note:"Expanded a common colorectal cancer synonym / abbreviation bucket.",domains:["colorectal"]},{key:"gastric-cancer",label:"gastric cancer",patterns:[/\bgastric cancer\b/i,/\bstomach cancer\b/i,/\bgastric neoplasms?\b/i,/\bstomach neoplasms?\b/i,/\bgastric carcinoma\b/i],titleAbstractTerms:["gastric cancer","stomach cancer","gastric neoplasms","stomach neoplasms","gastric carcinoma"],meshTerms:["Stomach Neoplasms"],note:"Expanded gastric / stomach cancer wording into one organ-consistent bucket.",domains:["gastric"]},{key:"pancreatic-cancer",label:"pancreatic cancer",patterns:[/\bpancreatic cancer\b/i,/\bpancreatic neoplasms?\b/i,/\bpancreatic carcinoma\b/i,/\bpancreas cancer\b/i],titleAbstractTerms:["pancreatic cancer","pancreatic neoplasms","pancreatic carcinoma","pancreas cancer"],meshTerms:["Pancreatic Neoplasms"],note:"Expanded pancreatic cancer wording without crossing into other GI organs.",domains:["pancreatic"]},{key:"hepatocellular-carcinoma",label:"hepatocellular carcinoma",patterns:[/\bhcc\b/i,/\bhepatocellular carcinoma\b/i,/\bliver cancer\b/i,/\bhepatic cancer\b/i],titleAbstractTerms:["hepatocellular carcinoma","HCC","liver cancer","hepatic cancer"],meshTerms:["Carcinoma, Hepatocellular"],note:"Expanded HCC / liver cancer wording into a liver-specific bucket.",domains:["liver"]},{key:"breast-cancer",label:"breast cancer",patterns:[/\bbreast cancer\b/i,/\bbreast neoplasms?\b/i,/\bmammary carcinoma\b/i],titleAbstractTerms:["breast cancer","breast neoplasms","mammary carcinoma"],meshTerms:["Breast Neoplasms"],note:"Expanded breast cancer wording into a breast-specific bucket.",domains:["breast"]},{key:"lung-cancer",label:"lung cancer",patterns:[/\blung cancer\b/i,/\blung neoplasms?\b/i,/\bnsclc\b/i,/\bnon-small cell lung cancer\b/i,/\bsmall cell lung cancer\b/i],titleAbstractTerms:["lung cancer","lung neoplasms","NSCLC","non-small cell lung cancer","small cell lung cancer"],meshTerms:["Lung Neoplasms"],note:"Expanded lung cancer wording into a thoracic-oncology bucket.",domains:["lung"]},{key:"melanoma",label:"melanoma",patterns:[/\bmelanoma\b/i,/\bcutaneous melanoma\b/i],titleAbstractTerms:["melanoma","cutaneous melanoma"],meshTerms:["Melanoma"],note:"Expanded melanoma wording while keeping skin-oncology scope isolated.",domains:["melanoma"]},{key:"prostate-cancer",label:"prostate cancer",patterns:[/\bprostate cancer\b/i,/\bprostatic neoplasms?\b/i,/\bprostate neoplasms?\b/i,/\bprostate carcinoma\b/i],titleAbstractTerms:["prostate cancer","prostatic neoplasms","prostate neoplasms","prostate carcinoma"],meshTerms:["Prostatic Neoplasms"],note:"Expanded prostate cancer wording into a prostate-specific oncology bucket."},{key:"generic-cancer",label:"cancer",patterns:[/\bcancer\b/i,/\bcancers\b/i,/\bneoplasm(?:s)?\b/i,/\btumo(?:r|ur)(?:s)?\b/i,/\boncology\b/i],titleAbstractTerms:["cancer","cancers","neoplasm","neoplasms","tumor","tumors","tumour","tumours","oncology"],meshTerms:["Neoplasms"],note:"Preserved a generic cancer / oncology anchor so broad disease framing is not lost during method-oriented expansion."},{key:"ibd",label:"inflammatory bowel disease",patterns:[/\bibd\b/i,/\binflammatory bowel disease\b/i,/\bulcerative colitis\b/i,/\bcrohn'?s disease\b/i],titleAbstractTerms:["inflammatory bowel disease","IBD","ulcerative colitis","Crohn's disease"],meshTerms:["Inflammatory Bowel Diseases","Colitis, Ulcerative","Crohn Disease"],note:"Expanded IBD wording into a bowel-inflammatory disease bucket.",domains:["ibd"]},{key:"diabetes",label:"diabetes",patterns:[/\bdiabetes\b/i,/\bdiabetes mellitus\b/i,/\btype 1 diabetes\b/i,/\btype 2 diabetes\b/i,/\bt1d\b/i,/\bt2d\b/i],titleAbstractTerms:["diabetes","diabetes mellitus","type 1 diabetes","type 2 diabetes","T1D","T2D"],meshTerms:["Diabetes Mellitus","Diabetes Mellitus, Type 1","Diabetes Mellitus, Type 2"],note:"Expanded diabetes wording into a disease-specific metabolic bucket."},{key:"screening",label:"screening",patterns:[/\bscreen(?:ing)?\b/i,/\bmass screening\b/i],titleAbstractTerms:["screening","mass screening"],meshTerms:["Mass Screening","Early Detection of Cancer"],note:"Keeps generic screening intent separate from organ-specific screening modalities."},{key:"surveillance",label:"surveillance",patterns:[/\bsurveillance\b/i,/\bmonitoring\b/i,/\bfollow-up\b/i],titleAbstractTerms:["surveillance","monitoring","follow-up"],meshTerms:[],note:"Keeps surveillance / monitoring intent as its own retrieval bucket."},{key:"colorectal-screening-modality",label:"colorectal screening modality",patterns:[/\bcolonoscopy\b/i,/\bfit\b/i,/\bfecal immunochemical test\b/i,/\bstool-based test\b/i,/\bstool dna\b/i,/\bfecal dna\b/i],titleAbstractTerms:["colonoscopy","FIT","fecal immunochemical test","stool-based test","stool DNA","fecal DNA"],meshTerms:["Colonoscopy"],note:"Groups colorectal-specific screening modalities so they are never injected by a generic screening intent alone.",domains:["colorectal"]},{key:"early-onset",label:"early-onset",patterns:[/\bearly[- ]onset\b/i,/\byoung[- ]onset\b/i,/\bunder 50\b/i,/\bbefore age 50\b/i,/\byounger adults?\b/i],titleAbstractTerms:["early-onset","young-onset","under 50","before age 50","younger adults"],meshTerms:["Age of Onset"],note:"Expanded age-at-onset wording into one explainable bucket."},{key:"liquid-biopsy",label:"liquid biopsy",patterns:[/\bliquid biopsy\b/i,/\bctdna\b/i,/\bcfdna\b/i,/\bcirculating tumor dna\b/i,/\bcell[- ]free dna\b/i],titleAbstractTerms:["liquid biopsy","ctDNA","cfDNA","circulating tumor DNA","cell-free DNA"],meshTerms:["Liquid Biopsy","DNA, Circulating","Cell-Free Nucleic Acids"],note:"Expanded liquid-biopsy shorthand into common circulating DNA variants."},{key:"organoid-model",label:"organoid model",patterns:[/\borganoid(s)?\b/i,/\bpatient[- ]derived organoid(s)?\b/i,/\bpdo(s)?\b/i],titleAbstractTerms:["organoid","organoids","patient-derived organoid","patient derived organoid","PDO"],meshTerms:["Organoids"],note:"Preserved organoid / patient-derived organoid wording as a model-system bucket."},{key:"early-detection",label:"early detection",patterns:[/\bearly detection\b/i,/\bearly diagnosis\b/i,/\bearly diagnostic\b/i],titleAbstractTerms:["early detection","early diagnosis"],meshTerms:["Early Detection of Cancer"],note:"Preserved the early-detection intent as a dedicated concept bucket."},{key:"microbiome",label:"microbiome",patterns:[/\bmicrobiome\b/i,/\bmicrobiota\b/i,/\bgut microbiome\b/i,/\bgut microbiota\b/i],titleAbstractTerms:["microbiome","microbiota","gut microbiome","gut microbiota"],meshTerms:["Microbiota","Gastrointestinal Microbiome"],note:"Grouped microbiome / microbiota variants together."},{key:"immunotherapy",label:"immunotherapy",patterns:[/\bimmunotherapy\b/i,/\bcheckpoint inhibitors?\b/i,/\bpd-1\b/i,/\bpd-l1\b/i,/\bctla-4\b/i,/\bpembrolizumab\b/i,/\bnivolumab\b/i,/\bipilimumab\b/i],titleAbstractTerms:["immunotherapy","checkpoint inhibitor","PD-1","PD-L1","CTLA-4","pembrolizumab","nivolumab","ipilimumab"],meshTerms:["Immunotherapy","Immune Checkpoint Inhibitors"],note:"Expanded common immunotherapy synonyms and checkpoint abbreviations."},{key:"her2-status",label:"HER2 status",patterns:[/\bher2[- ]positive\b/i,/\bher2[- ]negative\b/i,/\berbb2[- ]positive\b/i,/\berbb2[- ]negative\b/i],titleAbstractTerms:["HER2 positive","HER2 negative","HER2-positive","HER2-negative","ERBB2 positive","ERBB2 negative"],meshTerms:["Receptor, ErbB-2"],note:"Preserved HER2 status wording and linked it to the canonical ErbB-2 receptor concept."},{key:"targeted-therapy",label:"targeted therapy",patterns:[/\btargeted therapy\b/i,/\bmolecular targeted therapy\b/i,/\btargeted treatment\b/i],titleAbstractTerms:["targeted therapy","molecular targeted therapy","targeted treatment"],meshTerms:["Molecular Targeted Therapy"],note:"Expanded targeted therapy wording into the curated molecular targeted therapy bucket."},{key:"guideline",label:"guideline",patterns:[/\bguideline(s)?\b/i,/\brecommendation(s)?\b/i,/\bconsensus\b/i,/\bpolicy\b/i],titleAbstractTerms:["guideline","recommendation","consensus","policy"],meshTerms:["Practice Guidelines as Topic"],note:"Grouped guideline, recommendation, and policy language."},{key:"prevention",label:"prevention",patterns:[/\bprevention\b/i,/\bpreventive\b/i,/\brisk reduction\b/i],titleAbstractTerms:["prevention","preventive","risk reduction"],meshTerms:["Primary Prevention","Risk Reduction Behavior"],note:"Kept prevention-oriented language in its own bucket."},{key:"epidemiology",label:"epidemiology",patterns:[/\bepidemiology\b/i,/\bincidence\b/i,/\bmortality\b/i,/\bprevalence\b/i,/\btrend(s)?\b/i],titleAbstractTerms:["epidemiology","incidence","mortality","prevalence","trends"],meshTerms:["Epidemiology","Incidence","Mortality","Prevalence"],note:"Grouped epidemiology / trend-monitoring wording together."},{key:"survival",label:"survival",patterns:[/\bsurvival\b/i,/\boutcome(s)?\b/i,/\bprognos(is|tic)\b/i,/\brecurrence\b/i,/\brelapse\b/i],titleAbstractTerms:["survival","outcomes","prognosis","prognostic","recurrence","relapse"],meshTerms:["Survival Analysis","Treatment Outcome","Prognosis","Neoplasm Recurrence, Local"],note:"Grouped survival, prognosis, and recurrence wording together."},{key:"microsatellite-instability",label:"microsatellite instability",patterns:[/\bmicrosatellite instability\b/i,/\bMSI[- ]?H\b/i,/\bMSI\b/i,/\bmismatch repair\b/i,/\bdMMR\b/i,/\bpMMR\b/i],titleAbstractTerms:["microsatellite instability","MSI","MSI-H","mismatch repair","dMMR","pMMR"],meshTerms:["Microsatellite Instability"],note:"Preserved MSI / mismatch-repair wording as a molecular subtype bucket."},{key:"polygenic-risk-score",label:"polygenic risk score",patterns:[/\bpolygenic risk score(s)?\b/i,/\bpolygenic score(s)?\b/i,/\bgenetic risk score(s)?\b/i,/\bgenomic risk score(s)?\b/i,/\bgenome-wide polygenic score(s)?\b/i,/\bPRS\b/i],titleAbstractTerms:["polygenic risk score","polygenic score","genetic risk score","genomic risk score","genome-wide polygenic score","PRS"],meshTerms:[],note:"Preserved polygenic-risk-score phrasing as its own genetics anchor bucket instead of collapsing it into a generic risk-model synonym pool."},{key:"risk-stratification",label:"risk stratification",patterns:[/\brisk stratification\b/i,/\brisk-stratified\b/i,/\brisk stratified\b/i,/\brisk assessment\b/i],titleAbstractTerms:["risk stratification","risk-stratified","risk stratified","risk assessment"],meshTerms:["Risk Assessment"],note:"Preserved risk-stratification wording as an explicit must-match intent bucket rather than letting it dissolve into a generic model term."},{key:"prediction-model",label:"prediction model",patterns:[/\bprediction model(s)?\b/i,/\bpredictive model(s)?\b/i,/\brisk prediction\b/i,/\brisk model(s)?\b/i,/\brisk score(s)?\b/i,/\bprognostic model(s)?\b/i,/\bnomogram(s)?\b/i,/\bclinical prediction rule(s)?\b/i,/\bmachine learning model(s)?\b/i,/\bexternal validation\b/i,/\binternal validation\b/i,/\bmodel validation\b/i],titleAbstractTerms:["prediction model","predictive model","risk prediction","risk model","risk score","prognostic model","nomogram","clinical prediction rule","prediction tool","predictive performance","discrimination","calibration","external validation"],meshTerms:["Models, Statistical","Risk Assessment","Nomograms"],note:"Expanded prediction-model wording into common biomedical model-development and validation synonyms."},{key:"response-prediction",label:"response prediction",patterns:[/\bresponse prediction\b/i,/\bresponse predictor(s)?\b/i,/\btreatment response prediction\b/i,/\bresponse model(s)?\b/i],titleAbstractTerms:["response prediction","response predictor","treatment response prediction","response model"],meshTerms:[],note:"Preserved treatment-response prediction as a distinct execution bucket."},{key:"minimal-residual-disease",label:"minimal residual disease",patterns:[/\bminimal residual disease\b/i,/\bmeasurable residual disease\b/i,/\bMRD\b/i],titleAbstractTerms:["minimal residual disease","measurable residual disease","MRD"],meshTerms:[],note:"Preserved MRD wording as a dedicated disease-monitoring bucket."},{key:"biomarker",label:"biomarker",patterns:[/\bbiomarker(s)?\b/i,/\bsignature(s)?\b/i,/\bmethylation\b/i,/\bfragmentomics\b/i],titleAbstractTerms:["biomarker","signature","methylation","fragmentomics","cell-free DNA","ctDNA","blood-based"],meshTerms:["Biomarkers, Tumor","DNA Methylation","MicroRNAs"],note:"Expanded generic biomarker / signal terminology without injecting organ-specific assay modalities."},{key:"diagnosis",label:"diagnosis",patterns:[/\bdiagnos(is|tic)\b/i,/\bdiagnostic accuracy\b/i,/\bsensitivity\b/i,/\bspecificity\b/i,/\broc\b/i,/\bauc\b/i],titleAbstractTerms:["diagnosis","diagnostic","diagnostic accuracy","sensitivity","specificity","ROC","AUC"],meshTerms:["Diagnosis","Sensitivity and Specificity","ROC Curve"],note:"Expanded diagnostic-performance wording into common PubMed retrieval expressions."},{key:"artificial-intelligence",label:"artificial intelligence",patterns:[/\bai\b/i,/\bartificial intelligence\b/i,/\bmachine learning\b/i,/\bdeep learning\b/i,/\bneural network(s)?\b/i,/\bradiomics\b/i],titleAbstractTerms:["artificial intelligence","AI","machine learning","deep learning","neural network","radiomics"],meshTerms:["Artificial Intelligence","Machine Learning"],note:"Expanded AI / machine-learning wording into common biomedical informatics retrieval expressions."},{key:"digital-pathology",label:"digital pathology",patterns:[/\bdigital pathology\b/i,/\bcomputational pathology\b/i,/\bwhole[- ]slide imaging\b/i,/\bwhole slide\b/i,/\bWSI\b/i],titleAbstractTerms:["digital pathology","computational pathology","whole-slide imaging","whole slide imaging","WSI"],meshTerms:[],note:"Preserved digital pathology and whole-slide imaging wording as its own retrieval bucket."},{key:"high-risk-population",label:"high-risk population",patterns:[/\bhigh[- ]risk population(s)?\b/i,/\bhigh[- ]risk patient(s)?\b/i,/\belevated[- ]risk population(s)?\b/i,/\bhigh-risk group(s)?\b/i],titleAbstractTerms:["high-risk population","high-risk patients","elevated-risk population","high-risk group"],meshTerms:[],note:"Treats high-risk populations as an independent population bucket instead of a soft modifier."},{key:"asian-patients",label:"Asian patients",patterns:[/\basian patient(s)?\b/i,/\basian population(s)?\b/i,/\basian cohort(s)?\b/i],titleAbstractTerms:["Asian patients","Asian population","Asian cohort"],meshTerms:[],note:"Treats Asian populations as an independent population bucket."},{key:"primary-care",label:"primary care",patterns:[/\bprimary care\b/i,/\bcommunity setting\b/i,/\bambulatory care\b/i],titleAbstractTerms:["primary care","community setting","ambulatory care"],meshTerms:["Primary Health Care"],note:"Treats care setting language as its own setting bucket."},{key:"imaging",label:"imaging",patterns:[/\bimaging\b/i,/\bradiolog(y|ic)\b/i,/\bmri\b/i,/\bmagnetic resonance\b/i,/\bct\b/i,/\bcomputed tomography\b/i,/\bultrasound\b/i,/\bmammograph(y|ic)\b/i],titleAbstractTerms:["imaging","radiology","MRI","magnetic resonance imaging","CT","computed tomography","ultrasound","mammography"],meshTerms:["Diagnostic Imaging"],note:"Expanded explicit imaging wording into standard PubMed imaging expressions without adding new disease anchors."},{key:"randomized-trial",label:"randomized controlled trial",patterns:[/\brandomized controlled trial\b/i,/\brandomised controlled trial\b/i,/\brandomized trial\b/i,/\bclinical trial\b/i,/\bdouble-blind\b/i,/\bplacebo-controlled\b/i],titleAbstractTerms:["randomized controlled trial","randomised controlled trial","randomized trial","clinical trial","double-blind","placebo-controlled"],meshTerms:["Randomized Controlled Trials as Topic","Clinical Trials as Topic"],note:"Expanded randomized / interventional trial wording into a broader clinical-trial bucket."}],hf=new Set(["colorectal-cancer","gastric-cancer","pancreatic-cancer","hepatocellular-carcinoma","breast-cancer","lung-cancer","melanoma","prostate-cancer"]),eT=new Set(["control","disease","effect","effects","result","results","outcome","outcomes","study","review","trial","analysis","medicine","genome","nature","science","screening","therapy","detection","risk","patient","treatment","journal"]);function be(r){return r.replace(/\s+/g," ").trim()}function jl(r){return r.toLowerCase().split(/[^a-z0-9-]+/).map(e=>e.trim()).filter(e=>e.length>=2)}function ne(r){return Array.from(new Set(r.filter(Boolean)))}function $i(r,e=!1){const t=new Set,n=be(r);return t.add(n),e||(n.includes("-")&&t.add(n.replace(/-/g," ")),n.includes("/")&&!e&&n.split("/").map(a=>a.trim()).filter(a=>a.length>=2).forEach(a=>t.add(a)),/^[A-Z]{2,8}$/.test(n)&&t.add(n.toUpperCase())),Array.from(t)}function ff(r,e){return hf.has(r)||r==="generic-cancer"||r==="ibd"||r==="diabetes"?"disease":["screening","early-detection","surveillance","diagnosis","risk-stratification","response-prediction"].includes(r)?"intent":["colorectal-screening-modality","liquid-biopsy","imaging","artificial-intelligence","digital-pathology","organoid-model"].includes(r)?"modality":["biomarker","microbiome","her2-status","microsatellite-instability"].includes(r)?"biomarker":["high-risk-population","asian-patients","early-onset"].includes(r)?"population":["primary-care"].includes(r)?"setting":["survival","prediction-model","polygenic-risk-score","minimal-residual-disease"].includes(r)?"outcome":["immunotherapy","targeted-therapy"].includes(r)?"modality":/\bpatients?\b|\bpopulation\b|\bcohort\b/i.test(e)?"population":/\bcare\b|\bsetting\b/i.test(e)?"setting":"literal"}const tT=[{domain:"colorectal",patterns:[/\bcrc\b/i,/\bcolorectal\b/i,/\bcolon\b/i,/\brectal\b/i]},{domain:"gastric",patterns:[/\bgastric\b/i,/\bstomach\b/i]},{domain:"pancreatic",patterns:[/\bpancrea(?:tic|s)\b/i]},{domain:"liver",patterns:[/\bhcc\b/i,/\bhepatocellular\b/i,/\bliver cancer\b/i,/\bhepatic\b/i]},{domain:"breast",patterns:[/\bbreast cancer\b/i,/\bbreast neoplasm\b/i,/\bmammograph\w*\b/i]},{domain:"lung",patterns:[/\blung cancer\b/i,/\bnsclc\b/i,/\bsmall cell lung\b/i]},{domain:"melanoma",patterns:[/\bmelanoma\b/i]},{domain:"ibd",patterns:[/\bibd\b/i,/\binflammatory bowel disease\b/i,/\bulcerative colitis\b/i,/\bcrohn'?s\b/i]}];function nT(r){const e=new Set;return r.forEach(t=>{const n=be(t??"");n&&(tT.forEach(a=>{a.patterns.some(i=>i.test(n))&&e.add(a.domain)}),pf.forEach(a=>{!a.domains||a.domains.length===0||a.patterns.some(i=>i.test(n))&&a.domains.forEach(i=>e.add(i))}))}),e}function rT(r,e){return!r.domains||r.domains.length===0||e.size===0?!0:r.domains.some(t=>e.has(t))}function aT(r,e){let t=Number.MAX_SAFE_INTEGER;for(const n of r.patterns){const a=e.match(n);a?.index!==void 0&&(t=Math.min(t,a.index))}return t===Number.MAX_SAFE_INTEGER?0:t}function iT(r){return r.replace(/\b([a-z])/g,e=>e.toUpperCase())}function mf(r){return[/\bcancer\b/i,/\bneoplasm\b/i,/\bcolon\b/i,/\brectal\b/i,/\bcolorectal\b/i,/\btumor\b/i,/\btumour\b/i,/\boncology\b/i,/\bmalignan\b/i].some(t=>t.test(r))}function oT(r,e){if(!e.some(i=>i.key==="colorectal-cancer"))return!1;const n=r.trim();return/^crc$/i.test(n)?!mf(n):!1}function bf(r){const e=new Map,t=r.filter(n=>n.kind!=="author"&&n.kind!=="journal"&&!n.isDoi&&!n.isPmid&&!n.isLiteralBoolean);return t.forEach(n=>{if(n.matchedRules.length===0){const o=`literal:${n.cleaned.toLowerCase()}`,s=e.get(o),l=$i(n.cleaned),c=n.cleaned.includes(" ")&&!ql.has(n.cleaned.toLowerCase())?jl(n.cleaned).filter(p=>p.length>=3&&!l.includes(p)&&!Qw.has(p)&&!df.has(p)):[],u=ne([...l,...c]),d={key:o,label:iT(n.cleaned.toLowerCase()),anchor:n.cleaned,normalizedAnchor:n.cleaned.toLowerCase(),source:n.source==="builder"?"user_explicit":"auto_discovered",category:ff(o,n.cleaned),mustMatch:!0,confidence:.7,literalTerms:l,synonymTerms:[],abbreviationTerms:l.filter(p=>/^[A-Z0-9-]{2,10}$/.test(p)),titleAbstractTerms:u,meshTerms:[],sourceTerms:[n.cleaned],clause:"",note:"Kept the literal phrase because no curated synonym rule matched it.",usedInRecommendedQuery:!1};!s||n.priority<s.priority?e.set(o,{concept:d,priority:n.priority,order:n.order}):(s.concept.sourceTerms=ne([...s.concept.sourceTerms,n.cleaned]),s.concept.titleAbstractTerms=ne([...s.concept.titleAbstractTerms,...d.titleAbstractTerms]),s.concept.literalTerms=ne([...s.concept.literalTerms,...l]),s.order=Math.min(s.order,n.order));return}const a=oT(n.cleaned,n.matchedRules),i=mf(t.map(o=>o.cleaned).join(" "));n.matchedRules.forEach(o=>{const s=e.get(o.key),l=new Set(["cancer","cancers","neoplasm","neoplasms","tumor","tumors","tumour","tumours","oncology"]),c=o.key==="generic-cancer"&&jl(n.cleaned).some(C=>!l.has(C)),u=n.cleaned.length>o.label.length*2&&!c?o.label:n.cleaned,d=be(u),p=$i(d),h=ne([...o.titleAbstractTerms.filter(C=>/^[A-Z0-9-]{2,10}$/.test(C)),...p.filter(C=>/^[A-Z0-9-]{2,10}$/.test(C))]),f=ne(o.titleAbstractTerms.filter(C=>!p.includes(C)&&!h.includes(C))),y=n.order*1e3+aT(o,n.cleaned),x=ne([...p,...o.titleAbstractTerms]),T=o.key==="colorectal-cancer",E=T&&a&&!i,w=E?.6:.95;let v=o.note;T&&(E?v=`CRC interpreted as colorectal cancer, but confidence lowered due to lack of cancer context (could also mean Clinical Research Center, Cyclic Redundancy Check, etc.). ${o.note}`:v=`CRC expanded to colorectal cancer. ${o.note}`);const g={key:o.key,label:o.label,anchor:d,normalizedAnchor:d.toLowerCase(),source:n.source==="builder"?"user_explicit":"auto_discovered",category:ff(o.key,d),mustMatch:!0,confidence:w,literalTerms:p,synonymTerms:f,abbreviationTerms:h,titleAbstractTerms:x,meshTerms:o.meshTerms,sourceTerms:[d],clause:"",note:`${v} Preserved the user's original anchor phrase alongside broader synonym expansion.`,usedInRecommendedQuery:!1};!s||n.priority<s.priority?e.set(o.key,{concept:g,priority:n.priority,order:y}):(s.concept.sourceTerms=ne([...s.concept.sourceTerms,d]),s.concept.titleAbstractTerms=ne([...s.concept.titleAbstractTerms,...x]),s.concept.literalTerms=ne([...s.concept.literalTerms,...p]),s.concept.synonymTerms=ne([...s.concept.synonymTerms,...f]),s.concept.abbreviationTerms=ne([...s.concept.abbreviationTerms,...h]),s.order=Math.min(s.order,y))})}),Array.from(e.values()).sort((n,a)=>n.priority!==a.priority?n.priority-a.priority:n.order-a.order).map(n=>n.concept)}const sT=[{value:"Adaptive Clinical Trial",labelZh:"\u9002\u5E94\u6027\u4E34\u5E8A\u8BD5\u9A8C"},{value:"Address",labelZh:"\u5730\u5740/\u81F4\u8F9E"},{value:"Autobiography",labelZh:"\u81EA\u4F20",discontinued:!0},{value:"Bibliography",labelZh:"\u4E66\u76EE",discontinued:!0},{value:"Biography",labelZh:"\u4F20\u8BB0"},{value:"Case Reports",labelZh:"\u75C5\u4F8B\u62A5\u544A"},{value:"Clinical Conference",labelZh:"\u4E34\u5E8A\u4F1A\u8BAE",discontinued:!0},{value:"Clinical Study",labelZh:"\u4E34\u5E8A\u7814\u7A76"},{value:"Clinical Trial",labelZh:"\u4E34\u5E8A\u8BD5\u9A8C"},{value:"Clinical Trial, Phase I",labelZh:"I\u671F\u4E34\u5E8A\u8BD5\u9A8C"},{value:"Clinical Trial, Phase II",labelZh:"II\u671F\u4E34\u5E8A\u8BD5\u9A8C"},{value:"Clinical Trial, Phase III",labelZh:"III\u671F\u4E34\u5E8A\u8BD5\u9A8C"},{value:"Clinical Trial, Phase IV",labelZh:"IV\u671F\u4E34\u5E8A\u8BD5\u9A8C"},{value:"Clinical Trial Protocol",labelZh:"\u4E34\u5E8A\u8BD5\u9A8C\u65B9\u6848"},{value:"Clinical Trial, Veterinary",labelZh:"\u517D\u533B\u5B66\u4E34\u5E8A\u8BD5\u9A8C"},{value:"Collected Work",labelZh:"\u6587\u96C6"},{value:"Comment",labelZh:"\u8BC4\u8BBA"},{value:"Comparative Study",labelZh:"\u6BD4\u8F83\u7814\u7A76"},{value:"Conference Proceedings",labelZh:"\u4F1A\u8BAE\u8BBA\u6587\u96C6"},{value:"Consensus Statement",labelZh:"\u5171\u8BC6\u58F0\u660E"},{value:"Consensus Development Conference, NIH",labelZh:"NIH\u5171\u8BC6\u53D1\u5C55\u4F1A\u8BAE",discontinued:!0},{value:"Controlled Clinical Trial",labelZh:"\u5BF9\u7167\u4E34\u5E8A\u8BD5\u9A8C"},{value:"Corrected and Republished Article",labelZh:"\u66F4\u6B63\u540E\u91CD\u53D1\u6587\u7AE0"},{value:"Dataset",labelZh:"\u6570\u636E\u96C6"},{value:"Dictionary",labelZh:"\u8BCD\u5178",discontinued:!0},{value:"Directory",labelZh:"\u540D\u5F55",discontinued:!0},{value:"Duplicate Publication",labelZh:"\u91CD\u590D\u53D1\u8868"},{value:"Editorial",labelZh:"\u793E\u8BBA"},{value:"Electronic Supplementary Materials",labelZh:"\u7535\u5B50\u8865\u5145\u6750\u6599"},{value:"English Abstract",labelZh:"\u82F1\u6587\u6458\u8981"},{value:"Equivalence Trial",labelZh:"\u7B49\u6548\u6027\u8BD5\u9A8C"},{value:"Evaluation Study",labelZh:"\u8BC4\u4F30\u7814\u7A76"},{value:"Evidence Synthesis",labelZh:"\u8BC1\u636E\u7EFC\u5408"},{value:"Expression of Concern",labelZh:"\u5173\u6CE8\u58F0\u660E"},{value:"Festschrift",labelZh:"\u7EAA\u5FF5\u6587\u96C6"},{value:"Government Publication",labelZh:"\u653F\u5E9C\u51FA\u7248\u7269",discontinued:!0},{value:"Guideline",labelZh:"\u6307\u5357"},{value:"Historical Article",labelZh:"\u5386\u53F2\u6587\u7AE0"},{value:"Interactive Tutorial",labelZh:"\u4E92\u52A8\u6559\u7A0B",discontinued:!0},{value:"Interview",labelZh:"\u8BBF\u8C08"},{value:"Introductory Journal Article",labelZh:"\u671F\u520A\u5BFC\u8BFB"},{value:"Journal Article",labelZh:"\u671F\u520A\u6587\u7AE0"},{value:"Lecture",labelZh:"\u8BB2\u5EA7"},{value:"Legal Case",labelZh:"\u6CD5\u5F8B\u6848\u4F8B",discontinued:!0},{value:"Legislation",labelZh:"\u7ACB\u6CD5",discontinued:!0},{value:"Letter",labelZh:"\u901A\u8BAF"},{value:"Meta-Analysis",labelZh:"\u835F\u8403\u5206\u6790"},{value:"Multicenter Study",labelZh:"\u591A\u4E2D\u5FC3\u7814\u7A76"},{value:"Network Meta-Analysis",labelZh:"\u7F51\u7EDC\u835F\u8403\u5206\u6790"},{value:"News",labelZh:"\u65B0\u95FB"},{value:"Newspaper Article",labelZh:"\u62A5\u7EB8\u6587\u7AE0",discontinued:!0},{value:"Observational Study",labelZh:"\u89C2\u5BDF\u6027\u7814\u7A76"},{value:"Observational Study, Veterinary",labelZh:"\u517D\u533B\u5B66\u89C2\u5BDF\u6027\u7814\u7A76"},{value:"Overall",labelZh:"\u603B\u4F53",discontinued:!0},{value:"Patient Education Handout",labelZh:"\u60A3\u8005\u6559\u80B2\u624B\u518C"},{value:"Periodical Index",labelZh:"\u671F\u520A\u7D22\u5F15",discontinued:!0},{value:"Personal Narrative",labelZh:"\u4E2A\u4EBA\u53D9\u8FF0"},{value:"Portrait",labelZh:"\u4EBA\u7269\u8096\u50CF",discontinued:!0},{value:"Practice Guideline",labelZh:"\u5B9E\u8DF5\u6307\u5357"},{value:"Pragmatic Clinical Trial",labelZh:"\u5B9E\u7528\u6027\u4E34\u5E8A\u8BD5\u9A8C"},{value:"Preprint",labelZh:"\u9884\u5370\u672C"},{value:"Published Erratum",labelZh:"\u5DF2\u53D1\u8868\u52D8\u8BEF"},{value:"Randomized Controlled Trial",labelZh:"\u968F\u673A\u5BF9\u7167\u8BD5\u9A8C"},{value:"Randomized Controlled Trial, Veterinary",labelZh:"\u517D\u533B\u5B66\u968F\u673A\u5BF9\u7167\u8BD5\u9A8C"},{value:"Research Support, American Recovery and Reinvestment Act",labelZh:"\u7F8E\u56FD\u590D\u82CF\u4E0E\u518D\u6295\u8D44\u6CD5\u6848\u8D44\u52A9\u7814\u7A76"},{value:"Research Support, N.I.H., Extramural",labelZh:"NIH\u6821\u5916\u8D44\u52A9\u7814\u7A76"},{value:"Research Support, N.I.H., Intramural",labelZh:"NIH\u6821\u5185\u8D44\u52A9\u7814\u7A76"},{value:"Research Support, Non-U.S. Gov't",labelZh:"\u975E\u7F8E\u56FD\u653F\u5E9C\u8D44\u52A9\u7814\u7A76"},{value:"Research Support, U.S. Gov't, Non-P.H.S.",labelZh:"\u7F8E\u56FD\u653F\u5E9C\u975E\u516C\u5171\u536B\u751F\u670D\u52A1\u8D44\u52A9\u7814\u7A76"},{value:"Research Support, U.S. Gov't, P.H.S.",labelZh:"\u7F8E\u56FD\u653F\u5E9C\u516C\u5171\u536B\u751F\u670D\u52A1\u8D44\u52A9\u7814\u7A76"},{value:"Retracted Publication",labelZh:"\u64A4\u7A3F\u6587\u7AE0"},{value:"Retraction Notice",labelZh:"\u64A4\u7A3F\u901A\u77E5"},{value:"Review",labelZh:"\u7EFC\u8FF0"},{value:"Scientific Integrity Review",labelZh:"\u79D1\u5B66\u8BDA\u4FE1\u5BA1\u67E5",discontinued:!0},{value:"Scoping Review",labelZh:"\u8303\u56F4\u7EFC\u8FF0"},{value:"Seminal Article",labelZh:"\u5F00\u521B\u6027\u6587\u7AE0",discontinued:!0},{value:"Systematic Review",labelZh:"\u7CFB\u7EDF\u7EFC\u8FF0"},{value:"Technical Report",labelZh:"\u6280\u672F\u62A5\u544A",discontinued:!0},{value:"Twin Study",labelZh:"\u53CC\u80DE\u80CE\u7814\u7A76"},{value:"Validation Study",labelZh:"\u9A8C\u8BC1\u7814\u7A76"},{value:"Video-Audio Media",labelZh:"\u97F3\u89C6\u9891\u5A92\u4F53"},{value:"Webcast",labelZh:"\u7F51\u7EDC\u76F4\u64AD"}];new Set(sT.map(r=>r.value));function lT(r){return be(r.normalize("NFKC").replace(/[“”„‟]/g,'"').replace(/[‘’‚‛]/g,"'").replace(/[‐‑‒–—―]/g,"-").replace(/[＆&]/g," and ").replace(/[／]/g,"/").replace(/[，、；·•]+/g,", ").replace(/[（）]/g," "))}function cT(r){return/[A-Za-z]/.test(r)}function gf(r){return Array.from(r.matchAll(/"([^"]{2,120})"/g)).map(e=>be(e[1]))}function uT(r){return Array.from(r.matchAll(/([A-Za-z][A-Za-z0-9\-\s]{3,80})\s+([A-Z][A-Z0-9-]{1,9})\b/g)).filter(e=>!/^(?:AND|OR|NOT)$/i.test(e[2])).flatMap(e=>[e[1],e[2]]).map(e=>be(e))}function $l(r){const e=be(r.replace(/^[\s,;:|\-]+/,"").replace(/[\s,;:|\-]+$/,"").replace(/^topic\s*:/i,"").replace(/^focus(?: area)?\s*:/i,"").replace(/^keywords?\s*:/i,"").replace(/^description\s*:/i,""));return!e||!cT(e)||jl(e).length===0||e.length<3&&!/^[A-Z]{2,6}$/.test(e)?null:e}function dT(r){return r.includes(" ")||r.includes("-")||r.includes("/")?"phrase":"keyword"}function pT(r,e,t){const n=r.matchedRules.length>0,a=ji(r.cleaned),i=Xw.has(r.cleaned.toLowerCase())||n,o=e||t;if(a&&a.confidence>=.95&&(!i||o))return{kind:"journal",metadataNote:`"${r.cleaned}" \u2192 detected as journal`,queryTerms:Bl(a.entry)};const s=qi(r.cleaned,{hasJournalSibling:e,hitsConceptRule:n});return s?{kind:"author",metadataNote:s.note,queryTerms:s.terms}:o&&a&&a.confidence>=.8?{kind:"journal",metadataNote:`"${r.cleaned}" \u2192 detected as journal (context-supported)`,queryTerms:Bl(a.entry)}:{kind:r.kind}}function yf(r){const e=be(r.toLowerCase());if(ql.has(e))return[r];if(!/\b(?:AND|OR|NOT)\b/i.test(r))return[r];if(Ul(r,["OR"]))return[r];const a=[];let i="",o=!1,s=0;for(let c=0;c<r.length;c++){const u=r[c];if(u==='"')o=!o,i+=u;else if(u==="("&&!o)s++,i+=u;else if(u===")"&&!o)s--,i+=u;else if(!o&&s===0){const d=Ol(r,c,["AND","NOT"]);if(d){const p=i.trim();p&&a.push(p),i="",c+=d.length-1}else i+=u}else i+=u}const l=i.trim();return l&&a.push(l),a.length>0?a:[r]}function hT(r){return/\[[^\]]+\]/.test(r)||/PMID:\s*\d+/i.test(r)?!0:/(^|\s|\()\b(AND|OR|NOT)\b(\s|\)|$)/i.test(r)}function da(r){return be(r).replace(/\b(and|or|not)\b/gi,e=>e.toUpperCase())}function Ol(r,e,t){const n=e>0?r[e-1]:"";if(n&&/[A-Za-z0-9_]/.test(n))return null;const i=r.slice(e).match(/^(AND|OR|NOT)\b/i);if(!i)return null;const o=i[1].toUpperCase();return t.includes(o)?o:null}function Ul(r,e){const t=da(r);let n=!1,a=0;for(let i=0;i<t.length;i+=1){const o=t[i];if(o==='"'){n=!n;continue}if(!n&&o==="("){a+=1;continue}if(!n&&o===")"){a-=1;continue}if(!n&&a===0&&Ol(t,i,e))return!0}return!1}function Hl(r){const e=da(r);return!e||!/\b(?:AND|OR|NOT)\b/.test(e)?!1:Ul(e,["OR"])?!0:/[()]/.test(e)&&xT(e)&&Ul(e,["AND","OR","NOT"])}function xf(r){const e=be(r);if(!e)return null;if(Il(e))return{value:e,isDoi:!0,isPmid:!1,pmidValue:null};const t=Ml(e);if(t.isValid&&t.pmid)return{value:t.pmid,isDoi:!1,isPmid:!0,pmidValue:t.pmid};if(Hl(e))return{value:da(e),isDoi:!1,isPmid:!1,pmidValue:null};const n=$l(e);return n?{value:n,isDoi:!1,isPmid:!1,pmidValue:null}:null}function fT(r){const e=[];let t="",n="",a=!1,i=0,o=!1;const s=()=>{const l=n.trim();if(!l){n="";return}o?e.push(l):t+=l,n=""};for(let l=0;l<r.length;l+=1){const c=r[l];if(c==='"'){a=!a,n+=c;continue}if(!a&&c==="("){i+=1,n+=c;continue}if(!a&&c===")"){i-=1,n+=c;continue}if(!a&&i===0){const u=Ol(r,l,["AND","OR","NOT"]);if(u){s(),u==="NOT"?o=!0:(t&&!t.endsWith(" ")&&(t+=" "),t+=`${u} `,o=!1),l+=u.length-1;continue}}n+=c}return s(),{cleaned:be(t).replace(/\b(?:AND|OR)\b$/i,"").trim(),exclusions:e.map(l=>be(l)).filter(Boolean)}}function Af(r){const e=r.trim();if(!/^[A-Za-z][A-Za-z'\-.]*(?:\s+[A-Za-z][A-Za-z'\-.]*)?,\s+[A-Za-z][A-Za-z'\-.]*(?:\s+[A-Za-z]\.?)?$/.test(e))return!1;const t=e.toLowerCase().split(/[^a-z]+/).filter(Boolean);return t.length>=2&&t.every(n=>!eT.has(n))}function Cf(r){const e=r.split(/[;\n|]+/).map(n=>n.trim()).filter(Boolean),t=[];for(const n of e){const a=n.split(",").map(o=>o.trim()).filter(Boolean);let i=0;for(;i<a.length;){const o=a[i];i+1<a.length&&Af(`${o}, ${a[i+1]}`)?(t.push(`${o}, ${a[i+1]}`),i+=2):(o.length>=2&&t.push(o),i+=1)}}return t}function mT(r){const e=lT(r),t=e.trim();if(Il(t))return[{value:t,isDoi:!0,isPmid:!1,pmidValue:null}];const n=Ml(t);if(n.isValid&&n.pmid)return[{value:n.pmid,isDoi:!1,isPmid:!0,pmidValue:n.pmid}];if(Hl(t)){const s=da(t);if(/\([^)]*\b(?:AND|OR|NOT)\b[^)]*\)/i.test(s))return[{value:s,isDoi:!1,isPmid:!1,pmidValue:null}]}if(hT(e)){const s=gf(e),{cleaned:l}=fT(e),c=l.replace(/"[^"]+"/g," "),u=Cf(c).flatMap(p=>yf(p)).map(p=>p.trim()).filter(Boolean),d=[...s,...u];return ne(d).map(p=>xf(p)).filter(p=>p!==null)}const a=gf(e),i=e.replace(/"[^"]+"/g," "),o=Cf(i).flatMap(yf).map(s=>be(s)).filter(Boolean);return ne([...a,...o]).map(s=>xf(s)).filter(s=>s!==null)}function bT(r,e){return pf.filter(t=>t.patterns.some(n=>n.test(r))&&rT(t,e))}function zl(r,e,t,n,a,i=!1,o=!1,s=!1,l=!1,c=null){if(s){const y=$l(r);return y?{raw:r,cleaned:y,kind:"phrase",source:e,priority:0,order:a,matchedRules:[],variants:[y],isDoi:!0,isPmid:!1,metadataNote:`Detected DOI: ${y}`,queryTerms:[y]}:null}if(l&&c)return{raw:r,cleaned:c,kind:"phrase",source:e,priority:0,order:a,matchedRules:[],variants:[c],isDoi:!1,isPmid:!0,metadataNote:`Detected PMID: ${c}`,queryTerms:[c]};if(Hl(r)){const y=da(r);return{raw:r,cleaned:y,kind:"phrase",source:e,priority:0,order:a,matchedRules:[],variants:[y],isLiteralBoolean:!0,metadataNote:"Preserved literal boolean expression",queryTerms:[y]}}const u=$l(r);if(!u)return null;const d=gT(bT(u,n),u),p=d.length>0?ne(d.flatMap(y=>y.titleAbstractTerms)):$i(u),h={raw:r,cleaned:u,kind:dT(u),source:e,priority:t,order:a,matchedRules:d,variants:p},f=pT(h,i,o);return{...h,kind:f.kind,metadataNote:f.metadataNote,queryTerms:f.queryTerms}}function gT(r,e=""){if(r.length<=1)return r;let t=[...r];t.some(o=>hf.has(o.key))&&(t=t.filter(o=>o.key!=="generic-cancer"));const a=t.some(o=>o.key==="polygenic-risk-score"),i=/\b(polygenic|genetic|genomic|genome-wide|PRS)\b/i.test(e)&&!/\b(?:and|or|versus|vs)\b/i.test(e)&&!/[;,/]/.test(e)&&!/\bclinical\b/i.test(e);return a&&i&&(t=t.filter(o=>o.key!=="prediction-model")),t}function vf(r,e){const t=r.findIndex(n=>n.cleaned.toLowerCase()===e.cleaned.toLowerCase()&&n.source===e.source);if(t===-1){r.push(e);return}if(e.priority<r[t].priority){r[t]=e;return}r[t]={...r[t],order:Math.min(r[t].order,e.order)}}function yT(r){const e=be(r);if(!e||!e.includes(" "))return[e];if(ql.has(e.toLowerCase()))return[e];const t=e.split(/\s+/),n=[];let a=[];for(const i of t)df.has(i.toLowerCase())?a.length>0&&(n.push(a.join(" ")),a=[]):a.push(i);return a.length>0&&n.push(a.join(" ")),n.filter(i=>i.length>=2)}function Sf({topicText:r,focusAreaText:e,notesText:t,keywordTexts:n=[]}){const a=[],i=nT([r,e,...n]);let o=0;return[{value:r,source:"topic",priority:1},{value:e,source:"focusArea",priority:2},...n.map(l=>({value:l,source:"keywords",priority:2})),{value:t,source:"notes",priority:3}].forEach(l=>{const c=l.value?.trim();if(!c)return;const u=mT(c),d=u.map((f,y)=>{const x=u.filter((w,v)=>v!==y),T=x.some(w=>{const v=ji(w.value);return v&&v.confidence>=.9}),E=x.some(w=>w.isDoi||w.isPmid||Af(w.value)?!0:!!ji(w.value));return{candidate:f,hasJournalSibling:T,hasMetadataSibling:E}});d.flatMap(({candidate:f,hasJournalSibling:y,hasMetadataSibling:x})=>{o+=1;const T=zl(f.value,l.source,f.isDoi||f.isPmid?0:l.priority,i,o,y,x,f.isDoi,f.isPmid,f.pmidValue);if(!T)return[];if(T.kind!=="author"&&T.kind!=="journal"&&!T.isDoi&&!T.isPmid&&!T.isLiteralBoolean&&T.kind==="phrase"&&T.matchedRules.length===0){const E=yT(f.value);if(E.length>=1&&E[0]!==f.value.trim()){const w=E.map(v=>(o+=1,zl(v,l.source,l.priority,i,o,y,x))).filter(v=>v!=null&&v.cleaned.length>=2);if(w.length>0)return w}}return[T]}).forEach(f=>vf(a,f));const p=d.some(f=>f.hasJournalSibling),h=d.some(f=>f.hasMetadataSibling);uT(c).map(f=>(o+=1,zl(f,l.source,l.priority+1,i,o,p,h))).filter(f=>!!f).forEach(f=>vf(a,f))}),a}function xT(r){let e=0;for(const t of r)if(t==="("&&(e+=1),t===")"&&(e-=1,e<0))return!1;return e===0}const wf=[{value:"Abstract",query:"hasabstract"},{value:"Free full text",query:"free full text[sb]"},{value:"Full text",query:"full text[sb]"}],Tf=[{value:"Associated data",query:"data[sb]"}],AT=["Adaptive Clinical Trial","Address","Biography","Books and Documents","Case Reports","Clinical Study","Clinical Trial","Clinical Trial Protocol","Clinical Trial, Phase I","Clinical Trial, Phase II","Clinical Trial, Phase III","Clinical Trial, Phase IV","Clinical Trial, Veterinary","Collected Work","Comment","Comparative Study","Conference Proceedings","Consensus Statement","Controlled Clinical Trial","Corrected and Republished Article","Dataset","Duplicate Publication","Editorial","Electronic Supplementary Materials","English Abstract","Equivalence Trial","Evaluation Study","Evidence Synthesis","Expression of Concern","Festschrift","Guideline","Historical Article","Interview","Introductory Journal Article","Lecture","Letter","Meta-Analysis","Multicenter Study","Network Meta-Analysis","News","Observational Study","Observational Study, Veterinary","Patient Education Handout","Personal Narrative","Practice Guideline","Pragmatic Clinical Trial","Preprint","Published Erratum","Randomized Controlled Trial","Randomized Controlled Trial, Veterinary","Research Support, American Recovery and Reinvestment Act","Research Support, N.I.H., Extramural","Research Support, N.I.H., Intramural","Research Support, Non-U.S. Gov't","Research Support, U.S. Gov't, Non-P.H.S.","Research Support, U.S. Gov't, P.H.S.","Research Support, U.S. Gov't","Retracted Publication","Retraction Notice","Review","Scoping Review","Systematic Review","Twin Study","Validation Study","Video-Audio Media","Webcast"],Ef=["Afrikaans","Albanian","Arabic","Armenian","Azerbaijani","Bosnian","Bulgarian","Catalan","Chinese","Croatian","Czech","Danish","Dutch","English","Esperanto","Estonian","Finnish","French","Georgian","German","Greek, Modern","Hebrew","Hindi","Hungarian","Icelandic","Indonesian","Italian","Japanese","Kinyarwanda","Korean","Latin","Latvian","Lithuanian","Macedonian","Malay","Malayalam","Maori","Multiple Languages","Norwegian","Persian","Polish","Portuguese","Pushto","Romanian","Russian","Sanskrit","Scottish gaelic","Serbian","Slovak","Slovenian","Spanish","Swedish","Thai","Turkish","Ukrainian","Undetermined","Vietnamese","Welsh"],Ff=[{value:"humans",label:"Humans",query:"humans[mh]"},{value:"animals",label:"Other Animals",query:'"animals"[mh:noexp]'}],Df=[{value:"Female",query:"female[mh]"},{value:"Male",query:"male[mh]"}],_f=[{value:"Child: birth-18 years",query:"(infant[mh] OR child[mh] OR adolescent[mh])"},{value:"Newborn: birth-1 month",query:"infant, newborn[mh]"},{value:"Infant: birth-23 months",query:"infant[mh]"},{value:"Infant: 1-23 months",query:"infant[mh:noexp]"},{value:"Preschool Child: 2-5 years",query:"child, preschool[mh]"},{value:"Child: 6-12 years",query:"child[mh:noexp]"},{value:"Adolescent: 13-18 years",query:"adolescent[mh]"},{value:"Adult: 19+ years",query:"adult[mh]"},{value:"Young Adult: 19-24 years",query:'"young adult"[mh]'},{value:"Adult: 19-44 years",query:"adult[mh:noexp]"},{value:"Middle Aged + Aged: 45+ years",query:"(middle aged[mh] OR aged[mh])"},{value:"Middle Aged: 45-64 years",query:"middle aged[mh]"},{value:"Aged: 65+ years",query:"aged[mh]"},{value:"80 and over: 80+ years",query:"aged, 80 and over[mh]"}],kf=[{value:"Exclude preprints",query:"NOT preprint[pt]"},{value:"MEDLINE",query:"medline[sb]"}];new Set(wf.map(r=>r.value)),new Set(Tf.map(r=>r.value)),new Set(AT),new Set(Ef),new Set(Df.map(r=>r.value)),new Set(_f.map(r=>r.value)),new Set(kf.map(r=>r.value)),new Map(wf.map(r=>[r.value,r.query])),new Map(Tf.map(r=>[r.value,r.query])),new Map(Ef.map(r=>[r,r])),new Map(Ff.map(r=>[r.value,r.query])),new Map(Ff.map(r=>[r.value,r.label])),new Map(Df.map(r=>[r.value,r.query])),new Map(_f.map(r=>[r.value,r.query])),new Map(kf.map(r=>[r.value,r.query]));const Nf="balanced",CT={strict:4,balanced:6},Lf="Title/Abstract",vT="MeSH Terms";function ST(r){const e=be(r).replace(/"/g,"");return/[^A-Za-z0-9]/.test(e)?`"${e}"[${Lf}]`:`${e}[${Lf}]`}function wT(r){return`"${r}"[${vT}]`}function TT(r,e){if(e!=="strict")return r;const t=ne(r.sourceTerms.flatMap(a=>$i(a))),n=ne([...t,...r.titleAbstractTerms]).slice(0,Math.max(t.length,3));return{...r,titleAbstractTerms:n}}function ET(r,e=Nf){const t=TT(r,e),n=ne(t.titleAbstractTerms).map(ST),a=ne(t.meshTerms).map(wT);return`(${ne([...a,...n]).join(" OR ")})`}function FT(r,e=Nf){return r.length===0?"":r.map(t=>ET(t,e)).join(" AND ")}const DT=/\b(?:[a-z][a-z0-9+.-]*:\/\/|www\.|[a-z0-9-]+(?:\.[a-z0-9-]+)+(?:\/\S*)?)|\/\/[a-z0-9.-]+\//i,_T=/\b(?:select|insert|update|delete|drop|alter|truncate|union|create|show|describe|grant|revoke)\b(?:\s+\S+){0,12}\s*\b(?:from|where|table|tables|database|databases|values|set|into|select|int|varchar|text)?\b/i,Rf=String.raw`\b(?:gpt|o[0-9]|claude|deepseek|qwen|glm|gemini|llama|mistral|mixtral|moonshot|kimi|yi|doubao|ernie|hunyuan|command-r|sonar|grok|nova|phi|pplx)[\w.\-:/]*\b`,kT=new RegExp(Rf,"i"),NT=new RegExp(Rf,"gi");function LT(r){return r?`\u6765\u6E90\uFF1A${r.provider==="custom"?"\u81EA\u5B9A\u4E49\u6A21\u578B":r.provider==="paperlens"||r.provider==="backend"?"PaperLens AI \u6A21\u578B":r.provider==="local-rules"?"\u672C\u5730\u89C4\u5219":"PaperLens AI \u6A21\u578B"}`:""}function RT(r,e){const t=e==="strict"?"High Specificity":"AI enhanced",n=r.trim().replace(/\s+/g," ").slice(0,80);return n?kT.test(n)?t:n:t}function mt(r){return r.trim().replace(/\s+/g," ").replace(NT,"\u6A21\u578B")}function Pf(r){return/需要先(?:在 Popup 设置中)?配置自定义模型接口|接口在当前服务器上未部署|切换自定义模型|AI 服务暂未配置|请联系管理员/.test(r)?!1:/(?:Pro|永久版权益|开通|当前账户暂不能使用|请先登录|账户状态已切换|本月.*次数已用完|次数已用完|QUOTA_EXCEEDED|NOT_AUTHENTICATED|SESSION_CHANGED|REMOTE_CHECK_FAILED)/i.test(r)}function Bf(r,e="balanced"){const t=r.trim();if(!t)throw new Error("\u8BF7\u8F93\u5165\u6709\u6548\u7684\u82F1\u6587\u5173\u952E\u8BCD\u6216 PubMed \u68C0\u7D22\u5F0F");if(/^[\u4e00-\u9fff\u3000-\u303f\uff00-\uffef\s,.;:!?]+$/.test(t))throw new Error("\u4E2D\u6587\u7814\u7A76\u95EE\u9898\u9700\u8981\u4F7F\u7528 AI \u589E\u5F3A\u751F\u6210 PubMed \u68C0\u7D22\u5F0F");const n=PT(t);if(n)return{query:n.query,tag:n.tag,mode:"special",concepts:[]};if(DT.test(t)||_T.test(t))throw new Error("\u8BF7\u8F93\u5165\u6709\u6548\u7684\u82F1\u6587\u5173\u952E\u8BCD\u6216 PubMed \u68C0\u7D22\u5F0F");const a=IT(t,e);if(!a.query.trim())throw new Error("\u8BF7\u8F93\u5165\u6709\u6548\u7684\u82F1\u6587\u5173\u952E\u8BCD\u6216 PubMed \u68C0\u7D22\u5F0F");return{query:a.query,tag:e==="strict"?"High Specificity":"Recommended",mode:e,concepts:a.concepts}}function PT(r){const e=r.trim();if(Il(e))return{query:`${e}[doi]`,tag:"DOI"};const t=Ml(e);if(t.isValid&&t.pmid)return{query:`${t.pmid}[PMID]`,tag:"PMID"};const n=/\b(?:AND|OR|NOT)\b/i.test(e),a=/\[.*?\]/.test(e);if(a)return{query:e.replace(/\b(and|or|not)\b/gi,c=>c.toUpperCase()),tag:n?"Boolean":"PubMed Syntax"};if(n&&(a||/^["]?[A-Za-z0-9\s/\-_.]+["]?(?:\s+(?:AND|OR|NOT)\s+[\"']?[A-Za-z0-9\s/\-_.]+[\"']?\s*)*[\"']?$/i.test(e)||/\(/.test(e)))try{const c=Sf({topicText:e,focusAreaText:null,notesText:null,keywordTexts:[]});if(bf(c).length===0)return{query:e.replace(/\b(and|or|not)\b/gi,p=>p.toUpperCase()),tag:"Boolean"}}catch{return{query:e.replace(/\b(and|or|not)\b/gi,c=>c.toUpperCase()),tag:"Boolean"}}const i=BT(e);if(i)return i;const o=qi(e,{hasJournalSibling:!1,hitsConceptRule:!1});if(o&&o.terms.length>0)return{query:o.terms.map(c=>`"${c}"[Author]`).join(" OR "),tag:"Author"};const s=ji(e);if(s&&s.confidence>=.9){const l=Bl(s.entry);if(l.length>0)return{query:l.map(u=>`"${u}"[Journal]`).join(" OR "),tag:"Journal"}}return null}function BT(r){const e=r.split(/[;,]+/).map(i=>i.trim()).filter(Boolean);if(e.length>=2){const i=e.map(o=>qi(o,{hasJournalSibling:!1,hitsConceptRule:!1}));if(i.every(Boolean))return{query:i.flatMap(o=>o?.terms??[]).map(o=>`"${o}"[Author]`).join(" OR "),tag:"Author"}}const t=Array.from(r.matchAll(/\b[A-Z][A-Za-z'\-.]+\s+[A-Z]{1,4}\b/g)).map(i=>i[0].trim()).filter(Boolean);if(t.length<2||t.join(" ")!==r.trim())return null;const a=t.map(i=>qi(i,{hasJournalSibling:!1,hitsConceptRule:!1}));return a.every(Boolean)?{query:a.flatMap(i=>i?.terms??[]).map(i=>`"${i}"[Author]`).join(" OR "),tag:"Author"}:null}function IT(r,e){const n=Sf({topicText:r,focusAreaText:null,notesText:null,keywordTexts:[]}),a=bf(n),i=CT[e]??6,o=a.slice(0,i);for(const l of o)l.usedInRecommendedQuery=!0;return{query:FT(o,e),concepts:o}}const MT=`.pl-zotero-batch-btn {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  height: 28px;
  padding: 0 12px;
  border: none;
  border-radius: 6px;
  background: #eff6ff;
  color: #1d4ed8;
  font-size: 12px;
  font-weight: 600;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", "Noto Sans SC", "Source Han Sans SC", "Helvetica Neue", Arial, sans-serif;
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  transition: background 0.15s;
}

.pl-zotero-batch-btn:hover {
  background: #dbeafe;
}

.pl-zotero-batch-btn:active {
  background: #bfdbfe;
}

.pl-zotero-batch-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
`,qT="paperlens-zotero-batch-host";function If(r){r.dataset.busy!=="true"&&(r.disabled=!1),r.title="",r.textContent="\u{1F4DA} \u6279\u91CF\u4FDD\u5B58 Zotero",r.removeAttribute("aria-disabled")}function Mf(r,e){r.disabled=!0,r.title=e,r.textContent="\u{1F4DA} \u6279\u91CF\u4FDD\u5B58 Zotero Pro",r.setAttribute("aria-disabled","true")}async function qf(r){const e=await or();if(e.allowed){If(r);return}if(e.transient){r.dataset.busy!=="true"&&(r.disabled=!1),r.title=e.error||"",r.textContent="\u{1F4DA} \u6279\u91CF\u4FDD\u5B58 Zotero",r.removeAttribute("aria-disabled");return}Mf(r,e.error||"Zotero \u5BFC\u51FA\u662F Pro \u6C38\u4E45\u7248\u6743\u76CA")}function jT(r){xn();const e=t=>{const n=t.detail;if(n?.featureKey===Mt){if(n.allowed===!0){If(r);return}Mf(r,n.error||"Zotero \u5BFC\u51FA\u662F Pro \u6C38\u4E45\u7248\u6743\u76CA")}};document.addEventListener(pe,e),window.addEventListener("pagehide",()=>{document.removeEventListener(pe,e)},{once:!0})}function $T(r){const e=document.createElement("div");e.className=qT;const t=e.attachShadow({mode:"open"}),n=document.createElement("style");n.textContent=MT,t.appendChild(n);const a=document.createElement("button");return a.type="button",a.className="pl-zotero-batch-btn",a.textContent="\u{1F4DA} \u6279\u91CF\u4FDD\u5B58 Zotero",t.appendChild(a),qf(a),jT(a),a.addEventListener("click",async i=>{i.preventDefault(),i.stopPropagation();const o=await or();if(!o.allowed){D.error(o.error||"Zotero \u5BFC\u51FA\u662F Pro \u6C38\u4E45\u7248\u6743\u76CA"),await qf(a);return}const s=r();if(s.length===0){D.info("\u8BF7\u5148\u9009\u62E9\u8981\u4FDD\u5B58\u7684\u8BBA\u6587");return}a.disabled=!0,a.dataset.busy="true";try{await JC(s)}finally{delete a.dataset.busy,a.disabled=!1}}),e}const jf={Q1:"Q1",Q2:"Q2",Q3:"Q3",Q4:"Q4",Unknown:"\u672A\u5339\u914D"},OT={guideline:"\u6307\u5357",meta_analysis:"Meta-analysis",review:"\u7EFC\u8FF0 / \u7CFB\u7EDF\u7EFC\u8FF0",rct:"\u968F\u673A\u5BF9\u7167\u8BD5\u9A8C",clinical_trial:"\u4E34\u5E8A\u8BD5\u9A8C",observational:"\u89C2\u5BDF\u6027\u7814\u7A76",other:"\u5176\u4ED6"},UT=["guideline","meta_analysis","review","rct","clinical_trial","observational","other"],$f={1:"1\u533A",2:"2\u533A",3:"3\u533A",4:"4\u533A",Unknown:"\u672A\u5339\u914D"};function Oi(r,e){return e<=0?0:Number((r/e).toFixed(4))}function HT(r){const e=r?.trim().toUpperCase();return e==="Q1"||e==="Q2"||e==="Q3"||e==="Q4"?e:"Unknown"}function zT(r){const e=r?.trim().replace("\u533A","");return e==="1"||e==="2"||e==="3"||e==="4"?e:"Unknown"}function JT(r){if(!Array.isArray(r)||r.length===0)return[];const e=new Set,t=[];for(const n of r){const a=n.trim();if(!a)continue;const i=a.toLowerCase();e.has(i)||(e.add(i),t.push(a))}return t}function VT(r){const e=JT(r).map(t=>t.toLowerCase());return e.some(t=>t.includes("guideline"))?"guideline":e.some(t=>t.includes("meta-analysis"))?"meta_analysis":e.some(t=>t.includes("systematic review")||t==="review"||t.endsWith(" review"))?"review":e.some(t=>t.includes("randomized controlled trial"))?"rct":e.some(t=>t.includes("clinical trial"))?"clinical_trial":e.some(t=>t.includes("observational")||t.includes("cohort")||t.includes("case-control")||t.includes("comparative study")||t.includes("cross-sectional")||t.includes("retrospective")||t.includes("prospective"))?"observational":"other"}function WT(r){const e=new Map;for(const n of r){const a=n.year;typeof a!="number"||!Number.isFinite(a)||a<1800||a>2100||e.set(a,(e.get(a)??0)+1)}const t=Array.from(e.values()).reduce((n,a)=>n+a,0);return t===0?[]:Array.from(e.entries()).map(([n,a])=>({year:n,count:a,share:Oi(a,t)})).sort((n,a)=>n.year-a.year)}function GT(r){const e=new Map;for(const n of r){const a=HT(n.jcrQuartile);e.set(a,(e.get(a)??0)+1)}const t=r.length;return t===0?[]:Object.keys(jf).map(n=>{const a=e.get(n)??0;return{key:n,label:jf[n],count:a,share:Oi(a,t)}}).filter(n=>n.count>0)}function ZT(r){const e=new Map;for(const n of r){const a=VT(n.articleTypes);e.set(a,(e.get(a)??0)+1)}const t=r.length;return t===0?[]:UT.map(n=>{const a=e.get(n)??0;return{key:n,label:OT[n],count:a,share:Oi(a,t)}}).filter(n=>n.count>0)}function YT(r){const e=new Map;for(const n of r){const a=zT(n.casQuartile);e.set(a,(e.get(a)??0)+1)}const t=r.length;return t===0?[]:Object.keys($f).map(n=>({key:n,label:$f[n],count:e.get(n)??0,share:Oi(e.get(n)??0,t)})).filter(n=>n.count>0)}function Jl(r){return r.scope==="global"?"\u5168\u91CF\u7B5B\u9009\u7ED3\u679C":"\u5F53\u524D\u9875\u7ED3\u679C"}function pr(r){if(r.scope==="global"){if(r.loading&&r.sourceTotal===0&&r.analyzed===0)return"\u6B63\u5728\u8BFB\u53D6 PubMed \u5168\u91CF\u7ED3\u679C...";const e=`\u5F53\u524D\u663E\u793A ${r.visible.toLocaleString()} \u6761\uFF0C\u5DF2\u5206\u6790 ${r.analyzed.toLocaleString()}/${r.sourceTotal.toLocaleString()} \u6761`;return r.done?`${e} \xB7 \u7EDF\u8BA1\u5B8C\u6210`:r.loading?`${e} \xB7 \u6301\u7EED\u5206\u6790\u4E2D`:`${e} \xB7 \u53EF\u7EE7\u7EED\u5206\u6790\u66F4\u591A`}return`\u5F53\u524D\u9875\u5171 ${r.visible.toLocaleString()} \u6761\u53EF\u89C1\u7ED3\u679C`}function Of(r){const e=r.records,t=WT(e),n=GT(e),a=YT(e),i=ZT(e),o=t[0]?.year,s=t[t.length-1]?.year,l=n.find(d=>d.key==="Q1")?.count??0,c=n.filter(d=>d.key!=="Unknown").reduce((d,p)=>d+p.count,0),u=a.filter(d=>d.key!=="Unknown").reduce((d,p)=>d+p.count,0);return{snapshot:r,yearDistribution:t,quartileDistribution:n,casDistribution:a,evidenceDistribution:i,earliestYear:o,latestYear:s,q1Count:l,matchedQuartileCount:c,matchedCasCount:u}}const KT=`/**
 * Filter Toolbar Styles \u2014 injected into Shadow DOM
 *
 * \u7B5B\u9009\u6392\u5E8F\u5DE5\u5177\u6761\u6837\u5F0F\uFF0C\u4F7F\u7528 --pl-* Design Tokens\u3002
 * \u591A\u884C\u5DE5\u5177\u6761\u5E03\u5C40\uFF0C\u907F\u514D PubMed \u7ED3\u679C\u9875\u9876\u90E8\u6A2A\u5411\u6EDA\u52A8\u3002
 */

/* \u2500\u2500 \u5BBF\u4E3B\u5143\u7D20\uFF08\u63D2\u5165\u5230 PubMed DOM \u4E2D\u7684 div\uFF09 \u2500\u2500\u2500\u2500 */
:host {
  display: block;
  width: 100%;
  background-color: var(--pl-color-white);
  border-bottom: 1px solid var(--pl-color-gray-200);
  box-shadow: var(--pl-shadow-sm);
  font-family: var(--pl-font-sans);
  font-size: var(--pl-font-xs);
  color: var(--pl-color-gray-700);
  line-height: 1;
  z-index: 1;
  position: relative;
}

/* \u2500\u2500 \u5DE5\u5177\u6761\u5BB9\u5668 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-toolbar {
  display: grid;
  grid-template-rows: auto auto auto;
  gap: 6px;
  padding: 8px 10px;
  min-height: 48px;
  box-sizing: border-box;
  overflow: visible;
}

.pl-toolbar * {
  box-sizing: border-box;
}

.pl-toolbar-row {
  display: flex;
  align-items: center;
  gap: var(--pl-space-sm);
  min-width: 0;
  max-width: 100%;
  flex-wrap: wrap;
}

.pl-toolbar-row--primary {
  align-items: center;
}

.pl-toolbar-row--optimizer {
  align-items: stretch;
}

/* \u2500\u2500 \u5206\u7EC4\u6807\u7B7E \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-toolbar-group {
  display: flex;
  align-items: center;
  gap: var(--pl-space-xs);
  min-width: 0;
}

.pl-toolbar-group + .pl-toolbar-group {
  padding-left: var(--pl-space-sm);
  border-left: 1px solid var(--pl-color-gray-200);
}

.pl-toolbar-label {
  font-size: var(--pl-font-xs);
  font-weight: var(--pl-weight-semibold);
  color: var(--pl-color-gray-500);
  white-space: nowrap;
  user-select: none;
}

/* \u2500\u2500 \u6392\u5E8F\u4E0B\u62C9\u6846 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-sort-select {
  appearance: none;
  -webkit-appearance: none;
  background-color: var(--pl-color-white);
  border: 1px solid var(--pl-color-gray-300);
  border-radius: var(--pl-radius-sm);
  padding: 4px 24px 4px 8px;
  font-size: var(--pl-font-xs);
  font-family: var(--pl-font-sans);
  color: var(--pl-color-gray-800);
  cursor: pointer;
  line-height: 1.4;
  height: 28px;
  max-width: 190px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%236b7280' d='M3 5l3 3 3-3'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 6px center;
  transition: border-color var(--pl-transition-fast);
}

.pl-sort-select:hover {
  border-color: var(--pl-color-primary);
}

.pl-sort-select:focus {
  outline: none;
  border-color: var(--pl-color-primary);
  box-shadow: 0 0 0 2px var(--pl-color-primary-light);
}

/* \u2500\u2500 OA \u5F00\u5173 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-oa-toggle {
  position: relative;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  user-select: none;
}

.pl-oa-toggle input[type="checkbox"] {
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;
}

.pl-oa-switch {
  display: inline-block;
  width: 32px;
  height: 18px;
  background-color: var(--pl-color-gray-300);
  border-radius: 9px;
  position: relative;
  transition: background-color var(--pl-transition-fast);
  flex-shrink: 0;
}

.pl-oa-switch::after {
  content: '';
  position: absolute;
  top: 2px;
  left: 2px;
  width: 14px;
  height: 14px;
  background-color: var(--pl-color-white);
  border-radius: 50%;
  transition: transform var(--pl-transition-fast);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.pl-oa-toggle input:checked + .pl-oa-switch {
  background-color: var(--pl-color-success);
}

.pl-oa-toggle input:checked + .pl-oa-switch::after {
  transform: translateX(14px);
}

.pl-oa-toggle input:focus + .pl-oa-switch {
  box-shadow: 0 0 0 2px var(--pl-color-success-light);
}

.pl-oa-text {
  font-size: var(--pl-font-xs);
  font-weight: var(--pl-weight-medium);
  color: var(--pl-color-gray-700);
  white-space: nowrap;
}

/* \u2500\u2500 \u5206\u533A\u6309\u94AE\uFF08Q1/Q2/Q3/Q4 / 1\u533A/2\u533A/3\u533A/4\u533A\uFF09 \u2500\u2500 */
.pl-quartile-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 3px 8px;
  border: 1px solid var(--pl-color-gray-300);
  border-radius: var(--pl-radius-sm);
  background-color: var(--pl-color-white);
  font-size: var(--pl-font-xs);
  font-weight: var(--pl-weight-medium);
  font-family: var(--pl-font-sans);
  color: var(--pl-color-gray-600);
  cursor: pointer;
  user-select: none;
  white-space: nowrap;
  height: 24px;
  line-height: 1;
  transition: all var(--pl-transition-fast);
}

.pl-quartile-btn:hover {
  border-color: var(--pl-color-primary);
  color: var(--pl-color-primary);
}

.pl-quartile-btn.active {
  border-color: var(--pl-color-primary);
  background-color: var(--pl-color-primary-light);
  color: var(--pl-color-primary);
  font-weight: var(--pl-weight-semibold);
}

/* JCR \u5206\u533A\u6FC0\u6D3B\u6001\u989C\u8272\u53D8\u4F53 */
.pl-quartile-btn[data-q="Q1"].active {
  border-color: var(--pl-color-primary);
  background-color: var(--pl-color-primary-light);
  color: var(--pl-color-primary);
}

.pl-quartile-btn[data-q="Q2"].active {
  border-color: var(--pl-color-success);
  background-color: var(--pl-color-success-light);
  color: var(--pl-color-success);
}

.pl-quartile-btn[data-q="Q3"].active {
  border-color: var(--pl-color-warning);
  background-color: var(--pl-color-warning-light);
  color: var(--pl-color-warning);
}

.pl-quartile-btn[data-q="Q4"].active {
  border-color: var(--pl-color-gray-500);
  background-color: var(--pl-color-gray-100);
  color: var(--pl-color-gray-600);
}

/* \u4E2D\u79D1\u9662\u5206\u533A\u6FC0\u6D3B\u6001\u989C\u8272\u53D8\u4F53 */
.pl-quartile-btn[data-cas="1"].active {
  border-color: var(--pl-color-primary);
  background-color: var(--pl-color-primary-light);
  color: var(--pl-color-primary);
}

.pl-quartile-btn[data-cas="2"].active {
  border-color: var(--pl-color-success);
  background-color: var(--pl-color-success-light);
  color: var(--pl-color-success);
}

.pl-quartile-btn[data-cas="3"].active {
  border-color: var(--pl-color-warning);
  background-color: var(--pl-color-warning-light);
  color: var(--pl-color-warning);
}

.pl-quartile-btn[data-cas="4"].active {
  border-color: var(--pl-color-gray-500);
  background-color: var(--pl-color-gray-100);
  color: var(--pl-color-gray-600);
}

/* \u2500\u2500 \u5E74\u4EFD\u8F93\u5165\u6846 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-year-input {
  width: 52px;
  padding: 3px 4px;
  border: 1px solid var(--pl-color-gray-300);
  border-radius: var(--pl-radius-sm);
  font-size: var(--pl-font-xs);
  font-family: var(--pl-font-mono);
  color: var(--pl-color-gray-800);
  text-align: center;
  height: 24px;
  line-height: 1;
  transition: border-color var(--pl-transition-fast);
}

.pl-year-input:hover {
  border-color: var(--pl-color-primary);
}

.pl-year-input:focus {
  outline: none;
  border-color: var(--pl-color-primary);
  box-shadow: 0 0 0 2px var(--pl-color-primary-light);
}

.pl-year-input::placeholder {
  color: var(--pl-color-gray-400);
  font-family: var(--pl-font-sans);
}

.pl-year-sep {
  color: var(--pl-color-gray-400);
  font-size: var(--pl-font-xs);
}

/* \u2500\u2500 \u6062\u590D\u6309\u94AE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-restore-btn {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 10px;
  border: 1px solid var(--pl-color-gray-300);
  border-radius: var(--pl-radius-sm);
  background-color: var(--pl-color-white);
  font-size: var(--pl-font-xs);
  font-weight: var(--pl-weight-medium);
  font-family: var(--pl-font-sans);
  color: var(--pl-color-gray-600);
  cursor: pointer;
  white-space: nowrap;
  height: 26px;
  line-height: 1;
  transition: all var(--pl-transition-fast);
}

.pl-restore-btn:hover {
  border-color: var(--pl-color-primary);
  color: var(--pl-color-primary);
  background-color: var(--pl-color-primary-light);
}

.pl-restore-btn:disabled {
  cursor: not-allowed;
  opacity: 0.55;
}

.pl-apply-filter-btn {
  border-color: var(--pl-color-primary);
  color: var(--pl-color-primary);
  font-weight: var(--pl-weight-semibold);
}

.pl-apply-filter-btn--pending {
  background-color: var(--pl-color-primary);
  color: var(--pl-color-white);
}

.pl-apply-filter-btn--pending:hover:not(:disabled) {
  background-color: #1d4ed8;
  color: var(--pl-color-white);
}

.pl-restore-btn-icon {
  font-size: 13px;
  line-height: 1;
}

/* \u2500\u2500 \u8FDB\u5EA6\u6761 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-toolbar-progress {
  width: 120px;
  height: 4px;
  background: var(--pl-color-gray-200);
  border-radius: 2px;
  overflow: hidden;
  flex-shrink: 0;
}

.pl-toolbar-progress-fill {
  height: 100%;
  background: var(--pl-color-primary);
  border-radius: 2px;
  width: 0%;
  transition: width 0.3s ease;
}

/* \u672A\u5F00\u59CB\u65F6\u7528 indeterminate \u52A8\u753B */
.pl-toolbar-progress-fill[style*="width: 100%"] {
  animation: pl-progress-indeterminate 1.5s ease-in-out infinite;
  background: linear-gradient(
    90deg,
    var(--pl-color-primary) 0%,
    var(--pl-color-primary) 50%,
    var(--pl-color-gray-200) 50%,
    var(--pl-color-gray-200) 100%
  );
  background-size: 200% 100%;
}

@keyframes pl-progress-indeterminate {
  0% { background-position: 100% 0; }
  100% { background-position: 0% 0; }
}

/* \u2500\u2500 \u53D6\u6D88\u7B5B\u9009\u6309\u94AE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-toolbar-cancel-btn {
 display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  border: none;
  border-radius: 4px;
  background: transparent;
  color: var(--pl-color-gray-400);
  cursor: pointer;
  flex-shrink: 0;
  padding: 0;
  transition: all 0.15s ease;
}

.pl-toolbar-cancel-btn:hover {
  background: var(--pl-color-gray-100);
  color: var(--pl-color-red-500, #ef4444);
}

/* \u2500\u2500 \u4FE1\u606F\u63D0\u793A \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-toolbar-info {
  margin-left: auto;
  font-size: 10px;
  color: var(--pl-color-gray-400);
  white-space: nowrap;
  flex-shrink: 0;
  user-select: none;
}

/* \u2500\u2500 \u5185\u8054 PubMed \u68C0\u7D22\u8BCD\u4F18\u5316 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-query-optimizer-inline {
  display: grid;
  grid-template-columns: minmax(92px, 120px) minmax(0, 1fr);
  gap: 8px;
  align-items: stretch;
  width: 100%;
  max-width: 100%;
  min-width: 0;
  padding: 8px;
  border: 1px solid var(--pl-color-gray-200);
  border-radius: var(--pl-radius-md);
  background-color: var(--pl-color-gray-50);
}

.pl-query-optimizer-header {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 5px;
  justify-content: center;
  min-width: 0;
}

.pl-query-optimizer-label {
  color: var(--pl-color-gray-700);
  line-height: 1.25;
  white-space: normal;
}

.pl-query-mode-controls {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: flex-start;
}

.pl-query-mode-group {
  display: inline-flex;
  width: fit-content;
  padding: 2px;
  border: 1px solid var(--pl-color-gray-200);
  border-radius: var(--pl-radius-sm);
  background-color: var(--pl-color-gray-50);
}

.pl-query-mode-btn {
  height: 22px;
  padding: 0 8px;
  border: none;
  border-radius: calc(var(--pl-radius-sm) - 1px);
  background: transparent;
  color: var(--pl-color-gray-500);
  font-family: var(--pl-font-sans);
  font-size: 11px;
  font-weight: var(--pl-weight-semibold);
  cursor: pointer;
  white-space: nowrap;
}

.pl-query-mode-btn.active {
  background-color: var(--pl-color-white);
  color: var(--pl-color-primary);
  box-shadow: var(--pl-shadow-sm);
}

.pl-query-optimizer-body {
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  gap: 6px;
  align-items: center;
  min-width: 0;
}

.pl-query-input,
.pl-query-output {
  width: 100%;
  min-width: 0;
  min-height: 66px;
  max-height: 180px;
  box-sizing: border-box;
  padding: 6px 8px;
  border: 1px solid var(--pl-color-gray-300);
  border-radius: var(--pl-radius-sm);
  background-color: var(--pl-color-white);
  color: var(--pl-color-gray-800);
  font-family: var(--pl-font-sans);
  font-size: var(--pl-font-xs);
  line-height: 1.35;
  resize: vertical;
  white-space: pre-wrap;
  overflow-wrap: anywhere;
  overflow-x: hidden;
  overflow-y: auto;
}

.pl-query-output {
  background-color: var(--pl-color-gray-50);
  font-family: var(--pl-font-mono);
  grid-column: 1 / -1;
}

.pl-query-input:focus,
.pl-query-output:focus {
  outline: none;
  border-color: var(--pl-color-primary);
  box-shadow: 0 0 0 2px var(--pl-color-primary-light);
}

.pl-query-action-group {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  gap: 4px;
  min-width: 0;
}

.pl-query-action-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-height: 24px;
  padding: 4px 8px;
  border: 1px solid var(--pl-color-gray-300);
  border-radius: var(--pl-radius-sm);
  background-color: var(--pl-color-white);
  color: var(--pl-color-gray-600);
  font-family: var(--pl-font-sans);
  font-size: var(--pl-font-xs);
  font-weight: var(--pl-weight-semibold);
  cursor: pointer;
  white-space: nowrap;
}

.pl-query-action-btn--primary {
  border-color: var(--pl-color-primary);
  background-color: var(--pl-color-primary);
  color: var(--pl-color-white);
}

.pl-query-action-btn:hover:not(:disabled) {
  border-color: var(--pl-color-primary);
  color: var(--pl-color-primary);
  background-color: var(--pl-color-primary-light);
}

.pl-query-action-btn--primary:hover:not(:disabled) {
  background-color: #1d4ed8;
  color: var(--pl-color-white);
}

.pl-query-action-btn:disabled {
  cursor: not-allowed;
  opacity: 0.55;
}

.pl-query-status,
.pl-query-provider-badge,
.pl-query-warnings {
  grid-column: 1 / -1;
  min-height: 16px;
  color: var(--pl-color-gray-500);
  font-size: 11px;
  line-height: 1.35;
  overflow-wrap: anywhere;
}

.pl-query-provider-badge {
  display: inline-flex;
  width: fit-content;
  min-height: 0;
  padding: 2px 6px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  color: #4b5563;
  background: #f9fafb;
  font-size: 11px;
}

.pl-query-provider-badge:empty {
  display: none;
}

.pl-query-status--pending {
  color: #0369a1;
}

.pl-query-status--success {
  color: #047857;
}

.pl-query-status--warning,
.pl-query-warnings {
  color: var(--pl-color-warning);
}

.pl-query-optimizer-inline--ai-pending .pl-query-output {
  border-color: rgba(3, 105, 161, 0.35);
}

/* \u2500\u2500 \u5DE5\u5177\u680F\u5BFC\u51FA\u4E0B\u62C9 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-export-menu-group {
  position: relative;
}

.pl-toolbar-export-dropdown {
  position: absolute;
  top: calc(100% + 4px);
  right: 0;
  min-width: 180px;
  background-color: var(--pl-color-white);
  border: 1px solid var(--pl-color-gray-200);
  border-radius: var(--pl-radius-md);
  box-shadow: var(--pl-shadow-lg);
  z-index: var(--pl-z-dropdown);
  padding: var(--pl-space-xs) 0;
  overflow: hidden;
}

@media (max-width: 1120px) {
  .pl-query-optimizer-inline {
    grid-template-columns: minmax(0, 1fr);
  }

  .pl-query-optimizer-header {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }

  .pl-query-optimizer-body {
    grid-template-columns: minmax(180px, 1fr) auto;
  }
}

@media (max-width: 720px) {
  .pl-query-action-group {
    width: 100%;
  }

  .pl-query-optimizer-body {
    grid-template-columns: 1fr;
  }
}

.pl-toolbar-info-count {
  font-weight: var(--pl-weight-medium);
  color: var(--pl-color-gray-500);
}

/* \u2500\u2500 \u6279\u91CF\u64CD\u4F5C\u680F \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-batch-bar {
  display: none;
  align-items: center;
  gap: var(--pl-space-sm);
  padding: var(--pl-space-xs) var(--pl-space-md);
  height: 40px;
  box-sizing: border-box;
  background-color: var(--pl-color-primary-light);
  border-top: 1px solid var(--pl-color-primary-light);
  font-family: var(--pl-font-sans);
  font-size: var(--pl-font-xs);
  position: relative;
}

.pl-batch-count {
  font-size: var(--pl-font-sm);
  font-weight: var(--pl-weight-semibold);
  color: var(--pl-color-primary);
  white-space: nowrap;
  user-select: none;
}

.pl-batch-btn {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 10px;
  border: 1px solid var(--pl-color-gray-300);
  border-radius: var(--pl-radius-sm);
  background-color: var(--pl-color-white);
  font-size: var(--pl-font-xs);
  font-weight: var(--pl-weight-medium);
  font-family: var(--pl-font-sans);
  color: var(--pl-color-gray-600);
  cursor: pointer;
  white-space: nowrap;
  height: 26px;
  line-height: 1;
  transition: all var(--pl-transition-fast);
}

.pl-batch-btn:hover {
  border-color: var(--pl-color-primary);
  color: var(--pl-color-primary);
  background-color: var(--pl-color-white);
}

.pl-batch-btn--primary {
  border-color: var(--pl-color-primary);
  color: var(--pl-color-primary);
  background-color: var(--pl-color-white);
}

.pl-batch-btn--primary:hover {
  background-color: var(--pl-color-primary);
  color: var(--pl-color-white);
}

.pl-batch-export-group {
  position: relative;
  display: inline-flex;
  align-items: center;
}

.pl-batch-dropdown {
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  right: auto;
  min-width: 180px;
  background-color: var(--pl-color-white);
  border: 1px solid var(--pl-color-gray-200);
  border-radius: var(--pl-radius-md);
  box-shadow: var(--pl-shadow-lg);
  z-index: var(--pl-z-dropdown);
  padding: var(--pl-space-xs) 0;
  overflow: hidden;
}

.pl-batch-dropdown-item {
  display: block;
  width: 100%;
  padding: 6px 12px;
  border: none;
  background: none;
  font-family: var(--pl-font-sans);
  font-size: var(--pl-font-xs);
  font-weight: var(--pl-weight-medium);
  color: var(--pl-color-gray-700);
  cursor: pointer;
  text-align: left;
  transition: background-color var(--pl-transition-fast);
}

.pl-batch-dropdown-item:hover {
  background-color: var(--pl-color-primary-light);
  color: var(--pl-color-primary);
}

.pl-batch-dropdown-item:disabled {
  cursor: not-allowed;
  opacity: 0.55;
}

.pl-batch-dropdown-item:disabled:hover {
  background: none;
  color: var(--pl-color-gray-700);
}

/* \u2500\u2500 \u671F\u520A\u7B5B\u9009\u8F93\u5165\u6846 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-journal-input {
  width: 140px;
  height: 26px;
  padding: 0 6px;
  border: 1px solid var(--pl-color-gray-300);
  border-radius: var(--pl-radius-sm);
  font-family: var(--pl-font-sans);
  font-size: var(--pl-font-xs);
  color: var(--pl-color-gray-800);
  background-color: var(--pl-color-white);
  outline: none;
  transition: border-color 0.15s;
  box-sizing: border-box;
}

.pl-journal-input::placeholder {
  color: var(--pl-color-gray-400);
}

.pl-journal-input:focus {
  border-color: var(--pl-color-primary);
  box-shadow: 0 0 0 2px var(--pl-color-primary-light);
}

/* \u2500\u2500 \u7ED3\u679C\u5206\u6790\u6D6E\u7A97 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
.pl-analysis-overlay {
  position: fixed;
  inset: 0;
  display: none;
  align-items: center;
  justify-content: center;
  padding: 24px;
  background: #0f172a;
  z-index: 100000;
  pointer-events: auto;
}

.pl-analysis-overlay.is-open {
  display: flex;
}

.pl-analysis-panel {
  width: min(1080px, calc(100vw - 48px));
  max-height: min(820px, calc(100vh - 48px));
  overflow: auto;
  background: var(--pl-color-white);
  border: 1px solid var(--pl-color-gray-200);
  border-radius: 14px;
  box-shadow: 0 24px 80px rgba(15, 23, 42, 0.22);
  padding: 18px 18px 20px;
}

.pl-analysis-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
}

.pl-analysis-header-text {
  min-width: 0;
}

.pl-analysis-title {
  font-size: 18px;
  line-height: 1.2;
  font-weight: 700;
  color: var(--pl-color-gray-900);
}

.pl-analysis-subtitle {
  margin-top: 6px;
  font-size: 12px;
  line-height: 1.4;
  color: var(--pl-color-gray-500);
}

.pl-analysis-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pl-analysis-action-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 30px;
  padding: 0 12px;
  border: 1px solid var(--pl-color-gray-300);
  border-radius: 8px;
  background: var(--pl-color-white);
  color: var(--pl-color-gray-700);
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
}

.pl-analysis-action-btn:hover {
  border-color: var(--pl-color-primary);
  color: var(--pl-color-primary);
}

.pl-analysis-action-btn--primary {
  border-color: var(--pl-color-primary);
  background: var(--pl-color-primary);
  color: var(--pl-color-white);
}

.pl-analysis-action-btn--primary:hover {
  opacity: 0.92;
  color: var(--pl-color-white);
}

.pl-analysis-status {
  margin-top: 12px;
  padding: 10px 12px;
  border-radius: 10px;
  background: #eff6ff;
  color: #1d4ed8;
  font-size: 12px;
  line-height: 1.5;
}

.pl-analysis-body {
  margin-top: 16px;
}

.pl-analysis-loading,
.pl-analysis-error,
.pl-analysis-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 180px;
  border: 1px dashed var(--pl-color-gray-300);
  border-radius: 12px;
  background: var(--pl-color-gray-50);
  color: var(--pl-color-gray-500);
  font-size: 13px;
  text-align: center;
}

.pl-analysis-content {
  display: grid;
  gap: 16px;
}

.pl-analysis-summary-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 12px;
}

.pl-analysis-metric {
  min-width: 0;
  padding: 12px 14px;
  border: 1px solid var(--pl-color-gray-200);
  border-radius: 12px;
  background: linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
}

.pl-analysis-metric-label {
  font-size: 11px;
  font-weight: 600;
  color: var(--pl-color-gray-500);
}

.pl-analysis-metric-value {
  margin-top: 6px;
  font-size: 22px;
  line-height: 1.1;
  font-weight: 700;
  color: var(--pl-color-gray-900);
}

.pl-analysis-metric-hint {
  margin-top: 6px;
  font-size: 11px;
  line-height: 1.4;
  color: var(--pl-color-gray-500);
}

.pl-analysis-sections {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 16px;
}

.pl-analysis-card {
  min-width: 0;
  padding: 14px 14px 16px;
  border: 1px solid var(--pl-color-gray-200);
  border-radius: 12px;
  background: var(--pl-color-white);
}

.pl-analysis-card--chart {
  grid-column: 1 / -1;
}

.pl-analysis-card-title {
  font-size: 14px;
  font-weight: 700;
  color: var(--pl-color-gray-900);
}

.pl-analysis-card-subtitle {
  margin-top: 4px;
  font-size: 12px;
  line-height: 1.4;
  color: var(--pl-color-gray-500);
}

.pl-analysis-year-chart {
  position: relative;
  margin-top: 12px;
  border: 1px solid var(--pl-color-gray-100);
  border-radius: 10px;
  padding: 10px 8px 4px;
  background: linear-gradient(180deg, #f8fbff 0%, #ffffff 100%);
}

.pl-analysis-year-svg {
  display: block;
  width: 100%;
  height: 240px;
  overflow: visible;
}

.pl-analysis-year-guide {
  stroke: #dbeafe;
  stroke-width: 1;
}

.pl-analysis-year-guide-label,
.pl-analysis-year-label {
  fill: var(--pl-color-gray-500);
  font-size: 11px;
}

.pl-analysis-year-line {
  fill: none;
  stroke: #0284c7;
  stroke-width: 3;
  stroke-linecap: round;
  stroke-linejoin: round;
}

.pl-analysis-year-point {
  fill: #ffffff;
  stroke: #0284c7;
  stroke-width: 2;
  cursor: pointer;
  transition: r 0.15s ease, stroke-width 0.15s ease, fill 0.15s ease;
}

.pl-analysis-year-point:hover,
.pl-analysis-year-point.is-active,
.pl-analysis-year-point:focus {
  fill: #0ea5e9;
  stroke: #0369a1;
  stroke-width: 3;
}

.pl-analysis-year-tooltip {
  position: absolute;
  transform: translate(-50%, -100%);
  min-width: 88px;
  padding: 8px 10px;
  border-radius: 10px;
  background: rgba(15, 23, 42, 0.94);
  color: #ffffff;
  box-shadow: 0 10px 28px rgba(15, 23, 42, 0.22);
  pointer-events: none;
  text-align: center;
  z-index: 2;
}

.pl-analysis-year-tooltip-year {
  font-size: 11px;
  font-weight: 600;
  opacity: 0.82;
}

.pl-analysis-year-tooltip-count {
  margin-top: 4px;
  font-size: 14px;
  font-weight: 700;
}

.pl-analysis-distribution-list {
  margin-top: 14px;
  display: grid;
  gap: 12px;
}

.pl-analysis-distribution-row {
  display: grid;
  gap: 6px;
}

.pl-analysis-distribution-label,
.pl-analysis-distribution-value {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  min-width: 0;
  font-size: 12px;
}

.pl-analysis-distribution-label {
  justify-content: flex-start;
  color: var(--pl-color-gray-700);
  font-weight: 600;
}

.pl-analysis-distribution-value {
  color: var(--pl-color-gray-500);
}

.pl-analysis-distribution-dot {
  width: 10px;
  height: 10px;
  border-radius: 999px;
  flex-shrink: 0;
}

.pl-analysis-distribution-track {
  position: relative;
  width: 100%;
  height: 8px;
  overflow: hidden;
  background: var(--pl-color-gray-100);
  border-radius: 999px;
}

.pl-analysis-distribution-fill {
  position: absolute;
  inset: 0 auto 0 0;
  border-radius: inherit;
}

@media (max-width: 900px) {
  .pl-analysis-panel {
    width: calc(100vw - 24px);
    max-height: calc(100vh - 24px);
    padding: 16px;
  }

  .pl-analysis-header {
    flex-direction: column;
    align-items: stretch;
  }

  .pl-analysis-actions {
    justify-content: flex-end;
  }

  .pl-analysis-sections {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (max-width: 720px) {
  .pl-analysis-sections {
    grid-template-columns: 1fr;
  }
}
`,QT=45e3,Uf=ve+`
`+KT,Hf="paperlens-filter-toolbar-host",zf="data-pl-info";function XT(r){return r?`\u6765\u6E90\uFF1A${r.provider==="custom"?"\u81EA\u5B9A\u4E49\u6A21\u578B":r.provider==="paperlens"||r.provider==="backend"?"PaperLens AI \u6A21\u578B":r.provider==="local-rules"?"\u672C\u5730\u89C4\u5219":"PaperLens AI \u6A21\u578B"}`:""}const e1=/\b(?:gpt|o[0-9]|claude|deepseek|qwen|glm|gemini|llama|mistral|mixtral|moonshot|kimi|yi|doubao|ernie|hunyuan|command-r|sonar|grok|nova|phi|pplx)[\w.\-:/]*\b/i;function t1(r){const e=r.trim().replace(/\s+/g," ").slice(0,80);return e?e1.test(e)?"AI enhanced":e:""}const Jf="paperlens:analysis-refresh",n1="http://www.w3.org/2000/svg",pa=760,hr=220,Ui=28,Vl=16,Wl=32,r1=9e4,a1=3e5,Vf={Q1:"#0f766e",Q2:"#0284c7",Q3:"#d97706",Q4:"#475569",1:"#dc2626",2:"#16a34a",3:"#d97706",4:"#475569",Unknown:"#94a3b8",guideline:"#0f766e",meta_analysis:"#0ea5e9",review:"#2563eb",rct:"#7c3aed",clinical_trial:"#f97316",observational:"#14b8a6",other:"#94a3b8"};function i1(){const r=document.createElement("div");r.className=Hf;const e=r.attachShadow({mode:"open"}),t=document.createElement("style");return t.textContent=Uf,e.appendChild(t),{host:r,shadow:e}}function o1(){const r=document.createElement("div");r.className=`${Hf}__modal-root`,r.style.position="fixed",r.style.inset="0",r.style.zIndex="2147483647",r.style.pointerEvents="none",r.style.display="block",r.style.width="auto",r.style.height="auto",r.style.background="transparent",r.style.border="0",r.style.boxShadow="none",r.style.color="inherit",r.style.lineHeight="normal";const e=r.attachShadow({mode:"open"}),t=document.createElement("style");return t.textContent=`${Uf}

:host {
  background: transparent !important;
  border: 0 !important;
  box-shadow: none !important;
  width: auto !important;
  height: auto !important;
  font-size: inherit !important;
  color: inherit !important;
  line-height: normal !important;
}
`,e.appendChild(t),{host:r,shadow:e}}function Wf(r){return{sortField:r.sortField,oaOnly:r.oaOnly,jcrQuartiles:Array.from(r.jcrQuartiles),casQuartiles:Array.from(r.casQuartiles),yearMin:r.yearMin,yearMax:r.yearMax,ifMin:r.ifMin,ifMax:r.ifMax,journalQuery:r.journalQuery}}function s1(r){return r.sortField!=="default"||r.oaOnly||r.jcrQuartiles.length>0||r.casQuartiles.length>0||r.yearMin!==void 0||r.yearMax!==void 0||r.ifMin!==void 0||r.ifMax!==void 0||!!r.journalQuery}function Gf(){try{return new URL(window.location.href).searchParams.get("term")?.trim()??""}catch{return""}}async function l1(r){try{return await navigator.clipboard.writeText(r),!0}catch{const e=document.createElement("textarea");e.value=r,e.style.position="fixed",e.style.left="-9999px",e.style.opacity="0",document.body.appendChild(e),e.select();try{return document.execCommand("copy")}catch{return!1}finally{e.remove()}}}function Zf(r){r.addEventListener("keydown",e=>{(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==="a"&&(e.preventDefault(),e.stopPropagation(),r.select())})}function ha(r){r.style.height="auto",r.style.height=`${r.scrollHeight}px`}function c1(r){const e=r.trim();if(!e)return;const t=new URL(window.location.href);t.pathname="/",t.search="",t.hash="",t.searchParams.set("term",e),window.location.assign(t.toString())}function fa(r){return Number.isFinite(r)?`${Math.round(Math.max(0,Math.min(1,r))*100)}%`:"0%"}function Te(r){r.replaceChildren()}function ge(r){return document.createElementNS(n1,r)}function fr(r,e,t){const n=document.createElement("div");n.className="pl-analysis-metric";const a=document.createElement("div");a.className="pl-analysis-metric-label",a.textContent=r;const i=document.createElement("div");if(i.className="pl-analysis-metric-value",i.textContent=e,n.append(a,i),t){const o=document.createElement("div");o.className="pl-analysis-metric-hint",o.textContent=t,n.appendChild(o)}return n}function u1(r){return r<=10?1:Math.ceil(r/10)}function d1(r){const e=document.createElement("section");e.className="pl-analysis-card pl-analysis-card--chart";const t=document.createElement("div");t.className="pl-analysis-card-title",t.textContent="\u7814\u7A76\u65F6\u95F4\u5206\u5E03";const n=document.createElement("div");if(n.className="pl-analysis-card-subtitle",n.textContent="\u57FA\u4E8E\u5F53\u524D\u7ED3\u679C\u96C6\u6309\u5E74\u4EFD\u805A\u5408",e.append(t,n),r.length===0){const k=document.createElement("div");return k.className="pl-analysis-empty",k.textContent="\u5F53\u524D\u7ED3\u679C\u7F3A\u5C11\u7A33\u5B9A\u7684\u5E74\u4EFD\u5143\u6570\u636E",e.appendChild(k),e}const a=document.createElement("div");a.className="pl-analysis-year-chart";const i=document.createElement("div");i.className="pl-analysis-year-tooltip",i.hidden=!0;const o=ge("svg");o.setAttribute("viewBox",`0 0 ${pa} ${hr}`),o.setAttribute("class","pl-analysis-year-svg");const s=pa-Ui*2,l=hr-Vl-Wl,c=Math.max(...r.map(k=>k.count),1),u=u1(r.length),d=r.map((k,N)=>{const S=r.length===1?pa/2:Ui+s*N/(r.length-1),_=k.count/c,P=Vl+l-_*l;return{...k,x:S,y:P}});for(const k of[c,Math.round(c*.5),0]){const N=c>0?k/c:0,S=Vl+l-N*l,_=ge("line");_.setAttribute("x1",String(Ui)),_.setAttribute("x2",String(pa-Ui)),_.setAttribute("y1",S.toFixed(2)),_.setAttribute("y2",S.toFixed(2)),_.setAttribute("class","pl-analysis-year-guide"),o.appendChild(_);const P=ge("text");P.textContent=String(k),P.setAttribute("x","4"),P.setAttribute("y",String(S+4)),P.setAttribute("class","pl-analysis-year-guide-label"),o.appendChild(P)}const p=d.map((k,N)=>`${N===0?"M":"L"} ${k.x.toFixed(2)} ${k.y.toFixed(2)}`).join(" "),h=[`M ${d[0].x.toFixed(2)} ${(hr-Wl).toFixed(2)}`,`L ${d[0].x.toFixed(2)} ${d[0].y.toFixed(2)}`,...d.slice(1).map(k=>`L ${k.x.toFixed(2)} ${k.y.toFixed(2)}`),`L ${d[d.length-1].x.toFixed(2)} ${(hr-Wl).toFixed(2)}`,"Z"].join(" "),f=ge("defs"),y=ge("linearGradient");y.setAttribute("id","pl-analysis-year-fill"),y.setAttribute("x1","0"),y.setAttribute("x2","0"),y.setAttribute("y1","0"),y.setAttribute("y2","1");const x=ge("stop");x.setAttribute("offset","0%"),x.setAttribute("stop-color","#0ea5e9"),x.setAttribute("stop-opacity","0.24");const T=ge("stop");T.setAttribute("offset","100%"),T.setAttribute("stop-color","#0ea5e9"),T.setAttribute("stop-opacity","0.02"),y.append(x,T),f.appendChild(y),o.appendChild(f);const E=ge("path");E.setAttribute("d",h),E.setAttribute("fill","url(#pl-analysis-year-fill)"),o.appendChild(E);const w=ge("path");w.setAttribute("d",p),w.setAttribute("class","pl-analysis-year-line"),o.appendChild(w);let v=null,g=null;const C=k=>{g&&g!==k&&g.classList.remove("is-active"),g=k,g?.classList.add("is-active")},L=(k,N,S)=>{C(N),v=S?k.year:v,i.hidden=!1;const _=document.createElement("div");_.className="pl-analysis-year-tooltip-year",_.textContent=String(k.year);const P=document.createElement("div");P.className="pl-analysis-year-tooltip-count",P.textContent=`${k.count.toLocaleString()} \u7BC7`,i.replaceChildren(_,P);const R=k.x/pa*100,M=Math.max(12,k.y/hr*100-10);i.style.left=`${R}%`,i.style.top=`${M}%`},$=()=>{v===null&&(i.hidden=!0,g&&(g.classList.remove("is-active"),g=null))};return d.forEach((k,N)=>{const S=ge("circle");S.setAttribute("cx",k.x.toFixed(2)),S.setAttribute("cy",k.y.toFixed(2)),S.setAttribute("r","4"),S.setAttribute("class","pl-analysis-year-point"),S.setAttribute("tabindex","0"),S.setAttribute("role","button"),S.setAttribute("aria-label",`${k.year} \u5E74 ${k.count.toLocaleString()} \u7BC7`);const _=ge("title");if(_.textContent=`${k.year}: ${k.count.toLocaleString()} \u7BC7`,S.appendChild(_),S.addEventListener("mouseenter",()=>{v!==null&&v!==k.year||L(k,S,!1)}),S.addEventListener("focus",()=>{v!==null&&v!==k.year||L(k,S,!1)}),S.addEventListener("mouseleave",$),S.addEventListener("blur",$),S.addEventListener("click",()=>{if(v===k.year){v=null,$();return}v=k.year,L(k,S,!0)}),o.appendChild(S),N%u===0||N===d.length-1){const P=ge("text");P.textContent=String(k.year),P.setAttribute("x",k.x.toFixed(2)),P.setAttribute("y",String(hr-8)),P.setAttribute("text-anchor","middle"),P.setAttribute("class","pl-analysis-year-label"),o.appendChild(P)}}),a.addEventListener("mouseleave",$),a.append(o,i),e.appendChild(a),e}function Gl(r,e,t){const n=document.createElement("section");n.className="pl-analysis-card";const a=document.createElement("div");a.className="pl-analysis-card-title",a.textContent=r;const i=document.createElement("div");if(i.className="pl-analysis-card-subtitle",i.textContent=e,n.append(a,i),t.length===0){const s=document.createElement("div");return s.className="pl-analysis-empty",s.textContent="\u5F53\u524D\u7ED3\u679C\u7F3A\u5C11\u53EF\u7EDF\u8BA1\u7684\u6837\u672C",n.appendChild(s),n}const o=document.createElement("div");o.className="pl-analysis-distribution-list";for(const s of t){const l=document.createElement("div");l.className="pl-analysis-distribution-row";const c=document.createElement("div");c.className="pl-analysis-distribution-label";const u=document.createElement("span");u.className="pl-analysis-distribution-dot",u.style.backgroundColor=Vf[s.key]??"#94a3b8";const d=document.createElement("span");d.textContent=s.label,c.append(u,d);const p=document.createElement("div");p.className="pl-analysis-distribution-value",p.textContent=`${s.count.toLocaleString()} \xB7 ${fa(s.share)}`;const h=document.createElement("div");h.className="pl-analysis-distribution-track";const f=document.createElement("div");f.className="pl-analysis-distribution-fill",f.style.width=fa(s.share),f.style.backgroundColor=Vf[s.key]??"#94a3b8",h.appendChild(f),l.append(c,p,h),o.appendChild(l)}return n.appendChild(o),n}function Yf(r){const e=document.createElement("div");e.className="pl-analysis-content";const t=document.createElement("div");t.className="pl-analysis-summary-grid";const n=r.earliestYear&&r.latestYear?r.earliestYear===r.latestYear?String(r.latestYear):`${r.earliestYear} - ${r.latestYear}`:"\u6682\u65E0",a=r.snapshot.records.length>0?fa(r.q1Count/r.snapshot.records.length):"0%",i=`${r.matchedQuartileCount.toLocaleString()}/${r.snapshot.records.length.toLocaleString()} \u6761\u5DF2\u5339\u914D`,o=`${r.matchedCasCount.toLocaleString()}/${r.snapshot.records.length.toLocaleString()} \u6761\u5DF2\u5339\u914D`,s=r.evidenceDistribution[0]?.label??"\u6682\u65E0";t.append(fr("\u6837\u672C\u6570",r.snapshot.records.length.toLocaleString(),Jl(r.snapshot)),fr("\u65F6\u95F4\u8DE8\u5EA6",n,r.yearDistribution.length>0?"\u6309\u5E74\u4EFD\u7EDF\u8BA1":"\u7F3A\u5C11\u5E74\u4EFD\u6570\u636E"),fr("Q1 \u5360\u6BD4",a,`${r.q1Count.toLocaleString()} \u6761\u843D\u5165 Q1`),fr("JCR \u5339\u914D",fa(r.snapshot.records.length>0?r.matchedQuartileCount/r.snapshot.records.length:0),i),fr("\u4E2D\u79D1\u9662\u5339\u914D",fa(r.snapshot.records.length>0?r.matchedCasCount/r.snapshot.records.length:0),o),fr("\u4E3B\u5BFC\u8BC1\u636E",s,r.evidenceDistribution[0]?`${r.evidenceDistribution[0].count.toLocaleString()} \u6761`:void 0));const l=document.createElement("div");return l.className="pl-analysis-sections",l.append(d1(r.yearDistribution),Gl("JCR \u5206\u533A\u5206\u5E03","\u6309\u5F53\u524D\u7ED3\u679C\u96C6\u7684 JCR \u5206\u533A\u7EDF\u8BA1",r.quartileDistribution),Gl("\u4E2D\u79D1\u9662\u5206\u533A\u5206\u5E03","\u6309\u5F53\u524D\u7ED3\u679C\u96C6\u7684\u4E2D\u79D1\u9662\u5206\u533A\u7EDF\u8BA1",r.casDistribution),Gl("\u8BC1\u636E\u7C7B\u578B\u5206\u5E03","\u57FA\u4E8E PubMed publication type / article type \u5F52\u7C7B",r.evidenceDistribution)),e.append(t,l),e}function p1(r,e,t){const{host:n,shadow:a}=i1(),{host:i,shadow:o}=o1();xn(),document.body.appendChild(i);const s={sortField:"default",oaOnly:!1,jcrQuartiles:new Set,casQuartiles:new Set},l=()=>{r(Wf(s))};let c=!1,u=null,d=null,p=!1,h=0,f=!1,y=!1,x=!1,T=!1,E="";const w=[],v=document.body.style.overflow,g=document.documentElement.style.overflow,C=b=>{c=b,n.dataset.plFilterPending=b?"true":"false",u&&(u.disabled=T||!b,u.classList.toggle("pl-apply-filter-btn--pending",b))},L=()=>{C(!0),d&&(d.textContent=T?E:"\u7B5B\u9009\u6761\u4EF6\u5DF2\u4FEE\u6539\uFF0C\u70B9\u51FB\u6267\u884C\u7B5B\u9009")},$=(b,A="")=>{for(const G of w)G.disabled=b,b?(G.title=A,G.setAttribute("aria-disabled","true")):(G.title="",G.removeAttribute("aria-disabled"))};function k(b=!0){Q.value="default",s.sortField="default",X.checked=!1,s.oaOnly=!1;for(const A of Oe.querySelectorAll(".pl-quartile-btn"))A.classList.remove("active");s.jcrQuartiles.clear();for(const A of Ct.querySelectorAll(".pl-quartile-btn"))A.classList.remove("active");s.casQuartiles.clear(),Ue.value="",He.value="",s.yearMin=void 0,s.yearMax=void 0,Fe.value="",De.value="",s.ifMin=void 0,s.ifMax=void 0,vt.value="",s.journalQuery=void 0,C(!1),b&&l()}const N=b=>{T=!0,E=b,k(!0),$(!0,b),u&&(u.textContent="\u5347\u7EA7\u540E\u7B5B\u9009",u.title=b,u.setAttribute("aria-disabled","true")),d&&(d.textContent=b)},S=()=>{T&&(T=!1,E="",$(!1),u&&(u.textContent="\u6267\u884C\u7B5B\u9009",u.title="",u.removeAttribute("aria-disabled")),C(c),d&&(d.textContent=c?"\u6743\u76CA\u5DF2\u5237\u65B0\uFF0C\u53EF\u7EE7\u7EED\u7B5B\u9009":""))},_=async()=>{if(!c)return;const b=Wf(s);if(s1(b)){u?.setAttribute("disabled","true"),d&&(d.textContent="\u6B63\u5728\u6821\u9A8C\u9AD8\u7EA7\u7B5B\u9009\u6743\u9650...");const A=await Os();if(!A.allowed){const G=A.error||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528 PubMed \u9AD8\u7EA7\u7B5B\u9009";N(G),D.error(G);return}}C(!1),r(b)},P=document.createElement("div");P.className="pl-toolbar";const R=document.createElement("div");R.className="pl-toolbar-group";const M=document.createElement("span");M.className="pl-toolbar-label",M.textContent="\u6392\u5E8F";const Q=document.createElement("select");Q.className="pl-sort-select";const se=[{value:"default",label:"PubMed \u9ED8\u8BA4\u6392\u5E8F"},{value:"impactFactor-desc",label:"IF \u964D\u5E8F \u2193"},{value:"impactFactor-asc",label:"IF \u5347\u5E8F \u2191"},{value:"citationCount-desc",label:"\u88AB\u5F15\u6570\u964D\u5E8F \u2193"},{value:"citationCount-asc",label:"\u88AB\u5F15\u6570\u5347\u5E8F \u2191"},{value:"year-desc",label:"\u5E74\u4EFD\u964D\u5E8F \u2193"},{value:"year-asc",label:"\u5E74\u4EFD\u5347\u5E8F \u2191"}];for(const b of se){const A=document.createElement("option");A.value=b.value,A.textContent=b.label,Q.appendChild(A)}Q.addEventListener("change",()=>{s.sortField=Q.value,L()}),R.append(M,Q);const at=document.createElement("div");at.className="pl-toolbar-group";const fe=document.createElement("label");fe.className="pl-oa-toggle";const X=document.createElement("input");X.type="checkbox";const xt=document.createElement("span");xt.className="pl-oa-switch";const Xt=document.createElement("span");Xt.className="pl-oa-text",Xt.textContent="\u4EC5 OA",fe.append(X,xt,Xt),X.addEventListener("change",()=>{s.oaOnly=X.checked,L()}),at.appendChild(fe);const Oe=document.createElement("div");Oe.className="pl-toolbar-group";const At=document.createElement("span");At.className="pl-toolbar-label",At.textContent="JCR",Oe.appendChild(At);for(const b of["Q1","Q2","Q3","Q4"]){const A=document.createElement("button");A.className="pl-quartile-btn",A.setAttribute("data-q",b),A.textContent=b,A.addEventListener("click",()=>{s.jcrQuartiles.has(b)?(s.jcrQuartiles.delete(b),A.classList.remove("active")):(s.jcrQuartiles.add(b),A.classList.add("active")),L()}),Oe.appendChild(A)}const Ct=document.createElement("div");Ct.className="pl-toolbar-group";const xr=document.createElement("span");xr.className="pl-toolbar-label",xr.textContent="\u4E2D\u79D1\u9662\u5206\u533A",Ct.appendChild(xr);for(const b of["1","2","3","4"]){const A=document.createElement("button");A.className="pl-quartile-btn",A.setAttribute("data-cas",b),A.textContent=`${b}\u533A`,A.addEventListener("click",()=>{s.casQuartiles.has(b)?(s.casQuartiles.delete(b),A.classList.remove("active")):(s.casQuartiles.add(b),A.classList.add("active")),L()}),Ct.appendChild(A)}const Ar=document.createElement("div");Ar.className="pl-toolbar-group";const Ec=document.createElement("span");Ec.className="pl-toolbar-label",Ec.textContent="\u5E74\u4EFD";const Ue=document.createElement("input");Ue.className="pl-year-input",Ue.type="number",Ue.placeholder="\u8D77",Ue.min="1900",Ue.max="2100";const Fc=document.createElement("span");Fc.className="pl-year-sep",Fc.textContent="\u2013";const He=document.createElement("input");He.className="pl-year-input",He.type="number",He.placeholder="\u6B62",He.min="1900",He.max="2100";const ao=()=>{const b=Ue.value?parseInt(Ue.value,10):void 0,A=He.value?parseInt(He.value,10):void 0;s.yearMin=b!==void 0&&!isNaN(b)&&b>=1900&&b<=2100?b:void 0,s.yearMax=A!==void 0&&!isNaN(A)&&A>=1900&&A<=2100?A:void 0,L()};Ue.addEventListener("input",ao),Ue.addEventListener("change",ao),He.addEventListener("input",ao),He.addEventListener("change",ao),Ar.append(Ec,Ue,Fc,He);const Dc=document.createElement("div");Dc.className="pl-toolbar-group";const _c=document.createElement("span");_c.className="pl-toolbar-label",_c.textContent="IF \u8303\u56F4";const Fe=document.createElement("input");Fe.className="pl-year-input pl-if-input",Fe.type="number",Fe.placeholder="\u6700\u4F4E",Fe.min="0",Fe.max="500",Fe.step="0.5";const kc=document.createElement("span");kc.className="pl-year-sep",kc.textContent="\u2013";const De=document.createElement("input");De.className="pl-year-input pl-if-input",De.type="number",De.placeholder="\u6700\u9AD8",De.min="0",De.max="500",De.step="0.5";const io=()=>{let b=Fe.value?parseFloat(Fe.value):void 0,A=De.value?parseFloat(De.value):void 0;b=b!==void 0&&!isNaN(b)&&b>=0?b:void 0,A=A!==void 0&&!isNaN(A)&&A>=0?A:void 0,b!==void 0&&A!==void 0&&b>A&&([b,A]=[A,b],Fe.value=String(b),De.value=String(A)),s.ifMin=b,s.ifMax=A,L()};Fe.addEventListener("change",io),Fe.addEventListener("input",io),De.addEventListener("change",io),De.addEventListener("input",io),Dc.append(_c,Fe,kc,De);const Nc=document.createElement("div");Nc.className="pl-toolbar-group";const Lc=document.createElement("span");Lc.className="pl-toolbar-label",Lc.textContent="\u671F\u520A";const vt=document.createElement("input");vt.className="pl-journal-input",vt.type="text",vt.placeholder="\u8F93\u5165\u671F\u520A\u540D";const kF=()=>{const b=vt.value.trim();s.journalQuery=b||void 0,L()};vt.addEventListener("input",kF),vt.addEventListener("keydown",b=>{b.key==="Enter"&&(b.preventDefault(),_())}),Nc.append(Lc,vt);const Rc=document.createElement("div");Rc.className="pl-toolbar-group",u=document.createElement("button"),u.className="pl-restore-btn pl-apply-filter-btn",u.type="button",u.textContent="\u6267\u884C\u7B5B\u9009",u.disabled=!0,u.addEventListener("click",()=>{_()}),Rc.appendChild(u),w.push(Q,X,...Array.from(Oe.querySelectorAll(".pl-quartile-btn")),...Array.from(Ct.querySelectorAll(".pl-quartile-btn")),Ue,He,Fe,De,vt),T&&N(E);const Pc=document.createElement("div");Pc.className="pl-toolbar-group";const Da=document.createElement("button");Da.className="pl-restore-btn",Da.setAttribute("data-pl-action","restore");const Bc=document.createElement("span");Bc.className="pl-restore-btn-icon",Bc.textContent="\u21A9";const hb=document.createElement("span");hb.textContent="\u6062\u590D",Da.append(Bc,hb),Da.addEventListener("click",()=>{k(!0)}),Pc.appendChild(Da);const fb=[{value:"ris",label:"RIS (EndNote/Zotero)"},{value:"bibtex",label:"BibTeX (LaTeX)"},{value:"medline",label:"NBIB (MEDLINE)"},{value:"csv",label:"CSV (Excel)"}],oo=document.createElement("div");oo.className="pl-toolbar-group pl-export-menu-group";const Fn=document.createElement("button");Fn.type="button",Fn.className="pl-restore-btn",Fn.textContent="\u6279\u91CF\u5BFC\u51FA",Fn.title="\u4F18\u5148\u5BFC\u51FA\u5DF2\u9009\u6587\u732E\uFF0C\u5426\u5219\u5BFC\u51FA\u5F53\u524D\u53EF\u89C1\u7ED3\u679C",Fn.setAttribute("aria-label","\u6279\u91CF\u5BFC\u51FA\u6587\u732E");const it=document.createElement("div");it.className="pl-toolbar-export-dropdown",it.style.display="none";for(const b of fb){const A=document.createElement("button");A.type="button",A.className="pl-batch-dropdown-item",A.textContent=b.label,A.dataset.exportFormat=b.value,A.dataset.defaultLabel=b.label,A.addEventListener("click",async()=>{it.style.display="none",await Xf(b.value)}),it.appendChild(A)}Fn.addEventListener("click",b=>{b.preventDefault(),b.stopPropagation();const A=it.style.display!=="none";it.style.display=A?"none":"block",!A&&tm(it)}),oo.append(Fn,it);const Ic=document.createElement("div");Ic.className="pl-toolbar-group";const ye=document.createElement("button");ye.type="button",ye.className="pl-restore-btn",ye.textContent="\u7ED3\u679C\u5206\u6790",ye.title="\u5206\u6790\u5F53\u524D\u7B5B\u9009\u7ED3\u679C\u7684\u5E74\u4EFD\u3001JCR \u5206\u533A\u548C\u8BC1\u636E\u7C7B\u578B\u5206\u5E03",ye.disabled=!t,Ic.appendChild(ye);const ot=document.createElement("div");ot.className="pl-analysis-overlay",ot.setAttribute("aria-hidden","true");const Cr=document.createElement("div");Cr.className="pl-analysis-panel",Cr.setAttribute("role","dialog"),Cr.setAttribute("aria-modal","true"),Cr.setAttribute("aria-label","PubMed \u7ED3\u679C\u5206\u6790");const Mc=document.createElement("div");Mc.className="pl-analysis-header";const qc=document.createElement("div");qc.className="pl-analysis-header-text";const jc=document.createElement("div");jc.className="pl-analysis-title",jc.textContent="\u5168\u91CF\u7ED3\u679C\u5206\u6790";const $c=document.createElement("div");$c.className="pl-analysis-subtitle",$c.textContent="\u57FA\u4E8E\u5F53\u524D\u7B5B\u9009\u7ED3\u679C\u5B9E\u65F6\u7EDF\u8BA1",qc.append(jc,$c);const Oc=document.createElement("div");Oc.className="pl-analysis-actions";const St=document.createElement("button");St.type="button",St.className="pl-analysis-action-btn",St.textContent="\u5237\u65B0";const _a=document.createElement("button");_a.type="button",_a.className="pl-analysis-action-btn pl-analysis-action-btn--primary",_a.textContent="\u5173\u95ED",Oc.append(St,_a),Mc.append(qc,Oc);const me=document.createElement("div");me.className="pl-analysis-status";const xe=document.createElement("div");xe.className="pl-analysis-body",Cr.append(Mc,me,xe),ot.appendChild(Cr);const so=b=>{Te(me),me.textContent=b,Te(xe);const A=document.createElement("div");A.className="pl-analysis-loading",A.textContent="\u6B63\u5728\u6574\u7406\u7ED3\u679C\u5206\u5E03...",xe.appendChild(A)},lo=b=>{Te(me),me.textContent=b,Te(xe);const A=document.createElement("div");A.className="pl-analysis-empty",A.textContent="\u5F53\u524D\u6CA1\u6709\u53EF\u7EDF\u8BA1\u7684\u7B5B\u9009\u7ED3\u679C",xe.appendChild(A)},NF=b=>{Te(me),me.textContent=b,Te(xe);const A=document.createElement("div");A.className="pl-analysis-error",A.textContent="\u7ED3\u679C\u5206\u6790\u52A0\u8F7D\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",xe.appendChild(A)},LF=b=>{Te(me),me.textContent=b,Te(xe);const A=document.createElement("div");A.className="pl-analysis-error",A.textContent=b,xe.appendChild(A)},mb=(b,A=!1)=>{x=!0,A&&(h+=1,f=!1,y=!1),ye.disabled=!0,ye.textContent="\u7ED3\u679C\u5206\u6790 Pro",ye.title=b,ye.setAttribute("aria-disabled","true"),St.disabled=!0,St.title=b,LF(b)},RF=()=>{x&&(x=!1,ye.disabled=!t,ye.textContent="\u7ED3\u679C\u5206\u6790",ye.title=t?"\u5206\u6790\u5F53\u524D\u7B5B\u9009\u7ED3\u679C\u7684\u5E74\u4EFD\u3001JCR \u5206\u533A\u548C\u8BC1\u636E\u7C7B\u578B\u5206\u5E03":"\u5F53\u524D\u73AF\u5883\u4E0D\u652F\u6301\u7ED3\u679C\u5206\u6790",ye.removeAttribute("aria-disabled"),St.disabled=!1,St.title="",p&&(Te(me),me.textContent="\u6743\u76CA\u5DF2\u5237\u65B0\uFF0C\u53EF\u91CD\u65B0\u52A0\u8F7D\u7ED3\u679C\u5206\u6790",Te(xe)))},co=async(b=!1)=>{if(f){y=!0;return}if(!t){lo("\u5F53\u524D\u73AF\u5883\u4E0D\u652F\u6301\u7ED3\u679C\u5206\u6790");return}const A=++h;f=!0,y=!1,so("\u6B63\u5728\u6821\u9A8C\u7ED3\u679C\u5206\u6790\u6743\u9650...");try{const G=await _p();if(A!==h)return;if(!G.allowed){const z=G.error||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528 PubMed \u5168\u91CF\u7ED3\u679C\u5206\u6790";mb(z),D.error(z);return}so("\u6B63\u5728\u6C47\u603B\u5F53\u524D\u7B5B\u9009\u7ED3\u679C...");const ae=await t(z=>{if(A!==h)return;if(z.records.length===0&&(z.loading||!z.done)){so(pr(z));return}if(z.records.length===0){lo(pr(z));return}const st=Of(z);Te(me),me.textContent=`${Jl(z)} \xB7 ${pr(z)}`,Te(xe),xe.appendChild(Yf(st))});if(A!==h)return;if(!ae){lo("\u5F53\u524D\u6CA1\u6709\u7ED3\u679C\u6570\u636E");return}if(ae.records.length===0&&(ae.loading||!ae.done)){so(pr(ae));return}if(ae.records.length===0){lo(ae?pr(ae):"\u5F53\u524D\u6CA1\u6709\u7ED3\u679C\u6570\u636E");return}const O=Of(ae);Te(me),me.textContent=`${Jl(ae)} \xB7 ${pr(ae)}`,Te(xe),xe.appendChild(Yf(O))}catch(G){if(A!==h)return;console.error("[PaperLens] result analysis render failed:",G),NF("\u7ED3\u679C\u5206\u6790\u6E32\u67D3\u5931\u8D25")}finally{A===h&&(f=!1,p&&y&&(y=!1,co(b)))}},PF=()=>{p=!0,document.body.style.overflow="hidden",document.documentElement.style.overflow="hidden",ot.classList.add("is-open"),ot.setAttribute("aria-hidden","false"),co()},Uc=()=>{p=!1,y=!1,document.body.style.overflow=v,document.documentElement.style.overflow=g,ot.classList.remove("is-open"),ot.setAttribute("aria-hidden","true")};ye.addEventListener("click",()=>{PF()}),St.addEventListener("click",()=>{co(!0)}),_a.addEventListener("click",Uc),ot.addEventListener("click",b=>{b.target===ot&&Uc()}),document.addEventListener("keydown",b=>{if(p){if((b.metaKey||b.ctrlKey)&&b.key.toLowerCase()==="a"){b.preventDefault(),b.stopPropagation();return}b.key==="Escape"&&p&&(b.preventDefault(),b.stopPropagation(),Uc())}},!0),n.addEventListener(Jf,()=>{p&&co()});const uo=document.createElement("div");uo.className="pl-toolbar-progress",uo.style.display="none";const bb=document.createElement("div");bb.className="pl-toolbar-progress-fill",uo.appendChild(bb);const Dn=document.createElement("button");Dn.className="pl-toolbar-cancel-btn",Dn.type="button",Dn.title="\u505C\u6B62\u7B5B\u9009",Dn.style.display="none",Dn.appendChild(h1()),e&&Dn.addEventListener("click",b=>{b.preventDefault(),b.stopPropagation(),e()});const ka=document.createElement("span");ka.className="pl-toolbar-info",ka.setAttribute(zf,""),ka.textContent="\u9ED8\u8BA4\u5168\u91CF\u7B5B\u9009",d=ka;const Na=document.createElement("div");Na.className="pl-batch-bar",Na.style.display="none";const po=document.createElement("span");po.className="pl-batch-count",po.textContent="\u5DF2\u9009 0 \u7BC7";const La=document.createElement("button");La.type="button",La.className="pl-batch-btn",La.textContent="\u5168\u9009\u5F53\u524D\u9875";const Ra=document.createElement("button");Ra.type="button",Ra.className="pl-batch-btn",Ra.textContent="\u53D6\u6D88\u9009\u62E9";const ho=document.createElement("div");ho.className="pl-batch-export-group";const _n=document.createElement("button");_n.type="button",_n.className="pl-batch-btn pl-batch-btn--primary",_n.textContent="\u6279\u91CF\u5BFC\u51FA",_n.title="\u5BFC\u51FA\u5DF2\u9009\u6587\u732E",_n.setAttribute("aria-label","\u6279\u91CF\u5BFC\u51FA\u5DF2\u9009\u6587\u732E");const wt=document.createElement("div");wt.className="pl-batch-dropdown",wt.style.display="none";for(const b of fb){const A=document.createElement("button");A.type="button",A.className="pl-batch-dropdown-item",A.textContent=b.label,A.dataset.exportFormat=b.value,A.dataset.defaultLabel=b.label,A.addEventListener("click",async()=>{wt.style.display="none",await Xf(b.value)}),wt.appendChild(A)}_n.addEventListener("click",b=>{b.preventDefault(),b.stopPropagation();const A=wt.style.display!=="none";it.style.display="none",wt.style.display=A?"none":"block",!A&&tm(wt)}),ho.append(_n,wt);const BF=$T(()=>{const A=Be.getInstance().getSelected(),G=[];for(const[ae,O]of A)G.push({pmid:ae,title:O.title,authors:O.authors,doi:O.DOI,journal:O.journal,year:O.year,publicationDate:O.publicationDate,abstract:O.abstractSnippet});return G});Na.append(po,La,Ra,ho,BF);const fo=document.createElement("div");fo.className="pl-query-optimizer-inline";const Hc=document.createElement("div");Hc.className="pl-query-optimizer-header";const zc=document.createElement("span");zc.className="pl-toolbar-label pl-query-optimizer-label",zc.textContent="PubMed \u68C0\u7D22\u8BCD\u4F18\u5316";const Jc=document.createElement("div");Jc.className="pl-query-mode-controls";const mo=document.createElement("div");mo.className="pl-query-mode-group pl-query-mode-group--generation",mo.setAttribute("aria-label","\u4F18\u5316\u6A21\u5F0F");let kn="rules";const en=document.createElement("button");en.type="button",en.className="pl-query-mode-btn active",en.textContent="\u57FA\u7840\u89C4\u5219";const tn=document.createElement("button");tn.type="button",tn.className="pl-query-mode-btn",tn.textContent="AI \u589E\u5F3A";const gb=b=>{kn=b,en.classList.toggle("active",b==="rules"),tn.classList.toggle("active",b==="ai")};mo.append(en,tn);const bo=document.createElement("div");bo.className="pl-query-mode-group",bo.setAttribute("aria-label","\u68C0\u7D22\u7B56\u7565");let Pa="balanced";const nn=document.createElement("button");nn.type="button",nn.className="pl-query-mode-btn active",nn.textContent="\u5E73\u8861";const rn=document.createElement("button");rn.type="button",rn.className="pl-query-mode-btn",rn.textContent="\u7CBE\u51C6";const yb=b=>{Pa=b,nn.classList.toggle("active",b==="balanced"),rn.classList.toggle("active",b==="strict")};bo.append(nn,rn),Jc.append(mo,bo),Hc.append(zc,Jc);const Vc=document.createElement("div");Vc.className="pl-query-optimizer-body";const _e=document.createElement("textarea");_e.className="pl-query-input",_e.rows=3,_e.placeholder="\u8F93\u5165\u5173\u952E\u8BCD / PMID / DOI / \u4F5C\u8005 / \u671F\u520A",_e.value=Gf(),Zf(_e);const Wc=document.createElement("div");Wc.className="pl-query-action-group";const Ae=document.createElement("button");Ae.type="button",Ae.className="pl-query-action-btn pl-query-action-btn--primary",Ae.textContent="\u751F\u6210";const Tt=document.createElement("button");Tt.type="button",Tt.className="pl-query-action-btn",Tt.textContent="\u590D\u5236\u68C0\u7D22\u8BCD",Tt.disabled=!0;const Nn=document.createElement("button");Nn.type="button",Nn.className="pl-query-action-btn pl-query-action-btn--primary",Nn.textContent="\u5E94\u7528\u68C0\u7D22",Nn.disabled=!0;const Ba=document.createElement("button");Ba.type="button",Ba.className="pl-query-action-btn",Ba.textContent="\u91CD\u7F6E",Wc.append(Ae,Tt,Nn,Ba);const Et=document.createElement("textarea");Et.className="pl-query-output",Et.rows=3,Et.readOnly=!0,Et.placeholder="\u751F\u6210\u540E\u7684 PubMed \u68C0\u7D22\u5F0F\u4F1A\u663E\u793A\u5728\u8FD9\u91CC",Zf(Et);let vr="",Ft=0,Sr=0,Ia=!1,go="";const Ma=document.createElement("div");Ma.className="pl-query-status";const Gc=document.createElement("div");Gc.className="pl-query-warnings";const qa=document.createElement("div");qa.className="pl-query-provider-badge";const ze=(b,A="neutral")=>{Ma.className="pl-query-status",A!=="neutral"&&Ma.classList.add(`pl-query-status--${A}`),Ma.textContent=b},Ln=b=>{qa.textContent=XT(b),qa.hidden=!qa.textContent},wr=b=>{const A=b.map(mt).filter(Boolean).join(" \xB7 ");Gc.textContent=A},Dt=b=>{const A=b.trim().length>0;vr=b,Et.value=b,Tt.disabled=!A,Nn.disabled=!A,ha(Et)},Tr=b=>{if(fo.classList.toggle("pl-query-optimizer-inline--ai-pending",b),Ia){Ae.disabled=!0,Ae.textContent="\u5347\u7EA7\u540E\u4F7F\u7528",Ae.title=go;return}Ae.disabled=b,Ae.title="",Ae.textContent=b?"AI \u589E\u5F3A\u4E2D...":"\u751F\u6210"},Rn=()=>{if(Ft+=1,Sr=0,Ia){Tr(!1),Dt(""),ze(go,"warning"),Ln(),wr([]);return}Tr(!1),Dt(""),ze(""),Ln(),wr([])},Zc=b=>{Ia=!0,go=b,Ft+=1,Sr=0,Tr(!1),Dt(""),ze(b,"warning"),Ln(),wr([]);for(const A of[en,tn,nn,rn])A.disabled=!0,A.title=b,A.setAttribute("aria-disabled","true")},IF=()=>{if(Ia){Ia=!1,go="",Ae.disabled=!1,Ae.textContent="\u751F\u6210",Ae.title="",Ae.removeAttribute("aria-disabled");for(const b of[en,tn,nn,rn])b.disabled=!1,b.title="",b.removeAttribute("aria-disabled");ze(vr?"\u6743\u76CA\u5DF2\u5237\u65B0\uFF0C\u53EF\u7EE7\u7EED\u4F7F\u7528\u5F53\u524D\u68C0\u7D22\u5F0F":"","neutral")}},MF=async(b,A,G)=>{const O=await H({type:"OPTIMIZE_PUBMED_QUERY",payload:{inputText:A,strategyMode:Pa,baseQuery:G,timeoutMs:r1}},a1);if(b!==Ft)return;const z=O?.data?.query?.trim()??"";if(!O?.success||!z)throw new Error(mt(O?.error||O?.data?.fallbackReason||"AI \u589E\u5F3A\u5931\u8D25"));if(O.data?.generation?.provider==="local-rules"||O.data?.tag==="Rules fallback")throw new Error(mt(O.data?.fallbackReason||O.data?.generation?.fallbackReason||O.data?.warnings?.[0]||"AI \u589E\u5F3A\u5931\u8D25"));Dt(z);const qF=O.data?.mode==="hybrid"?"\u6DF7\u5408\u589E\u5F3A":"AI \u589E\u5F3A",Cb=O.data?.tag?t1(O.data.tag):"",jF=Cb?`\uFF08${Cb}\uFF09`:"";ze(`\u5DF2\u751F\u6210${qF}\u68C0\u7D22\u5F0F${jF}`,"success"),Ln(O.data?.generation),wr([...O.data?.fallbackReason?[O.data.fallbackReason]:[],...O.data?.warnings??[]]),D.success("AI \u589E\u5F3A\u68C0\u7D22\u5F0F\u5DF2\u751F\u6210")},xb=async()=>{const b=_e.value.trim();if(!b){Rn(),D.error("\u8BF7\u8F93\u5165\u6709\u6548\u7684\u82F1\u6587\u5173\u952E\u8BCD\u6216 PubMed \u68C0\u7D22\u5F0F");return}const A=Ft+1;Ft=A,Sr=A,Tr(!1),wr([]);try{ze("\u6B63\u5728\u6821\u9A8C PubMed \u68C0\u7D22\u8BCD\u4F18\u5316\u6743\u9650...","pending");const G=await Dp();if(A!==Ft)return;if(!G.allowed){const z=G.error||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528 PubMed \u68C0\u7D22\u8BCD\u4F18\u5316";if(G.transient){Dt(""),ze(z,"warning"),Ln(),wr([]),D.error(z);return}Zc(z),D.error(z);return}let ae=null,O="";try{const z=Bf(b,Pa);ae=z.query,Dt(z.query),ze(kn==="ai"?"\u5DF2\u751F\u6210\u57FA\u7840\u89C4\u5219\u7ED3\u679C\uFF0C\u6B63\u5728\u8BF7\u6C42 AI \u589E\u5F3A...":"\u5DF2\u751F\u6210\u57FA\u7840\u89C4\u5219\u68C0\u7D22\u5F0F",kn==="ai"?"pending":"success")}catch(z){if(O=z instanceof Error?z.message:"\u57FA\u7840\u89C4\u5219\u751F\u6210\u5931\u8D25",Dt(""),kn==="rules"){ze(O,"warning"),D.error(O);return}ze(`${O}\uFF0C\u6B63\u5728\u5C1D\u8BD5 AI \u589E\u5F3A...`,"pending")}if(kn==="rules"){D.success("\u5DF2\u751F\u6210 PubMed \u68C0\u7D22\u5F0F");return}Tr(!0);try{await MF(A,b,ae)}catch(z){if(A!==Ft)return;const st=z instanceof Error&&z.message?mt(z.message):"AI \u589E\u5F3A\u5931\u8D25";if(Pf(st)){if(await $t({featureKey:Le,featureLabel:It,error:st}),A!==Ft)return;Zc(st),D.error(st);return}ae?(Dt(ae),ze(`AI \u589E\u5F3A\u672A\u5B8C\u6210\uFF1A${st}\u3002\u5DF2\u4FDD\u7559\u57FA\u7840\u89C4\u5219\u7ED3\u679C\u3002`,"warning"),Ln(),D.info("AI \u589E\u5F3A\u672A\u5B8C\u6210\uFF0C\u5DF2\u4FDD\u7559\u57FA\u7840\u89C4\u5219\u7ED3\u679C")):(Dt(""),ze(`AI \u589E\u5F3A\u672A\u5B8C\u6210\uFF1A${st}`,"warning"),Ln(),D.error(st))}}finally{Sr===A&&(Sr=0),A===Ft&&Tr(!1)}};en.addEventListener("click",()=>{kn!=="rules"&&(gb("rules"),Rn())}),tn.addEventListener("click",()=>{kn!=="ai"&&(gb("ai"),Rn())}),nn.addEventListener("click",()=>{Pa!=="balanced"&&(yb("balanced"),Rn())}),rn.addEventListener("click",()=>{Pa!=="strict"&&(yb("strict"),Rn())}),Ae.addEventListener("click",()=>{xb()}),_e.addEventListener("input",()=>{Rn(),ha(_e)}),_e.addEventListener("keydown",b=>{(b.metaKey||b.ctrlKey)&&b.key==="Enter"&&(b.preventDefault(),xb())}),Tt.addEventListener("click",async()=>{if(!vr){D.info("\u8BF7\u5148\u751F\u6210\u68C0\u7D22\u8BCD");return}try{if(!await l1(vr))throw new Error("copy failed");Tt.textContent="\u5DF2\u590D\u5236",D.success("\u68C0\u7D22\u8BCD\u5DF2\u590D\u5236"),setTimeout(()=>{Tt.textContent="\u590D\u5236\u68C0\u7D22\u8BCD"},1600)}catch{D.error("\u590D\u5236\u5931\u8D25\uFF0C\u8BF7\u624B\u52A8\u9009\u62E9\u68C0\u7D22\u8BCD")}}),Nn.addEventListener("click",()=>{if(!vr){D.info("\u8BF7\u5148\u751F\u6210\u68C0\u7D22\u8BCD");return}c1(vr)}),Ba.addEventListener("click",()=>{_e.value=Gf(),Rn(),ha(_e),_e.focus()}),Vc.append(_e,Wc,Et,Ma,qa,Gc),fo.append(Hc,Vc),requestAnimationFrame(()=>{ha(_e),ha(Et)});const Yc=document.createElement("div");Yc.className="pl-toolbar-row pl-toolbar-row--optimizer",Yc.appendChild(fo);const Kc=document.createElement("div");Kc.className="pl-toolbar-row pl-toolbar-row--primary",Kc.append(R,at,Oe,Ct);const Qc=document.createElement("div");Qc.className="pl-toolbar-row pl-toolbar-row--secondary",Qc.append(Nc,Dc,Ar,Rc,Pc,oo,Ic,uo,Dn,ka),P.append(Yc,Kc,Qc),a.appendChild(P),a.appendChild(Na),o.appendChild(ot);const yo=Be.getInstance();La.addEventListener("click",()=>{const b=Kf();yo.selectAll(b),Qf()}),Ra.addEventListener("click",()=>{yo.deselectAll(),Qf()}),yo.onChange(()=>{const b=yo.getCount();po.textContent=`\u5DF2\u9009 ${b} \u7BC7`,Na.style.display=b>0?"flex":"none"}),document.addEventListener("click",b=>{oo.contains(b.target)||(it.style.display="none"),ho.contains(b.target)||(wt.style.display="none")});const Ab=b=>{const A=b.detail;if(!A?.featureKey)return;const G=A.error||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528\u8BE5\u529F\u80FD";if(A.featureKey===tr){if(A.allowed===!0){S();return}N(G);return}if(A.featureKey===Le){if(Sr!==0)return;if(A.allowed===!0){IF();return}Zc(G);return}if(A.featureKey===nr){if(A.allowed===!0){RF();return}mb(G,!0);return}};return document.addEventListener(pe,Ab),window.addEventListener("pagehide",()=>{document.body.style.overflow=v,document.documentElement.style.overflow=g,document.removeEventListener(pe,Ab),i.remove()},{once:!0}),n}function h1(){const r=ge("svg");r.setAttribute("width","14"),r.setAttribute("height","14"),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke","currentColor"),r.setAttribute("stroke-width","2.5"),r.setAttribute("stroke-linecap","round");const e=ge("line");e.setAttribute("x1","6"),e.setAttribute("y1","6"),e.setAttribute("x2","18"),e.setAttribute("y2","18");const t=ge("line");return t.setAttribute("x1","18"),t.setAttribute("y1","6"),t.setAttribute("x2","6"),t.setAttribute("y2","18"),r.append(e,t),r}function vn(r,e,t,n={}){const a=r.shadowRoot;if(!a)return;const i=a.querySelector(`[${zf}]`),o=a.querySelector(Eb),s=a.querySelector(".pl-toolbar-progress-fill"),l=a.querySelector(Fb),c=r.dataset.plFilterPending==="true";if(l){const u=n.scope==="global"&&!n.done&&(n.loading||(n.analyzed??0)>0);l.style.display=u?"":"none"}if(n.scope==="global"){const u=n.analyzed??0,d=e>0?Math.min(u/e*100,100):0;if(n.loading&&e===0){i&&!c&&(i.textContent="\u8BFB\u53D6 PubMed \u5168\u91CF\u7ED3\u679C..."),o&&(o.style.display="block"),s&&(s.style.width="100%");return}const p=`\u5168\u91CF\u7B5B\u9009\uFF1A\u663E\u793A ${t.toLocaleString()} \xB7 \u5DF2\u5206\u6790 ${u.toLocaleString()}/${e.toLocaleString()}`;n.done?(i&&!c&&(i.textContent=`${p} \xB7 \u5B8C\u6210`),o&&(o.style.display="none")):(i&&!c&&(i.textContent=n.loading?`${p} \xB7 \u5206\u6790\u4E2D`:`${p} \xB7 \u53EF\u7EE7\u7EED\u5206\u6790\u66F4\u591A`),o&&(o.style.display="block"),s&&(s.style.width=`${Math.max(d,u>0?4:0)}%`));return}if(o&&(o.style.display="none"),e===t)i&&!c&&(i.textContent=`\u5F53\u524D\u9875 ${e} \u6761 \xB7 \u7B5B\u9009\u9ED8\u8BA4\u5168\u91CF`);else{const u=`\u663E\u793A ${t}/${e}`;i&&!c&&(i.textContent=`${u} \xB7 \u5F53\u524D\u9875`)}}function Sn(r){r.dispatchEvent(new CustomEvent(Jf))}function Kf(){const r=document.querySelectorAll("article.full-docsum"),e=[];for(const t of r){if(!f1(t))continue;const a=t.querySelector("a.docsum-title"),i=a?.getAttribute("data-article-id");if(!i)continue;const o=a?.textContent?.trim()??"",l=t.querySelector("span.docsum-journal-citation.full-journal-citation")?.textContent?.trim()??"",c=l.split(".")[0]?.trim()??"",u=l.match(/\b(19|20)\d{2}\b/),d=u?parseInt(u[0],10):void 0;e.push({PMID:i,title:o,journal:c,year:d})}return e}function f1(r){return r.style.display==="none"?!1:r.closest("#paperlens-global-results-root")?!0:r.offsetParent!==null||getComputedStyle(r).display!=="none"}function Qf(){const r=Be.getInstance();document.querySelectorAll(Tb).forEach(e=>{const t=e,n=t.dataset.pmid;if(!n)return;const a=r.isSelected(n),i=t.shadowRoot;if(!i)return;const o=i.querySelector(".pl-checkbox");o&&(o.setAttribute("aria-checked",String(a)),o.setAttribute("data-pl-checked",String(a)))})}async function Xf(r){const e=await lt(r);if(!e.allowed){D.error(e.error||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528\u8BE5\u5BFC\u51FA\u683C\u5F0F");return}const n=Be.getInstance().getSelectedPmids(),a=Kf().map(s=>s.PMID).filter(s=>!!s),i=n.length>0?n:a;if(i.length===0){D.info("\u5F53\u524D\u9875\u6CA1\u6709\u53EF\u5BFC\u51FA\u7684\u6587\u732E");return}const o={type:"EXPORT_PUBMED_RECORDS",payload:{pmids:i,format:r}};try{const s=await H(o,QT);if(!s?.success||!s.data){D.error(s?.error?`\u5BFC\u51FA\u5931\u8D25\uFF1A${s.error}`:"\u5BFC\u51FA\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5");return}const{downloadFile:l,EXPORT_MIME_TYPES:c,EXPORT_EXTENSIONS:u}=await Promise.resolve().then(()=>Ds),d=u[r]??".txt",p=c[r]??"text/plain",h=new Date().toISOString().slice(0,10),y=`paperlens_${n.length>0?"selected":"current_page"}_${h}_${i.length}\u7BC7${d}`;l(s.data,y,p),D.success(`\u5DF2\u5BFC\u51FA ${i.length} \u7BC7\u6587\u732E`)}catch(s){D.error(m1(s))}}function m1(r){return!(r instanceof Error)||!r.message?"\u5BFC\u51FA\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5":r.message==="runtime message timed out"?"\u5BFC\u51FA\u5931\u8D25\uFF1A\u540E\u53F0\u54CD\u5E94\u8D85\u65F6":`\u5BFC\u51FA\u5931\u8D25\uFF1A${r.message}`}function b1(r){return r==="ris"||r==="bibtex"||r==="medline"||r==="csv"}let em=0;async function tm(r){const e=++em,t=Array.from(r.querySelectorAll(".pl-batch-dropdown-item[data-export-format]"));await Promise.all(t.map(async n=>{const a=n.dataset.exportFormat;if(!b1(a))return;const i=n.dataset.defaultLabel||n.textContent||"",o=await lt(a);if(!(e!==em||!n.isConnected)){if(o.allowed){n.disabled=!1,n.title="",n.textContent=i,n.removeAttribute("aria-disabled");return}n.disabled=!0,n.title=o.error||"\u8BE5\u5BFC\u51FA\u683C\u5F0F\u6682\u4E0D\u53EF\u7528",n.textContent=`${i} \xB7 Pro`,n.setAttribute("aria-disabled","true")}}))}const g1="https://api.litlink.cc/api/v1",y1="https://litlink.cc",nm="https://api.litlink.cc/api/v1";function rm(r,e=g1){const t=r?.trim()||nm;try{const n=new URL(t);if(n.protocol==="http:"&&!["localhost","127.0.0.1"].includes(n.hostname))return console.warn("[BackendClient] Refusing unsupported HTTP backend; using production domain endpoint."),e}catch{return e}return t.replace(/\/+$/,"")}rm(nm);const x1=rm("https://litlink.cc",y1);function A1(r,e){const t=new URL(r.startsWith("/")?r:`/${r}`,`${x1}/`);if(e)for(const[n,a]of Object.entries(e))a&&t.searchParams.set(n,a);return t.toString()}const C1=`.pl-selection-ai-toolbar {
  position: fixed;
  z-index: 2147483647;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px;
  border: 1px solid rgba(15, 23, 42, 0.12);
  border-radius: 8px;
  background: #ffffff;
  box-shadow: 0 12px 32px rgba(15, 23, 42, 0.16);
  pointer-events: auto;
  font: 13px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", "Noto Sans SC", "Source Han Sans SC", "Helvetica Neue", Arial, sans-serif;
}

.pl-selection-ai-toolbar[hidden],
.pl-selection-ai-panel[hidden] {
  display: none;
}

.pl-selection-ai-button {
  min-height: 30px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  background: #ffffff;
  color: #111827;
  cursor: pointer;
  font: inherit;
  font-weight: 650;
  padding: 0 9px;
  white-space: nowrap;
}

.pl-selection-ai-button:hover {
  border-color: #2563eb;
  color: #1d4ed8;
  background: #eff6ff;
}

.pl-selection-ai-panel {
  position: fixed;
  z-index: 2147483647;
  width: min(420px, calc(100vw - 24px));
  min-width: min(320px, calc(100vw - 24px));
  min-height: 160px;
  max-height: min(420px, calc(100vh - 24px));
  overflow: auto;
  resize: both;
  border: 1px solid rgba(15, 23, 42, 0.12);
  border-radius: 8px;
  background: #ffffff;
  box-shadow: 0 18px 48px rgba(15, 23, 42, 0.2);
  color: #111827;
  pointer-events: auto;
  font: 14px/1.65 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", "Noto Sans SC", "Source Han Sans SC", "Helvetica Neue", Arial, sans-serif;
}

.pl-selection-ai-panel__header {
  position: sticky;
  top: 0;
  display: flex;
  justify-content: space-between;
  gap: 12px;
  padding: 12px 14px;
  border-bottom: 1px solid #e5e7eb;
  background: #ffffff;
  cursor: move;
  touch-action: none;
  user-select: none;
}

.pl-selection-ai-panel__title {
  margin: 0;
  font-size: 14px;
  font-weight: 750;
}

.pl-selection-ai-panel__close {
  border: 0;
  background: transparent;
  color: #6b7280;
  cursor: pointer;
  font-size: 18px;
  line-height: 1;
  padding: 0 2px;
}

.pl-selection-ai-panel__body {
  padding: 12px 14px 14px;
}

.pl-selection-ai-panel__selected {
  margin-bottom: 12px;
  padding: 10px;
  border-radius: 6px;
  background: #f9fafb;
  color: #4b5563;
  font-size: 12px;
  line-height: 1.55;
}

.pl-selection-ai-panel__label {
  display: block;
  margin-bottom: 4px;
  color: #6b7280;
  font-weight: 700;
}

.pl-selection-ai-panel__selected-text {
  display: block;
  max-height: 180px;
  overflow: auto;
  white-space: pre-wrap;
}

.pl-selection-ai-panel__result {
  white-space: pre-wrap;
}

.pl-selection-ai-panel__provider {
  display: inline-flex;
  margin-bottom: 8px;
  padding: 2px 6px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  color: #4b5563;
  background: #f9fafb;
  font-size: 12px;
  white-space: normal;
}

.pl-selection-ai-panel__result-text {
  white-space: pre-wrap;
}

.pl-selection-ai-panel__language-notice {
  padding: 10px 12px;
  border: 1px solid #fed7aa;
  border-radius: 7px;
  background: #fff7ed;
  color: #9a3412;
  font-size: 12px;
  font-weight: 650;
  line-height: 1.55;
  white-space: normal;
}

.pl-selection-ai-panel__loading {
  color: #4b5563;
}

.pl-selection-ai-panel__error {
  color: #dc2626;
}
`,am="paperlens-selection-ai-toolbar",im="paperlens-selection-ai-panel",om="paperlens-selection-ai-style",sm=4e3,lm=12e3,cm=600,v1=3e3,um=2e3,dm=10,Zl=12,S1=460,Yl=420,w1=44,Kl=360,T1=24e4,Ql="zh-CN",E1="AI \u8FD4\u56DE\u7684\u7ED3\u679C\u4E0D\u662F\u4E2D\u6587\uFF0C\u5DF2\u9690\u85CF\u82F1\u6587\u5185\u5BB9\u3002\u8BF7\u91CD\u65B0\u9009\u62E9\u6587\u672C\u5E76\u518D\u6B21\u751F\u6210\u4E2D\u6587\u7ED3\u679C\u3002";let Hi="",pm=!1,mr=null,hm=!1,zi=0,fm=0,Wt=null;const Ke=new Map;let br=null,ma=null;function F1(r){return{...r,targetLanguage:Ql,target_language:Ql,locale:Ql}}const D1=[{action:"translate",label:"\u7FFB\u8BD1"},{action:"summarize",label:"\u603B\u7ED3"},{action:"article-abstract",label:"\u6458\u8981\u89E3\u8BFB"}];function _1(r,e){if(hm)return;hm=!0,k1(r);const t=ba(r,e),n=Xl(r);bt(t),Ji(n),xn(),P1(r);let a=null;const i=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,N1(r,e)},80)};document.addEventListener("mouseup",i),document.addEventListener("keyup",o=>{if(o.key==="Escape"){ga(),bt(t),Ji(n);return}i()}),document.addEventListener("selectionchange",i),window.addEventListener("scroll",()=>bt(t),{passive:!0}),window.addEventListener("resize",()=>{bt(t),n.hidden||tc(n)},{passive:!0})}function k1(r){if(r.getElementById(om))return;const e=document.createElement("style");e.id=om,e.textContent=C1,r.appendChild(e)}function ba(r,e){const t=r.getElementById(am);if(t)return t;const n=document.createElement("div");n.id=am,n.className="pl-selection-ai-toolbar",n.setAttribute("role","toolbar"),n.setAttribute("aria-label","\u9009\u4E2D\u6587\u672C AI \u64CD\u4F5C");for(const a of D1){const i=document.createElement("button");i.type="button",i.className="pl-selection-ai-button",i.textContent=a.label,i.dataset.action=a.action,i.dataset.defaultLabel=a.label,i.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),q1(r,a.action,e)}),n.appendChild(i)}return r.appendChild(n),n}function Xl(r){const e=r.getElementById(im);if(e)return e;const t=document.createElement("section");return t.id=im,t.className="pl-selection-ai-panel",t.setAttribute("role","dialog"),t.setAttribute("aria-live","polite"),r.appendChild(t),t}function N1(r,e){const t=ba(r,e);ec(t);const n=window.getSelection();if(!n||n.rangeCount===0||n.isCollapsed){bt(t);return}if(bm(n.anchorNode)||bm(n.focusNode)){bt(t);return}const a=I1(n.toString());if(a.length<2){bt(t);return}const i=n.getRangeAt(0),o=M1(i);if(!o){bt(t);return}a!==Hi&&ga(),Hi=a,pm=a.length>sm,mr=o,gm(t,o,"toolbar"),t.hidden=!1}function mm(r){return r==="summarize"?{key:aa,label:lp}:r==="article-abstract"?{key:et,label:ar}:{key:rr,label:_s}}function L1(r){return r===aa?"summarize":r===et?"article-abstract":r===rr?"translate":null}function ec(r){const e=Array.from(r.querySelectorAll(".pl-selection-ai-button[data-action]"));for(const t of e){const n=t.dataset.action;if(!n)continue;const a=Ke.get(n),i=t.dataset.defaultLabel||t.textContent||"";if(!a){t.disabled=!1,t.title="",t.textContent=i,t.removeAttribute("aria-disabled");continue}t.disabled=!0,t.title=a,t.textContent=`${i} Pro`,t.setAttribute("aria-disabled","true")}}async function R1(r,e){if(!B1(e))return!1;const t=mm(r);Ke.set(r,e);const n=await $t({featureKey:t.key,featureLabel:t.label,error:e});return n&&Ke.delete(r),n}function P1(r){br&&ma===document||(ma?.removeEventListener(pe,br),br=e=>{const t=e.detail;if(!t?.featureKey)return;const n=L1(t.featureKey);if(!n)return;if(t.allowed===!0){if(!Ke.has(n))return;Ke.delete(n),ec(ba(r));return}const a=t.error||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528\u8BE5\u529F\u80FD";Ke.set(n,a);const i=Xl(r),o=!i.hidden&&i.dataset.plAction===n;(o||Wt===n)&&ga(n),ec(ba(r)),o&&Qe(i,n,Hi,{status:"error",error:a},mr?ym(mr):null)},ma=document,document.addEventListener(pe,br),window.addEventListener("pagehide",()=>{ma?.removeEventListener(pe,br),br=null,ma=null,Ke.clear()},{once:!0}))}function B1(r){return/AI 服务暂未配置|请联系管理员/.test(r)||/需要先(?:在 Popup 设置中)?配置自定义模型接口|接口在当前服务器上未部署|切换自定义模型/.test(r)?!1:/(?:Pro|永久版权益|开通|当前账户暂不能使用|请先登录|账户状态已切换|AI 服务包|本月.*次数已用完|次数已用完|QUOTA_EXCEEDED|NOT_AUTHENTICATED|SESSION_CHANGED|REMOTE_CHECK_FAILED)/i.test(r)}function I1(r){return r.replace(/[ \t\f\v]+/g," ").replace(/\s*\n\s*/g,`
`).replace(/\n{3,}/g,`

`).trim()}function M1(r){return Array.from(r.getClientRects()).filter(t=>t.width>0&&t.height>0)[0]??(r.getBoundingClientRect().width>0?r.getBoundingClientRect():null)}function bm(r){return!!(r instanceof Element?r:r?.parentElement)?.closest('input, textarea, select, button, [contenteditable=""], [contenteditable="true"]')}function gm(r,e,t){const n=Zl,a=window.innerWidth||document.documentElement.clientWidth,i=window.innerHeight||document.documentElement.clientHeight,s=Math.min(t==="toolbar"?S1:Yl,a-n*2);let l=e.left+e.width/2-s/2;l=wn(l,n,a-s-n);const c=r.getBoundingClientRect(),u=Math.min(c.height||(t==="toolbar"?w1:Kl),i-n*2),d=e.bottom+dm,p=e.top-u-dm;let h;t==="toolbar"?h=p>=n?p:d:d+u<=i-n?h=d:p>=n?h=p:h=wn(d,n,i-u-n),r.style.left=`${l}px`,r.style.top=`${wn(h,n,i-u-n)}px`,t==="toolbar"&&(r.style.maxWidth=`${s}px`)}function tc(r){const e=Zl,t=window.innerWidth||document.documentElement.clientWidth,n=window.innerHeight||document.documentElement.clientHeight,a=r.getBoundingClientRect(),i=Math.min(a.width||Yl,t-e*2),o=Math.min(a.height||Kl,n-e*2),s=Number.parseFloat(r.style.left)||a.left||e,l=Number.parseFloat(r.style.top)||a.top||e;r.style.left=`${wn(s,e,t-i-e)}px`,r.style.top=`${wn(l,e,n-o-e)}px`}function wn(r,e,t){return t<e?e:Math.max(e,Math.min(r,t))}async function q1(r,e,t){const n=Xl(r),a=ba(r,t),i=Hi.trim();if(!i)return;ga();const o=++zi,s=mr?ym(mr):null;if(n.dataset.plManualPosition="false",bt(a),e==="article-abstract"){Wt=e;try{await j1(n,i,t,s,o);return}finally{o===zi&&(Wt=null)}}if(pm||i.length>sm){Qe(n,e,i,{status:"error",error:"\u9009\u4E2D\u6587\u672C\u6700\u591A 4000 \u4E2A\u5B57\u7B26\uFF0C\u8BF7\u7F29\u77ED\u540E\u91CD\u8BD5"},s);return}Wt=e,Qe(n,e,i,{status:"loading"},s);try{let l;try{l=await H({type:"SELECTION_AI_REQUEST",payload:F1({text:i,action:e,context:xm(t?.())})},T1)}catch(u){if(console.error("[PaperLens] Selection AI request failed:",u),ya(o))return;Qe(n,e,i,{status:"error",error:"AI \u8BF7\u6C42\u8D85\u65F6\u6216\u7F51\u7EDC\u4E2D\u65AD\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},s);return}if(ya(o))return;if(Ke.has(e)){Qe(n,e,i,{status:"error",error:Ke.get(e)||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528\u8BE5\u529F\u80FD"},s);return}if(!l?.success||!l.data){const u=l?.error==="NOT_AUTHENTICATED"?"\u8BF7\u5148\u767B\u5F55 PaperLens \u8D26\u6237":l?.error||"\u8BF7\u6C42\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5";if(await R1(e,u),ya(o))return;Qe(n,e,i,{status:"error",error:u},s);return}const c=mm(e);yn(c.key,c.label),Qe(n,e,i,{status:"success",data:l.data},s)}finally{o===zi&&(Wt=null)}}async function j1(r,e,t,n,a){if(e.length>lm){Qe(r,"article-abstract",e,{status:"error",error:"\u9009\u4E2D\u6458\u8981\u6700\u591A 12000 \u4E2A\u5B57\u7B26\uFF0C\u8BF7\u7F29\u77ED\u540E\u91CD\u8BD5"},n);return}Qe(r,"article-abstract",e,{status:"loading"},n);try{if(await KC($1(e,t?.())),ya(a))return;if(Ke.has("article-abstract")){Qe(r,"article-abstract",e,{status:"error",error:Ke.get("article-abstract")||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528\u8BE5\u529F\u80FD"},n);return}Ji(r)}catch{if(ya(a))return;Qe(r,"article-abstract",e,{status:"error",error:"\u7F51\u7EDC\u9519\u8BEF\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},n)}}function $1(r,e){const t=xm(e)??{},n=t.source_url??Ee(location.href,um),a=Ee(O1(document.title),cm)||"\u9009\u4E2D\u6458\u8981\u89E3\u8BFB",i=t.title||a,o=t.paper_id??t.pmid??t.doi??n;return{...t,paper_id:Ee(o,256),title:i,abstract:Ee(r,lm),source_url:n}}function O1(r){return r.replace(/\s*[|-]\s*(PubMed|Science|PNAS|JAMA Network|ACS Publications).*$/i,"").trim()}function ym(r){return new DOMRect(r.x,r.y,r.width,r.height)}function ga(r){r&&Wt&&Wt!==r||(fm=zi,Wt=null)}function ya(r){return r<=fm}function xm(r){if(r)return{paper_id:Ee(r.paper_id,256),pmid:Ee(r.pmid,64),doi:Ee(r.doi,256),title:Ee(r.title,cm),abstract:Ee(r.abstract,v1),journal:Ee(r.journal,512),authors:r.authors?.slice(0,20).map(e=>Ee(e,160)).filter(Boolean),year:r.year,publication_date:Ee(r.publication_date,64),source:Ee(r.source,80),source_url:Ee(r.source_url??location.href,um)}}function Ee(r,e){const t=r?.trim();if(t)return t.length>e?t.slice(0,e):t}function Qe(r,e,t,n,a=mr){const i=r.dataset.plManualPosition==="true";r.dataset.plAction=e,r.textContent="";const o=document.createElement("div");o.className="pl-selection-ai-panel__header",o.title="\u62D6\u52A8\u8C03\u6574\u4F4D\u7F6E";const s=document.createElement("p");s.className="pl-selection-ai-panel__title",s.textContent=Y1(e);const l=document.createElement("button");l.type="button",l.className="pl-selection-ai-panel__close",l.setAttribute("aria-label","\u5173\u95ED"),l.textContent="\xD7",l.addEventListener("click",()=>{ga(),Ji(r)}),o.append(s,l),U1(r,o);const c=document.createElement("div");if(c.className="pl-selection-ai-panel__body",c.appendChild(H1(t)),n.status==="loading"){const u=document.createElement("div");u.className="pl-selection-ai-panel__loading",u.textContent="\u6B63\u5728\u5904\u7406\u2026",c.appendChild(u)}else if(n.status==="error"){const u=document.createElement("div");u.className="pl-selection-ai-panel__error",u.textContent=n.error,c.appendChild(u)}else c.appendChild(z1(n.data));r.append(o,c),r.hidden=!1,a&&!i?gm(r,a,"panel"):tc(r)}function U1(r,e){e.addEventListener("pointerdown",t=>{if(t.target?.closest("button"))return;t.preventDefault(),r.dataset.plManualPosition="true";const a=r.getBoundingClientRect(),i=t.clientX,o=t.clientY,s=c=>{const u=a.left+c.clientX-i,d=a.top+c.clientY-o,p=Zl,h=window.innerWidth||document.documentElement.clientWidth,f=window.innerHeight||document.documentElement.clientHeight,y=Math.min(a.width||Yl,h-p*2),x=Math.min(a.height||Kl,f-p*2);r.style.left=`${wn(u,p,h-y-p)}px`,r.style.top=`${wn(d,p,f-x-p)}px`},l=()=>{window.removeEventListener("pointermove",s),window.removeEventListener("pointerup",l),window.removeEventListener("pointercancel",l),tc(r)};window.addEventListener("pointermove",s),window.addEventListener("pointerup",l,{once:!0}),window.addEventListener("pointercancel",l,{once:!0})})}function H1(r){const e=document.createElement("div");e.className="pl-selection-ai-panel__selected";const t=document.createElement("span");t.className="pl-selection-ai-panel__label",t.textContent="\u9009\u4E2D\u6587\u672C";const n=document.createElement("span");return n.className="pl-selection-ai-panel__selected-text",n.textContent=r,e.append(t,n),e}function z1(r){const e=document.createElement("div");e.className="pl-selection-ai-panel__result";const t=r.action==="summarize"?Am(r.result.text,r.result.summary,r.result.explanation,r.result.translation):Am(r.result.translation,r.result.text,r.result.explanation,r.result.summary),n=W1(t),a=Z1(r);if(a&&e.appendChild(a),t&&!n)return e.appendChild(G1()),e;const i=document.createElement("div");return i.className="pl-selection-ai-panel__result-text",n?(i.textContent=n,e.appendChild(i),e):(i.textContent="\u672A\u8FD4\u56DE\u53EF\u663E\u793A\u5185\u5BB9",e.appendChild(i),e)}function Am(...r){for(const e of r)if(e?.trim())return e.trim()}function J1(r){return/[\u3400-\u9fff]/.test(r)}function V1(r){const e=r?.trim();if(!e||J1(e))return!1;const t=e.match(/[A-Za-z]/g)?.length??0,n=e.match(/[A-Za-z]{2,}/g)?.length??0;return t>=24&&n>=4}function W1(r){if(r?.trim())return V1(r)?void 0:r}function G1(){const r=document.createElement("div");return r.className="pl-selection-ai-panel__language-notice",r.textContent=E1,r}function Z1(r){if(!r.aiProvider)return null;const e=document.createElement("div");e.className="pl-selection-ai-panel__provider";const t=r.aiProvider==="custom"?"\u81EA\u5B9A\u4E49\u6A21\u578B":(r.aiProvider==="paperlens"||r.aiProvider==="backend","PaperLens AI \u6A21\u578B");return e.textContent=`\u6765\u6E90\uFF1A${t}`,e}function Y1(r){switch(r){case"translate":return"\u7FFB\u8BD1";case"summarize":return"\u603B\u7ED3\u8FD9\u6BB5";case"article-abstract":return"\u6458\u8981\u89E3\u8BFB"}}function bt(r){r.hidden=!0}function Ji(r){r.hidden=!0,delete r.dataset.plAction}const K1=`:host {
  display: block;
  box-sizing: border-box;
  width: 100%;
  margin: 7px 0 0;
  color: #111827;
  font-family: var(--pl-font-sans, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif);
}

* {
  box-sizing: border-box;
}

.pl-home-qo {
  width: 100%;
  border: 1px solid rgba(15, 23, 42, 0.12);
  border-radius: 10px;
  background: rgba(255, 255, 255, 0.96);
  box-shadow: 0 10px 24px rgba(8, 32, 57, 0.16);
  padding: 8px 10px 7px;
  backdrop-filter: blur(10px);
}

.pl-home-qo__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  margin-bottom: 6px;
}

.pl-home-qo__heading {
  display: flex;
  align-items: center;
  gap: 7px;
  min-width: 0;
}

.pl-home-qo__title {
  margin: 0;
  color: #0f172a;
  font-size: 14px;
  font-weight: 750;
  line-height: 1.25;
  white-space: nowrap;
}

.pl-home-qo__badge {
  border: 1px solid rgba(37, 99, 235, 0.16);
  border-radius: 999px;
  background: #eff6ff;
  color: #1d4ed8;
  font-size: 10px;
  font-weight: 750;
  line-height: 1;
  padding: 4px 7px;
  white-space: nowrap;
}

.pl-home-qo__controls {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 6px;
  flex-wrap: wrap;
}

.pl-home-qo__segment {
  display: inline-flex;
  align-items: center;
  gap: 2px;
  border: 1px solid rgba(15, 23, 42, 0.13);
  border-radius: 8px;
  background: #f8fafc;
  padding: 2px;
}

.pl-home-qo__mode {
  border: 0;
  border-radius: 6px;
  background: transparent;
  color: #475569;
  cursor: pointer;
  font: inherit;
  font-size: 11px;
  font-weight: 750;
  line-height: 1;
  min-height: 23px;
  padding: 0 8px;
  white-space: nowrap;
}

.pl-home-qo__mode:hover:not(:disabled) {
  background: rgba(37, 99, 235, 0.08);
  color: #1d4ed8;
}

.pl-home-qo__mode.is-active {
  background: #2563eb;
  color: #fff;
  box-shadow: 0 5px 12px rgba(37, 99, 235, 0.22);
}

.pl-home-qo__mode:disabled {
  cursor: not-allowed;
  opacity: 0.55;
}

.pl-home-qo__grid {
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  gap: 8px;
  align-items: stretch;
}

.pl-home-qo__field {
  display: flex;
  min-width: 0;
}

.pl-home-qo__textarea {
  width: 100%;
  min-height: 38px;
  max-height: 60px;
  resize: none;
  border: 1px solid rgba(15, 23, 42, 0.17);
  border-radius: 8px;
  background: #fff;
  color: #111827;
  font: inherit;
  font-size: 13px;
  line-height: 1.38;
  outline: none;
  overflow-y: auto;
  padding: 8px 10px;
}

.pl-home-qo__textarea::placeholder {
  color: #94a3b8;
}

.pl-home-qo__textarea:focus {
  border-color: #2563eb;
  box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15);
}

.pl-home-qo__textarea[readonly] {
  background: #f8fafc;
  color: #1f2937;
}

.pl-home-qo__textarea--input {
  min-height: 44px;
  max-height: 60px;
}

.pl-home-qo__textarea--output {
  min-height: 38px;
  max-height: 50px;
}

.pl-home-qo__actions {
  display: grid;
  grid-template-columns: repeat(2, minmax(92px, 1fr));
  gap: 6px;
  align-content: start;
}

.pl-home-qo__action {
  border: 1px solid rgba(15, 23, 42, 0.14);
  border-radius: 8px;
  background: #fff;
  color: #334155;
  cursor: pointer;
  font: inherit;
  font-size: 12px;
  font-weight: 750;
  line-height: 1;
  min-height: 29px;
  padding: 0 10px;
  white-space: nowrap;
}

.pl-home-qo__action:hover:not(:disabled) {
  border-color: rgba(37, 99, 235, 0.38);
  color: #1d4ed8;
}

.pl-home-qo__action--primary {
  border-color: #15803d;
  background: #15803d;
  color: #fff;
}

.pl-home-qo__action--primary:hover:not(:disabled) {
  border-color: #166534;
  background: #166534;
  color: #fff;
}

.pl-home-qo__action:disabled {
  cursor: not-allowed;
  opacity: 0.55;
}

.pl-home-qo__result {
  display: grid;
  grid-template-columns: minmax(0, 1fr);
  gap: 4px;
  margin-top: 6px;
}

.pl-home-qo__meta {
  display: flex;
  align-items: center;
  gap: 7px;
  min-height: 19px;
  min-width: 0;
}

.pl-home-qo__status {
  flex: 0 1 auto;
  min-width: 0;
  color: #64748b;
  font-size: 11px;
  font-weight: 650;
  line-height: 1.35;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pl-home-qo__status--pending {
  color: #1d4ed8;
}

.pl-home-qo__status--success {
  color: #15803d;
}

.pl-home-qo__status--warning {
  color: #b45309;
}

.pl-home-qo__provider,
.pl-home-qo__warnings {
  border-radius: 999px;
  flex: 0 1 auto;
  font-size: 11px;
  font-weight: 650;
  line-height: 1.25;
  max-width: 42%;
  overflow: hidden;
  padding: 3px 7px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pl-home-qo__provider {
  background: #eef2ff;
  color: #3730a3;
}

.pl-home-qo__warnings {
  background: #fffbeb;
  color: #92400e;
}

.pl-home-qo__provider[hidden],
.pl-home-qo__warnings[hidden] {
  display: none;
}

@media (max-width: 760px) {
  .pl-home-qo__header,
  .pl-home-qo__grid {
    grid-template-columns: 1fr;
  }

  .pl-home-qo__header {
    display: grid;
  }

  .pl-home-qo__controls {
    justify-content: flex-start;
  }

  .pl-home-qo__actions {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }

  .pl-home-qo__meta {
    align-items: flex-start;
    flex-direction: column;
    gap: 4px;
  }

  .pl-home-qo__status,
  .pl-home-qo__provider,
  .pl-home-qo__warnings {
    max-width: 100%;
    white-space: normal;
  }
}

@media (max-width: 440px) {
  .pl-home-qo__controls,
  .pl-home-qo__segment,
  .pl-home-qo__actions {
    width: 100%;
  }

  .pl-home-qo__mode,
  .pl-home-qo__action {
    flex: 1 1 0;
    min-width: 0;
    padding-left: 8px;
    padding-right: 8px;
  }

  .pl-home-qo__actions {
    grid-template-columns: 1fr;
  }

  .pl-home-qo__badge {
    display: none;
  }
}
`,Cm="paperlens-pubmed-home-query-optimizer",Q1=9e4,X1=3e5,eE=4,tE=ve+`
`+K1;function nE(){const r=document.getElementById(Cm);if(r)return r;const e=pE(),t=hE(e),n=document.createElement("div");n.id=Cm,n.className="paperlens-pubmed-home-query-optimizer-host";const a=n.attachShadow({mode:"open"}),i=document.createElement("style");i.textContent=tE,a.appendChild(i);const o=document.createElement("section");o.className="pl-home-qo",o.setAttribute("aria-label","PaperLens PubMed \u68C0\u7D22\u4F18\u5316"),o.innerHTML=`
    <div class="pl-home-qo__header">
      <div class="pl-home-qo__heading">
        <h2 class="pl-home-qo__title">PubMed \u68C0\u7D22\u4F18\u5316</h2>
        <span class="pl-home-qo__badge">PaperLens AI</span>
      </div>
      <div class="pl-home-qo__controls">
        <div class="pl-home-qo__segment" aria-label="\u751F\u6210\u6A21\u5F0F">
          <button type="button" class="pl-home-qo__mode is-active" data-generation-mode="rules">\u57FA\u7840\u89C4\u5219</button>
          <button type="button" class="pl-home-qo__mode" data-generation-mode="ai">AI \u589E\u5F3A</button>
        </div>
        <div class="pl-home-qo__segment" aria-label="\u68C0\u7D22\u7B56\u7565">
          <button type="button" class="pl-home-qo__mode is-active" data-strategy-mode="balanced">\u5E73\u8861</button>
          <button type="button" class="pl-home-qo__mode" data-strategy-mode="strict">\u7CBE\u786E</button>
        </div>
      </div>
    </div>
    <div class="pl-home-qo__grid">
      <label class="pl-home-qo__field">
        <textarea class="pl-home-qo__textarea pl-home-qo__textarea--input" rows="1" data-role="input"
          placeholder="\u8F93\u5165\u7814\u7A76\u4E3B\u9898\u3001PMID\u3001DOI\u3001\u4F5C\u8005\u3001\u671F\u520A\u6216\u5173\u952E\u8BCD"></textarea>
      </label>
      <div class="pl-home-qo__actions">
        <button type="button" class="pl-home-qo__action pl-home-qo__action--primary" data-action="generate">\u751F\u6210</button>
        <button type="button" class="pl-home-qo__action" data-action="copy" disabled>\u590D\u5236</button>
        <button type="button" class="pl-home-qo__action pl-home-qo__action--primary" data-action="search" disabled>\u68C0\u7D22 PubMed</button>
        <button type="button" class="pl-home-qo__action" data-action="clear">\u6E05\u7A7A</button>
      </div>
    </div>
    <div class="pl-home-qo__result">
      <textarea class="pl-home-qo__textarea pl-home-qo__textarea--output" rows="1" data-role="output" readonly
        placeholder="\u751F\u6210\u7684 PubMed \u68C0\u7D22\u5F0F\u4F1A\u663E\u793A\u5728\u8FD9\u91CC"></textarea>
      <div class="pl-home-qo__meta">
        <div class="pl-home-qo__status" data-role="status" aria-live="polite"></div>
        <div class="pl-home-qo__provider" data-role="provider" hidden></div>
        <div class="pl-home-qo__warnings" data-role="warnings" hidden></div>
      </div>
    </div>
  `,a.appendChild(o);const s=rE(a),l={generationMode:"rules",strategyMode:"balanced",generatedQuery:"",runId:0,generationInFlightRunId:0,accessDenied:!1,deniedMessage:""};aE(s,l),iE(s,l),e?.parentElement?e.insertAdjacentElement("afterend",n):document.body.prepend(n),rc(n,t);const c=()=>{rc(n,t),Tn(s.input),Tn(s.output)};return window.addEventListener("resize",c),window.addEventListener("pagehide",()=>{window.removeEventListener("resize",c)},{once:!0}),xn(),requestAnimationFrame(()=>{rc(n,t),Tn(s.input),Tn(s.output)}),n}function rE(r){return{input:r.querySelector('[data-role="input"]'),output:r.querySelector('[data-role="output"]'),status:r.querySelector('[data-role="status"]'),provider:r.querySelector('[data-role="provider"]'),warnings:r.querySelector('[data-role="warnings"]'),generateBtn:r.querySelector('[data-action="generate"]'),copyBtn:r.querySelector('[data-action="copy"]'),searchBtn:r.querySelector('[data-action="search"]'),clearBtn:r.querySelector('[data-action="clear"]'),generationModeBtns:Array.from(r.querySelectorAll("[data-generation-mode]")),strategyModeBtns:Array.from(r.querySelectorAll("[data-strategy-mode]"))}}function aE(r,e){for(const t of r.generationModeBtns)t.addEventListener("click",()=>{const n=t.dataset.generationMode;!n||e.generationMode===n||(e.generationMode=n,vm(r,e),xa(r,e))});for(const t of r.strategyModeBtns)t.addEventListener("click",()=>{const n=t.dataset.strategyMode;!n||e.strategyMode===n||(e.strategyMode=n,vm(r,e),xa(r,e))});r.input.addEventListener("input",()=>{xa(r,e),Tn(r.input)}),r.input.addEventListener("keydown",t=>{(t.metaKey||t.ctrlKey)&&t.key==="Enter"&&(t.preventDefault(),Sm(r,e)),(t.metaKey||t.ctrlKey)&&t.key.toLowerCase()==="a"&&(t.preventDefault(),r.input.select())}),r.output.addEventListener("keydown",t=>{(t.metaKey||t.ctrlKey)&&t.key.toLowerCase()==="a"&&(t.preventDefault(),r.output.select())}),r.generateBtn.addEventListener("click",()=>{Sm(r,e)}),r.copyBtn.addEventListener("click",async()=>{if(!e.generatedQuery){de(r,"\u8BF7\u5148\u751F\u6210\u68C0\u7D22\u5F0F\u3002","warning");return}if(await uE(e.generatedQuery)){const n=r.copyBtn.textContent||"\u590D\u5236";r.copyBtn.textContent="\u5DF2\u590D\u5236",de(r,"\u68C0\u7D22\u5F0F\u5DF2\u590D\u5236\u3002","success"),setTimeout(()=>{r.copyBtn.textContent=n},1600)}else de(r,"\u590D\u5236\u5931\u8D25\uFF0C\u8BF7\u624B\u52A8\u9009\u4E2D\u68C0\u7D22\u5F0F\u3002","warning")}),r.searchBtn.addEventListener("click",()=>{if(!e.generatedQuery){de(r,"\u8BF7\u5148\u751F\u6210\u68C0\u7D22\u5F0F\u3002","warning");return}dE(e.generatedQuery)}),r.clearBtn.addEventListener("click",()=>{e.runId+=1,r.input.value="",xa(r,e),Tn(r.input),r.input.focus()})}function iE(r,e){document.addEventListener(pe,t=>{const n=t.detail;if(n?.featureKey===Le&&e.generationInFlightRunId===0){if(n.allowed===!0){lE(r,e);return}nc(r,e,n.error||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528 PubMed \u68C0\u7D22\u4F18\u5316\u3002")}})}function vm(r,e){for(const t of r.generationModeBtns)t.classList.toggle("is-active",t.dataset.generationMode===e.generationMode);for(const t of r.strategyModeBtns)t.classList.toggle("is-active",t.dataset.strategyMode===e.strategyMode)}function xa(r,e){if(e.runId+=1,e.generationInFlightRunId=0,e.accessDenied){nt(r,e,""),de(r,e.deniedMessage,"warning"),Gt(r),gr(r,[]),gt(r,e,!1);return}nt(r,e,""),de(r,""),Gt(r),gr(r,[]),gt(r,e,!1)}async function Sm(r,e){const t=r.input.value.trim();if(!t){xa(r,e),de(r,"\u8BF7\u8F93\u5165\u7814\u7A76\u4E3B\u9898\u6216\u5173\u952E\u8BCD\u3002","warning");return}const n=e.runId+1;e.runId=n,e.generationInFlightRunId=n,nt(r,e,""),Gt(r),gr(r,[]),gt(r,e,!1),de(r,"\u6B63\u5728\u6821\u9A8C PubMed \u68C0\u7D22\u4F18\u5316\u6743\u9650...","pending");const a=await Dp();if(n!==e.runId)return;if(!a.allowed){if(a.transient){sE(r,e,a.error||"\u6743\u76CA\u6821\u9A8C\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002");return}nc(r,e,a.error||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528 PubMed \u68C0\u7D22\u4F18\u5316\u3002");return}let i=null,o="";try{const s=Bf(t,e.strategyMode);i=s.query,nt(r,e,s.query),de(r,e.generationMode==="ai"?"\u5DF2\u751F\u6210\u57FA\u7840\u89C4\u5219\u7ED3\u679C\uFF0C\u6B63\u5728\u8BF7\u6C42 AI \u589E\u5F3A...":"\u5DF2\u751F\u6210\u57FA\u7840\u89C4\u5219\u68C0\u7D22\u5F0F\u3002",e.generationMode==="ai"?"pending":"success")}catch(s){if(o=s instanceof Error?s.message:"\u57FA\u7840\u89C4\u5219\u751F\u6210\u5931\u8D25\u3002",nt(r,e,""),e.generationMode==="rules"){de(r,o,"warning"),gt(r,e,!1);return}de(r,`${o} \u6B63\u5728\u5C1D\u8BD5 AI \u589E\u5F3A...`,"pending")}if(e.generationMode==="rules"){gt(r,e,!1);return}gt(r,e,!0);try{const s=await oE(t,e.strategyMode,i);if(n!==e.runId)return;const l=s?.data?.query?.trim()??"";if(!s?.success||!l)throw new Error(mt(s?.error||s?.data?.fallbackReason||"AI \u589E\u5F3A\u5931\u8D25\u3002"));if(s.data?.generation?.provider==="local-rules"||s.data?.tag==="Rules fallback")throw new Error(mt(s.data?.fallbackReason||s.data?.generation?.fallbackReason||s.data?.warnings?.[0]||"AI \u589E\u5F3A\u5931\u8D25\u3002"));nt(r,e,l);const u=s.data?.mode==="hybrid"?"\u6DF7\u5408\u589E\u5F3A":"AI \u589E\u5F3A",d=s.data?.tag?cE(s.data.tag,e.strategyMode):"",p=d?`\uFF08${d}\uFF09`:"";de(r,`\u5DF2\u751F\u6210${u}\u68C0\u7D22\u5F0F${p}\u3002`,"success"),Gt(r,s.data?.generation),gr(r,[...s.data?.fallbackReason?[s.data.fallbackReason]:[],...s.data?.warnings??[]])}catch(s){if(n!==e.runId)return;const l=mt(s instanceof Error&&s.message?s.message:"AI \u589E\u5F3A\u5931\u8D25\u3002");if(Pf(l)){if(await $t({featureKey:Le,featureLabel:It,error:l}),n!==e.runId)return;nc(r,e,l);return}i?(nt(r,e,i),de(r,`AI \u589E\u5F3A\u672A\u5B8C\u6210\uFF1A${l}\u3002\u5DF2\u4FDD\u7559\u57FA\u7840\u89C4\u5219\u7ED3\u679C\u3002`,"warning"),Gt(r)):(nt(r,e,""),de(r,`AI \u589E\u5F3A\u672A\u5B8C\u6210\uFF1A${l}`,"warning"),Gt(r))}finally{n===e.runId&&(e.generationInFlightRunId=0,gt(r,e,!1))}}async function oE(r,e,t){return H({type:"OPTIMIZE_PUBMED_QUERY",payload:{inputText:r,strategyMode:e,baseQuery:t,timeoutMs:Q1}},X1)}function nc(r,e,t){e.generationInFlightRunId=0,e.accessDenied=!0,e.deniedMessage=t,e.runId+=1,nt(r,e,""),de(r,t,"warning"),Gt(r),gr(r,[]),gt(r,e,!1);for(const n of[...r.generationModeBtns,...r.strategyModeBtns])n.disabled=!0,n.title=t,n.setAttribute("aria-disabled","true")}function sE(r,e,t){e.generationInFlightRunId=0,e.accessDenied=!1,e.deniedMessage="",nt(r,e,""),de(r,t,"warning"),Gt(r),gr(r,[]),gt(r,e,!1);for(const n of[...r.generationModeBtns,...r.strategyModeBtns])n.disabled=!1,n.title="",n.removeAttribute("aria-disabled")}function lE(r,e){if(e.accessDenied){e.accessDenied=!1,e.deniedMessage="",r.generateBtn.disabled=!1,r.generateBtn.textContent="\u751F\u6210",r.generateBtn.title="",r.generateBtn.removeAttribute("aria-disabled");for(const t of[...r.generationModeBtns,...r.strategyModeBtns])t.disabled=!1,t.title="",t.removeAttribute("aria-disabled");de(r,"\u6743\u76CA\u5DF2\u5237\u65B0\uFF0C\u8BF7\u91CD\u65B0\u751F\u6210\u68C0\u7D22\u5F0F\u3002","neutral")}}function gt(r,e,t){if(e.accessDenied){r.generateBtn.disabled=!0,r.generateBtn.textContent="\u5F00\u901A\u540E\u4F7F\u7528",r.generateBtn.title=e.deniedMessage,r.generateBtn.setAttribute("aria-disabled","true");return}r.generateBtn.disabled=t,r.generateBtn.textContent=t?"\u589E\u5F3A\u4E2D...":"\u751F\u6210",r.generateBtn.title="",r.generateBtn.removeAttribute("aria-disabled")}function nt(r,e,t){const n=t.trim();e.generatedQuery=n,r.output.value=n,r.copyBtn.disabled=n.length===0,r.searchBtn.disabled=n.length===0,Tn(r.output)}function de(r,e,t="neutral"){r.status.className="pl-home-qo__status",t!=="neutral"&&r.status.classList.add(`pl-home-qo__status--${t}`),r.status.textContent=mt(e)}function Gt(r,e){const t=LT(e);r.provider.textContent=t,r.provider.hidden=!t}function gr(r,e){const t=e.map(mt).filter(Boolean).join(" ");r.warnings.textContent=t,r.warnings.hidden=!t}function cE(r,e){const t=RT(r,e).trim();return t?/^(?:AI enhanced|Hybrid enhancement|LLM assisted)$/i.test(t)?"AI \u589E\u5F3A":/^(?:High Specificity|Strict)$/i.test(t)?"\u9AD8\u7CBE\u5EA6":/^(?:Recommended|Balanced)$/i.test(t)?"\u63A8\u8350":/^(?:Rules fallback|Base rules)$/i.test(t)?"\u57FA\u7840\u89C4\u5219":(/^(?:Boolean|PubMed Syntax|DOI|PMID)$/i.test(t),t):""}function Tn(r){const e=r.dataset.role==="output",t=e?38:44,n=e?50:60;r.style.height="auto";const a=Math.min(Math.max(r.scrollHeight,t),n);r.style.height=`${a}px`,r.style.overflowY=r.scrollHeight>n?"auto":"hidden"}async function uE(r){try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(r),!0}catch{}const e=document.createElement("textarea");e.value=r,e.style.position="fixed",e.style.left="-9999px",e.style.opacity="0",document.body.appendChild(e),e.select();try{return document.execCommand("copy")}catch{return!1}finally{e.remove()}}function dE(r){const e=r.trim();if(!e)return;const t=new URL(window.location.href);t.pathname="/",t.search="",t.hash="",t.searchParams.set("term",e),window.location.assign(t.toString())}function pE(){const r=bE();if(r){const n=r.closest("form");if(n)return n;const a=r.closest("p, div, section, nav, li");return a||r}const e=document.querySelector('main form[action="/"], main form[action=""], main form[role="search"], main .search-form, main .search-form-wrapper');if(e)return e;const t=document.querySelector("main");return t?.firstElementChild??t??document.body.firstElementChild}function hE(r){const e=r?.closest?.("form");return e||(document.querySelector('main form[action="/"], main form[action=""], main form[role="search"], main .search-form, main .search-form-wrapper')??r)}function rc(r,e){if(!e?.parentElement||!r.parentElement)return;const t=fE(e)??e.getBoundingClientRect(),n=r.parentElement.getBoundingClientRect();if(t.width<1||n.width<1)return;const a=Math.min(eE,Math.floor(t.width/4)),i=Math.max(0,Math.round(t.left-n.left+a)),o=Math.max(0,Math.round(Math.min(t.width-a*2,n.width-i)));o<1||(r.style.width=`${o}px`,r.style.maxWidth=`calc(100% - ${i}px)`,r.style.marginLeft=`${i}px`,r.style.marginRight="0")}function fE(r){const e=r.tagName.toLowerCase()==="form"?r:r.closest("form");if(!e)return null;const t=e.querySelector('input[name="term"], input[type="search"], input[type="text"]:not([type="hidden"])');if(!t)return null;const n=e.querySelector('button[type="submit"], input[type="submit"], .search-btn, .usa-search-submit'),a=t.getBoundingClientRect();if(a.width<1)return null;const i=n?.getBoundingClientRect();if(!i||i.width<1)return a;const o=Math.min(a.left,i.left),s=Math.max(a.right,i.right),l=Math.min(a.top,i.top),c=Math.max(a.bottom,i.bottom);return mE(o,l,s,c)}function mE(r,e,t,n){return{x:r,y:e,width:Math.max(0,t-r),height:Math.max(0,n-e),top:e,right:t,bottom:n,left:r,toJSON:()=>({})}}function bE(){return Array.from(document.querySelectorAll("a[href]")).find(e=>{const t=(e.textContent??"").trim().replace(/\s+/g," "),n=e.getAttribute("href")??"";return/^(?:Advanced|Advanced Search|高级检索)$/i.test(t)&&/\/advanced\/?/.test(n)})??null}const gE="pubmed.ncbi.nlm.nih.gov";function yE(){if(window.location.hostname!==gE)return!1;const r=new URL(window.location.href);return r.pathname!=="/"?!1:!r.searchParams.has("term")}const xE=ve+`
`+`/**
 * Journal Detail Card Styles
 *
 * \u671F\u520A\u8BE6\u60C5\u5361\u7247 \u2014 \u589E\u5F3A\u7248\u5E03\u5C40
 */

:host {
  display: block;
  position: relative;
  font-family: var(--pl-font-sans);
}

.pl-journal-card {
  background: var(--pl-color-bg);
  border: 1px solid var(--pl-color-border);
  border-radius: var(--pl-radius-md);
  overflow: hidden;
}

.pl-journal-header {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 14px;
  border-bottom: 1px solid var(--pl-color-border);
  font-size: 13px;
  font-weight: 600;
  color: var(--pl-color-text);
}

.pl-journal-header .icon {
  font-size: 14px;
}

.pl-journal-body {
  padding: 12px 14px;
}

/* \u2500\u2500 Journal Name \u2500\u2500 */
.pl-journal-name {
  font-size: 15px;
  font-weight: 700;
  color: var(--pl-color-text);
  margin-bottom: 4px;
  line-height: 1.3;
}

/* \u2500\u2500 ISSN \u2500\u2500 */
.pl-journal-issn {
  font-size: 11px;
  color: var(--pl-color-text-secondary);
  margin-bottom: 8px;
}

/* \u2500\u2500 Tags Row \u2500\u2500 */
.pl-journal-tags {
  display: flex;
  gap: 5px;
  margin-bottom: 10px;
  flex-wrap: wrap;
}

.pl-journal-tag {
  padding: 2px 7px;
  border-radius: 3px;
  font-size: 10px;
  font-weight: 600;
  white-space: nowrap;
  border: 1px solid var(--pl-color-border);
  background: var(--pl-color-surface);
  color: var(--pl-color-text-secondary);
}

.pl-journal-tag--jcr {
  color: #fff;
  font-weight: 700;
}
.pl-journal-tag--q1 { background: #b91c1c; border-color: #b91c1c; color: #fff; }
.pl-journal-tag--q2 { background: #15803d; border-color: #15803d; color: #fff; }
.pl-journal-tag--q3 { background: #b45309; border-color: #b45309; color: #fff; }
.pl-journal-tag--q4 { background: #475569; border-color: #475569; color: #fff; }

.pl-journal-tag--if {
  background: #ffedd5;
  color: #7c2d12;
  border-color: #fdba74;
}

.pl-journal-tag--if5 {
  background: #fef3c7;
  color: #78350f;
  border-color: #fcd34d;
}

.pl-journal-tag--cas {
  background: #ede9fe;
  color: #5b21b6;
  border-color: #c4b5fd;
}

.pl-journal-tag--emerging {
  font-weight: 700;
}

.pl-journal-tag--emerging-1 {
  background: #fee2e2;
  color: #7f1d1d;
  border-color: #fecaca;
}

.pl-journal-tag--emerging-2 {
  background: #dcfce7;
  color: #14532d;
  border-color: #bbf7d0;
}

.pl-journal-tag--emerging-3 {
  background: #fef3c7;
  color: #78350f;
  border-color: #fde68a;
}

.pl-journal-tag--emerging-4 {
  background: #e2e8f0;
  color: #334155;
  border-color: #cbd5e1;
}

.pl-journal-tag--sjr {
  font-weight: 700;
}
.pl-journal-tag--sjr.pl-journal-tag--q1 { background: #dc2626; border-color: #dc2626; color: #fff; }
.pl-journal-tag--sjr.pl-journal-tag--q2 { background: #16a34a; border-color: #16a34a; color: #fff; }
.pl-journal-tag--sjr.pl-journal-tag--q3 { background: #d97706; border-color: #d97706; color: #fff; }
.pl-journal-tag--sjr.pl-journal-tag--q4 { background: #64748b; border-color: #64748b; color: #fff; }

/* \u2500\u2500 Homepage Link \u2500\u2500 */
.pl-journal-homepage {
  margin-bottom: 8px;
}

.pl-journal-homepage-link {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  color: var(--pl-color-primary);
  font-size: 12px;
  font-weight: 500;
  text-decoration: none;
  transition: color var(--pl-transition-fast);
}

.pl-journal-homepage-link:hover {
  color: var(--pl-color-primary-hover);
  text-decoration: underline;
}

.pl-journal-homepage-icon {
  font-size: 13px;
}

.pl-journal-homepage-text {
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* \u2500\u2500 Info Row (country, OA, docs) \u2500\u2500 */
.pl-journal-info-row {
  font-size: 11px;
  color: var(--pl-color-text-secondary);
  margin-bottom: 6px;
  line-height: 1.5;
}

/* \u2500\u2500 Metrics Row (H-index, Cite/Doc) \u2500\u2500 */
.pl-journal-metrics-row {
  font-size: 11px;
  color: var(--pl-color-text);
  font-weight: 500;
  margin-bottom: 8px;
  line-height: 1.5;
}

/* \u2500\u2500 Trend Actions \u2500\u2500 */
.pl-trend-actions {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
  margin: 8px 0;
}

.pl-trend-actions-label {
  color: var(--pl-color-text-secondary);
  font-size: 11px;
  font-weight: 600;
}

.pl-trend-open-btn {
  border: 1px solid var(--pl-color-border);
  border-radius: 5px;
  background: var(--pl-color-bg);
  color: var(--pl-color-primary);
  font: inherit;
  font-size: 11px;
  font-weight: 700;
  line-height: 1;
  padding: 5px 8px;
  cursor: pointer;
}

.pl-trend-open-btn:hover {
  border-color: var(--pl-color-primary);
  background: var(--pl-color-primary-light);
}

/* \u2500\u2500 Trend Dialog \u2500\u2500 */
.pl-trend-dialog-overlay {
  position: fixed;
  inset: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24px;
  background: rgba(15, 23, 42, 0.22);
}

.pl-trend-dialog {
  width: min(590px, calc(100vw - 48px));
  max-height: min(88vh, 720px);
  overflow: auto;
  border: 1px solid var(--pl-color-border);
  border-radius: 10px;
  background: var(--pl-color-bg);
  box-shadow: 0 20px 48px rgba(15, 23, 42, 0.24);
  padding: 14px;
}

.pl-trend-dialog-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 10px;
}

.pl-trend-dialog-title-wrap {
  min-width: 0;
}

.pl-trend-dialog-title {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: var(--pl-color-text);
  font-size: 14px;
  font-weight: 800;
  line-height: 1.3;
}

.pl-trend-dialog-subtitle {
  color: var(--pl-color-text-secondary);
  font-size: 11px;
  line-height: 1.4;
}

.pl-trend-dialog-close {
  width: 28px;
  height: 28px;
  border: 1px solid var(--pl-color-border);
  border-radius: 50%;
  background: var(--pl-color-surface);
  color: var(--pl-color-text-secondary);
  font: inherit;
  font-size: 18px;
  line-height: 1;
  cursor: pointer;
}

.pl-trend-dialog-close:hover {
  color: var(--pl-color-text);
  background: var(--pl-color-bg);
}

.pl-trend-dialog-canvas {
  display: block;
  width: 100%;
  cursor: crosshair;
}

.pl-no-trend {
  padding: 12px;
  text-align: center;
  font-size: 12px;
  color: var(--pl-color-text-secondary);
}

/* \u2500\u2500 IF Hover Preview \u2500\u2500 */
.pl-if-hover-preview {
  position: absolute;
  z-index: 100;
  background: var(--pl-color-bg);
  border: 1px solid var(--pl-color-border);
  border-radius: var(--pl-radius-sm);
  padding: 6px 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
  pointer-events: none;
}

.pl-if-hover-preview canvas {
  display: block;
}

.pl-journal-tag--if-previewable {
  cursor: help;
}

/* \u2500\u2500 Similar Journals Section \u2500\u2500 */
.pl-similar-section {
  border-top: 1px solid var(--pl-color-border);
  padding-top: 8px;
  margin-top: 4px;
}

.pl-similar-header {
  font-size: 11px;
  font-weight: 600;
  color: var(--pl-color-text);
  margin-bottom: 6px;
}

.pl-similar-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.pl-similar-item {
  padding: 5px 8px;
  border-radius: var(--pl-radius-sm);
  background: var(--pl-color-surface);
  border: 1px solid var(--pl-color-border);
  font-size: 11px;
  line-height: 1.4;
}

.pl-similar-name {
  font-weight: 600;
  color: var(--pl-color-text);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.pl-similar-meta {
  color: var(--pl-color-text-secondary);
  font-size: 10px;
  margin-top: 2px;
}

.pl-similar-more {
  display: block;
  width: 100%;
  margin-top: 6px;
  padding: 4px 0;
  border: none;
  border-radius: var(--pl-radius-sm);
  background: transparent;
  color: var(--pl-color-primary);
  font-size: 11px;
  font-weight: 500;
  cursor: pointer;
  transition: background var(--pl-transition-fast);
  font-family: inherit;
}

.pl-similar-more:hover {
  background: var(--pl-color-primary-light);
}
`,Zt='-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", "Noto Sans SC", "Source Han Sans SC", "Helvetica Neue", Arial, sans-serif',AE="paperlens-journal-detail-card",CE=260,wm=54,vE=520,SE=204,wE=15e3,TE={"United States":"\u{1F1FA}\u{1F1F8}",US:"\u{1F1FA}\u{1F1F8}","United Kingdom":"\u{1F1EC}\u{1F1E7}",UK:"\u{1F1EC}\u{1F1E7}",China:"\u{1F1E8}\u{1F1F3}",CN:"\u{1F1E8}\u{1F1F3}",Germany:"\u{1F1E9}\u{1F1EA}",DE:"\u{1F1E9}\u{1F1EA}",Japan:"\u{1F1EF}\u{1F1F5}",JP:"\u{1F1EF}\u{1F1F5}",France:"\u{1F1EB}\u{1F1F7}",FR:"\u{1F1EB}\u{1F1F7}",Netherlands:"\u{1F1F3}\u{1F1F1}",NL:"\u{1F1F3}\u{1F1F1}",Switzerland:"\u{1F1E8}\u{1F1ED}",CH:"\u{1F1E8}\u{1F1ED}",Canada:"\u{1F1E8}\u{1F1E6}",CA:"\u{1F1E8}\u{1F1E6}",Australia:"\u{1F1E6}\u{1F1FA}",AU:"\u{1F1E6}\u{1F1FA}","South Korea":"\u{1F1F0}\u{1F1F7}",KR:"\u{1F1F0}\u{1F1F7}",India:"\u{1F1EE}\u{1F1F3}",IN:"\u{1F1EE}\u{1F1F3}",Italy:"\u{1F1EE}\u{1F1F9}",IT:"\u{1F1EE}\u{1F1F9}",Spain:"\u{1F1EA}\u{1F1F8}",ES:"\u{1F1EA}\u{1F1F8}",Brazil:"\u{1F1E7}\u{1F1F7}",BR:"\u{1F1E7}\u{1F1F7}",Sweden:"\u{1F1F8}\u{1F1EA}",SE:"\u{1F1F8}\u{1F1EA}",Norway:"\u{1F1F3}\u{1F1F4}",NO:"\u{1F1F3}\u{1F1F4}",Denmark:"\u{1F1E9}\u{1F1F0}",DK:"\u{1F1E9}\u{1F1F0}",Finland:"\u{1F1EB}\u{1F1EE}",FI:"\u{1F1EB}\u{1F1EE}",Ireland:"\u{1F1EE}\u{1F1EA}",IE:"\u{1F1EE}\u{1F1EA}",Singapore:"\u{1F1F8}\u{1F1EC}",SG:"\u{1F1F8}\u{1F1EC}",Taiwan:"\u{1F1F9}\u{1F1FC}",TW:"\u{1F1F9}\u{1F1FC}","New Zealand":"\u{1F1F3}\u{1F1FF}",NZ:"\u{1F1F3}\u{1F1FF}",Russia:"\u{1F1F7}\u{1F1FA}",RU:"\u{1F1F7}\u{1F1FA}",Israel:"\u{1F1EE}\u{1F1F1}",IL:"\u{1F1EE}\u{1F1F1}",Poland:"\u{1F1F5}\u{1F1F1}",PL:"\u{1F1F5}\u{1F1F1}",Austria:"\u{1F1E6}\u{1F1F9}",AT:"\u{1F1E6}\u{1F1F9}",Belgium:"\u{1F1E7}\u{1F1EA}",BE:"\u{1F1E7}\u{1F1EA}",Portugal:"\u{1F1F5}\u{1F1F9}",PT:"\u{1F1F5}\u{1F1F9}"};function Tm(r){return r?TE[r]??"":""}function Em(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"")}function EE(){const r=document.createElement("div");r.className=AE;const e=r.attachShadow({mode:"open"}),t=document.createElement("style");return t.textContent=xE,e.appendChild(t),{host:r,shadow:e}}function FE(r){const{host:e,shadow:t}=EE(),n=r.journal,a=r.showScimagoSJR!==!1,i=Rt({quartileSources:r.quartileSources}),o=i.includes("jcr"),s=i.includes("cas"),l=i.includes("emerging"),c=document.createElement("div");c.className="pl-journal-card";const u=document.createElement("div");u.className="pl-journal-header";const d=document.createElement("span");d.className="icon",d.textContent="\u{1F4F0}",u.appendChild(d),u.appendChild(document.createTextNode(" \u671F\u520A\u8BE6\u60C5")),c.appendChild(u);const p=document.createElement("div");p.className="pl-journal-body";const h=document.createElement("div");if(h.className="pl-journal-name",h.textContent=n.journalName,p.appendChild(h),n.issn?.length){const S=document.createElement("div");S.className="pl-journal-issn",S.textContent=`ISSN: ${n.issn.join(", ")}`,p.appendChild(S)}const f=document.createElement("div");f.className="pl-journal-tags";const y=Lt(n.jcrQuartile);if(y){const S=document.createElement("span");S.className=`pl-journal-tag pl-journal-tag--jcr pl-journal-tag--${y.value.toLowerCase()}`,S.textContent=y.label,S.setAttribute("data-pl-jcr-quartile",""),o||(S.style.display="none"),f.appendChild(S)}const x=document.createElement("span"),T=zn(n.impactFactor,n.impactFactorLabel);if(Number.isFinite(n.impactFactor)&&(x.className="pl-journal-tag pl-journal-tag--if",x.textContent=`IF ${T}`,f.appendChild(x)),r.if5yr){const S=document.createElement("span");S.className="pl-journal-tag pl-journal-tag--if5",S.textContent=`5yr IF ${r.if5yr.toFixed(1)}`,f.appendChild(S)}const E=hn(n.casQuartile);if(E){const S=document.createElement("span");S.className="pl-journal-tag pl-journal-tag--cas",S.textContent=`\u4E2D\u79D1\u9662${E.label}`,S.setAttribute("data-pl-cas-quartile",""),s||(S.style.display="none"),f.appendChild(S)}const w=Jn(n.emergingQuartile,n.emergingTop);if(w){const S=document.createElement("span");S.className=`pl-journal-tag pl-journal-tag--emerging pl-journal-tag--emerging-${w.value}`,S.textContent=w.label,S.setAttribute("data-pl-emerging-quartile",""),l||(S.style.display="none"),f.appendChild(S)}if(a&&n.sjrQuartile){const S=document.createElement("span");S.className=`pl-journal-tag pl-journal-tag--sjr pl-journal-tag--${n.sjrQuartile.toLowerCase()}`,S.textContent=`SJR ${n.sjrQuartile}`,f.appendChild(S)}p.appendChild(f);const v=PE(n,r.trendData),g=a?BE(n,r.sjrTrendData):void 0;h.title=`${n.journalName} \xB7 \u60AC\u505C\u67E5\u770B IF \u8D8B\u52BF`,Number.isFinite(n.impactFactor)&&(x.title=`IF ${T} \xB7 \u60AC\u505C\u67E5\u770B IF \u8D8B\u52BF`,x.classList.add("pl-journal-tag--if-previewable")),Wn(h,{journalName:n.journalName,journal:n,getTrendData:v,...g?{getSJRTrendData:g}:{},quartileSources:i,delayMs:280}),Number.isFinite(n.impactFactor)&&Wn(x,{journalName:n.journalName,journal:n,getTrendData:v,...g?{getSJRTrendData:g}:{},quartileSources:i,delayMs:280});const C=r.homepageUrl;if(C){const S=document.createElement("div");S.className="pl-journal-homepage";const _=document.createElement("a");_.className="pl-journal-homepage-link",_.href=C,_.target="_blank",_.rel="noopener noreferrer",_.title=C;const P=document.createElement("span");P.className="pl-journal-homepage-icon",P.textContent="\u{1F3E0}";const R=document.createElement("span");R.className="pl-journal-homepage-text";try{const M=new URL(C);R.textContent=M.hostname.replace(/^www\./,"")}catch{R.textContent=C}_.appendChild(P),_.appendChild(R),S.appendChild(_),p.appendChild(S)}const L=[],$=Tm(n.country);if(n.country&&L.push(`${$} ${n.country}`),n.openAccess!==void 0&&L.push(n.openAccess?"\u2705 OA":"\u{1F512} \u975E OA"),n.openAccessDiamond&&L.push("\u{1F48E} Diamond OA"),n.totalDocs2025&&n.totalDocs2025>0&&L.push(`\u{1F4DD} ${Math.round(n.totalDocs2025)} \u7BC7 (2025)`),L.length>0){const S=document.createElement("div");S.className="pl-journal-info-row",S.textContent=L.join("  \xB7  "),p.appendChild(S)}if(a){const S=[];if(n.sjrHIndex&&S.push(`H-index: ${Math.round(n.sjrHIndex)}`),n.citationsPerDoc&&S.push(`Cite/Doc: ${n.citationsPerDoc.toFixed(1)}`),S.length>0){const _=document.createElement("div");_.className="pl-journal-metrics-row",_.textContent=S.join(" \xB7 "),p.appendChild(_)}}const k=!!(r.trendData&&r.trendData.length>=2),N=!!(a&&r.sjrTrendData&&r.sjrTrendData.length>=2);if(k||N){const S=document.createElement("div");S.className="pl-trend-actions";const _=document.createElement("span");_.className="pl-trend-actions-label",_.textContent="\u8D8B\u52BF",S.appendChild(_),k&&S.appendChild(Fm("IF Trend",()=>{Dm({shadow:t,host:e,journalName:n.journalName,trendData:r.trendData,sjrTrendData:r.sjrTrendData},"if")})),N&&S.appendChild(Fm("SJR Trend",()=>{Dm({shadow:t,host:e,journalName:n.journalName,trendData:r.trendData,sjrTrendData:r.sjrTrendData},"sjr")})),p.appendChild(S)}if(r.similarJournals&&r.similarJournals.length>0){const S=document.createElement("div");S.className="pl-similar-section";const _=document.createElement("div");_.className="pl-similar-header",_.textContent="\u{1F4D1} \u540C\u7C7B\u671F\u520A\u63A8\u8350",S.appendChild(_);const P=3,R=new Set([Em(n.journalName)]),M=r.similarJournals.filter(Q=>{const se=Em(Q.journalName);return!se||R.has(se)?!1:(R.add(se),!0)}).slice(0,5);if(M.length>0){const Q=M.length>P,se=document.createElement("div");se.className="pl-similar-list";const at=fe=>{se.innerHTML="";for(const X of fe){const xt=document.createElement("div");xt.className="pl-similar-item";const Xt=document.createElement("div");Xt.className="pl-similar-name",Xt.textContent=X.journalName;const Oe=document.createElement("div");Oe.className="pl-similar-meta";const At=[],Ct=zn(X.impactFactor,X.impactFactorLabel);Ct&&At.push(`IF ${Ct}`);const xr=Lt(X.jcrQuartile);xr&&At.push(xr.label),a&&X.sjrQuartile&&At.push(`SJR ${X.sjrQuartile}`);const Ar=Tm(X.country);Ar&&At.push(Ar),Oe.textContent=At.join(" \xB7 "),xt.appendChild(Xt),xt.appendChild(Oe),se.appendChild(xt)}};if(at(M.slice(0,P)),S.appendChild(se),Q){const fe=document.createElement("button");fe.className="pl-similar-more",fe.type="button",fe.textContent="\u67E5\u770B\u66F4\u591A \u25B8";let X=!1;fe.addEventListener("click",()=>{X=!X,at(X?M:M.slice(0,P)),fe.textContent=X?"\u6536\u8D77 \u25BE":"\u67E5\u770B\u66F4\u591A \u25B8"}),S.appendChild(fe)}p.appendChild(S)}}return c.appendChild(p),t.appendChild(c),e}function Fm(r,e){const t=document.createElement("button");return t.className="pl-trend-open-btn",t.type="button",t.textContent=r,t.addEventListener("click",e),t}function Dm(r,e){r.shadow.querySelector(".pl-trend-dialog-overlay")?.remove();const t=e==="sjr",n=t?"SJR Trend":"IF Trend",a=t?r.sjrTrendData:r.trendData;if(!a||a.length<2)return;const i=document.createElement("div");i.className="pl-trend-dialog-overlay";const o=document.createElement("div");o.className="pl-trend-dialog",o.setAttribute("role","dialog"),o.setAttribute("aria-modal","true"),o.setAttribute("aria-label",`${r.journalName} ${n}`);const s=document.createElement("div");s.className="pl-trend-dialog-header";const l=document.createElement("div");l.className="pl-trend-dialog-title-wrap";const c=document.createElement("div");c.className="pl-trend-dialog-title",c.textContent=n;const u=document.createElement("div");u.className="pl-trend-dialog-subtitle",u.textContent=`${r.journalName} \xB7 ${DE(a)}`,l.append(c,u);const d=document.createElement("button");d.className="pl-trend-dialog-close",d.type="button",d.setAttribute("aria-label","\u5173\u95ED\u8D8B\u52BF\u56FE"),d.textContent="\xD7",s.append(l,d);const p=document.createElement("canvas");p.className="pl-trend-dialog-canvas";const h=()=>{if(_E(p),t){ME(p,a,r.host);return}kE(p,a,r.host)};d.addEventListener("click",()=>i.remove()),i.addEventListener("click",f=>{f.target===i&&i.remove()}),o.append(s,p),i.appendChild(o),r.shadow.appendChild(i),requestAnimationFrame(h)}function DE(r){const e=r[0],t=r[r.length-1];return e&&t?`${e.year} - ${t.year}`:""}function _E(r,e){r.dataset.plTrendWidth=String(vE),r.dataset.plTrendHeight=String(SE)}function _m(r){const e=Number(r.dataset.plTrendWidth)||CE,t=Number(r.dataset.plTrendHeight)||wm;return{w:e,h:t,expanded:t>wm}}function km(r,e){const{w:t,h:n,expanded:a}=_m(r),i=a?{t:14,b:26,l:34,r:14}:{t:5,b:13,l:5,r:5},o=t-i.l-i.r,s=n-i.t-i.b,l=e.map(p=>p.if),c=Math.max(...l)*1.15,u=Math.min(...l)*.85,d=c-u||1;return{w:t,h:n,expanded:a,pad:i,plotW:o,plotH:s,maxV:c,minV:u,range:d,xScale:p=>i.l+p/(e.length-1)*o,yScale:p=>i.t+(1-(p-u)/d)*s}}function kE(r,e,t){Vi(r,e,t);const n=r;n._ifTrendHandler&&(r.removeEventListener("mousemove",n._ifTrendHandler),r.removeEventListener("mouseleave",n._ifTrendHandler));const a=NE(r,e,t);n._ifTrendHandler=a,r.addEventListener("mousemove",a),r.addEventListener("mouseleave",a)}function Vi(r,e,t,n=-1){const a=r.getContext("2d");if(!a||e.length<2)return;const i=window.devicePixelRatio||1,o=km(r,e),{w:s,h:l,expanded:c,pad:u,minV:d,range:p,xScale:h,yScale:f}=o;r.width=s*i,r.height=l*i,r.style.width="100%",r.style.height=`${l}px`,a.scale(i,i);const y=Aa("--pl-color-primary","#2563eb",t),x=Aa("--pl-color-text-secondary","#9ca3af",t),T=Aa("--pl-color-border","#e5e7eb",t);if(c){a.strokeStyle=T,a.lineWidth=.6,a.font=`10px ${Zt}`,a.fillStyle=x,a.textAlign="right",a.textBaseline="middle";for(let v=0;v<=3;v++){const g=d+p/3*v,C=f(g);a.beginPath(),a.moveTo(u.l,C),a.lineTo(s-u.r,C),a.stroke(),a.fillText(g.toFixed(g>=10?1:2),u.l-5,C)}}const E=a.createLinearGradient(0,0,0,l);E.addColorStop(0,"rgba(37, 99, 235, 0.12)"),E.addColorStop(1,"rgba(37, 99, 235, 0)"),a.beginPath(),e.forEach((v,g)=>{const C=h(g),L=f(v.if);g===0?a.moveTo(C,L):a.lineTo(C,L)}),a.lineTo(h(e.length-1),l-u.b),a.lineTo(u.l,l-u.b),a.closePath(),a.fillStyle=E,a.fill(),a.strokeStyle=y,a.lineWidth=1.5,a.beginPath(),e.forEach((v,g)=>{const C=h(g),L=f(v.if);g===0?a.moveTo(C,L):a.lineTo(C,L)}),a.stroke(),a.font=c?`10px ${Zt}`:`8px ${Zt}`,a.textAlign="center";const w=Rm(a,{years:e.map(v=>v.year),plotW:o.plotW,expanded:c});e.forEach((v,g)=>{const C=h(g),L=f(v.if);a.fillStyle=y,a.beginPath(),a.arc(C,L,g===n?5:2.5,0,Math.PI*2),a.fill(),g===n&&(a.strokeStyle="#ffffff",a.lineWidth=1.8,a.stroke()),w.has(g)&&(a.fillStyle=x,a.fillText(String(v.year),C,l-(c?7:1)))}),c&&Lm(a,{data:e.map((v,g)=>{const C={value:v.if,x:h(g),y:f(v.if)};return v.ifLabel&&(C.label=v.ifLabel),C}),w:s,h:l,pad:u,color:x,formatter:Pm}),n>=0&&Nm(a,{label:`${e[n].year}: IF ${LE(e[n])}`,x:h(n),y:f(e[n].if),w:s})}function NE(r,e,t){let n=-1;return a=>{if(a.type==="mouseleave"){n=-1,Vi(r,e,t);return}const i=km(r,e),o=r.getBoundingClientRect(),s=(a.clientX-o.left)*(i.w/o.width),l=(a.clientY-o.top)*(i.h/o.height);let c=-1,u=1/0;for(let d=0;d<e.length;d++){const p=i.xScale(d),h=i.yScale(e[d].if),f=Math.hypot(s-p,l-h);f<u&&(u=f,c=d)}if(u>(i.expanded?18:24)||c<0){n!==-1&&(n=-1,Vi(r,e,t));return}c!==n&&(n=c,Vi(r,e,t,c))}}function Nm(r,e){r.save(),r.font=`10px ${Zt}`;const t=r.measureText(e.label).width+12,n=18;let a=e.x-t/2,i=e.y-n-8;i<2&&(i=e.y+10),a<2&&(a=2),a+t>e.w-2&&(a=e.w-t-2),r.fillStyle="#1f2937",r.beginPath(),r.roundRect(a,i,t,n,3),r.fill(),r.fillStyle="#ffffff",r.textAlign="center",r.textBaseline="middle",r.fillText(e.label,a+t/2,i+n/2),r.restore()}function Lm(r,e){r.save(),r.font=`9px ${Zt}`,r.fillStyle=e.color,r.textAlign="center",r.textBaseline="middle";for(const t of e.data){const n=t.label??e.formatter(t.value),a=r.measureText(n).width;let i=t.x;i-a/2<e.pad.l&&(i=e.pad.l+a/2),i+a/2>e.w-e.pad.r&&(i=e.w-e.pad.r-a/2);let s=t.y-e.pad.t<14?t.y+13:t.y-12;s=Math.max(e.pad.t+8,Math.min(e.h-e.pad.b-8,s)),r.fillText(n,i,s)}r.restore()}function Rm(r,e){const{years:t,plotW:n,expanded:a}=e,i=t.length;if(i<=2)return new Set(t.map((d,p)=>p));const o=t.reduce((d,p)=>Math.max(d,r.measureText(String(p)).width),0),l=Math.max(2,Math.floor(n/Math.max(1,o+(a?12:10))));if(i<=l)return new Set(t.map((d,p)=>p));const c=Math.max(1,Math.ceil((i-1)/Math.max(1,l-1))),u=new Set([0,i-1]);for(let d=0;d<i;d+=c)u.add(d);return u}function Pm(r){return r>=10?r.toFixed(1):r.toFixed(2).replace(/\.?0+$/,"")}function LE(r){return r.ifLabel??Pm(r.if)}function RE(r){return r>=10?r.toFixed(1):r.toFixed(2).replace(/\.?0+$/,"")}function PE(r,e){let t=e&&e.length>=2?e:void 0,n=null;return()=>{if(t)return Promise.resolve(t);if(n)return n;const a=H({type:"GET_JOURNAL_TREND_DATA",payload:{normalizedName:r.normalizedName,journalName:r.journalName}},wE).then(async i=>{let o=i?.success&&Array.isArray(i.data?.trendData)?i.data.trendData:[];return o.length<2&&(o=await Bm(r)),o.length>=2&&(t=o),n=null,o}).catch(()=>(n=null,Bm(r)));return n=a,a}}function BE(r,e){let t=e&&e.length>=2?e:void 0,n=null;return()=>t?Promise.resolve(t):r?n||(n=IE(r).then(a=>(a.length>=2&&(t=a),n=null,a)).catch(()=>(n=null,[])),n):Promise.resolve([])}async function Bm(r){const e=ui(r.normalizedName,r.journalName);return e.length>0?hs(e):[]}async function IE(r){const e=ui(r.normalizedName,r.journalName);return e.length>0?fs(e):[]}const Im={Q1:"rgba(34, 197, 94, 0.10)",Q2:"rgba(59, 130, 246, 0.10)",Q3:"rgba(251, 191, 36, 0.10)",Q4:"rgba(239, 68, 68, 0.10)"};function ME(r,e,t){Wi(r,e,t);const n=r;n._sjrTrendHandler&&(r.removeEventListener("mousemove",n._sjrTrendHandler),r.removeEventListener("mouseleave",n._sjrTrendHandler));const a=qE(r,e,t);n._sjrTrendHandler=a,r.addEventListener("mousemove",a),r.addEventListener("mouseleave",a)}function Mm(r,e){const{w:t,h:n,expanded:a}=_m(r),i=a?{t:14,b:26,l:34,r:14}:{t:5,b:13,l:5,r:5},o=t-i.l-i.r,s=n-i.t-i.b,l=e.map(p=>p.sjr),c=Math.max(...l)*1.15,u=Math.min(...l)*.85,d=c-u||1;return{w:t,h:n,expanded:a,pad:i,plotW:o,plotH:s,maxV:c,minV:u,range:d,xScale:p=>i.l+p/(e.length-1)*o,yScale:p=>i.t+(1-(p-u)/d)*s}}function Wi(r,e,t,n=-1){const a=r.getContext("2d");if(!a||e.length<2)return;const i=window.devicePixelRatio||1,o=Mm(r,e),{w:s,h:l,expanded:c,pad:u,plotH:d,xScale:p,yScale:h}=o;r.width=s*i,r.height=l*i,r.style.width="100%",r.style.height=`${l}px`,a.scale(i,i);const f="#ea580c",y=Aa("--pl-color-text-secondary","#9ca3af",t),x=Aa("--pl-color-border","#e5e7eb",t);if(c){a.strokeStyle=x,a.lineWidth=.6,a.font=`10px ${Zt}`,a.fillStyle=y,a.textAlign="right",a.textBaseline="middle";for(let w=0;w<=3;w++){const v=o.minV+o.range/3*w,g=h(v);a.beginPath(),a.moveTo(u.l,g),a.lineTo(s-u.r,g),a.stroke(),a.fillText(v.toFixed(v>=10?1:2),u.l-5,g)}}if(e.length>2){let w=0;for(;w<e.length;){const v=e[w].sjrQuartile;if(v&&Im[v]){let g=w;for(;g<e.length&&e[g].sjrQuartile===v;)g++;const C=w===0?p(0):(p(w-1)+p(w))/2,L=g-1,$=L>=e.length-1?p(e.length-1):(p(L)+p(L+1))/2;a.fillStyle=Im[v],a.fillRect(C,u.t,$-C,d),w=g}else w++}}const T=a.createLinearGradient(0,0,0,l);T.addColorStop(0,"rgba(234, 88, 12, 0.12)"),T.addColorStop(1,"rgba(234, 88, 12, 0)"),a.beginPath(),e.forEach((w,v)=>{const g=p(v),C=h(w.sjr);v===0?a.moveTo(g,C):a.lineTo(g,C)}),a.lineTo(p(e.length-1),l-u.b),a.lineTo(u.l,l-u.b),a.closePath(),a.fillStyle=T,a.fill(),a.strokeStyle=f,a.lineWidth=1.5,a.beginPath(),e.forEach((w,v)=>{const g=p(v),C=h(w.sjr);v===0?a.moveTo(g,C):a.lineTo(g,C)}),a.stroke(),a.font=c?`10px ${Zt}`:`8px ${Zt}`,a.textAlign="center";const E=Rm(a,{years:e.map(w=>w.year),plotW:o.plotW,expanded:c});if(e.forEach((w,v)=>{const g=p(v),C=h(w.sjr);a.fillStyle=f,a.beginPath(),a.arc(g,C,v===n?5:2.5,0,Math.PI*2),a.fill(),v===n&&(a.strokeStyle="#ffffff",a.lineWidth=1.8,a.stroke()),E.has(v)&&(a.fillStyle=y,a.fillText(String(w.year),g,l-(c?7:1)))}),c&&Lm(a,{data:e.map((w,v)=>({value:w.sjr,x:p(v),y:h(w.sjr)})),w:s,h:l,pad:u,color:y,formatter:RE}),n>=0){const w=e[n],v=w.sjrQuartile?` \xB7 ${w.sjrQuartile}`:"";Nm(a,{label:`${w.year}: SJR ${w.sjr.toFixed(2)}${v}`,x:p(n),y:h(w.sjr),w:s})}}function qE(r,e,t){let n=-1;return a=>{if(a.type==="mouseleave"){n=-1,Wi(r,e,t);return}const i=Mm(r,e),o=r.getBoundingClientRect(),s=(a.clientX-o.left)*(i.w/o.width),l=(a.clientY-o.top)*(i.h/o.height);let c=-1,u=1/0;for(let d=0;d<e.length;d++){const p=i.xScale(d),h=i.yScale(e[d].sjr),f=Math.hypot(s-p,l-h);f<u&&(u=f,c=d)}if(u>(i.expanded?18:24)||c<0){n!==-1&&(n=-1,Wi(r,e,t));return}c!==n&&(n=c,Wi(r,e,t,c))}}function Aa(r,e,t){try{const n=t??document.documentElement;return getComputedStyle(n).getPropertyValue(r).trim()||e}catch{return e}}const jE=`.pl-export-save-card {
  background: #ffffff;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 12px;
}

.pl-export-save-card-header {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 12px 14px;
  background: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
  font-size: 13px;
  font-weight: 700;
  color: #111827;
}

.pl-export-save-card-header-icon {
  font-size: 14px;
}

.pl-export-save-card-body {
  padding: 12px 14px;
}

.pl-export-save-section-label {
  font-size: 11px;
  font-weight: 600;
  color: #6b7280;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  margin-bottom: 8px;
}

.pl-export-formats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 6px;
  margin-bottom: 14px;
}

.pl-export-format-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 30px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  background: #ffffff;
  color: #374151;
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.15s, border-color 0.15s;
}

.pl-export-format-btn:hover {
  background: #f9fafb;
  border-color: #9ca3af;
}

.pl-export-format-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pl-zotero-save-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  width: 100%;
  height: 34px;
  border: 1px solid #3b82f6;
  border-radius: 6px;
  background: #3b82f6;
  color: #ffffff;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.15s;
}

.pl-zotero-save-btn:hover {
  background: #2563eb;
}

.pl-zotero-save-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pl-zotero-last-target {
  font-size: 11px;
  color: #9ca3af;
  margin-top: 6px;
  text-align: center;
}
`,$E="paperlens-export-save-card",ac="paperlens_zotero_last_collection",ic="paperlens_zotero_last_collection_name",OE=35e3,UE=45e3,HE=45e3,zE=[{value:"ris",label:"RIS"},{value:"bibtex",label:"BibTeX"},{value:"medline",label:"NBIB"},{value:"csv",label:"CSV"}];async function qm(){try{const r=await I.storage.local.get([ac,ic]);return{key:r[ac]||"",name:r[ic]||""}}catch{return{key:"",name:""}}}async function JE(r,e){try{await I.storage.local.set({[ac]:r,[ic]:e})}catch{}}function oc(r,e){r.disabled=!0,r.title=e,r.setAttribute("aria-disabled","true")}function jm(r,e){r.dataset.busy!=="true"&&(r.disabled=!1),r.title="",e.textContent="\u4FDD\u5B58\u5230 Zotero",r.removeAttribute("aria-disabled")}async function VE(r,e,t){const n=await lt(e);if(n.allowed){r.disabled=!1,r.title="",r.textContent=t,r.removeAttribute("aria-disabled");return}oc(r,n.error||`${t} \u6682\u4E0D\u53EF\u7528`),r.textContent=`${t} Pro`}async function WE(r){const e=await lt(r);return e.allowed?!0:(D.error(e.error||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528\u8BE5\u5BFC\u51FA\u683C\u5F0F"),!1)}async function sc(r,e){const t=await or();if(t.allowed){jm(r,e);return}if(t.transient){r.dataset.busy!=="true"&&(r.disabled=!1),r.title=t.error||"",e.textContent="\u4FDD\u5B58\u5230 Zotero",r.removeAttribute("aria-disabled");return}oc(r,t.error||"Zotero \u5BFC\u51FA\u662F Pro \u6C38\u4E45\u7248\u6743\u76CA"),e.textContent="\u4FDD\u5B58\u5230 Zotero Pro"}function GE(r,e){xn();const t=n=>{const a=n.detail;if(a?.featureKey===Mt){if(a.allowed===!0){jm(r,e);return}oc(r,a.error||"Zotero \u5BFC\u51FA\u662F Pro \u6C38\u4E45\u7248\u6743\u76CA"),e.textContent="\u4FDD\u5B58\u5230 Zotero Pro"}};document.addEventListener(pe,t),window.addEventListener("pagehide",()=>{document.removeEventListener(pe,t)},{once:!0})}async function ZE(){const r=await or();return r.allowed?!0:(D.error(r.error||"Zotero \u5BFC\u51FA\u662F Pro \u6C38\u4E45\u7248\u6743\u76CA"),!1)}function YE(r){return/(?:Zotero 导出|Pro|永久版权益|开通|当前账户暂不能使用|请先登录|账户状态已切换|NOT_AUTHENTICATED|SESSION_CHANGED|FEATURE_|PLAN_REQUIRED)/i.test(r||"")}function KE(r){const e=document.createElement("div");e.className=$E;const t=e.attachShadow({mode:"open"}),n=document.createElement("style");n.textContent=jE,t.appendChild(n);const a=document.createElement("div");a.className="pl-export-save-card";const i=document.createElement("div");i.className="pl-export-save-card-header";const o=document.createElement("span");o.className="pl-export-save-card-header-icon",o.textContent="\u{1F4E4}";const s=document.createElement("span");s.textContent="\u5BFC\u51FA\u4E0E\u4FDD\u5B58",i.append(o,s);const l=document.createElement("div");l.className="pl-export-save-card-body";const c=document.createElement("div");c.className="pl-export-save-section-label",c.textContent="\u5BFC\u51FA\u683C\u5F0F";const u=document.createElement("div");u.className="pl-export-formats";for(const x of zE){const T=document.createElement("button");T.type="button",T.className="pl-export-format-btn",T.textContent=x.label,T.addEventListener("click",async()=>{await WE(x.value)&&await QE(r.pmid,x.value)}),u.appendChild(T),VE(T,x.value,x.label)}const d=document.createElement("div");d.className="pl-export-save-section-label",d.style.marginTop="4px",d.textContent="\u4FDD\u5B58\u5230 Zotero";const p=document.createElement("button");p.type="button",p.className="pl-zotero-save-btn";const h=document.createElement("span");h.textContent="\u{1F4DA}";const f=document.createElement("span");f.textContent="\u4FDD\u5B58\u5230 Zotero",p.append(h,f);const y=document.createElement("div");return y.className="pl-zotero-last-target",qm().then(x=>{x.name&&(y.textContent=`\u4E0A\u6B21\u76EE\u6807: ${x.name}`)}),p.addEventListener("click",async()=>{if(!await ZE()){await sc(p,f);return}p.disabled=!0,p.dataset.busy="true";try{D.info("\u6B63\u5728\u8FDE\u63A5 Zotero...");let x;try{x=await H({type:"ZOTERO_PING"},OE)}catch(E){x={success:!1,error:E instanceof Error&&E.message==="runtime message timed out"?"Zotero \u68C0\u6D4B\u8D85\u65F6":"Zotero \u68C0\u6D4B\u5931\u8D25"}}if(!x?.success||!x?.data){if(YE(x?.error)){D.error(x?.error||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528 Zotero \u5BFC\u51FA"),await sc(p,f);return}D.info(`\u672A\u68C0\u6D4B\u5230 Zotero\uFF0C\u5C06\u76F4\u63A5\u5C1D\u8BD5\u4FDD\u5B58${x?.error?`\uFF1A${x.error}`:""}`)}const T=await qm();Hs({defaultCollectionKey:T.key,defaultCollectionName:T.name,onConfirm:async(E,w,v)=>{const g=Us(r.paper),C=E?[E]:void 0;D.info("\u6B63\u5728\u4FDD\u5B58\u5230 Zotero...");const L=await H({type:"ZOTERO_SAVE_ITEMS",payload:{items:[g],collections:C}},UE);L?.success?(L.warning?D.info(L.warning):D.success(`\u5DF2\u4FDD\u5B58\u5230 Zotero${w?` \u2192 ${w}`:""}`),v&&E&&await JE(E,w),y.textContent=w?`\u76EE\u6807: ${w}`:""):D.error(`\u4FDD\u5B58\u5931\u8D25\uFF1A${L?.error||L?.message||"\u672A\u77E5\u9519\u8BEF"}`)}})}catch(x){D.error(x instanceof Error&&x.message==="runtime message timed out"?"Zotero \u68C0\u6D4B\u8D85\u65F6\uFF0C\u8BF7\u5237\u65B0\u6269\u5C55\u540E\u91CD\u8BD5":"\u65E0\u6CD5\u8FDE\u63A5 Zotero\uFF0C\u8BF7\u68C0\u67E5 Zotero \u662F\u5426\u8FD0\u884C")}finally{delete p.dataset.busy,p.disabled=!1}}),sc(p,f),GE(p,f),l.append(c,u,d,p,y),a.append(i,l),t.appendChild(a),e}async function QE(r,e){const t={type:"EXPORT_PUBMED_RECORDS",payload:{pmids:[r],format:e}};try{D.info("\u6B63\u5728\u5BFC\u51FA...");const n=await H(t,HE);if(!n?.success||!n.data){D.error(n?.error?`\u5BFC\u51FA\u5931\u8D25\uFF1A${n.error}`:"\u5BFC\u51FA\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5");return}const{downloadFile:a,EXPORT_MIME_TYPES:i,EXPORT_EXTENSIONS:o}=await Promise.resolve().then(()=>Ds),s=o[e]??".txt",l=i[e]??"text/plain",c=`PMID${r}${s}`;a(n.data,c,l),D.success("\u5DF2\u5BFC\u51FA")}catch{D.error("\u5BFC\u51FA\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5")}}const XE=ve+`
`+`/**
 * Article Sidebar Styles
 *
 * PubMed \u6587\u7AE0\u9875\u53F3\u4FA7\u539F\u751F\u680F\u5185\u7684 PaperLens \u589E\u5F3A\u9762\u677F\u3002
 */

:host {
  display: block;
  font-family: var(--pl-font-sans);
}

.pl-sidebar {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;
  margin-bottom: 16px;
}
`,e5="paperlens-article-sidebar";function t5(){const r=document.createElement("div");r.className=e5;const e=r.attachShadow({mode:"open"}),t=document.createElement("style");return t.textContent=XE,e.appendChild(t),{host:r,shadow:e}}function n5(r){const{host:e,shadow:t}=t5(),n=document.createElement("div");if(n.className="pl-sidebar",r.exportSave){const a=KE(r.exportSave);n.appendChild(a)}if(r.journal){const a=FE(r.journal);n.appendChild(a)}return t.appendChild(n),e}function r5(r){const e=r.replace(/\.$/,"").trim();return!e||e.includes(",")||e.includes(";")||/https?:\/\//i.test(e)||/\b(?:doi|pmid|pmc|epub|published|online|accessed)\b/i.test(e)||/^(accessed|vol|volume|edition|ed|eds)$/i.test(e)||!/[A-Za-z]/.test(e)?"":e.replace(/[;:\s]+$/,"").trim()}function a5(r){const e=r.replace(/\s+/g," ").trim();if(!e)return"";const t=[],n=/\b(?:18|19|20)\d{2}\b/g;let a;for(;(a=n.exec(e))!==null;){const o=e.slice(0,a.index).trim().split(/\.\s+/).map(r5).filter(Boolean),s=o[o.length-1];s&&s.length>=2&&s.length<=90&&t.push(s)}return t[t.length-1]??""}const $m="paperlens-article-page-style",i5=45e3,yr={abstract:10,citations:20,save:40,translate:60},lc="data-paperlens-related-metrics",Ca="data-paperlens-related-metrics-pending",o5=[".similar-cited-articles","#similar","#similar-articles","#citedby","#references",".similar-articles",".citedby-articles",".cited-by-articles",".cited-by"].join(", ");let cc=null,uc=null;function Om(){return window.location.pathname.match(/\/(\d+)\/?$/)?.[1]??""}function yt(r){return document.querySelector(`meta[name="${r}"]`)?.getAttribute("content")?.trim()??""}function s5(r){return Array.from(document.querySelectorAll(`meta[name="${r}"]`)).map(e=>e.getAttribute("content")?.trim()??"").filter(Boolean)}function l5(r){return document.querySelector(r)?.textContent?.replace(/\s+/g," ").trim()??""}function dc(){return document.body?.innerText??document.body?.textContent??""}function pc(r){return r.replace(/\s*[:：]\s*[^:：]+$/,"").trim()||r}function hc(){if(document.getElementById($m))return;const r=document.createElement("style");r.id=$m,r.textContent=`
    .paperlens-article-action-row {
      display: flex;
      align-items: center;
      flex-wrap: nowrap;
      gap: 8px;
      margin: 8px 0 14px;
      max-width: 100%;
      overflow-x: auto;
      scrollbar-width: none;
    }
    .paperlens-article-action-row::-webkit-scrollbar {
      display: none;
    }
    .paperlens-article-action-row > * {
      flex: 0 0 auto;
      align-self: center;
    }
    .paperlens-article-action-row .pl-translate-wrapper--article-page {
      display: inline-flex;
      align-items: center;
      flex-wrap: nowrap;
      margin: 0;
      max-width: 100%;
      line-height: 1;
      vertical-align: middle;
    }
    .paperlens-article-action-row .pl-translate-result,
    .paperlens-article-action-row .pl-translate-error {
      flex-basis: 100%;
      width: min(760px, calc(100vw - 48px));
      box-sizing: border-box;
    }
    .paperlens-article-citation-fallback {
      display: inline-flex;
      align-items: center;
      min-height: 28px;
      padding: 0 11px;
      border: 1px solid #e5e7eb;
      border-radius: 7px;
      background: #f8fafc;
      color: #64748b;
      font-size: 13px;
      font-weight: 650;
      line-height: 1;
      white-space: nowrap;
    }
    .paperlens-article-link-action,
    .paperlens-article-disabled-action {
      display: inline-flex;
      align-items: center;
      min-height: 28px;
      padding: 0 11px;
      border: 1px solid #d5dbe7;
      border-radius: 7px;
      font-size: 13px;
      font-weight: 650;
      line-height: 1;
      white-space: nowrap;
      text-decoration: none;
      box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
    }
    .paperlens-article-link-action {
      background: #f8fafc;
      color: #334155;
    }
    .paperlens-article-link-action:hover {
      border-color: #93c5fd;
      background: #eff6ff;
      color: #1d4ed8;
      text-decoration: none;
    }
    .paperlens-article-disabled-action {
      border-color: #e5e7eb;
      background: #f8fafc;
      color: #94a3b8;
      cursor: not-allowed;
      font-family: inherit;
    }
    .paperlens-article-citation-inline {
      display: inline-flex;
      align-items: center;
      flex-wrap: nowrap;
      gap: 0.35em;
      max-width: 100%;
      white-space: nowrap;
      vertical-align: baseline;
    }
    .paperlens-article-citation-inline > .publication-type {
      display: inline-flex;
      align-items: center;
      flex: 0 0 auto;
      margin: 0;
      vertical-align: middle;
      white-space: nowrap;
    }
    .paperlens-article-citation-inline > .article-source {
      display: inline;
      min-width: 0;
      vertical-align: baseline;
      white-space: nowrap;
    }
    .paperlens-native-fulltext-link .text {
      font-weight: 600;
    }
    .paperlens-native-fulltext-icon {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width: 56px;
      min-width: 56px;
      height: 34px;
      margin-right: 8px;
      border-radius: 2px;
      border: 1px solid #d1d5db;
      background: #ffffff;
      color: #374151;
      font-family: inherit;
      font-size: 20px;
      font-weight: 700;
      letter-spacing: 0;
    }
    .paperlens-native-fulltext-link--pmc .paperlens-native-fulltext-icon {
      background: #111827;
      color: #ffffff;
    }
    .paperlens-native-fulltext-link--extra-download,
    .paperlens-native-fulltext-link--oa-pdf {
      position: relative;
      display: inline-flex !important;
      align-items: center;
      width: 136px !important;
      max-width: 136px !important;
      min-width: 0 !important;
      padding: 0 !important;
    }
    .paperlens-native-fulltext-link--extra-download .paperlens-native-fulltext-icon,
    .paperlens-native-fulltext-link--oa-pdf .paperlens-native-fulltext-icon {
      width: 100%;
      min-width: 0;
      height: 38px;
      margin-right: 0;
      padding: 4px 6px;
      box-sizing: border-box;
      gap: 6px;
      justify-content: flex-start;
      border-color: #7dd3fc;
      background:
        linear-gradient(135deg, #ecfeff 0%, #ffffff 52%, #eff6ff 100%);
      color: #0f3b57;
      box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.85);
      text-align: left;
    }
    .paperlens-native-fulltext-link--oa-pdf .paperlens-native-fulltext-icon {
      border-color: #86efac;
      background:
        linear-gradient(135deg, #ecfdf5 0%, #ffffff 52%, #f0fdf4 100%);
    }
    .paperlens-native-fulltext-link--extra-download .paperlens-native-fulltext-logo-mark,
    .paperlens-native-fulltext-link--oa-pdf .paperlens-native-fulltext-logo-mark {
      position: relative;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width: 24px;
      height: 27px;
      flex: 0 0 24px;
      border-radius: 5px;
      background: linear-gradient(180deg, #0ea5e9 0%, #0369a1 100%);
      color: #ffffff;
      font-size: 15px;
      font-weight: 900;
      line-height: 1;
      box-shadow: 0 1px 3px rgba(3, 105, 161, 0.25);
    }
    .paperlens-native-fulltext-link--oa-pdf .paperlens-native-fulltext-logo-mark {
      background: linear-gradient(180deg, #22c55e 0%, #15803d 100%);
      box-shadow: 0 1px 3px rgba(21, 128, 61, 0.25);
    }
    .paperlens-native-fulltext-link--extra-download .paperlens-native-fulltext-logo-mark::after,
    .paperlens-native-fulltext-link--oa-pdf .paperlens-native-fulltext-logo-mark::after {
      content: '';
      position: absolute;
      top: 0;
      right: 0;
      width: 7px;
      height: 7px;
      border-bottom-left-radius: 3px;
      background: rgba(255, 255, 255, 0.78);
    }
    .paperlens-native-fulltext-link--extra-download .paperlens-native-fulltext-logo-copy,
    .paperlens-native-fulltext-link--oa-pdf .paperlens-native-fulltext-logo-copy {
      display: inline-flex;
      min-width: 0;
      flex-direction: column;
      gap: 1px;
    }
    .paperlens-native-fulltext-link--extra-download .paperlens-native-fulltext-logo-kicker,
    .paperlens-native-fulltext-link--oa-pdf .paperlens-native-fulltext-logo-kicker {
      display: block;
      width: 100%;
      color: #0284c7;
      font-size: 8.5px;
      font-weight: 800;
      line-height: 1;
    }
    .paperlens-native-fulltext-link--oa-pdf .paperlens-native-fulltext-logo-kicker {
      color: #059669;
    }
    .paperlens-native-fulltext-link--extra-download .paperlens-native-fulltext-logo-main,
    .paperlens-native-fulltext-link--oa-pdf .paperlens-native-fulltext-logo-main {
      display: block;
      width: 100%;
      color: #0f172a;
      font-size: 13px;
      font-weight: 800;
      line-height: 1.05;
    }
    .paperlens-native-fulltext-link--extra-download .text,
    .paperlens-native-fulltext-link--oa-pdf .text {
      position: absolute;
      width: 1px;
      height: 1px;
      margin: -1px;
      padding: 0;
      overflow: hidden;
      clip: rect(0 0 0 0);
      white-space: nowrap;
      border: 0;
    }
    .paperlens-inline-journal-metrics {
      display: inline-flex;
      align-items: baseline;
      max-width: 100%;
      margin: 0 0.35em 0 0;
      vertical-align: baseline;
      overflow: hidden;
      border: 1px solid var(--paperlens-inline-metric-border, #fdba74);
      border-radius: 3px;
      background: var(--paperlens-inline-metric-bg, #fff7ed);
      color: var(--paperlens-inline-metric-text, #7c2d12);
      font: inherit;
      line-height: 1;
      white-space: nowrap;
    }
    .paperlens-inline-journal-metrics__cell {
      display: inline-flex;
      align-items: center;
      min-height: 1.25em;
      padding: 0 0.4em;
      border-right: 1px solid color-mix(in srgb, var(--paperlens-inline-metric-border, #fdba74), transparent 35%);
      color: inherit;
      font: inherit;
      font-weight: 600;
      line-height: 1;
      white-space: nowrap;
    }
    .paperlens-inline-journal-metrics__cell:last-child {
      border-right: 0;
    }
    .paperlens-inline-journal-metrics__cell--if {
      background: var(--paperlens-inline-metric-soft-bg, #ffedd5);
    }
    .paperlens-inline-journal-metrics__cell--jcr {
      background: var(--paperlens-inline-jcr-bg, #b91c1c);
      color: #ffffff;
      font-weight: 700;
    }
    .paperlens-inline-journal-metrics__cell--cas {
      background: rgba(255, 255, 255, 0.55);
    }
    .paperlens-inline-journal-metrics__cell--emerging {
      font-weight: 700;
    }
    .paperlens-inline-journal-metrics__cell--emerging-1 {
      background: rgba(185, 28, 28, 0.1);
      color: #7f1d1d;
    }
    .paperlens-inline-journal-metrics__cell--emerging-2 {
      background: rgba(21, 128, 61, 0.1);
      color: #14532d;
    }
    .paperlens-inline-journal-metrics__cell--emerging-3 {
      background: rgba(180, 83, 9, 0.11);
      color: #78350f;
    }
    .paperlens-inline-journal-metrics__cell--emerging-4 {
      background: rgba(71, 85, 105, 0.1);
      color: #334155;
    }
    .paperlens-inline-journal-metrics--q1 {
      --paperlens-inline-metric-bg: #fff7ed;
      --paperlens-inline-metric-soft-bg: #ffedd5;
      --paperlens-inline-metric-border: #fdba74;
      --paperlens-inline-metric-text: #7c2d12;
      --paperlens-inline-jcr-bg: #b91c1c;
    }
    .paperlens-inline-journal-metrics--q2 {
      --paperlens-inline-metric-bg: #f0fdf4;
      --paperlens-inline-metric-soft-bg: #dcfce7;
      --paperlens-inline-metric-border: #86efac;
      --paperlens-inline-metric-text: #14532d;
      --paperlens-inline-jcr-bg: #15803d;
    }
    .paperlens-inline-journal-metrics--q3 {
      --paperlens-inline-metric-bg: #fffbeb;
      --paperlens-inline-metric-soft-bg: #fef3c7;
      --paperlens-inline-metric-border: #fcd34d;
      --paperlens-inline-metric-text: #78350f;
      --paperlens-inline-jcr-bg: #b45309;
    }
    .paperlens-inline-journal-metrics--q4 {
      --paperlens-inline-metric-bg: #f8fafc;
      --paperlens-inline-metric-soft-bg: #e2e8f0;
      --paperlens-inline-metric-border: #94a3b8;
      --paperlens-inline-metric-text: #1e293b;
      --paperlens-inline-jcr-bg: #475569;
    }
  `,document.head.appendChild(r)}function c5(){const r=document.querySelector("div.article-source");if(!r)return"";const e=r.cloneNode(!0);e.querySelectorAll(".journal-actions-dropdown, .dropdown, script, style").forEach(o=>o.remove());const n=e.querySelector("button.journal-actions-trigger")?.textContent?.replace(/\s+/g," ").trim();if(n)return n;const a=e.textContent?.replace(/\s+/g," ").trim()??"",i=a.indexOf(".");return i>0?a.substring(0,i).trim():a}function u5(){const r=l5("span.cit");if(r){const t=r.split(/[;.]/)[0]?.trim();if(t)return t}return yt("citation_date")||void 0}function d5(){const r=yt("citation_article_type");if(r)return r;const e=["Review","Systematic Review","Meta-Analysis","Clinical Trial","Randomized Controlled Trial","Guideline","Editorial","Case Report","Letter","Comment"],t=Array.from(document.querySelectorAll(".publication-types button")).map(n=>n.textContent?.replace(/\s+/g," ").trim()??"").filter(Boolean);return e.find(n=>t.some(a=>a.toLowerCase()===n.toLowerCase()))}function p5(){const r=s5("citation_author");if(r.length>0)return r;const e=Array.from(document.querySelectorAll(".authors-list .full-name, .authors .full-name")).map(t=>t.textContent?.replace(/\s+/g," ").trim()??"").filter(Boolean);return e.length>0?e:void 0}function h5(){const r=Om();let e=yt("citation_title"),t=yt("citation_journal_title")||yt("citation_journal_abbrev");const n=yt("citation_issn")||void 0;let a=yt("citation_doi")||void 0,i=yt("citation_pmcid")||void 0;const o=p5(),s=u5(),l=d5();if(e||(e=document.querySelector("h1.heading-title, h1.title, h1.document-title")?.textContent?.trim()??""),!t){const c=document.querySelector("button#full-view-journal-trigger, button.journal-actions-trigger, button.journal-link, a.journal-link, div.journal-info, div.current-journal, a#journal-link");c&&(t=(c.getAttribute("title")||c.textContent||"").trim())}if(t||(t=c5()),!a){const c=document.querySelector(du);if(c){const u=c.textContent?.trim()??"",d=c.href??"";u.startsWith("10.")?a=u:d.includes("doi.org/")&&(a=d.replace(/^.*doi\.org\//,""))}}if(!a){const u=dc().match(/doi:\s*(10\.\d{4,}\/[^\s]+)/i);u&&(a=u[1])}if(!i){const c=document.querySelector(Wb);if(c){const u=c.textContent?.trim()??"";u.startsWith("PMC")&&(i=u)}}if(!i){const u=dc().match(/PMCID:\s*(PMC\d+)/i);u&&(i=u[1])}return{pmid:r,title:e,journal:t,authors:o,issn:n,doi:a,pmcid:i,publicationDate:s,articleType:l}}function f5(r){try{return new URL(r,window.location.href).toString()}catch{return null}}function fc(r){try{const e=new URL(r,window.location.href);return e.protocol==="http:"||e.protocol==="https:"?e.toString():null}catch{return null}}function m5(r){const e=r.querySelector("img");return(r.getAttribute("aria-label")||r.getAttribute("title")||e?.getAttribute("alt")||e?.getAttribute("title")||r.textContent||"").replace(/\s+/g," ").trim()}function b5(r,e,t){const n=zm(r),a=t?zm(Gi(t)??""):"";return!!(a&&n===a)}function Um(r,e){return/\/pmc\/articles\//i.test(r)||/\bPMC\b/i.test(e)}function Hm(r,e){return/\.pdf(?:[?#]|$)/i.test(r)||/\b(?:PDF|OA)\b/i.test(e)}function zm(r){try{return new URL(r).hostname.replace(/^www\./,"")}catch{return""}}function Gi(r){const e=r.trim();return e?/^https?:\/\//i.test(e)?e:`https://${e}`:null}function g5(r){const e=r.match(/[A-Za-z]/g)?.length??0,t=r.match(/[\u3400-\u9fff]/g)?.length??0;return e>=12&&e>t}function y5(r,e,t={}){const n=x5();if(!n)return;const a=t.openAccessPdfUrl?fc(t.openAccessPdfUrl):null,i=!!r.pmcid||!!a||va(n,Um)||va(n,(c,u)=>Hm(c,u));r.pmcid&&!va(n,Um)&&mc(n,{variant:"pmc",icon:"PMC",label:"Free PMC article",href:`https://pmc.ncbi.nlm.nih.gov/articles/${r.pmcid}/`,title:"Free full text at PubMed Central"}),a&&!va(n,(c,u)=>Hm(c,u))&&mc(n,{variant:"oa-pdf",icon:"PDF",label:"Open access PDF",href:a,title:"\u6253\u5F00\u5F00\u653E\u83B7\u53D6 PDF"});const o=e.extraDownloadUrl?Gi(e.extraDownloadUrl):null,s=!!r.doi||g5(r.title),l=t.journalOpenAccess===!0;if(!i&&e.showExtraDownload&&(o||l&&r.doi)&&s){const c=o;if(n.querySelector('[data-paperlens-fulltext="extra-download"]')||c&&va(n,(p,h)=>b5(p,h,c)))return;const u=r.doi?l?v5(r.doi):A5(c??"",r.doi):c?C5(c,r.title):null,d=u?fc(u):null;d&&mc(n,{variant:"extra-download",icon:"",label:l?"\u5F00\u653E\u83B7\u53D6\u5168\u6587":"\u81EA\u52A9\u5168\u6587\u4E0B\u8F7D",href:d,title:l?"\u901A\u8FC7 DOI \u6253\u5F00\u5F00\u653E\u83B7\u53D6\u5168\u6587":"\u901A\u8FC7\u81EA\u5B9A\u4E49\u6E90\u83B7\u53D6\u5168\u6587",resolvePayload:{pmid:r.pmid,doi:r.doi,title:r.title,pmcid:r.pmcid,openAccessPdfUrl:t.openAccessPdfUrl,fallbackDomain:c??void 0,journalOpenAccess:t.journalOpenAccess}})}}function x5(){const r=Array.from(document.querySelectorAll(".full-text-links-list")).find(o=>!o.closest(".dialog, .overlay"));if(r)return r;const e=document.querySelector("aside.page-sidebar .inner-wrap, .page-sidebar .inner-wrap, aside.page-sidebar, aside#right-col, aside.right-rail, div.right-rail");if(!e)return null;const t=document.createElement("div");t.className="full-text-links paperlens-created-full-text-links";const n=document.createElement("div");n.className="full-view";const a=document.createElement("h3");a.className="title",a.textContent="Full text links";const i=document.createElement("div");return i.className="full-text-links-list",n.append(a,i),t.appendChild(n),e.insertBefore(t,e.firstChild),i}function va(r,e){return Array.from(r.querySelectorAll("a[href]")).some(t=>{const n=f5(t.getAttribute("href")??"");return n?e(n,m5(t)):!1})}function mc(r,e){const t=fc(e.href);if(!t)return;const n=document.createElement("a");n.className=`link-item paperlens-native-fulltext-link paperlens-native-fulltext-link--${e.variant}`,n.href=t,n.target="_blank",n.rel="noopener noreferrer",n.title=e.title,n.setAttribute("data-paperlens-fulltext",e.variant),e.variant==="extra-download"&&e.resolvePayload&&n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),S5(n.href,e.resolvePayload)});const a=document.createElement("span");if(a.className="paperlens-native-fulltext-icon",e.variant==="extra-download"||e.variant==="oa-pdf"){const o=document.createElement("span");o.className="paperlens-native-fulltext-logo-mark",o.textContent=e.variant==="oa-pdf"?"OA":"\u2193";const s=document.createElement("span");s.className="paperlens-native-fulltext-logo-copy";const l=document.createElement("span");l.className="paperlens-native-fulltext-logo-kicker",l.textContent=e.variant==="oa-pdf"?"\u5F00\u653E\u83B7\u53D6":"\u81EA\u52A9";const c=document.createElement("span");c.className="paperlens-native-fulltext-logo-main",c.textContent="\u5168\u6587\u4E0B\u8F7D",s.append(l,c),a.append(o,s)}else a.textContent=e.icon;const i=document.createElement("span");i.className="text",i.textContent=e.label,n.setAttribute("aria-label",e.title),n.append(a,i),r.appendChild(n)}function A5(r,e){const t=Gi(r);return t?`${t.replace(/\/+$/,"")}/${e.replace(/^\/+/,"")}`:null}function C5(r,e){const t=Gi(r);return t?`${t.replace(/\/+$/,"")}/search?q=${encodeURIComponent(e)}`:null}function v5(r){return`https://doi.org/${r.replace(/^\/+/,"")}`}async function S5(r,e){const t=window.open("","_blank");try{const n=await H({type:"RESOLVE_FULLTEXT_DOWNLOAD",payload:e},12e3);if(n?.success===!1&&n.error!=="No full text target found"){t?.close(),D.error(n.error||"\u5F53\u524D\u8D26\u6237\u6682\u4E0D\u80FD\u4F7F\u7528\u5168\u6587\u4E0B\u8F7D");return}const a=n?.success&&n.data?.url?n.data.url:r;w5(t,a)}catch{t?.close(),D.error("\u5728\u7EBF\u6743\u9650\u6821\u9A8C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5")}}function w5(r,e){if(r&&!r.closed){r.opener=null,r.location.href=e;return}window.open(e,"_blank","noopener,noreferrer")}function T5(r,e,t){const n=Rt({quartileSources:e}),a=n.includes("jcr"),i=n.includes("cas"),o=n.includes("emerging"),s=Lt(r.jcrQuartile),l=hn(r.casQuartile),c=Jn(r.emergingQuartile,r.emergingTop),u=zn(r.impactFactor,r.impactFactorLabel),d=s?.value??r.sjrQuartile??"Q4",p=document.createElement("span");if(p.className=`paperlens-inline-journal-metrics paperlens-inline-journal-metrics--${d.toLowerCase()}`,p.title=[r.journalName,u?`IF ${u}`:void 0,s?.label,l?`\u4E2D\u79D1\u9662${l.label}`:void 0,c?.label].filter(Boolean).join(" | "),p.setAttribute("data-paperlens-inline-metrics",""),Number.isFinite(r.impactFactor)){const h=document.createElement("span");h.className="paperlens-inline-journal-metrics__cell paperlens-inline-journal-metrics__cell--if",h.textContent=`IF ${u}`,h.title=`IF ${u} \xB7 \u60AC\u505C\u67E5\u770B IF \u8D8B\u52BF`,Wn(h,{journalName:r.journalName,journal:r,getTrendData:gc(r),...t===!1?{}:{getSJRTrendData:yc(r)},quartileSources:n,delayMs:280}),p.appendChild(h)}if(s){const h=document.createElement("span");h.className="paperlens-inline-journal-metrics__cell paperlens-inline-journal-metrics__cell--jcr",h.textContent=s.label,h.setAttribute("data-pl-jcr-quartile",""),a||(h.style.display="none"),p.appendChild(h)}if(l){const h=document.createElement("span");h.className="paperlens-inline-journal-metrics__cell paperlens-inline-journal-metrics__cell--cas",h.textContent=`\u4E2D\u79D1\u9662${l.label}`,h.setAttribute("data-pl-cas-quartile",""),i||(h.style.display="none"),p.appendChild(h)}if(c){const h=document.createElement("span");h.className=`paperlens-inline-journal-metrics__cell paperlens-inline-journal-metrics__cell--emerging paperlens-inline-journal-metrics__cell--emerging-${c.value}`,h.textContent=c.label,h.setAttribute("data-pl-emerging-quartile",""),o||(h.style.display="none"),p.appendChild(h)}return p}function E5(r){const e=r.querySelector("button#full-view-journal-trigger, button.journal-actions-trigger, button.journal-link, a.journal-link, div.journal-info, div.current-journal, a#journal-link");return e||(r instanceof HTMLElement?r:null)}function F5(r,e,t){const n=e.trim().toLowerCase();if(!n)return!1;const a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT);let i=a.nextNode();for(;i;){const o=i,l=(o.nodeValue??"").toLowerCase().indexOf(n);if(l>=0){const c=o.splitText(l);return c.parentNode?.insertBefore(t,c),!0}i=a.nextNode()}return!1}function D5(r){const e=r.querySelector(kr)?.textContent?.replace(/\s+/g," ").trim()??"",t=r.querySelector(wo)?.textContent?.replace(/\s+/g," ").trim()??"",n=e||t;if(!n)return"";const a=n.indexOf(".");return(a>0?n.slice(0,a):n).trim()}function _5(){const r=Array.from(document.querySelectorAll(o5)),e=new Set;for(const a of r)a.matches("article.full-docsum, li.full-docsum, div.full-docsum")&&e.add(a),a.querySelectorAll("article.full-docsum, li.full-docsum, div.full-docsum").forEach(i=>e.add(i));const t=[];let n=0;for(const a of e){if(!(a instanceof HTMLElement)||a.hasAttribute(lc)||a.hasAttribute(Ca))continue;const i=D5(a);if(!i)continue;const o=a.querySelector(kr)??a.querySelector(wo);if(!(o instanceof HTMLElement))continue;let s="";try{s=Za(a).PMID}catch{s=""}t.push({id:s||`docsum-${n++}-${i}`,journal:i,element:a,insert:l=>o.insertBefore(l,o.firstChild)})}return t}function k5(){const r=document.querySelector("#references");if(!r)return[];const e=Array.from(r.querySelectorAll(".references-list > li, .references-and-notes-list > li")),t=[],n=new Set;let a=0;for(const i of e){const o=i.matches(".references-and-notes-list > li")?i:i.querySelector(".references-and-notes-list > li");if(!o||n.has(o)||(n.add(o),o.hasAttribute(lc)||o.hasAttribute(Ca))||o.querySelector(".paperlens-inline-journal-metrics"))continue;const s=a5(o.textContent??"");s&&t.push({id:`reference-${a++}-${s}`,journal:s,element:o,insert:l=>{F5(o,s,l)||o.append(document.createTextNode(" "),l)}})}return t}async function Jm(){hc();const r=[..._5(),...k5()];if(r.length!==0){for(const e of r)e.element.setAttribute(Ca,"");try{const e=await we().catch(()=>{}),t=e?.quartileSources,n=await ri(r.map(a=>({id:a.id,journal:pc(a.journal)})));for(const a of r){a.element.removeAttribute(Ca);const i=n.get(a.id);i&&Vn(i.journal,{quartileSources:t})&&a.insert(T5(i.journal,t,e?.showScimagoSJR)),a.element.setAttribute(lc,"")}}catch(e){for(const t of r)t.element.removeAttribute(Ca);console.warn("[PaperLens] Failed to enhance related article journal metrics:",e)}}}function N5(){cc===null&&(cc=window.setTimeout(()=>{cc=null,Jm()},150))}function L5(){uc||(Jm(),uc=new MutationObserver(r=>{r.some(e=>e.addedNodes.length>0)&&N5()}),uc.observe(document.body,{childList:!0,subtree:!0}))}async function Yt(r,e){try{const t=await H({type:r,payload:e},i5);return t&&typeof t=="object"&&"success"in t?t:{success:!1,error:"Background returned an invalid response"}}catch(t){return console.warn(`[PaperLens] Background message failed (${r}):`,t),{success:!1,error:t instanceof Error?t.message:"Background message failed"}}}async function R5(r,e){const t=await Yt("GET_ARTICLE_PAGE_DATA",{pmid:r.pmid,journalName:pc(r.journal),...r.issn?{issn:r.issn}:{},...r.doi?{doi:r.doi}:{},...e!==void 0?{showScimagoSJR:e}:{}});return!t.success||!t.data?{}:t.data}async function P5(r,e){const t=await Yt("GET_JOURNAL_TREND_DATA",{normalizedName:r.normalizedName,journalName:r.journalName,includeSJR:e});if(!t.success&&bc(t.error))return{};const n=t.success&&t.data?t.data:{};let a=Array.isArray(n.trendData)?n.trendData:void 0,i=Array.isArray(n.sjrTrendData)?n.sjrTrendData:void 0;if(!a||a.length<2||e&&(!i||i.length<2)){const o=await Sa(r,e);(!a||a.length<2)&&(a=o.trendData),e&&(!i||i.length<2)&&(i=o.sjrTrendData)}return{trendData:a,sjrTrendData:i}}function bc(r){return/请先登录|当前账户暂不能使用|Pro\s*永久版权益|账户状态已切换|未授权|NOT_AUTHENTICATED|SESSION_CHANGED|PLAN_REQUIRED/i.test(r||"")}async function Sa(r,e){const t=ui(r.normalizedName,r.journalName);if(t.length===0)return{};const n=await hs(t),a=e?await fs(t):void 0;return{trendData:n,sjrTrendData:a}}function gc(r,e){let t=e&&e.length>=2?e:void 0,n=null;return()=>t?Promise.resolve(t):n||(n=Yt("GET_JOURNAL_TREND_DATA",{normalizedName:r.normalizedName,journalName:r.journalName}).then(async a=>{if(!a.success&&bc(a.error))return n=null,[];let i=a.success&&Array.isArray(a.data?.trendData)?a.data.trendData:[];return i.length<2&&(i=(await Sa(r,!1)).trendData??[]),i.length>=2&&(t=i),n=null,i}).catch(()=>(n=null,Sa(r,!1).then(a=>a.trendData??[]))),n)}function yc(r,e){let t=e&&e.length>=2?e:void 0,n=null;return()=>t?Promise.resolve(t):n||(n=Yt("GET_JOURNAL_TREND_DATA",{normalizedName:r.normalizedName,journalName:r.journalName,includeSJR:!0}).then(async a=>{if(!a.success&&bc(a.error))return n=null,[];let i=a.success&&Array.isArray(a.data?.sjrTrendData)?a.data.sjrTrendData:[];return i.length<2&&(i=(await Sa(r,!0)).sjrTrendData??[]),i.length>=2&&(t=i),n=null,i}).catch(()=>(n=null,Sa(r,!0).then(a=>a.sjrTrendData??[]))),n)}async function B5(r,e){const t=[r.issn??"",pc(r.journal),r.journal,yt("citation_publisher"),e?.journal?.name??"",e?.venue??""].map(a=>a.trim()).filter(Boolean),n=new Set;for(const a of t){const i=a.toLowerCase();if(n.has(i))continue;n.add(i);const o=await zr(a,r.issn);if(o)return o.journal}if(r.issn){const a=await zr("",r.issn);if(a)return a.journal}}function I5(r,e,t,n,a,i){if(hc(),!Vn(e,{quartileSources:a}))return;const o=document.querySelector("#full-view-heading > .article-citation, header#heading .full-view .article-citation, .article-citation");if(!o||o.querySelector(".paperlens-article-metrics-host"))return;const s=o.querySelector(".article-source");if(!s)return;const l=document.createElement("span");l.className="paperlens-article-metrics-host",Number.isFinite(e.impactFactor)&&(l.dataset.plIf=String(e.impactFactor));const c=Rt({quartileSources:a}),u=c.includes("jcr"),d=c.includes("cas"),p=c.includes("emerging"),h=Lt(e.jcrQuartile);h&&(l.dataset.plJcr=h.value);const f=hn(e.casQuartile);f&&(l.dataset.plCas=f.value);const y=Jn(e.emergingQuartile,e.emergingTop);y&&(l.dataset.plEmerging=y.value);const x=l.attachShadow({mode:"open"}),T=document.createElement("style");T.textContent=`
    :host {
      display: inline-flex;
      align-items: center;
      vertical-align: middle;
      margin: 0;
      max-width: 100%;
      font: inherit;
      flex: 0 0 auto;
    }
    .pl-article-metrics {
      display: inline-flex;
      align-items: center;
      overflow: hidden;
      border: 1px solid var(--pl-article-metric-border, #fdba74);
      border-radius: 4px;
      background: var(--pl-article-metric-bg, #fff7ed);
      box-shadow: 0 1px 2px rgba(15, 23, 42, 0.08);
      font: inherit;
      line-height: 1;
    }
    .pl-article-metric {
      display: inline-flex;
      align-items: center;
      min-height: 1.55em;
      padding: 0 0.6em;
      border-right: 1px solid color-mix(in srgb, var(--pl-article-metric-border, #fdba74), transparent 35%);
      color: var(--pl-article-metric-text, #7c2d12);
      font: inherit;
      font-weight: 700;
      line-height: 1;
      white-space: nowrap;
    }
    .pl-article-metric:last-child {
      border-right: 0;
    }
    .pl-article-metric--if {
      background: var(--pl-article-metric-soft-bg, #ffedd5);
      cursor: help;
    }
    .pl-article-metric--jcr {
      color: #fff;
    }
    .pl-article-metric--cas {
      background: rgba(255, 255, 255, 0.55);
    }
    .pl-article-metric--emerging {
      font-weight: 700;
    }
    .pl-article-metric--emerging-1 {
      background: rgba(185, 28, 28, 0.1);
      color: #7f1d1d;
    }
    .pl-article-metric--emerging-2 {
      background: rgba(21, 128, 61, 0.1);
      color: #14532d;
    }
    .pl-article-metric--emerging-3 {
      background: rgba(180, 83, 9, 0.11);
      color: #78350f;
    }
    .pl-article-metric--emerging-4 {
      background: rgba(71, 85, 105, 0.1);
      color: #334155;
    }
    .pl-article-metrics--q1 {
      --pl-article-metric-bg: #fff7ed;
      --pl-article-metric-soft-bg: #ffedd5;
      --pl-article-metric-border: #fdba74;
      --pl-article-metric-text: #7c2d12;
      --pl-article-jcr-bg: #b91c1c;
    }
    .pl-article-metrics--q2 {
      --pl-article-metric-bg: #f0fdf4;
      --pl-article-metric-soft-bg: #dcfce7;
      --pl-article-metric-border: #86efac;
      --pl-article-metric-text: #14532d;
      --pl-article-jcr-bg: #15803d;
    }
    .pl-article-metrics--q3 {
      --pl-article-metric-bg: #fffbeb;
      --pl-article-metric-soft-bg: #fef3c7;
      --pl-article-metric-border: #fcd34d;
      --pl-article-metric-text: #78350f;
      --pl-article-jcr-bg: #b45309;
    }
    .pl-article-metrics--q4 {
      --pl-article-metric-bg: #f8fafc;
      --pl-article-metric-soft-bg: #e2e8f0;
      --pl-article-metric-border: #94a3b8;
      --pl-article-metric-text: #1e293b;
      --pl-article-jcr-bg: #475569;
    }
    .pl-article-metric--jcr {
      background: var(--pl-article-jcr-bg, #475569);
    }
    @media (max-width: 760px) {
      .pl-article-metric {
        min-height: 1.45em;
        padding: 0 0.45em;
      }
    }
  `;const E=document.createElement("span"),w=h?.value??e.sjrQuartile??"Q4",v=zn(e.impactFactor,e.impactFactorLabel);if(E.className=`pl-article-metrics pl-article-metrics--${w.toLowerCase()}`,E.title=[e.journalName,v?`IF ${v}`:void 0,h?.label,f?`\u4E2D\u79D1\u9662${f.label}`:void 0,y?.label].filter(Boolean).join(" | "),Number.isFinite(e.impactFactor)){const C=document.createElement("span");C.className="pl-article-metric pl-article-metric--if",C.textContent=`IF ${v}`,C.title="\u60AC\u505C\u67E5\u770B IF \u8D8B\u52BF";const L=gc(e,t),$=i===!1?void 0:yc(e,n);Wn(C,{journalName:e.journalName,journal:e,getTrendData:L,...$?{getSJRTrendData:$}:{},quartileSources:c,delayMs:280}),E.appendChild(C)}const g=E5(s);if(g&&(g.title=[g.title||e.journalName,"\u60AC\u505C\u67E5\u770B IF \u8D8B\u52BF"].filter(Boolean).join(" \xB7 "),Wn(g,{journalName:e.journalName,journal:e,getTrendData:gc(e,t),...i===!1?{}:{getSJRTrendData:yc(e,n)},quartileSources:c,delayMs:280})),h){const C=document.createElement("span");C.className="pl-article-metric pl-article-metric--jcr",C.textContent=h.label,C.setAttribute("data-pl-jcr-quartile",""),u||(C.style.display="none"),E.appendChild(C)}if(f){const C=document.createElement("span");C.className="pl-article-metric pl-article-metric--cas",C.textContent=`\u4E2D\u79D1\u9662${f.label}`,C.setAttribute("data-pl-cas-quartile",""),d||(C.style.display="none"),E.appendChild(C)}if(y){const C=document.createElement("span");C.className=`pl-article-metric pl-article-metric--emerging pl-article-metric--emerging-${y.value}`,C.textContent=y.label,C.setAttribute("data-pl-emerging-quartile",""),p||(C.style.display="none"),E.appendChild(C)}if(e.casWarning||e.wosStatus){Td(x);const C=document.createElement("span");C.className="pl-article-metric pl-article-metric--warnings",C.style.display="inline-flex",C.style.gap="3px",C.appendChild(wd(e)),E.appendChild(C)}x.append(T,E),M5(o,s,l,r.articleType)}function M5(r,e,t,n){const a=r.querySelector(".paperlens-article-citation-inline");if(a){a.insertBefore(t,a.firstChild);return}let i=r.querySelector(".publication-type");!i&&n&&(i=document.createElement("span"),i.className="publication-type paperlens-created-publication-type",i.textContent=n);const o=document.createElement("span");o.className="paperlens-article-citation-inline";const s=e.parentNode;s&&(s.insertBefore(o,e),o.appendChild(t),i&&o.appendChild(i),o.appendChild(e))}function wa(r,e){r.style.order=String(e),Vm()?.appendChild(r)}function q5(r,e,t){const n=document.createElement("a");return n.className="paperlens-article-link-action",n.href=e,/^https?:\/\//i.test(e)&&(n.target="_blank",n.rel="noopener noreferrer"),n.textContent=r,n.title=t,n}function j5(r,e){const t=document.createElement("button");return t.className="paperlens-article-disabled-action",t.type="button",t.disabled=!0,t.textContent=r,t.title=e,t}function $5(r,e,t){const n={source:"PubMed",pmid:r.pmid,doi:r.doi,title:r.title,journal:r.journal,impactFactor:t?.impactFactor,jcrQuartile:t?.jcrQuartile,casQuartile:t?.casQuartile?String(t.casQuartile).replace("\u533A",""):void 0,year:e?.year,citationCount:e?.citationCount,url:window.location.href,authors:r.authors,abstract:e?.abstract,publicationTypes:r.articleType?[r.articleType]:void 0,volume:e?.journal?.volume,pages:e?.journal?.pages,issn:r.issn,pmcid:r.pmcid,pdfUrl:e?.openAccessPdf?.url,oaUrl:e?.openAccessPdf?.url,sourceUrl:window.location.href},a=Ss(n,!1);return gi(r.pmid).then(i=>ra(a,i)).catch(()=>{}),a}function Vm(){const r=document.querySelector(".paperlens-article-action-row");if(r instanceof HTMLElement)return r;hc();const e=document.createElement("div");e.className="paperlens-article-action-row";const t=document.querySelector("#full-view-identifiers, ul.identifiers");if(t?.parentElement)return t.insertAdjacentElement("afterend",e),e;const n=document.querySelector(".abstract-content, #enc-abstract, #eng-abstract"),a=document.querySelector("#abstract");if(a?.parentElement)return a.parentElement.insertBefore(e,a),e;if(n?.parentElement)return n.parentElement.insertBefore(e,n),e;const i=document.querySelector("#full-view-heading, header#heading, header .full-view, h1.heading-title, h1.title, h1.document-title");if(i?.parentElement)return i.insertAdjacentElement("afterend",e),e;const o=document.querySelector("main")??document.body;return o.insertBefore(e,o.firstElementChild),e}function O5(r,e,t,n,a){const i=Vm();if(i){if(document.querySelector("#abstract")&&!i.querySelector(".paperlens-article-abstract-action")){const o=q5("\u6458\u8981","#abstract","\u8DF3\u8F6C\u5230\u6458\u8981");o.classList.add("paperlens-article-abstract-action"),wa(o,yr.abstract)}if(r.title&&!i.querySelector(In+"--article-page")){const o=document.querySelector(".abstract-content, #enc-abstract, #eng-abstract"),s=Xs(r.pmid,r.title,o?.textContent||"",{journal:r.journal,authors:r.authors,doi:r.doi,publicationDate:r.publicationDate,articleType:r.articleType,hasFullAbstract:!!o?.textContent?.trim()});s.classList.add("pl-translate-wrapper--article-page"),wa(s,yr.translate)}if(e.showCitations&&t&&_h(t)&&!i.querySelector(kt)){i.querySelectorAll(".paperlens-article-citation-fallback").forEach(s=>s.remove());const o=Dh(t,{paperId:t.paperId,pmid:r.pmid,paperTitle:r.title,sendToBackground:Yt});wa(o,yr.citations)}else if(e.showCitations&&typeof n=="number"&&!i.querySelector(".paperlens-article-citation-fallback")){const o=document.createElement("span");o.className="paperlens-article-citation-fallback",o.style.order=String(yr.citations),o.textContent=`\u88AB\u5F15 ${n.toLocaleString("en-US")}`,i.appendChild(o)}else e.showCitations&&!i.querySelector(kt)&&!i.querySelector(".paperlens-article-citation-fallback")&&wa(j5("\u88AB\u5F15 \u2014","\u6682\u65E0\u88AB\u5F15\u6570\u636E"),yr.citations);i.querySelector(Pn)||wa($5(r,t,a),yr.save)}}function U5(r){if(document.querySelector(".paperlens-article-sidebar"))return;const e=n5(r),t=document.querySelector(".actions-buttons.sidebar");if(t?.parentElement){t.insertAdjacentElement("afterend",e);return}const n=document.querySelector("nav.page-navigator");if(n?.parentElement){n.parentElement.insertBefore(e,n);return}const a=document.querySelector("aside#right-col, aside.right-rail, div.right-rail");if(a){a.insertBefore(e,a.firstChild);return}(document.querySelector("main")??document.body).appendChild(e)}async function H5(){const r=Om();if(!r){console.warn("[PaperLens] Article page: no PMID found in URL");return}console.log("[PaperLens] Article page enhancement starting, PMID:",r),await J5();const e=h5();e.title||console.warn("[PaperLens] Article page: could not extract title");const t=await we().catch(l=>(console.warn("[PaperLens] Article page: failed to load settings, using defaults:",l),ut));let n=!1,a={},i,o,s;try{const l=await We("metrics.basic","\u57FA\u7840\u671F\u520A\u6307\u6807");if(n=l.allowed,n||console.warn("[PaperLens] Article page metrics disabled by entitlement:",l.error),a=n?await R5(e,t.showScimagoSJR):{},i=a.journalMatch?.journal,n&&!i&&(i=await B5(e,a.s2Paper).catch(c=>{console.warn("[PaperLens] Article page journal fallback failed:",c)})),n&&!i&&a.s2Paper){const c=a.s2Paper.journal?.name||a.s2Paper.venue;if(c){const u=await Yt("JOURNAL_LOOKUP",{journal:c});u.success&&u.data?.matched&&(i=u.data.journal)}}if(o=a.trendData,s=a.sjrTrendData,n&&t.showImpactFactor&&i&&(!o?.length||t.showScimagoSJR!==!1&&!s?.length)){const c=await P5(i,t.showScimagoSJR!==!1).catch(u=>(console.warn("[PaperLens] Article page trend fallback failed:",u),{}));o=o?.length?o:c.trendData,s=s?.length?s:c.sjrTrendData}n&&i&&t.showImpactFactor&&Vn(i,{quartileSources:t.quartileSources})&&I5(e,i,o,s,t.quartileSources,t.showScimagoSJR)}catch(l){n=!1,i=void 0,o=void 0,s=void 0,console.warn("[PaperLens] Article page metrics enhancement failed, rendering baseline UI:",l)}try{const l=a.s2Paper,c=n?a.journalMatch?.journal??i:void 0,u=z5();try{y5(e,t,{openAccessPdfUrl:l?.openAccessPdf?.url,journalOpenAccess:c?.openAccess===!0})}catch(h){console.warn("[PaperLens] Article page full-text link enhancement failed:",h)}const d={};if(c){let h;if(c.issn?.length){const y=await Yt("GET_JOURNAL_LINKS",{issn:c.issn[0]});y.success&&y.data?.homepageUrl&&(h=y.data.homepageUrl)}let f;if(c.scimagoCategories?.length){const y=await Yt("GET_SIMILAR_JOURNALS",{issn:c.issn?.[0]??"",issns:c.issn??[],journalName:c.journalName,normalizedName:c.normalizedName,scimagoCategories:c.scimagoCategories,sjrQuartile:c.sjrQuartile,count:5});y.success&&y.data?.journals&&(f=y.data.journals)}d.journal={journal:c,trendData:o,sjrTrendData:s,if5yr:c.if5yr,publisher:c.publisher,homepageUrl:h,showScimagoSJR:t.showScimagoSJR,quartileSources:t.quartileSources,similarJournals:f}}const p={pmid:e.pmid,paper:{pmid:e.pmid,title:e.title,authors:e.authors,doi:e.doi,pmcid:e.pmcid,journal:e.journal,publicationDate:e.publicationDate,abstract:document.querySelector(".abstract-content, #enc-abstract, #eng-abstract")?.textContent?.trim()||void 0}};d.exportSave=p,(d.journal||d.exportSave)&&U5(d),O5(e,t,l,u,c),n&&t.showImpactFactor&&L5(),console.log("[PaperLens] Article page enhancement complete")}catch(l){console.error("[PaperLens] Article page baseline enhancement failed:",l)}}function z5(){const r=["#core-citation-count",".citation-count","[data-citation-count]",'a[href*="citedby"]',".cited-by-count"];for(const n of r){const a=document.querySelector(n);if(a){const o=(a.textContent?.trim()??"").match(/(\d+(?:,\d+)*)/);if(o){const s=parseInt(o[1].replace(/,/g,""),10);if(!isNaN(s)&&s>0)return s}}}const t=dc().match(/Cited by\s+(\d+(?:,\d+)*)/i);if(t){const n=parseInt(t[1].replace(/,/g,""),10);if(!isNaN(n)&&n>0)return n}}function J5(){return new Promise(r=>{if(document.querySelector("h1.heading-title, h1.title, h1.document-title")){r();return}const e=Date.now(),t=5e3,a=setInterval(()=>{if(document.querySelector("h1.heading-title, h1.title, h1.document-title")){clearInterval(a),r();return}Date.now()-e>t&&(clearInterval(a),console.warn("[PaperLens] Timed out waiting for article page"),r())},100)})}const V5=ve+`
`+dS;function Wm(r){const e=r?.trim()??"";return/^10\./i.test(e)?e.toLowerCase():e}const xc="paperlens-root",Zi="paperlens-login-reminder",Gm="paperlens-login-reminder-style",Zm=new Set(["semantic-scholar","wanfang","baidu-scholar","dblp","ieee-xplore","sciencedirect","springerlink","wiley","taylor-francis","oxford-academic","cambridge-core","sage-journals","nature","science-org","preprint-servers","plos","openreview","cell-com","acm-dl","jstor","mdpi","lancet","bmj","nejm","jama-network","lww","publisher-network"]);function W5(r){return Zm.has(r.id)&&le()}function G5(r){if(r.getElementById(Gm))return;const e=document.createElement("style");e.id=Gm,e.textContent=`
    #${Zi} {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 2147483647;
      pointer-events: auto;
      width: min(430px, calc(100vw - 32px));
      max-height: calc(100vh - 32px);
      overflow: auto;
      box-sizing: border-box;
      border: 1px solid rgba(15, 23, 42, 0.12);
      border-radius: 8px;
      background: #fff;
      box-shadow: 0 24px 70px rgba(15, 23, 42, 0.24);
      color: #111827;
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", "Noto Sans SC", "Source Han Sans SC", "Helvetica Neue", Arial, sans-serif;
      padding: 18px;
    }

    .paperlens-login-reminder__header {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      gap: 12px;
      margin-bottom: 6px;
    }

    .paperlens-login-reminder__title {
      font-size: 15px;
      font-weight: 700;
      line-height: 1.35;
      margin: 0;
    }

    .paperlens-login-reminder__close {
      border: 0;
      background: transparent;
      color: #6b7280;
      cursor: pointer;
      font-size: 18px;
      line-height: 1;
      padding: 0 2px;
    }

    .paperlens-login-reminder__body {
      color: #4b5563;
      font-size: 14px;
      line-height: 1.55;
      margin: 0 0 10px;
    }

    .paperlens-login-reminder__hint {
      background: #eff6ff;
      border: 1px solid #bfdbfe;
      border-radius: 6px;
      color: #1d4ed8;
      font-size: 13px;
      line-height: 1.45;
      margin: 0 0 14px;
      padding: 8px 10px;
    }

    .paperlens-login-reminder__actions {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }

    .paperlens-login-reminder__button {
      align-items: center;
      border-radius: 6px;
      cursor: pointer;
      display: inline-flex;
      flex: 1;
      font-size: 14px;
      font-weight: 700;
      justify-content: center;
      line-height: 1;
      min-height: 40px;
      padding: 0 12px;
      user-select: none;
    }

    .paperlens-login-reminder__button--primary {
      background: #2563eb;
      border: 1px solid #2563eb;
      color: #fff;
      flex-basis: 100%;
    }

    .paperlens-login-reminder__button--secondary {
      background: #fff;
      border: 1px solid #d1d5db;
      color: #111827;
    }

    .paperlens-login-reminder__button--ghost {
      background: #f9fafb;
      border: 1px solid #e5e7eb;
      color: #4b5563;
    }
  `,r.appendChild(e)}function Ym(r){window.open(r,"_blank","noopener,noreferrer")}async function Z5(){try{if((await I.runtime.sendMessage({type:"OPEN_EXTENSION_LOGIN"}))?.success)return}catch(r){console.warn("[PaperLens] Failed to request extension login popup:",r)}Ym(I.runtime.getURL("/popup.html"))}function Y5(r){if(r.getElementById(Zi))return;G5(r);const e=document.createElement("aside");e.id=Zi,e.setAttribute("role","status"),e.setAttribute("aria-live","polite"),e.dataset.paperlensLoginReminder="true";const t=document.createElement("div");t.className="paperlens-login-reminder__header";const n=document.createElement("p");n.className="paperlens-login-reminder__title",n.textContent="\u767B\u5F55 PaperLens \xB7 \u7814\u955C";const a=document.createElement("button");a.type="button",a.className="paperlens-login-reminder__close",a.title="\u5173\u95ED\u63D0\u9192",a.setAttribute("aria-label","\u5173\u95ED\u767B\u5F55\u63D0\u9192"),a.textContent="\xD7",a.addEventListener("click",()=>{e.remove()}),t.append(n,a);const i=document.createElement("p");i.className="paperlens-login-reminder__body",i.textContent="\u8BF7\u5148\u767B\u5F55\u540E\u4F7F\u7528\u671F\u520A\u6307\u6807\u3001\u6536\u85CF\u3001\u5BFC\u51FA\u548C AI \u529F\u80FD\u3002";const o=document.createElement("p");o.className="paperlens-login-reminder__hint",o.textContent="\u767B\u5F55\u6210\u529F\u540E\u5237\u65B0\u5F53\u524D\u9875\u9762\u5373\u53EF\u542F\u7528\u529F\u80FD\u3002";const s=document.createElement("div");s.className="paperlens-login-reminder__actions";const l=document.createElement("button");l.type="button",l.className="paperlens-login-reminder__button paperlens-login-reminder__button--primary",l.textContent="\u767B\u5F55\u63D2\u4EF6",l.addEventListener("click",()=>{o.textContent="\u5DF2\u6253\u5F00\u767B\u5F55\u7A97\u53E3\u3002\u767B\u5F55\u6210\u529F\u540E\u5237\u65B0\u5F53\u524D\u9875\u9762\u5373\u53EF\u542F\u7528\u529F\u80FD\u3002",Z5()});const c=document.createElement("button");c.type="button",c.className="paperlens-login-reminder__button paperlens-login-reminder__button--secondary",c.textContent="\u6CE8\u518C",c.addEventListener("click",()=>{Ym(A1("/auth/register",{source:"extension_content"}))});const u=document.createElement("button");u.type="button",u.className="paperlens-login-reminder__button paperlens-login-reminder__button--ghost",u.textContent="\u53D6\u6D88",u.addEventListener("click",()=>{e.remove()}),s.append(l,c,u),e.append(t,i,o,s),r.appendChild(e)}function K5(r){r.getElementById(Zi)?.remove()}async function Q5(r){return await Xd()?(K5(r),!1):(Y5(r),console.log("[PaperLens] Login required; page enhancement skipped"),!0)}function Ie(r){const e=`meta[name="${r}"], meta[property="${r}"]`;return document.querySelector(e)?.content?.trim()??""}function rt(r){return r?.replace(/\s+/g," ").trim()||void 0}function X5(r){let e;try{e=r.isArticlePage()?r.parseArticlePage():null}catch{e=null}const t=rt(Ie("citation_title")||Ie("og:title")||document.title),n=rt(Ie("citation_journal_title")||Ie("citation_publisher")),a=rt(Ie("citation_doi")||Ie("dc.Identifier")),i=rt(Ie("citation_abstract")||Ie("dc.description")||Ie("description")||Ie("og:description")),o=rt(Ie("citation_publication_date")||Ie("citation_online_date")||Ie("dc.Date")),s=Array.from(document.querySelectorAll('meta[name="citation_author"]')).map(l=>rt(l.content)).filter(l=>!!l).slice(0,20);return{paper_id:e?.pmid??e?.doi??e?.sourceId??a??location.href,pmid:e?.pmid,doi:e?.doi??a,title:rt(e?.title)??t,abstract:rt(e?.abstractSnippet)??i,journal:rt(e?.journalName)??n,authors:e?.authors?.length?e.authors:s,year:e?.year,publication_date:rt(e?.publicationDate)??o,source:e?.source??r.id,source_url:e?.url??location.href}}const eF=200,tF=300;let Kt=Hh(),Y=null,Ta=null,Qt=null,Yi=null,En=null,Ea=null;function nF(r){if(Kt=r,Ac(),Ki(),Qt&&clearTimeout(Qt),kl(r)){if(Qt=null,Pi(),_l(),Y){const e=document.querySelectorAll(`${ke} ${ie}`);vn(Y,e.length,e.length),Sn(Y)}}else Qt=setTimeout(()=>{Qt=null,(async()=>{const e=await Nw(r);Y&&(vn(Y,e.sourceTotal,e.visible,{scope:"global",analyzed:e.analyzed,done:e.done,loading:e.loading}),Sn(Y))})()},300)}async function Km(){if(kl(Kt)||(await Os()).allowed)return!0;if(Kt=Hh(),Ac(),Ki(),Pi(),_l(),Y){const e=document.querySelectorAll(`${ke} ${ie}`);vn(Y,e.length,e.length),Sn(Y)}return!1}function rF(r){if(!Y)return;const e=r.detail;e&&(vn(Y,e.sourceTotal,e.visible,{scope:"global",analyzed:e.analyzed,done:e.done,loading:e.loading}),Sn(Y))}function aF(){try{return new URL(window.location.href).searchParams.get("term")?.trim()??""}catch{return""}}function Qm(r){return JSON.stringify({term:aF(),state:r})}function Ac(){Yi=null,En=null}function Ki(){Ea?.abort(),Ea=null}async function iF(r){if(!await Km())return null;const e=Dw();if(e)return En=e,Yi=Qm(Kt),r?.(e),e;const t=Qm(Kt);if(Yi===t&&En?.done)return r?.(En),En;Ki();const n=new AbortController;return Ea=n,Yi=t,_w(Kt,{signal:n.signal,onUpdate:a=>{En=a,r?.(a)}}).then(a=>(Ea===n&&(Ea=null),En=a,a))}function oF(){if(Y)return;const r=document.querySelector(Xc);if(r){Y=r;return}let e=document.querySelector($b)??document.querySelector(Ob);if(!e){console.warn("[PaperLens] No suitable insertion target found for toolbar");return}Y=p1(nF,()=>{if(Qt&&(clearTimeout(Qt),Qt=null),Ac(),Ki(),kw(),_l(),Y){const n=document.querySelectorAll(`${ke} ${ie}`);vn(Y,n.length,n.length),Sn(Y)}},iF),e.before(Y);const t=document.querySelectorAll(`${ke} ${ie}`);vn(Y,t.length,t.length),console.log("[PaperLens] Filter toolbar injected")}function sF(){Ta&&clearTimeout(Ta),Ta=setTimeout(()=>{(async()=>{if(!kl(Kt)&&!Ew()){if(!await Km()){Ta=null;return}const{total:r,visible:e}=vw(Kt);Y&&(vn(Y,r,e),Sn(Y))}we().then(r=>to(r)).catch(()=>{}),Y&&Sn(Y),Ta=null})()},300)}function lF(r){return r.style.display==="none"?!1:r.closest("#paperlens-global-results-root")?!0:r.offsetParent!==null||getComputedStyle(r).display!=="none"}function cF(){document.addEventListener("keydown",r=>{const e=r.target,t=e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.tagName==="SELECT"||e.isContentEditable;if((r.ctrlKey||r.metaKey)&&r.key==="a"&&!t){r.preventDefault();const n=Be.getInstance(),a=document.querySelectorAll(`${ke} ${ie}`),i=[];for(const o of a){if(!lF(o))continue;const l=o.querySelector(Nt),c=l?.getAttribute(sn);if(!c)continue;const u=l?.textContent?.trim()??"",p=o.querySelector("span.docsum-journal-citation.full-journal-citation")?.textContent?.trim()??"",h=p.split(".")[0]?.trim()??"",f=p.match(/\b(19|20)\d{2}\b/),y=f?parseInt(f[0],10):void 0;i.push({PMID:c,title:u,journal:h,year:y})}n.selectAll(i),document.querySelectorAll(`.${Al().split(" ").join(".")}`).forEach(o=>{const s=o,l=s.dataset.pmid;l&&xl(s,n.isSelected(l))})}if(r.key==="Escape"){const n=Be.getInstance();n.getCount()>0&&(n.deselectAll(),document.querySelectorAll(`.${Al().split(" ").join(".")}`).forEach(a=>{xl(a,!1)}))}}),console.log("[PaperLens] Keyboard shortcuts registered")}function uF(){return window.location.hostname==="pubmed.ncbi.nlm.nih.gov"}function dF(){return uF()&&(window.location.pathname==="/"||new URLSearchParams(window.location.search).has("term"))}function pF(){const r=document.getElementById(xc);if(r)return Xm(r),r.shadowRoot;const e=document.createElement("div");e.id=xc,Xm(e),document.body.appendChild(e);const t=e.attachShadow({mode:"open"});return console.log("[PaperLens] Shadow DOM container created (mode: open)"),t}function Xm(r){r.style.position="fixed",r.style.inset="0",r.style.width="100vw",r.style.height="100vh",r.style.zIndex="2147483647",r.style.pointerEvents="none",r.style.background="transparent"}function hF(r){const e=document.createElement("style");e.textContent=V5,r.appendChild(e)}async function fF(){if(ZS()===0)return;const e=setTimeout(()=>{KS()>0&&YS()},tF);try{await QS()}catch(t){console.error("[PaperLens] resolveMetrics failed:",t),tw()}finally{clearTimeout(e)}}let eb=null,Qi=null,Xi=[];async function mF(){if(Xi.length===0)return;const r=Xi;Xi=[],Qi=null;try{await Fl(r);const e=await we();to(e)}catch(e){console.error("[PaperLens] enhanceNewArticles failed:",e)}}function bF(r){const e=[];for(const t of r)if(t.type==="childList")for(const n of t.addedNodes){if(!(n instanceof Element))continue;n.matches(ie)&&e.push(n);const a=n.querySelectorAll?.(ie);if(a)for(const i of a)e.push(i)}e.length!==0&&(Xi.push(...e),Qi&&clearTimeout(Qi),Qi=setTimeout(()=>{mF()},eF))}let eo=0;const tb=8;function nb(){const r=document.querySelector(Ja);if(!r){if(eo>=tb){console.warn("[PaperLens] search-results-chunks not found after retries, giving up");return}eo++,console.warn(`[PaperLens] search-results-chunks container not found, retrying in 2s (${eo}/${tb})`),setTimeout(nb,2e3);return}eo=0,eb=new MutationObserver(bF),eb.observe(r,{childList:!0,subtree:!0}),console.log("[PaperLens] MutationObserver started on",Ja)}function to(r){if(!document.getElementById(xc))return;if(r.showImpactFactor!==void 0&&(document.querySelectorAll(_t).forEach(a=>{a.style.display=r.showImpactFactor?"":"none"}),document.querySelectorAll("[data-paperlens-inline-metrics]").forEach(a=>{a.style.display=r.showImpactFactor?"":"none"})),r.showCitations!==void 0&&document.querySelectorAll(kt).forEach(a=>{a.style.display=r.showCitations?"":"none"}),r.showReferences!==void 0&&document.querySelectorAll(".paperlens-citation-panel").forEach(a=>{a.style.display=r.showReferences?"":"none"}),(r.showExtraDownload!==void 0||r.extraDownloadUrl!==void 0)&&(async()=>{try{const n=await we();$A(n.showExtraDownload,n.extraDownloadUrl),document.querySelectorAll('[data-paperlens-fulltext="extra-download"]').forEach(a=>{a.style.display=n.showExtraDownload&&n.extraDownloadUrl?"":"none"})}catch{}})(),r.showOpenAccess!==void 0&&document.querySelectorAll(kt).forEach(a=>{a.shadowRoot?.querySelectorAll("[data-pl-oa-badge]").forEach(i=>{i.style.display=r.showOpenAccess?"":"none"})}),r.quartileSources!==void 0||r.quartileSource!==void 0){const n=Rt(r),a=n.includes("jcr"),i=n.includes("cas"),o=n.includes("emerging");if(G0(n),document.querySelectorAll(_t).forEach(s=>{s.shadowRoot?.querySelectorAll("[data-pl-jcr-quartile]").forEach(l=>{l.style.display=a?"":"none"}),s.shadowRoot?.querySelectorAll("[data-pl-cas-quartile]").forEach(l=>{l.style.display=i?"":"none"}),s.shadowRoot?.querySelectorAll("[data-pl-emerging-quartile]").forEach(l=>{l.style.display=o?"":"none"})}),document.querySelectorAll("[data-pl-jcr-quartile]").forEach(s=>{s.style.display=a?"":"none"}),document.querySelectorAll("[data-pl-cas-quartile]").forEach(s=>{s.style.display=i?"":"none"}),document.querySelectorAll("[data-pl-emerging-quartile]").forEach(s=>{s.style.display=o?"":"none"}),document.querySelectorAll(".paperlens-journal-detail-card, .paperlens-article-metrics-host").forEach(s=>{s.shadowRoot?.querySelectorAll("[data-pl-jcr-quartile]").forEach(l=>{l.style.display=a?"":"none"}),s.shadowRoot?.querySelectorAll("[data-pl-cas-quartile]").forEach(l=>{l.style.display=i?"":"none"}),s.shadowRoot?.querySelectorAll("[data-pl-emerging-quartile]").forEach(l=>{l.style.display=o?"":"none"})}),a||i||o){const s=Array.from(document.querySelectorAll(`${ke} ${ie}`));Fl(s).catch(l=>{console.warn("[PaperLens] Failed to refresh metrics after quartile source change:",l)})}}const t={...r};delete t.pubmedApiKey,console.log("[PaperLens] Settings applied:",t)}function gF(){I.runtime.onMessage.addListener((r,e,t)=>{switch(r.type){case"PING":{const a={success:!0,data:{bgTimestamp:r.payload?.bgTimestamp??0,csReceivedAt:Date.now()}};t(a);break}case"SETTINGS_UPDATED":{const n=r.payload;to(n),t({success:!0});break}case"LIBRARY_PAPER_REMOVED":{const n=r.payload,a=Array.from(new Set([n?.pmid,...n?.ids??[]].map(Wm).filter(Boolean)));a.length>0&&document.querySelectorAll(".paperlens-save-host").forEach(i=>{const o=new Set([i.dataset.pmid,...i.dataset.paperlensIds?.split("	")??[]].map(Wm).filter(Boolean));a.some(s=>o.has(s))&&ra(i,!1)}),t({success:!0});break}case"ONBOARDING_RESET":{const n=an.getInstance();(async()=>(await n.reset(),Lb(),dF()?nu(async()=>{await n.markComplete()}):console.log("[PaperLens] Onboarding reset, but not on search results page \u2014 state cleared only")))(),t({success:!0});break}}}),console.log("[PaperLens] Background message listener registered")}async function rb(){q(new eg),q(new ig),q(new sg),q(new lg),q(new fg),q(new gg),q(new wg),q(new Lg),q(new qg),q(new Jg),q(new Zg),q(new ay),q(new uy),q(new my),q(new yy),q(new Sy),q(new Ey),q(new Ry),q(new My),q(new Oy),q(new zy),q(new Zy),q(new tx),q(new ax),q(new ox),q(new px),q(new xx),q(new wx),q(new kx),q(new Mx),q(new Ux);const r=jb();if(!r){console.log("[PaperLens] No matching adapter for",location.href,"- skipping");return}console.log("[PaperLens] Initializing with adapter:",r.name);const e=pF();if(e&&(hF(e),gF(),!await Q5(e))){if(_1(e,()=>X5(r)),r.isArticlePage()){console.log("[PaperLens] Article page detected, starting enhancement"),r.id==="pubmed"?await H5():r.id==="cnki"?(await V(r),await J(r)):r.id==="wos"?(await V(r),await J(r)):r.id==="semantic-scholar"?(await V(r),await J(r),W(r)):r.id==="wanfang"?(await V(r),await J(r),W(r)):r.id==="dblp"?(await V(r),await J(r),W(r)):r.id==="ieee-xplore"?(await V(r),await J(r),W(r)):r.id==="sciencedirect"?(await V(r),await J(r),W(r)):r.id==="springerlink"?(await V(r),await J(r),W(r)):r.id==="wiley"?(await V(r),await J(r),W(r)):r.id==="taylor-francis"?(await V(r),await J(r),W(r)):r.id==="oxford-academic"?(await V(r),await J(r),W(r)):r.id==="cambridge-core"?(await V(r),await J(r),W(r)):r.id==="sage-journals"?(await V(r),await J(r),W(r)):r.id==="nature"?(await V(r),await J(r),W(r)):r.id==="science-org"?(await V(r),await J(r),W(r)):r.id==="preprint-servers"?(await V(r),await J(r),W(r)):r.id==="plos"?(await V(r),await J(r),W(r)):r.id==="openreview"?(await V(r),await J(r),W(r)):r.id==="cell-com"?(await V(r),await J(r),W(r)):r.id==="acm-dl"?(await V(r),await J(r),W(r)):r.id==="jstor"?(await V(r),await J(r),W(r)):r.id==="mdpi"?(await V(r),await J(r),W(r)):r.id==="lancet"?(await V(r),await J(r),W(r)):r.id==="bmj"?(await V(r),await J(r),W(r)):r.id==="nejm"?(await V(r),await J(r),W(r)):r.id==="jama-network"?(await V(r),await J(r),W(r)):r.id==="lww"?(await V(r),await J(r),W(r)):r.id==="publisher-network"&&(await V(r),await J(r),W(r));return}if(r.id==="pubmed"&&yE()){console.log("[PaperLens] PubMed homepage detected, mounting query optimizer"),nE();return}if(r.isSearchPage())if(r.id==="pubmed"){console.log("[PaperLens] PubMed search results detected, starting full enhancement"),Hn().catch(()=>{}),await yF(),oF(),document.addEventListener("paperlens:data-updated",sF),document.addEventListener("paperlens:global-filter-updated",rF),await fF(),nb(),cF();try{const n=await we();to(n)}catch{}console.log("[PaperLens] Enhancement pipeline active");const t=an.getInstance();await t.shouldShow()&&setTimeout(()=>{nu(async()=>{await t.markComplete()})},1500)}else console.log(`[PaperLens] ${r.name} search page detected, starting multi-site enhancement`),await Cc(r),await bl(r),Zm.has(r.id)?W(r):vF(r);else r.id==="google-scholar"?r.isCitationLibraryPage()?(console.log("[PaperLens] Google Scholar citation library page detected"),await uS(r)):console.log(`[PaperLens] ${r.name} page detected but not a recognized page, skipping`):W5(r)?(console.log(`[PaperLens] ${r.name} is behind a challenge page, arming deferred enhancement`),W(r)):console.log(`[PaperLens] ${r.name} page detected but not a search page, skipping`)}}function yF(){return new Promise(r=>{if(document.querySelector(ie)){r();return}const e=Date.now(),t=15e3,a=setInterval(()=>{if(document.querySelector(ie)){clearInterval(a),r();return}Date.now()-e>t&&(clearInterval(a),console.warn("[PaperLens] Timed out waiting for search results"),r())},100)})}function ab(r){if(r.id==="baidu-scholar"){const e=r.getResultsContainer()??document.body;return!!(e?.querySelector(Sc)||e?.querySelector(vc))}return r.parseSearchResults().length>0}function Cc(r){return new Promise(e=>{if(ab(r)){e();return}const t=Date.now(),n=1e4,i=setInterval(()=>{if(ab(r)){clearInterval(i),e();return}Date.now()-t>n&&(clearInterval(i),console.warn(`[PaperLens] Timed out waiting for ${r.name} search results`),e())},150)})}function V(r){return new Promise(e=>{if(r.parseArticlePage()){e();return}const t=Date.now(),n=1e4,i=setInterval(()=>{if(r.parseArticlePage()){clearInterval(i),e();return}Date.now()-t>n&&(clearInterval(i),console.warn(`[PaperLens] Timed out waiting for ${r.name} article page`),e())},150)})}const ib=["#resultsList","#paper-content-wrap",".mod-results-list",".result-list","[data-paperlens-results]"].join(","),ob=['iframe[src*="verify"]','iframe[src*="captcha"]','iframe[src*="challenge"]','iframe[src*="access-check"]','iframe[src*="security-check"]','form[action*="verify"]','form[action*="captcha"]','form[action*="challenge"]','form[action*="access-check"]','form[action*="security-check"]','[id*="captcha" i]','[class*="captcha" i]','[id*="challenge" i]','[class*="challenge" i]','[id*="access-check" i]','[class*="access-check" i]','[id*="security-check" i]','[class*="security-check" i]','[id*="verify-code" i]','[class*="verify-code" i]'].join(","),vc=[".sc_content",".result",".result-item","[data-paperlens-baidu-result]",".sc_title","h3",".result-title"].join(","),Sc=[".sc_title a","h3 a",".result-title a",'a[data-click*="title"]'].join(","),sb=["#completesearch-publs","#completesearch-publs .body","#main","ul.publ-list","li.entry","#infinitescroll-status","#infinitescroll-pagination","#completesearch-info-skipping","a.next"].join(","),lb=[".search-results",".search__results",".search-result__item","li.search__item",".search-result__body",".search-result",".issue-item",".search-result__meta",".journal-title"].join(",");function xF(r){return!!r.closest('[class^="paperlens-"], [class*=" paperlens-"]')}function cb(r){return r instanceof Element?r:r.parentElement}function AF(r){return/(?:百度安全验证|安全验证|安全校验|滑块验证|拖动滑块|请完成以下验证|请输入验证码|系统检测到您的请求存在异常|Access check|Continue after check)/i.test(r)}function CF(r){return r.matches(ob)||!!r.querySelector(ob)||AF(r.textContent??"")}function ub(r,e,t){if(xF(e))return!1;if(r.id==="baidu-scholar")return CF(e)?!0:e.matches(vc)||!!e.querySelector(vc)||e.matches(Sc)||!!e.querySelector(Sc)||t&&e.matches("main, #bdxs_result_lists, #bdxs_result_list, #container, [data-paperlens-baidu-results]");if(r.id==="dblp")return e.matches(sb)||!!e.querySelector(sb)||t&&e.matches("body");if(r.id==="science-org")return e.matches(lb)||t&&!!e.querySelector(lb)||t&&e.matches("main, body, section, [aria-label], [aria-labelledby]");const n=r.getResultsContainer();return n?n.contains(e)||e.matches(ib)||!!e.querySelector(ib)||t&&e.contains(n):!0}function db(r,e){return e.some(t=>{if(r.id==="baidu-scholar"&&t.type!=="childList")return!1;if(t.type==="childList")return Array.from(t.addedNodes).some(a=>{const i=cb(a);return i?ub(r,i,!0):!1});if(t.type==="attributes"&&t.attributeName?.startsWith("data-paperlens-"))return!1;const n=cb(t.target);return!!(n&&ub(r,n,!1))})}function vF(r){if(!document.body)return;wc();let e=null,t=!1,n=!1,a=!1;const i=()=>{a||(e&&clearTimeout(e),e=setTimeout(()=>{e=null,o()},300))},o=async()=>{if(!a){if(t){n=!0;return}t=!0;try{await Cc(r),await bl(r)}finally{t=!1,!a&&n&&(n=!1,i())}}},s=new MutationObserver(c=>{a||db(r,c)&&i()});s.observe(document.body,{childList:!0,subtree:!0});const l=()=>{if(!a){if(document.hidden){s.disconnect();return}s.observe(document.body,{childList:!0,subtree:!0})}};document.addEventListener("visibilitychange",l),Fa=()=>{a=!0,s.disconnect(),e&&clearTimeout(e),document.removeEventListener("visibilitychange",l)}}let Fa=null;function wc(){Fa&&(Fa(),Fa=null)}function W(r){if(!document.body)return;wc();let e=null,t=!1,n=!1,a=location.href,i=!1;const o=async()=>{if(!i){if(t){n=!0;return}t=!0;try{r.isArticlePage()?(await V(r),await J(r)):r.isSearchPage()&&(await Cc(r),await bl(r))}finally{t=!1,!i&&n&&(n=!1,s())}}},s=()=>{i||(e&&clearTimeout(e),e=setTimeout(()=>{e=null,o()},300))},l=r.id==="baidu-scholar"?{childList:!0,subtree:!0}:{childList:!0,subtree:!0,attributes:!0,characterData:!0},c=r.id==="baidu-scholar"?r.getResultsContainer()??document.body:document.body,d=!!c?new MutationObserver(y=>{i||db(r,y)&&s()}):null;d?.observe(c,l);const p=setInterval(()=>{i||location.href!==a&&(a=location.href,s())},500),h=()=>{if(!(i||r.id==="baidu-scholar")){if(document.hidden){d?.disconnect();return}d?.observe(c,l),s()}},f=()=>wc();r.id!=="baidu-scholar"&&document.addEventListener("visibilitychange",h),window.addEventListener("pagehide",f,{once:!0}),s(),Fa=()=>{i=!0,d?.disconnect(),clearInterval(p),e&&clearTimeout(e),r.id!=="baidu-scholar"&&document.removeEventListener("visibilitychange",h),window.removeEventListener("pagehide",f)}}function SF(){console.log("[PaperLens] Content script loaded on:",window.location.href),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{rb()}):rb()}const wF={matches:["*://pubmed.ncbi.nlm.nih.gov/*","*://scholar.google.com/*","*://scholar.google.com.hk/*","*://scholar.google.co.jp/*","*://scholar.google.com.tw/*","*://www.webofscience.com/*","*://www.semanticscholar.org/*","*://www.wanfangdata.com.cn/*","*://med.wanfangdata.com.cn/*","*://s.wanfangdata.com.cn/*","*://d.wanfangdata.com.cn/*","*://xueshu.baidu.com/*","*://dblp.org/*","*://dblp.uni-trier.de/*","*://ieeexplore.ieee.org/*","*://www.sciencedirect.com/*","*://link.springer.com/*","*://onlinelibrary.wiley.com/*","*://*.onlinelibrary.wiley.com/*","*://www.tandfonline.com/*","*://academic.oup.com/*","*://www.cambridge.org/*","*://journals.sagepub.com/*","*://www.nature.com/*","*://www.science.org/*","*://www.biorxiv.org/*","*://biorxiv.org/*","*://www.medrxiv.org/*","*://medrxiv.org/*","*://arxiv.org/*","*://journals.plos.org/*","*://openreview.net/*","*://www.cell.com/*","*://dl.acm.org/*","*://www.jstor.org/*","*://jstor.org/*","*://www.mdpi.com/*","*://www.thelancet.com/*","*://thelancet.com/*","*://www.lancet.com/*","*://lancet.com/*","*://www.bmj.com/content/*","*://www.bmj.com/search*","*://*.bmj.com/content/*","*://*.bmj.com/search*","*://www.nejm.org/*","*://nejm.org/*","*://jamanetwork.com/*","*://www.jamanetwork.com/*","*://journals.lww.com/*","*://*.ovid.com/*","*://www.frontiersin.org/*","*://frontiersin.org/*","*://pubs.acs.org/*","*://pubs.rsc.org/*","*://journals.aps.org/*","*://link.aps.org/*","*://pubs.aip.org/*","*://iopscience.iop.org/*","*://karger.com/*","*://www.karger.com/*","*://www.thieme-connect.de/*","*://thieme-connect.de/*","*://www.thieme-connect.com/*","*://thieme-connect.com/*","*://www.jmir.org/*","*://jmir.org/*","*://*.jmir.org/*","*://www.annualreviews.org/*","*://annualreviews.org/*","*://elifesciences.org/*","*://pnas.org/*","*://www.pnas.org/*","*://rupress.org/*","*://www.rupress.org/*","*://*.rupress.org/*","*://cshperspectives.cshlp.org/*","*://genesdev.cshlp.org/*","*://kns.cnki.net/*","*://www.cnki.net/*","*://navi.cnki.net/*"],main(){SF()}};function no(r,...e){}const TF={debug:(...r)=>no(console.debug,...r),log:(...r)=>no(console.log,...r),warn:(...r)=>no(console.warn,...r),error:(...r)=>no(console.error,...r)};var pb=class vb extends Event{static EVENT_NAME=Tc("wxt:locationchange");constructor(e,t){super(vb.EVENT_NAME,{}),this.newUrl=e,this.oldUrl=t}};function Tc(r){return`${I?.runtime?.id}:content:${r}`}const EF=typeof globalThis.navigation?.addEventListener=="function";function FF(r){let e,t=!1;return{run(){t||(t=!0,e=new URL(location.href),EF?globalThis.navigation.addEventListener("navigate",n=>{const a=new URL(n.destination.url);a.href!==e.href&&(window.dispatchEvent(new pb(a,e)),e=a)},{signal:r.signal}):r.setInterval(()=>{const n=new URL(location.href);n.href!==e.href&&(window.dispatchEvent(new pb(n,e)),e=n)},1e3))}}}var DF=class ja{static SCRIPT_STARTED_MESSAGE_TYPE=Tc("wxt:content-script-started");id;abortController;locationWatcher=FF(this);constructor(e,t){this.contentScriptName=e,this.options=t,this.id=Math.random().toString(36).slice(2),this.abortController=new AbortController,this.stopOldScripts(),this.listenForNewerScripts()}get signal(){return this.abortController.signal}abort(e){return this.abortController.abort(e)}get isInvalid(){return I.runtime?.id==null&&this.notifyInvalidated(),this.signal.aborted}get isValid(){return!this.isInvalid}onInvalidated(e){return this.signal.addEventListener("abort",e),()=>this.signal.removeEventListener("abort",e)}block(){return new Promise(()=>{})}setInterval(e,t){const n=setInterval(()=>{this.isValid&&e()},t);return this.onInvalidated(()=>clearInterval(n)),n}setTimeout(e,t){const n=setTimeout(()=>{this.isValid&&e()},t);return this.onInvalidated(()=>clearTimeout(n)),n}requestAnimationFrame(e){const t=requestAnimationFrame((...n)=>{this.isValid&&e(...n)});return this.onInvalidated(()=>cancelAnimationFrame(t)),t}requestIdleCallback(e,t){const n=requestIdleCallback((...a)=>{this.signal.aborted||e(...a)},t);return this.onInvalidated(()=>cancelIdleCallback(n)),n}addEventListener(e,t,n,a){t==="wxt:locationchange"&&this.isValid&&this.locationWatcher.run(),e.addEventListener?.(t.startsWith("wxt:")?Tc(t):t,n,{...a,signal:this.signal})}notifyInvalidated(){this.abort("Content script context invalidated"),TF.debug(`Content script "${this.contentScriptName}" context invalidated`)}stopOldScripts(){document.dispatchEvent(new CustomEvent(ja.SCRIPT_STARTED_MESSAGE_TYPE,{detail:{contentScriptName:this.contentScriptName,messageId:this.id}})),window.postMessage({type:ja.SCRIPT_STARTED_MESSAGE_TYPE,contentScriptName:this.contentScriptName,messageId:this.id},"*")}verifyScriptStartedEvent(e){const t=e.detail?.contentScriptName===this.contentScriptName,n=e.detail?.messageId===this.id;return t&&!n}listenForNewerScripts(){const e=t=>{!(t instanceof CustomEvent)||!this.verifyScriptStartedEvent(t)||this.notifyInvalidated()};document.addEventListener(ja.SCRIPT_STARTED_MESSAGE_TYPE,e),this.onInvalidated(()=>document.removeEventListener(ja.SCRIPT_STARTED_MESSAGE_TYPE,e))}};function ZF(){}function ro(r,...e){}const _F={debug:(...r)=>ro(console.debug,...r),log:(...r)=>ro(console.log,...r),warn:(...r)=>ro(console.warn,...r),error:(...r)=>ro(console.error,...r)};return(async()=>{try{const{main:r,...e}=wF;return await r(new DF("content",e))}catch(r){throw _F.error('The content script "content" crashed on startup!',r),r}})()})();

content;