@embedpdf-editor/react-chapter-viewer 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +351 -46
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +584 -557
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),e=require("react"),a=require("@embedpdf/core/react"),s=require("@embedpdf/plugin-interaction-manager/react"),i=require("@embedpdf/plugin-rotate/react"),r=require("@embedpdf/plugin-selection/react"),o=require("@embedpdf/plugin-selection"),n=require("@embedpdf/plugin-annotation/react"),h=require("@embedpdf/plugin-redaction/react"),l=require("@embedpdf/plugin-document-manager"),d=require("@embedpdf/core"),c=require("@embedpdf/models"),u=require("@embedpdf/plugin-render/react");require("@embedpdf/plugin-tiling/react");const p=require("@embedpdf/plugin-annotation"),g=require("@embedpdf/plugin-interaction-manager"),f=require("@embedpdf/plugin-render"),m=require("@embedpdf/plugin-rotate"),v=require("@embedpdf/plugin-history"),b=require("@embedpdf/plugin-redaction"),P=require("@embedpdf/plugin-form"),w=require("@embedpdf/plugin-stamp"),I=require("@embedpdf/plugin-signature"),y=require("@embedpdf/plugin-commands"),C=require("@embedpdf/plugin-i18n"),M=require("@embedpdf/plugin-ui"),S=require("@embedpdf/engines/react"),x={kind:"first-wins"};function L(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let $=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const D=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=x,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??x,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=x){const a=function(t,e=x){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,L(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new $(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};D.id="chapter-manager";let k=D;const T=class extends d.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=d.createBehaviorEmitter(),this.visibleChange$=d.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(k.id),this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){if(!this.chapterManager.provides().getChapter(t))return!1;const e=this.documentManager.provides().getDocumentState(t);return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){if(!this.chapterManager.provides().getChapter(t))return;const e=this.documentManager.provides();e.getActiveDocumentId()||e.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){this.chapterManager.provides().getChapter(t)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};T.id="chapter-scroll";let z=T;function G({renderPage:s,renderPlaceholder:i,className:r,style:o,...n}){const{provides:h}=a.useCapability(z.id),l=e.useRef(null),[d,c]=e.useState(null);e.useEffect(()=>{if(!h)return;const t=l.current;h.registerViewport(t);const e=h.onLayoutChange(t=>c(t));return()=>{e(),h.registerViewport(null)}},[h]);const u=(null==d?void 0:d.totalHeight)??0,p=(null==d?void 0:d.totalWidth)??0;return t.jsx("div",{...n,ref:l,"data-chapter-scroll-viewport":"",className:r,style:{overflow:"auto",position:"relative",width:"100%",height:"100%",...o},children:t.jsx("div",{style:{position:"relative",width:`${p}px`,height:`${u}px`,margin:"0 auto"},children:null==d?void 0:d.items.map(e=>t.jsx("div",{"data-global-page-index":e.globalPageIndex,"data-chapter-id":e.chapterId,"data-local-page-index":e.localPageIndex,style:{position:"absolute",top:`${e.offsetTop}px`,left:"50%",transform:"translateX(-50%)",width:`${e.width}px`,height:`${e.height}px`,backgroundColor:e.isPlaceholder?"#f3f4f6":"#fff",boxShadow:"0 1px 4px rgba(0,0,0,0.08)"},children:e.isPlaceholder?(null==i?void 0:i(e))??t.jsx("div",{style:{display:"flex",width:"100%",height:"100%",alignItems:"center",justifyContent:"center",color:"#9ca3af",fontSize:"12px"},children:"Loading chapter…"}):s(e)},e.globalPageIndex))})})}function O({chapterId:e,localPageIndex:a,scale:s,dpr:i,className:r}){return t.jsx(u.RenderLayer,{documentId:e,pageIndex:a,scale:s,dpr:i,className:r,style:{pointerEvents:"none"}})}const A={kind:"first-wins"};function N(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let E=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const R=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=A,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??A,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=A){const a=function(t,e=A){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,N(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new E(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};R.id="chapter-manager";let V=R;const _={kind:"first-wins"};function U(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let F=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const q=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=_,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??_,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=_){const a=function(t,e=_){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,U(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new F(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};q.id="chapter-manager";let B=q;const j=class extends d.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=d.createBehaviorEmitter(),this.visibleChange$=d.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(B.id),this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){if(!this.chapterManager.provides().getChapter(t))return!1;const e=this.documentManager.provides().getDocumentState(t);return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){if(!this.chapterManager.provides().getChapter(t))return;const e=this.documentManager.provides();e.getActiveDocumentId()||e.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){this.chapterManager.provides().getChapter(t)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};j.id="chapter-scroll";let W=j;const H=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.notesChange$=d.createBehaviorEmitter([]),this.noteActivated$=d.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(W.id),this.chapterManager=this.registry.getPlugin(V.id),this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,e.callbacks.loadNotes)try{const t=await e.callbacks.loadNotes();for(const e of t)this.notes.set(e.noteId,e);this.notesChange$.emit(this.listAll())}catch(a){this.logger.error(t.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:t=>this.createNoteFromSelection(t),requestCreateFromSelection:t=>this.requestCreateFromSelection(t),registerNote:t=>this.registerNote(t),listNotesForPage:(t,e)=>this.listAll().filter(a=>a.chapterId===t&&a.localPageIndex===e),listAllNotes:()=>this.listAll(),getNote:t=>this.notes.get(t)??null,deleteNote:t=>this.deleteNote(t),updateNoteContent:(t,e)=>this.updateNoteContent(t,e),scrollToNote:t=>this.scrollToNote(t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(t){this.notes.set(t.noteId,t),this.notesChange$.emit(this.listAll())}requestEdit(t){const e=this.notes.get(t);e&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(t,e):this.activateNote(t))}activateNote(t){var e,a;const s=this.notes.get(t);s&&(null==(a=(e=this.config.callbacks).onActivateNote)||a.call(e,t,s),this.noteActivated$.emit({noteId:t,anchor:s}))}listAll(){return Array.from(this.notes.values())}buildDraft(t){return{chapterId:t.chapterId,localPageIndex:t.localPageIndex,globalPageNumber:t.globalPageNumber,globalPageIndex:t.globalPageIndex,rectsPdfCoord:t.rectsPdfCoord,endAnchor:K(t.rectsPdfCoord),selectedText:t.selectedText,content:t.content}}async requestCreateFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const e=this.buildDraft(t),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:e,complete:async t=>{const a={...e,noteId:t};this.registerNote(a)}}),null):this.createNoteFromSelection(t)}async createNoteFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const a=this.buildDraft(e),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(t.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let i=null;try{i=await s(a)}catch(o){return this.logger.error(t.id,"OnCreateNote","Callback failed",o),null}if(!i)return null;const r={...a,noteId:i.noteId};return this.registerNote(r),r}async deleteNote(e){var a,s;if(this.notes.has(e)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,e))}catch(i){return void this.logger.error(t.id,"OnDeleteNote","Callback failed",i)}this.notes.delete(e),this.notesChange$.emit(this.listAll())}}async updateNoteContent(e,a){var s,i;const r=this.notes.get(e);if(!r)return;const o={...r,content:a};try{await(null==(i=(s=this.config.callbacks).onUpdateNote)?void 0:i.call(s,o))}catch(n){return void this.logger.error(t.id,"OnUpdateNote","Callback failed",n)}this.notes.set(e,o),this.notesChange$.emit(this.listAll())}async scrollToNote(t){var e;const a=this.notes.get(t);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(e=this.documentManager.provides().getDocument(a.chapterId))?void 0:e.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(t){const e=this.chapterScroll.provides(),a=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{i(),a(null)},2500),i=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(s),i(),a(r))})})}};H.id="note";let Y=H;function K(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function X({chapterId:s,localPageIndex:i,pdfPageWidth:r,pdfPageHeight:o,cssPageWidth:n,cssPageHeight:h,color:l="#f59e0b",ui:d,className:c,style:u}){const{plugin:p}=(()=>{const{registry:t}=a.useRegistry();if(null===t)return{plugin:null,isLoading:!0,ready:new Promise(()=>{})};const e=t.getPlugin(Y.id);return{plugin:e,isLoading:!1,ready:(null==e?void 0:e.ready())??Promise.resolve()}})(),{provides:g}=(()=>{const{registry:t}=a.useRegistry();if(null===t)return{provides:null,isLoading:!0,ready:new Promise(()=>{})};const e=t.getPlugin(Y.id);return(null==e?void 0:e.provides)?{provides:e.provides(),isLoading:!1,ready:e.ready()}:{provides:null,isLoading:!1,ready:Promise.resolve()}})(),[f,m]=e.useState([]),[v,b]=e.useState(null),[P,w]=e.useState(null);if(e.useEffect(()=>{if(g)return g.onNotesChange(t=>{m(t.filter(t=>t.chapterId===s&&t.localPageIndex===i))})},[g,s,i]),e.useEffect(()=>{if(!P)return;const t=t=>{var e;const a=t.target;(null==(e=a.closest)?void 0:e.call(a,`[data-note-marker-zone="${P}"]`))||(w(null),b(null))};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[P]),!g||0===f.length||!r||!o)return null;const I=n/r,y=h/o,C=(null==d?void 0:d.iconSize)??16,M=(null==d?void 0:d.highlightColor)??"rgba(245, 158, 11, 0.08)";return t.jsx("div",{className:c,style:{position:"absolute",inset:0,pointerEvents:"none",zIndex:25,...u},children:f.map(e=>{const a=v===e.noteId,s=P===e.noteId,i=a||s,{left:r,top:o}=function(t){const{markerPdf:e,lineRects:a,sx:s,sy:i,cssPageWidth:r,iconSize:o,gapPx:n=6}=t,h=(null==a?void 0:a.length)?a[a.length-1]:void 0;let l,d;h?(l=(h.origin.x+h.size.width)*s+n,d=h.origin.y*i+(h.size.height*i-o)/2):(l=e.x*s-o/2,d=e.y*i-o-n);const c=Math.max(0,r-o-2);return l>c&&(l=c),d<0&&(d=0),{left:l,top:d}}({markerPdf:e.endAnchor,lineRects:e.rectsPdfCoord,sx:I,sy:y,cssPageWidth:n,iconSize:C}),h=function(t,e,a){let s=1/0,i=1/0,r=-1/0,o=-1/0;for(const n of t)s=Math.min(s,n.origin.x*e),i=Math.min(i,n.origin.y*a),r=Math.max(r,(n.origin.x+n.size.width)*e),o=Math.max(o,(n.origin.y+n.size.height)*a);return{left:s,top:i,width:r-s,height:o-i}}(e.rectsPdfCoord,I,y),c=s?72:0,u=Math.max(0,Math.min(h.left,r)-8),f=Math.max(0,Math.min(h.top,o)-8),m=Math.min(n,Math.max(h.left+h.width,r+C)+8)-u,S=Math.max(h.top+h.height,o+C+6+c)+8-f;return t.jsxs("div",{children:[e.rectsPdfCoord.map((a,s)=>t.jsx("div",{style:{position:"absolute",left:a.origin.x*I+"px",top:a.origin.y*y+"px",width:a.size.width*I+"px",height:a.size.height*y+"px",background:M,borderRadius:"2px",pointerEvents:"auto",cursor:"default"},onMouseEnter:()=>b(e.noteId)},`${e.noteId}-bg-${s}`)),i&&t.jsxs("div",{"data-note-marker-zone":e.noteId,style:{position:"absolute",left:`${u}px`,top:`${f}px`,width:`${m}px`,height:`${S}px`,pointerEvents:"auto",zIndex:26},onMouseEnter:()=>b(e.noteId),onMouseLeave:()=>{P!==e.noteId&&b(null)},children:[(null==d?void 0:d.renderIcon)?t.jsx("div",{role:"button",tabIndex:0,title:"笔记","aria-label":"笔记",onMouseDown:t=>t.stopPropagation(),onClick:t=>{t.stopPropagation(),w(t=>t===e.noteId?null:e.noteId)},style:{position:"absolute",left:r-u+"px",top:o-f+"px",width:`${C}px`,height:`${C}px`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",padding:0},children:d.renderIcon({note:e})}):t.jsx("button",{type:"button",title:"笔记",onMouseDown:t=>t.stopPropagation(),onClick:t=>{t.stopPropagation(),w(t=>t===e.noteId?null:e.noteId)},style:{position:"absolute",left:r-u+"px",top:o-f+"px",width:`${C}px`,height:`${C}px`,border:"none",borderRadius:"50%",background:l,color:"#fff",cursor:"pointer",boxShadow:"0 2px 6px rgba(0,0,0,0.2)",padding:0,display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",lineHeight:1},"aria-label":"笔记",children:"💬"}),s&&((null==d?void 0:d.renderMenuActions)?t.jsx("div",{style:{position:"absolute",left:r-u+C/2+"px",top:`${o-f+C+6}px`,transform:"translateX(-50%)",zIndex:30,pointerEvents:"auto"},onMouseDown:t=>t.stopPropagation(),children:d.renderMenuActions({note:e,onEdit:()=>{w(null),b(null),null==p||p.requestEdit(e.noteId)},onDelete:()=>{w(null),b(null),g.deleteNote(e.noteId)}})}):t.jsxs("div",{style:{position:"absolute",left:r-u+C/2+"px",top:`${o-f+C+6}px`,transform:"translateX(-50%)",zIndex:30,pointerEvents:"auto",minWidth:"80px",padding:"4px",borderRadius:"6px",background:"#fff",border:"1px solid #e5e7eb",boxShadow:"0 4px 12px rgba(0,0,0,0.12)"},onMouseDown:t=>t.stopPropagation(),children:[t.jsx("button",{type:"button",style:Z,onClick:t=>{t.stopPropagation(),w(null),b(null),null==p||p.requestEdit(e.noteId)},children:"编辑"}),t.jsx("button",{type:"button",style:{...Z,color:"#dc2626"},onClick:t=>{t.stopPropagation(),w(null),b(null),g.deleteNote(e.noteId)},children:"删除"})]}))]})]},e.noteId)})})}const Z={display:"block",width:"100%",padding:"6px 10px",fontSize:"12px",border:"none",borderRadius:"4px",background:"transparent",color:"#334155",cursor:"pointer",textAlign:"left"},Q={kind:"first-wins"};function J(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let tt=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const et=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=Q,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Q,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Q){const a=function(t,e=Q){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,J(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new tt(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};et.id="chapter-manager";let at=et;const st={kind:"first-wins"};function it(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let rt=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const ot=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=st,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??st,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=st){const a=function(t,e=st){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,it(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new rt(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};ot.id="chapter-manager";let nt=ot;const ht=class extends d.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=d.createBehaviorEmitter(),this.visibleChange$=d.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(nt.id),this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){if(!this.chapterManager.provides().getChapter(t))return!1;const e=this.documentManager.provides().getDocumentState(t);return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){if(!this.chapterManager.provides().getChapter(t))return;const e=this.documentManager.provides();e.getActiveDocumentId()||e.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){this.chapterManager.provides().getChapter(t)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};ht.id="chapter-scroll";let lt=ht;function dt(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function ct(t,e){const a=t.origin.y,s=t.origin.y+t.size.height,i=e.origin.y,r=e.origin.y+e.size.height,o=Math.max(s,r)-Math.min(a,i);return o<=0?0:Math.max(0,Math.min(s,r)-Math.max(a,i))/o}function ut(t,e){var a,s;if(t.chapterId!==e.chapterId||t.localPageIndex!==e.localPageIndex)return!1;const i=(null==(a=t.rectsPdfCoord)?void 0:a.length)?t.rectsPdfCoord:[t.rectPdfCoord],r=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],o=t.markerAnchor??dt(i),n=e.markerAnchor??dt(r);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const h of i)for(const t of r){if(ct(h,t)<.5)continue;const e=Math.max(h.origin.x,t.origin.x);if(Math.min(h.origin.x+h.size.width,t.origin.x+t.size.width)-e>.25*Math.min(h.size.width,t.size.width))return!0}return!1}const pt=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.change$=d.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(lt.id),this.chapterManager=this.registry.getPlugin(at.id),this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(e){var a;if(this.config=e,null==(a=e.callbacks)?void 0:a.load)try{const t=await e.callbacks.load();for(const e of t)this.entries.set(e.id,e);this.change$.emit(this.list())}catch(s){this.logger.error(t.id,"Load","Failed to load paragraph bookmarks",s)}}buildCapability(){return{addBookmark:t=>this.addBookmark(t),removeBookmark:t=>this.removeBookmark(t),updateBookmark:(t,e)=>this.updateBookmark(t,e),listBookmarks:()=>this.list(),getBookmark:t=>this.entries.get(t)??null,scrollToBookmark:t=>this.scrollToBookmark(t),requestRemoveBookmark:t=>this.requestRemoveBookmark(t),onBookmarksChange:this.change$.on}}addBookmark(t){for(const s of this.entries.values())if(ut(s.anchor,t.anchor))return s;const e=t.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:e,label:t.label,anchor:t.anchor,metadata:t.metadata,createdAt:Date.now()};return this.entries.set(e,a),this.notifyAndPersist(),a}removeBookmark(t){var e,a,s;this.entries.delete(t)&&(this.notifyAndPersist(),null==(s=null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,t))}async requestRemoveBookmark(e){var a,s;const i=this.entries.get(e);if(!i)return!1;const r=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(r)try{if(!(await r(i)))return!1}catch(o){return this.logger.error(t.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(e),!0}updateBookmark(t,e){const a=this.entries.get(t);a&&(this.entries.set(t,{...a,...e}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((t,e)=>t.createdAt-e.createdAt)}notifyAndPersist(){var e,a;const s=this.list();this.change$.emit(s),(null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.persist)&&Promise.resolve(this.config.callbacks.persist(s)).catch(e=>this.logger.error(t.id,"Persist","persist callback rejected",e))}async scrollToBookmark(t){const e=this.entries.get(t);if(!e)return;const a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(e.anchor.chapterId);let s=e.anchor.globalPageIndex;if(void 0===s){const t=this.chapterManager.provides().getVirtualPageMap().toGlobal(e.anchor.chapterId,e.anchor.localPageIndex);if(!t)return;s=t.globalPageIndex}const i=function(t){if(t.markerAnchor)return t.markerAnchor.y;const e=t.rectPdfCoord;return e.origin.y+e.size.height}(e.anchor);await async function(t,e,a){t.scrollToGlobalPageIndex(e),await function(t,e,a=2500){const s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const i=setTimeout(()=>{r(),s(null)},a),r=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(i),r(),s(a))})})}(t,e),t.scrollToGlobalPdfPoint(e,a,{marginTop:80})}(a,s,i)}};pt.id="paragraph-bookmark";let gt=pt;function ft({chapterId:s,localPageIndex:i,pdfPageWidth:r,pdfPageHeight:o,cssPageWidth:n,cssPageHeight:h,onBookmarkClick:l,ui:d,className:c,style:u}){const{provides:p}=a.useCapability(gt.id),[g,f]=e.useState([]),[m,v]=e.useState(null),b=e.useRef(null);if(e.useEffect(()=>{if(!p)return;const t=()=>{f(p.listBookmarks().filter(t=>t.anchor.chapterId===s&&t.anchor.localPageIndex===i))};return t(),p.onBookmarksChange(t)},[p,s,i]),e.useEffect(()=>{if(!m)return;const t=t=>{var e;(null==(e=b.current)?void 0:e.contains(t.target))||v(null)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[m]),!p||0===g.length||!r||!o)return null;const P=n/r,w=h/o,I=(null==d?void 0:d.iconSize)??16;return t.jsx("div",{className:c,style:{position:"absolute",inset:0,pointerEvents:"none",...u},children:g.map(e=>{var a;const s=(null==(a=e.anchor.rectsPdfCoord)?void 0:a.length)?e.anchor.rectsPdfCoord:[e.anchor.rectPdfCoord],i=e.anchor.markerAnchor??{x:e.anchor.rectPdfCoord.origin.x+e.anchor.rectPdfCoord.size.width,y:e.anchor.rectPdfCoord.origin.y+e.anchor.rectPdfCoord.size.height},{left:r,top:o}=function(t){const{markerPdf:e,lineRects:a,sx:s,sy:i,cssPageWidth:r,iconSize:o,gapPx:n=6}=t,h=(null==a?void 0:a.length)?a[a.length-1]:void 0;let l,d;h?(l=(h.origin.x+h.size.width)*s+n,d=h.origin.y*i+(h.size.height*i-o)/2):(l=e.x*s-o/2,d=e.y*i-o-n);const c=Math.max(0,r-o-2);return l>c&&(l=c),d<0&&(d=0),{left:l,top:d}}({markerPdf:i,lineRects:s,sx:P,sy:w,cssPageWidth:n,iconSize:I}),h=Math.max(0,r-6),c=Math.max(0,o-6);return t.jsxs("div",{style:{position:"absolute",left:`${h}px`,top:`${c}px`,width:`${I+12}px`,height:`${I+12}px`,pointerEvents:"auto",zIndex:20},onMouseDown:t=>t.stopPropagation(),children:[(null==d?void 0:d.renderIcon)?t.jsx("div",{role:"button",tabIndex:0,title:e.label,"aria-label":`bookmark ${e.label}`,style:{position:"absolute",left:"6px",top:"6px",width:`${I}px`,height:`${I}px`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",padding:0},onClick:t=>{t.stopPropagation(),v(t=>t===e.id?null:e.id),null==l||l(e)},children:d.renderIcon({bookmark:e})}):t.jsx("button",{type:"button",title:e.label,onClick:t=>{t.stopPropagation(),v(t=>t===e.id?null:e.id),null==l||l(e)},style:{position:"absolute",left:"6px",top:"6px",width:`${I}px`,height:`${I}px`,border:"none",borderRadius:"4px",background:"#3b82f6",color:"#fff",cursor:"pointer",boxShadow:"0 2px 6px rgba(37, 99, 235, 0.35)",padding:0,display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",lineHeight:1},"aria-label":`bookmark ${e.label}`,children:"🔖"}),m===e.id&&t.jsx("div",{ref:b,style:{position:"absolute",left:"6px",top:"-36px",zIndex:30,pointerEvents:"auto",minWidth:"88px",padding:"4px",borderRadius:"6px",background:"#fff",border:"1px solid #e5e7eb",boxShadow:"0 4px 12px rgba(0,0,0,0.12)"},onClick:t=>t.stopPropagation(),children:t.jsx("button",{type:"button",style:{width:"100%",padding:"6px 8px",fontSize:"12px",border:"none",borderRadius:"4px",background:"transparent",color:"#dc2626",cursor:"pointer",textAlign:"left"},onClick:()=>{p.requestRemoveBookmark(e.id).then(t=>{t&&v(null)})},children:"删除书签"})})]},e.id)})})}function mt(t){return t.chapterId}function vt(t,e){t.wait(e,()=>{})}const bt="note",Pt={id:bt,name:"Note Plugin",version:"0.1.0",provides:["note"],requires:["selection","chapter-scroll","chapter-manager"],optional:[],defaultConfig:{callbacks:{onCreateNote:async()=>null,onActivateNote:()=>{}},markerSize:18}},wt={kind:"first-wins"};function It(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let yt=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const Ct=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=wt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??wt,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=wt){const a=function(t,e=wt){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,It(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new yt(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Ct.id="chapter-manager";let Mt=Ct;const St={kind:"first-wins"};function xt(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Lt=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const $t=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=St,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??St,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=St){const a=function(t,e=St){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,xt(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Lt(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};$t.id="chapter-manager";let Dt=$t;const kt=class extends d.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=d.createBehaviorEmitter(),this.visibleChange$=d.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Dt.id),this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){if(!this.chapterManager.provides().getChapter(t))return!1;const e=this.documentManager.provides().getDocumentState(t);return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){if(!this.chapterManager.provides().getChapter(t))return;const e=this.documentManager.provides();e.getActiveDocumentId()||e.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){this.chapterManager.provides().getChapter(t)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};kt.id="chapter-scroll";let Tt=kt;const zt=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.notesChange$=d.createBehaviorEmitter([]),this.noteActivated$=d.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(Tt.id),this.chapterManager=this.registry.getPlugin(Mt.id),this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,e.callbacks.loadNotes)try{const t=await e.callbacks.loadNotes();for(const e of t)this.notes.set(e.noteId,e);this.notesChange$.emit(this.listAll())}catch(a){this.logger.error(t.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:t=>this.createNoteFromSelection(t),requestCreateFromSelection:t=>this.requestCreateFromSelection(t),registerNote:t=>this.registerNote(t),listNotesForPage:(t,e)=>this.listAll().filter(a=>a.chapterId===t&&a.localPageIndex===e),listAllNotes:()=>this.listAll(),getNote:t=>this.notes.get(t)??null,deleteNote:t=>this.deleteNote(t),updateNoteContent:(t,e)=>this.updateNoteContent(t,e),scrollToNote:t=>this.scrollToNote(t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(t){this.notes.set(t.noteId,t),this.notesChange$.emit(this.listAll())}requestEdit(t){const e=this.notes.get(t);e&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(t,e):this.activateNote(t))}activateNote(t){var e,a;const s=this.notes.get(t);s&&(null==(a=(e=this.config.callbacks).onActivateNote)||a.call(e,t,s),this.noteActivated$.emit({noteId:t,anchor:s}))}listAll(){return Array.from(this.notes.values())}buildDraft(t){return{chapterId:t.chapterId,localPageIndex:t.localPageIndex,globalPageNumber:t.globalPageNumber,globalPageIndex:t.globalPageIndex,rectsPdfCoord:t.rectsPdfCoord,endAnchor:Ot(t.rectsPdfCoord),selectedText:t.selectedText,content:t.content}}async requestCreateFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const e=this.buildDraft(t),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:e,complete:async t=>{const a={...e,noteId:t};this.registerNote(a)}}),null):this.createNoteFromSelection(t)}async createNoteFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const a=this.buildDraft(e),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(t.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let i=null;try{i=await s(a)}catch(o){return this.logger.error(t.id,"OnCreateNote","Callback failed",o),null}if(!i)return null;const r={...a,noteId:i.noteId};return this.registerNote(r),r}async deleteNote(e){var a,s;if(this.notes.has(e)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,e))}catch(i){return void this.logger.error(t.id,"OnDeleteNote","Callback failed",i)}this.notes.delete(e),this.notesChange$.emit(this.listAll())}}async updateNoteContent(e,a){var s,i;const r=this.notes.get(e);if(!r)return;const o={...r,content:a};try{await(null==(i=(s=this.config.callbacks).onUpdateNote)?void 0:i.call(s,o))}catch(n){return void this.logger.error(t.id,"OnUpdateNote","Callback failed",n)}this.notes.set(e,o),this.notesChange$.emit(this.listAll())}async scrollToNote(t){var e;const a=this.notes.get(t);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(e=this.documentManager.provides().getDocument(a.chapterId))?void 0:e.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(t){const e=this.chapterScroll.provides(),a=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{i(),a(null)},2500),i=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(s),i(),a(r))})})}};zt.id="note";let Gt=zt;function Ot(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}const At={manifest:Pt,create:t=>new Gt(bt,t),reducer:t=>t,initialState:{}},Nt="paragraph-bookmark",Et={id:Nt,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}},Rt={kind:"first-wins"};function Vt(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let _t=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const Ut=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=Rt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Rt,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Rt){const a=function(t,e=Rt){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Vt(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new _t(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Ut.id="chapter-manager";let Ft=Ut;const qt={kind:"first-wins"};function Bt(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class jt{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}const Wt=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=qt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??qt,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=qt){const a=function(t,e=qt){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Bt(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new jt(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Wt.id="chapter-manager";let Ht=Wt;const Yt=class extends d.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=d.createBehaviorEmitter(),this.visibleChange$=d.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Ht.id),this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){if(!this.chapterManager.provides().getChapter(t))return!1;const e=this.documentManager.provides().getDocumentState(t);return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){if(!this.chapterManager.provides().getChapter(t))return;const e=this.documentManager.provides();e.getActiveDocumentId()||e.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){this.chapterManager.provides().getChapter(t)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};Yt.id="chapter-scroll";let Kt=Yt;function Xt(t){if(0===t.length)throw new Error("unionRects: empty rects");let e=1/0,a=1/0,s=-1/0,i=-1/0;for(const r of t)e=Math.min(e,r.origin.x),a=Math.min(a,r.origin.y),s=Math.max(s,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:e,y:a},size:{width:s-e,height:i-a}}}function Zt(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function Qt(t,e){const a=t.origin.y,s=t.origin.y+t.size.height,i=e.origin.y,r=e.origin.y+e.size.height,o=Math.max(s,r)-Math.min(a,i);return o<=0?0:Math.max(0,Math.min(s,r)-Math.max(a,i))/o}function Jt(t,e){var a,s;if(t.chapterId!==e.chapterId||t.localPageIndex!==e.localPageIndex)return!1;const i=(null==(a=t.rectsPdfCoord)?void 0:a.length)?t.rectsPdfCoord:[t.rectPdfCoord],r=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],o=t.markerAnchor??Zt(i),n=e.markerAnchor??Zt(r);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const h of i)for(const t of r){if(Qt(h,t)<.5)continue;const e=Math.max(h.origin.x,t.origin.x);if(Math.min(h.origin.x+h.size.width,t.origin.x+t.size.width)-e>.25*Math.min(h.size.width,t.size.width))return!0}return!1}const te=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.change$=d.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(Kt.id),this.chapterManager=this.registry.getPlugin(Ft.id),this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(e){var a;if(this.config=e,null==(a=e.callbacks)?void 0:a.load)try{const t=await e.callbacks.load();for(const e of t)this.entries.set(e.id,e);this.change$.emit(this.list())}catch(s){this.logger.error(t.id,"Load","Failed to load paragraph bookmarks",s)}}buildCapability(){return{addBookmark:t=>this.addBookmark(t),removeBookmark:t=>this.removeBookmark(t),updateBookmark:(t,e)=>this.updateBookmark(t,e),listBookmarks:()=>this.list(),getBookmark:t=>this.entries.get(t)??null,scrollToBookmark:t=>this.scrollToBookmark(t),requestRemoveBookmark:t=>this.requestRemoveBookmark(t),onBookmarksChange:this.change$.on}}addBookmark(t){for(const s of this.entries.values())if(Jt(s.anchor,t.anchor))return s;const e=t.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:e,label:t.label,anchor:t.anchor,metadata:t.metadata,createdAt:Date.now()};return this.entries.set(e,a),this.notifyAndPersist(),a}removeBookmark(t){var e,a,s;this.entries.delete(t)&&(this.notifyAndPersist(),null==(s=null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,t))}async requestRemoveBookmark(e){var a,s;const i=this.entries.get(e);if(!i)return!1;const r=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(r)try{if(!(await r(i)))return!1}catch(o){return this.logger.error(t.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(e),!0}updateBookmark(t,e){const a=this.entries.get(t);a&&(this.entries.set(t,{...a,...e}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((t,e)=>t.createdAt-e.createdAt)}notifyAndPersist(){var e,a;const s=this.list();this.change$.emit(s),(null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.persist)&&Promise.resolve(this.config.callbacks.persist(s)).catch(e=>this.logger.error(t.id,"Persist","persist callback rejected",e))}async scrollToBookmark(t){const e=this.entries.get(t);if(!e)return;const a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(e.anchor.chapterId);let s=e.anchor.globalPageIndex;if(void 0===s){const t=this.chapterManager.provides().getVirtualPageMap().toGlobal(e.anchor.chapterId,e.anchor.localPageIndex);if(!t)return;s=t.globalPageIndex}const i=function(t){if(t.markerAnchor)return t.markerAnchor.y;const e=t.rectPdfCoord;return e.origin.y+e.size.height}(e.anchor);await async function(t,e,a){t.scrollToGlobalPageIndex(e),await function(t,e,a=2500){const s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const i=setTimeout(()=>{r(),s(null)},a),r=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(i),r(),s(a))})})}(t,e),t.scrollToGlobalPdfPoint(e,a,{marginTop:80})}(a,s,i)}};te.id="paragraph-bookmark";let ee=te;const ae={manifest:Et,create:t=>new ee(Nt,t),reducer:t=>t,initialState:{}};function se({item:s,pdfPageWidth:i,pdfPageHeight:r,cssPageWidth:n,cssPageHeight:h,hoverUi:l}){const d=mt(s),{provides:c}=a.useCapability(o.SelectionPlugin.id),{provides:u}=a.useCapability(ee.id),p=e.useRef(null),[g,f]=e.useState(null),[m,v]=e.useState(null),[b,P]=e.useState(null),w=(null==l?void 0:l.iconSize)??16;e.useEffect(()=>{if(!c)return;const t=c.forDocument(d),e=()=>{const e=t.getState().geometry[s.localPageIndex];e&&f(e)},a=t.onSelectionChange(e);let i=!1;const r=()=>{if(!i){try{if(e(),t.getState().geometry[s.localPageIndex])return}catch{}requestAnimationFrame(r)}};return r(),()=>{i=!0,a()}},[c,d,s.localPageIndex]);const I=b??m;e.useEffect(()=>{if(!g||!i)return;const t=t=>{if(b)return;if(c)try{if(c.forDocument(d).getState().selecting)return void v(null)}catch{}const e=p.current;if(!e)return;const a=e.getBoundingClientRect();if(t.clientX<a.left||t.clientX>a.right||t.clientY<a.top||t.clientY>a.bottom)return void v(null);const s=function(t,e){const a=o.glyphAt(t,e);if(a<0)return null;const s=o.expandToLineBoundary(t,a);if(!s)return null;const i=o.rectsWithinSlice(t,s.from,s.to);return 0===i.length?null:{lineRects:i,charFrom:s.from,charTo:s.to}}(g,{x:(t.clientX-a.left)/(n/i),y:(t.clientY-a.top)/(h/r)});v((null==s?void 0:s.lineRects)??null)};return document.addEventListener("mousemove",t),()=>document.removeEventListener("mousemove",t)},[g,i,r,n,h,c,d,b]);const y=(null==I?void 0:I.length)?function(t,e,a,s){const i=a.length>0?a:[];if(0===i.length)throw new Error("buildParagraphBookmarkAnchor: no rects");return{chapterId:t,localPageIndex:e,globalPageIndex:null==s?void 0:s.globalPageIndex,globalPageNumber:null==s?void 0:s.globalPageNumber,rectPdfCoord:Xt(i),rectsPdfCoord:i,markerAnchor:Zt(i)}}(s.chapterId,s.localPageIndex,I,{globalPageIndex:s.globalPageIndex,globalPageNumber:s.globalPageNumber}):null,C=y&&(null==u?void 0:u.listBookmarks().some(t=>Jt(t.anchor,y))),M=e.useCallback(()=>{u&&y&&!C&&(u.addBookmark({label:`书签 ${(new Date).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"})}`,anchor:y}),v(null),P(null))},[u,y,C]);if(!u||!i||!r)return null;const S=n/i,x=h/r,L=null==I?void 0:I[I.length-1],$=L?Math.min((L.origin.x+L.size.width)*S+6,Math.max(0,n-w-2)):0,D=L?L.origin.y*x+(L.size.height*x-w)/2:0,k=L?Math.max(0,(L.origin.x+L.size.width)*S-4):0,T=L?Math.max(0,L.origin.y*x-4):0;return t.jsx("div",{ref:p,style:{position:"absolute",inset:0,zIndex:14,pointerEvents:"none"},children:I&&L&&!C&&t.jsx("div",{style:{position:"absolute",left:`${k}px`,top:`${T}px`,width:`${w+20}px`,height:`${L.size.height*x+w+12}px`,pointerEvents:"auto"},onMouseEnter:()=>P(I),onMouseLeave:()=>P(null),children:(null==l?void 0:l.renderAddIcon)?t.jsx("div",{role:"button",tabIndex:0,title:"添加书签",onClick:t=>{t.stopPropagation(),M()},style:{position:"absolute",left:$-k+"px",top:D-T+"px",width:w,height:w,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",padding:0},children:l.renderAddIcon()}):t.jsx("button",{type:"button",title:"添加书签",onClick:t=>{t.stopPropagation(),M()},style:{position:"absolute",left:$-k+"px",top:D-T+"px",width:`${w}px`,height:`${w}px`,border:"none",borderRadius:"4px",background:"#3b82f6",color:"#fff",cursor:"pointer",boxShadow:"0 2px 8px rgba(37, 99, 235, 0.45)",fontSize:"12px",lineHeight:1,padding:0,display:"flex",alignItems:"center",justifyContent:"center"},children:"🔖"})})})}const ie={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:0},strikeout:{offsetY:0}},re={highlight:c.PdfAnnotationSubtype.HIGHLIGHT,underline:c.PdfAnnotationSubtype.UNDERLINE,squiggly:c.PdfAnnotationSubtype.SQUIGGLY,strikeout:c.PdfAnnotationSubtype.STRIKEOUT};function oe(t,e){return 0===e?t:t.map(t=>({origin:{x:t.origin.x,y:t.origin.y+e},size:{...t.size}}))}function ne(t){let e=1/0,a=1/0,s=-1/0,i=-1/0;for(const r of t)e=Math.min(e,r.origin.x),a=Math.min(a,r.origin.y),s=Math.max(s,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:e,y:a},size:{width:s-e,height:i-a}}}const he=[{id:"highlight",label:"高亮背景",icon:t.jsx(ue,{})},{id:"underline",label:"下划线",icon:t.jsx(pe,{})},{id:"squiggly",label:"波浪线",icon:t.jsx(ge,{})},{id:"strikeout",label:"删除线",icon:t.jsx(fe,{})},{id:"note",label:"添加笔记",icon:t.jsx(me,{})}];function le({placementAbove:e,anchorHeight:a,onAction:s,hiddenBuiltinActions:i=[],extraActions:r=[]}){const o=new Set(i),n=he.filter(t=>"note"!==t.id&&!o.has(t.id)),h=he.find(t=>"note"===t.id),l=h&&!o.has("note"),d=[...r].sort((t,e)=>(t.order??0)-(e.order??0));return t.jsxs("div",{style:{position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:e?void 0:a+10,bottom:e?a+10:void 0,display:"flex",alignItems:"center",gap:2,padding:"6px 8px",borderRadius:10,background:"#ffffff",border:"1px solid rgba(15, 23, 42, 0.08)",boxShadow:"0 4px 6px -1px rgba(15, 23, 42, 0.08), 0 10px 24px -4px rgba(15, 23, 42, 0.12)"},role:"toolbar","aria-label":"选区工具",children:[n.map(e=>t.jsx(de,{label:e.label,onClick:()=>s(e.id),children:e.icon},e.id)),d.map(e=>t.jsx(de,{label:e.label,onClick:()=>s(e.id),children:t.jsx("span",{style:{fontSize:11,fontWeight:600},children:e.label.slice(0,2)})},e.id)),l&&t.jsxs(t.Fragment,{children:[t.jsx("span",{style:{width:1,height:28,margin:"0 4px",background:"#e2e8f0",flexShrink:0},"aria-hidden":!0}),t.jsx(de,{label:h.label,onClick:()=>s("note"),accent:!0,children:h.icon})]})]})}function de({label:e,onClick:a,accent:s,children:i}){return t.jsx("button",{type:"button",title:e,"aria-label":e,onClick:a,style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,border:"none",borderRadius:8,background:"transparent",color:s?"#b45309":"#334155",cursor:"pointer"},onMouseEnter:t=>{t.currentTarget.style.background=s?"#fffbeb":"#f1f5f9"},onMouseLeave:t=>{t.currentTarget.style.background="transparent"},children:i})}function ce({behind:e,mark:a}){return t.jsxs("svg",{width:"28",height:"28",viewBox:"0 0 28 28",fill:"none","aria-hidden":!0,children:[e,t.jsx("text",{x:"14",y:"19",textAnchor:"middle",fontSize:"15",fontWeight:"700",fontFamily:"system-ui, sans-serif",fill:"#0f172a",children:"A"}),a]})}function ue(){return t.jsx(ce,{behind:t.jsx("rect",{x:"5",y:"4",width:"18",height:"20",rx:"3",fill:"#facc15"})})}function pe(){return t.jsx(ce,{mark:t.jsx("path",{d:"M6 22h16",stroke:"#dc2626",strokeWidth:"2.2",strokeLinecap:"round"})})}function ge(){return t.jsx(ce,{mark:t.jsx("path",{d:"M6 22c2-2 3-2 5 0s3 2 5 0 3-2 5 0",stroke:"#dc2626",strokeWidth:"2",strokeLinecap:"round",fill:"none"})})}function fe(){return t.jsx(ce,{mark:t.jsx("path",{d:"M5 14h18",stroke:"#dc2626",strokeWidth:"2.2",strokeLinecap:"round"})})}function me(){return t.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:[t.jsx("path",{d:"M8 3h8l4 4v14H8V3z",fill:"#fef3c7",stroke:"#d97706",strokeWidth:"1.2",strokeLinejoin:"round"}),t.jsx("path",{d:"M16 3v4h4",stroke:"#d97706",strokeWidth:"1.2"}),t.jsx("path",{d:"M10 12h6M10 16h4",stroke:"#92400e",strokeWidth:"1.2",strokeLinecap:"round"})]})}const ve={highlight:"highlight",underline:"underline",squiggly:"squiggly",strikeout:"strikeout"};function be(s,i){var r,n,h,l;const d=null==s?void 0:s.selectionToolbar,u=!1!==(null==(r=null==s?void 0:s.markup)?void 0:r.enabled),g=!1!==(null==(n=null==s?void 0:s.notes)?void 0:n.enabled);if(!1===(null==d?void 0:d.enabled))return;if(!u&&!g&&!(null==(h=null==d?void 0:d.extraActions)?void 0:h.length))return;const{provides:f}=a.useCapability(o.SelectionPlugin.id),{provides:m}=a.useCapability(p.AnnotationPlugin.id),{provides:v}=a.useCapability(Gt.id);return e.useMemo(()=>e=>{const a=mt(e.item);return r=>{var o;return t.jsx("div",{...r.menuWrapperProps,children:t.jsx(le,{placementAbove:!!(null==(o=r.placement)?void 0:o.suggestTop),anchorHeight:r.rect.size.height,onAction:t=>{var r,o;if("highlight"!==t&&"underline"!==t&&"squiggly"!==t&&"strikeout"!==t){if("note"===t){if(!f||!v||!g)return;const t=f.getHighlightRectsForPage(e.item.localPageIndex,a);return void vt(f.getSelectedText(a),a=>{v.requestCreateFromSelection({chapterId:e.item.chapterId,localPageIndex:e.item.localPageIndex,globalPageIndex:e.item.globalPageIndex,globalPageNumber:e.item.globalPageNumber,rectsPdfCoord:t,selectedText:a.join("\n")})})}null==(r=null==i?void 0:i.onExtraAction)||r.call(i,t,e)}else{if(!f||!m||!u)return;!function(t,e,a,s,i){const r=a.forDocument(t),o=s.forDocument(t);if(!r||!o)return!1;const n="highlight"===e?"highlight":"underline"===e?"underline":"squiggly"===e?"squiggly":"strikeout",h=a.getTool(n);if(!h)return!1;const l=h.defaults,d={...ie[g=e],...null==(f=i)?void 0:f[g]},u=o.getFormattedSelection();var g,f;if(0===u.length)return!1;r.setLocked({type:p.LockModeType.Exclude,categories:["markup","shape"]});for(const p of u){const t=c.uuidV4(),a=d.color??l.color??l.strokeColor,s=d.opacity??l.opacity,i=d.thickness??l.strokeWidth,o=d.offsetY??0,n="underline"===e||"squiggly"===e||"strikeout"===e?oe(p.segmentRects,o):p.segmentRects,h="underline"===e||"squiggly"===e||"strikeout"===e?ne(n):p.rect;r.createAnnotation(p.pageIndex,{id:t,created:new Date,flags:["print"],type:re[e],..."highlight"===e?{blendMode:c.PdfBlendMode.Multiply}:{},strokeColor:a,opacity:s,...null!=i?{strokeWidth:i}:{},pageIndex:p.pageIndex,rect:h,segmentRects:n})}o.clear()}(a,ve[t],m,f,null==(o=null==s?void 0:s.markup)?void 0:o.styles)}},hiddenBuiltinActions:null==d?void 0:d.hiddenBuiltinActions,extraActions:null==d?void 0:d.extraActions})})}},[m,null==(l=null==s?void 0:s.markup)?void 0:l.styles,null==i?void 0:i.onExtraAction,u,v,g,f,null==d?void 0:d.extraActions,null==d?void 0:d.hiddenBuiltinActions])}function Pe({className:s,buildSelectionMenu:i,annotationSelectionMenu:r,redactionSelectionMenu:o,showNoteMarkers:n=!0,showBookmarkMarkers:h=!0,showRedactionLayer:l=!1,renderPageOverlay:d,features:c,onExtraSelectionAction:u,children:p}){var g,f,m,v;const b=function(){const{registry:t}=a.useRegistry();return e.useMemo(()=>{var e,a;const s=null==(a=null==(e=null==t?void 0:t.getPlugin(Gt.id))?void 0:e.provides)?void 0:a.call(e);return s?t=>s.createNoteFromSelection(t):null},[t])}(),P=function(){const{registry:t}=a.useRegistry();return!!(null==t?void 0:t.getPlugin(Gt.id))}(),w=function(){const{registry:t}=a.useRegistry();return!!(null==t?void 0:t.getPlugin(ee.id))}(),I=n&&P&&!1!==(null==(g=null==c?void 0:c.notes)?void 0:g.enabled),y=h&&w&&!1!==(null==(f=null==c?void 0:c.bookmarks)?void 0:f.enabled),C=w&&!1!==(null==(m=null==c?void 0:c.bookmarks)?void 0:m.enabled),M=be(c,{onExtraAction:u}),S=e.useMemo(()=>{if(i||M)return t=>{const e=M?M(t):t.defaultMenu;return i?i({...t,defaultMenu:e}):e}},[i,M]),x=e.useMemo(()=>d||C?e=>{var a;return t.jsxs(t.Fragment,{children:[C&&t.jsx(we,{item:e,hoverUi:null==(a=null==c?void 0:c.bookmarks)?void 0:a.hover}),null==d?void 0:d(e)]})}:d,[null==(v=null==c?void 0:c.bookmarks)?void 0:v.hover,C,d]);return t.jsxs("div",{className:s??"relative h-full w-full",children:[t.jsx(G,{renderPage:e=>{var a,s;return t.jsx(Ie,{item:e,showNoteMarkers:I,showBookmarkMarkers:y,noteMarkerUi:null==(a=null==c?void 0:c.notes)?void 0:a.marker,bookmarkMarkerUi:null==(s=null==c?void 0:c.bookmarks)?void 0:s.marker,renderPageOverlay:x,buildSelectionMenu:S,createNote:b,annotationSelectionMenu:r,redactionSelectionMenu:o,showRedactionLayer:l})}}),p]})}function we({item:s,hoverUi:i}){const{provides:r}=a.useCapability(l.DocumentManagerPlugin.id),o=mt(s),n=e.useMemo(()=>{var t;return null==(t=null==r?void 0:r.getDocument(o))?void 0:t.pages[s.localPageIndex]},[r,o,s.localPageIndex]);return s.isPlaceholder||!n?null:t.jsx(se,{item:s,pdfPageWidth:n.size.width,pdfPageHeight:n.size.height,cssPageWidth:s.width,cssPageHeight:s.height,hoverUi:i})}function Ie({item:d,showNoteMarkers:c,showBookmarkMarkers:u,noteMarkerUi:p,bookmarkMarkerUi:g,renderPageOverlay:f,createNote:m,buildSelectionMenu:v,annotationSelectionMenu:b,redactionSelectionMenu:P,showRedactionLayer:w=!1}){const I=mt(d);!function(t){const{provides:s}=a.useCapability(l.DocumentManagerPlugin.id);e.useEffect(()=>{s&&t&&s.isDocumentOpen(t)&&s.setActiveDocument(t)},[s,t])}(I);const{provides:y}=a.useCapability(l.DocumentManagerPlugin.id),C=e.useMemo(()=>{const t=null==y?void 0:y.getDocument(I);return null==t?void 0:t.pages[d.localPageIndex]},[y,I,d.localPageIndex]),M=function(s,i){const{provides:r}=a.useCapability(o.SelectionPlugin.id),n=mt(s);return e.useMemo(()=>{if(i)return e=>{var a;const o={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==(a=e.placement)?void 0:a.suggestTop)?-40:e.rect.size.height+8};return t.jsx("div",{...e.menuWrapperProps,children:t.jsx("div",{style:o,children:t.jsx("button",{type:"button",onClick:()=>{if(!r)return;const t=r.getHighlightRectsForPage(s.localPageIndex,n);vt(r.getSelectedText(n),e=>{const a=e.join("\n"),r=function(t,e,a){return{chapterId:t.chapterId,localPageIndex:t.localPageIndex,globalPageIndex:t.globalPageIndex,globalPageNumber:t.globalPageNumber,rectsPdfCoord:e,selectedText:a}}(s,t,a);i(r)})},style:{padding:"6px 10px",fontSize:"12px",border:"1px solid #e5e7eb",borderRadius:"6px",background:"#fff",cursor:"pointer",boxShadow:"0 2px 8px rgba(0,0,0,0.08)"},children:"添加附注"})})})}},[i,n,s,r])}(d,m),S=void 0!==v?v({item:d,defaultMenu:M,createNote:m}):M;return d.isPlaceholder?null:t.jsx(s.GlobalPointerProvider,{documentId:I,children:t.jsx(i.Rotate,{documentId:I,pageIndex:d.localPageIndex,style:{backgroundColor:"#fff"},children:t.jsxs(s.PagePointerProvider,{documentId:I,pageIndex:d.localPageIndex,children:[t.jsx(O,{chapterId:I,localPageIndex:d.localPageIndex}),t.jsx(r.SelectionLayer,{documentId:I,pageIndex:d.localPageIndex,selectionMenu:S}),w&&t.jsx(h.RedactionLayer,{documentId:I,pageIndex:d.localPageIndex,selectionMenu:P}),t.jsx(n.AnnotationLayer,{documentId:I,pageIndex:d.localPageIndex,selectionMenu:b}),u&&C&&t.jsx(ft,{chapterId:I,localPageIndex:d.localPageIndex,pdfPageWidth:C.size.width,pdfPageHeight:C.size.height,cssPageWidth:d.width,cssPageHeight:d.height,ui:g}),null==f?void 0:f(d),c&&C&&t.jsx(X,{chapterId:I,localPageIndex:d.localPageIndex,pdfPageWidth:C.size.width,pdfPageHeight:C.size.height,cssPageWidth:d.width,cssPageHeight:d.height,ui:p})]})})})}const ye="chapter-manager",Ce={id:ye,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}},Me={kind:"first-wins"};function Se(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let xe=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const Le=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=Me,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Me,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Me){const a=function(t,e=Me){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Se(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new xe(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Le.id="chapter-manager";let $e=Le;const De={manifest:Ce,create:t=>new $e(ye,t),reducer:t=>t,initialState:{}},ke="chapter-scroll",Te={id:ke,name:"Chapter Scroll Plugin",version:"0.1.0",provides:["chapter-scroll"],requires:["chapter-manager"],optional:[],defaultConfig:{placeholderPageHeight:1200,placeholderPageWidth:900,bufferSize:2,pageGap:20}},ze={kind:"first-wins"};function Ge(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class Oe{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}const Ae=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=ze,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??ze,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=ze){const a=function(t,e=ze){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Ge(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Oe(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Ae.id="chapter-manager";let Ne=Ae;const Ee=class extends d.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=d.createBehaviorEmitter(),this.visibleChange$=d.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Ne.id),this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){if(!this.chapterManager.provides().getChapter(t))return!1;const e=this.documentManager.provides().getDocumentState(t);return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){if(!this.chapterManager.provides().getChapter(t))return;const e=this.documentManager.provides();e.getActiveDocumentId()||e.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){this.chapterManager.provides().getChapter(t)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};Ee.id="chapter-scroll";let Re=Ee;const Ve={manifest:Te,create:t=>new Re(ke,t),reducer:t=>t,initialState:{}},_e={"annotation-toolbar":{id:"annotation-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"],show:["overflow-annotation-tools"]},md:{minWidth:640,hide:["overflow-annotation-tools"],show:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"]}}},permanent:!1,categories:["annotation"],items:[{type:"spacer",id:"spacer-3",flex:!0},{type:"group",id:"annotation-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-highlight",commandId:"annotation:add-highlight",variant:"icon",categories:["annotation","annotation-markup","annotation-highlight"]},{type:"command-button",id:"add-strikeout",commandId:"annotation:add-strikeout",variant:"icon",categories:["annotation","annotation-markup","annotation-strikeout"]},{type:"command-button",id:"add-underline",commandId:"annotation:add-underline",variant:"icon",categories:["annotation","annotation-markup","annotation-underline"]},{type:"command-button",id:"add-squiggly",commandId:"annotation:add-squiggly",variant:"icon",categories:["annotation","annotation-markup","annotation-squiggly"]},{type:"command-button",id:"add-ink",commandId:"annotation:add-ink",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-ink-highlighter",commandId:"annotation:add-ink-highlighter",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-text",commandId:"annotation:add-text",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"add-insert-text",commandId:"annotation:add-insert-text",variant:"icon",categories:["annotation","annotation-markup","annotation-insert-text"]},{type:"command-button",id:"add-replace-text",commandId:"annotation:add-replace-text",variant:"icon",categories:["annotation","annotation-markup","annotation-replace-text"]},{type:"command-button",id:"add-comment",commandId:"annotation:add-comment",variant:"icon",categories:["annotation","annotation-comment-tool"]},{type:"command-button",id:"add-callout",commandId:"annotation:add-callout",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"overflow-annotation-tools",commandId:"annotation:overflow-tools",variant:"icon",categories:["annotation","annotation-overflow"]},{type:"divider",id:"annotation-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"annotation-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-4",flex:!0}]},"shapes-toolbar":{id:"shapes-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-polygon","add-polyline"],show:["overflow-shapes-tools"]},md:{minWidth:640,hide:["overflow-shapes-tools"],show:["add-polygon","add-polyline"]}}},permanent:!1,categories:["annotation","annotation-shape"],items:[{type:"spacer",id:"spacer-5",flex:!0},{type:"group",id:"shapes-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rectangle",commandId:"annotation:add-rectangle",variant:"icon",categories:["annotation","annotation-shape","annotation-rectangle"]},{type:"command-button",id:"add-circle",commandId:"annotation:add-circle",variant:"icon",categories:["annotation","annotation-shape","annotation-circle"]},{type:"command-button",id:"add-line",commandId:"annotation:add-line",variant:"icon",categories:["annotation","annotation-shape","annotation-line"]},{type:"command-button",id:"add-arrow",commandId:"annotation:add-arrow",variant:"icon",categories:["annotation","annotation-shape","annotation-arrow"]},{type:"command-button",id:"add-polygon",commandId:"annotation:add-polygon",variant:"icon",categories:["annotation","annotation-shape","annotation-polygon"]},{type:"command-button",id:"add-polyline",commandId:"annotation:add-polyline",variant:"icon",categories:["annotation","annotation-shape","annotation-polyline"]},{type:"command-button",id:"overflow-shapes-tools",commandId:"annotation:overflow-shapes",variant:"icon",categories:["annotation","annotation-shape","annotation-overflow"]},{type:"divider",id:"shapes-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"shapes-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-6",flex:!0}]},"form-toolbar":{id:"form-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-form-select","add-form-listbox"],show:["overflow-forms-tools"]},md:{minWidth:640,hide:["overflow-forms-tools"],show:["add-form-select","add-form-listbox"]}}},permanent:!1,categories:["form"],items:[{type:"spacer",id:"spacer-form-1",flex:!0},{type:"group",id:"form-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-form-textfield",commandId:"form:add-textfield",variant:"icon",categories:["form","form-textfield"]},{type:"command-button",id:"add-form-checkbox",commandId:"form:add-checkbox",variant:"icon",categories:["form","form-checkbox"]},{type:"command-button",id:"add-form-radio",commandId:"form:add-radio",variant:"icon",categories:["form","form-radio"]},{type:"command-button",id:"add-form-select",commandId:"form:add-select",variant:"icon",categories:["form","form-select"]},{type:"command-button",id:"add-form-listbox",commandId:"form:add-listbox",variant:"icon",categories:["form","form-listbox"]},{type:"command-button",id:"overflow-forms-tools",commandId:"form:overflow-tools",variant:"icon",categories:["form","form-overflow"]},{type:"divider",id:"form-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"command-button",id:"toggle-form-fill-mode",commandId:"form:toggle-fill-mode",variant:"icon",categories:["form","form-fill-mode"]},{type:"divider",id:"form-tools-divider-2",orientation:"vertical"},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-form-2",flex:!0}]},"insert-toolbar":{id:"insert-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["insert"],items:[{type:"spacer",id:"spacer-insert-1",flex:!0},{type:"group",id:"insert-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rubber-stamp",commandId:"insert:add-rubber-stamp",variant:"icon",categories:["insert","insert-rubber-stamp"]},{type:"command-button",id:"add-signature",commandId:"insert:add-signature",variant:"icon",categories:["insert","insert-signature"]},{type:"command-button",id:"add-image",commandId:"insert:add-image",variant:"icon",categories:["insert","insert-image"]},{type:"divider",id:"insert-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"insert-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-insert-2",flex:!0}]},"redaction-toolbar":{id:"redaction-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["redaction"],items:[{type:"spacer",id:"spacer-7",flex:!0},{type:"group",id:"redaction-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"redact",commandId:"redaction:redact",variant:"icon",categories:["redaction","redaction-combined"]},{type:"divider",id:"redaction-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-redaction-panel",commandId:"panel:toggle-redaction",variant:"icon",categories:["panel","panel-redaction"]},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"redaction-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-8",flex:!0}]}};class Ue{constructor(){this.specs=[]}register(t){if(this.specs.some(e=>e.id===t.id))throw new Error(`OperationRegistry: duplicate operation id "${t.id}"`);this.specs.push(t)}registerAll(t){for(const e of t)e&&this.register(e)}list(){return this.specs}buildToolbars(){const t=structuredClone(_e);for(const e of this.specs){const a=t[e.toolbarSlot];if(!a)continue;const s={type:"command-button",id:e.id,commandId:e.commandId,variant:"icon",...e.icon?{icon:e.icon}:{},...e.i18nKey?{labelKey:e.i18nKey}:{},...e.label?{label:e.label}:{},categories:e.categories??[]};a.items=Fe(a.items,s,e.position)}return t}}function Fe(t,e,a){return(null==a?void 0:a.after)||(null==a?void 0:a.before)?function(t,e,a){const s=t=>{const i=[];for(const r of t)"group"!==r.type?a.before&&r.id===a.before?i.push(e,r):(i.push(r),a.after&&r.id===a.after&&i.push(e)):i.push({...r,items:s(r.items)});return i};return s(t)}(t,e,a):(s=e,t.map(t=>"group"===t.type?{...t,items:[...t.items,s]}:t));var s}const qe={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function Be(t){const e={};for(const a of t)a.handler&&(e[a.commandId]={id:a.commandId,labelKey:a.i18nKey,label:a.label,icon:a.icon,categories:a.categories,action:({documentId:t})=>{var e;null==(e=a.handler)||e.call(a,{documentId:t,chapterId:t})}});return e}const je={markup:{enabled:!0},bookmarks:{enabled:!0},notes:{enabled:!0},selectionToolbar:{enabled:!0},zoom:{enabled:!0,min:.5,max:3,initial:1}};function We(t){var e,a,s,i,r;return function(t){var e,a,s,i,r,n;const h=t.toolbar??{},c=h.enabledModes??["view","annotate","shapes","insert","form","redact"],u=c.length>0,{schema:S,operationRegistry:x}=function(t={}){var e,a,s,i,r,o;const n=new Set(t.enabledModes??["view","annotate","shapes","insert","form","redact"]),h=new Ue;(null==(e=t.customOperations)?void 0:e.length)&&h.registerAll(t.customOperations);const l=h.buildToolbars(),d={};for(const u of n){if("view"===u)continue;const t=qe[u];l[t]&&(d[t]=l[t])}const c=function(t){if(0===t.size)return null;const e=(t,e,a)=>({type:"command-button",id:`${t}-mode`,commandId:a,variant:"text",label:e,categories:["mode",t]});return{id:"chapter-editor-main-toolbar",position:{placement:"top",slot:"main",order:0},permanent:!0,items:[{type:"spacer",id:"main-spacer-left",flex:!0},{type:"group",id:"mode-group",alignment:"start",gap:2,items:[...t.has("view")?[e("view","View","mode:view")]:[],...t.has("annotate")?[e("annotate","Annotate","mode:annotate")]:[],...t.has("shapes")?[e("shapes","Shapes","mode:shapes")]:[],...t.has("insert")?[e("insert","Insert","mode:insert")]:[],...t.has("form")?[e("form","Form","mode:form")]:[],...t.has("redact")?[e("redact","Redact","mode:redact")]:[]]},{type:"spacer",id:"main-spacer-right",flex:!0}]}}(n);return c&&(d["chapter-editor-main-toolbar"]=c),(null==(a=t.extend)?void 0:a.toolbars)&&Object.assign(d,t.extend.toolbars),{schema:{id:"chapter-pdf-editor-ui",version:"1.0.0",toolbars:d,menus:(null==(s=t.extend)?void 0:s.menus)??{},sidebars:(null==(i=t.extend)?void 0:i.sidebars)??{},modals:(null==(r=t.extend)?void 0:r.modals)??{},selectionMenus:(null==(o=t.extend)?void 0:o.selectionMenus)??{}},operationRegistry:h}}({...h,enabledModes:c}),L={...u?{"mode:view":{id:"mode:view",label:"View",categories:["mode","mode-view"],action:({registry:t,documentId:e})=>{var a,s,i,r;const o=null==(a=t.getPlugin("ui"))?void 0:a.provides(),n=null==(s=t.getPlugin("interaction-manager"))?void 0:s.provides();o&&n&&(null==(i=n.forDocument(e))||i.activateDefaultMode(),o.forDocument(e).closeToolbarSlot("top","secondary"),null==(r=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(e).setLocked(t.getPluginConfig(p.ANNOTATION_PLUGIN_ID).locked??{type:p.LockModeType.None}))},active:({state:t,documentId:e})=>!M.isToolbarOpen(t.plugins,e,"top","secondary")},"mode:annotate":{id:"mode:annotate",label:"Annotate",categories:["mode","mode-annotate","annotation"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","annotation-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","annotation-toolbar")},"mode:shapes":{id:"mode:shapes",label:"Shapes",categories:["mode","mode-shapes","annotation"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","shapes-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","shapes-toolbar")},"mode:insert":{id:"mode:insert",label:"Insert",categories:["mode","mode-insert","insert"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","insert-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","insert-toolbar")},"mode:form":{id:"mode:form",label:"Form",categories:["mode","mode-form","form"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","form-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.None}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","form-toolbar")},"mode:redact":{id:"mode:redact",label:"Redact",categories:["mode","mode-redact","redaction"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","redaction-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","redaction-toolbar")}}:{},...u?Be(x.list()):{},...t.commands??{}},$=[d.createPluginRegistration(l.DocumentManagerPluginPackage,{initialDocuments:[]}),d.createPluginRegistration(De,{manifest:t.manifest,overlapStrategy:t.overlapStrategy,passwordProvider:t.passwordProvider,chapterPdfLoader:t.chapterPdfLoader,prefetchChapters:t.prefetchChapters,unloadTimeoutMs:t.unloadTimeoutMs}),d.createPluginRegistration(Ve,{placeholderPageHeight:t.placeholderPageHeight,placeholderPageWidth:t.placeholderPageWidth}),d.createPluginRegistration(g.InteractionManagerPluginPackage),d.createPluginRegistration(f.RenderPluginPackage),d.createPluginRegistration(m.RotatePluginPackage),d.createPluginRegistration(o.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),d.createPluginRegistration(v.HistoryPluginPackage),d.createPluginRegistration(p.AnnotationPluginPackage),d.createPluginRegistration(b.RedactionPluginPackage),d.createPluginRegistration(P.FormPluginPackage),d.createPluginRegistration(w.StampPluginPackage,!1===t.loadDefaultStampLibrary?{manifests:[]}:void 0),d.createPluginRegistration(I.SignaturePluginPackage),...Object.keys(L).length>0?[d.createPluginRegistration(y.CommandsPluginPackage,{commands:L})]:[],...u?[d.createPluginRegistration(C.I18nPluginPackage),d.createPluginRegistration(M.UIPluginPackage,{schema:S})]:[]];return t.notes&&$.push(d.createPluginRegistration(At,{callbacks:t.notes.callbacks,ui:null==(a=null==(e=t.features)?void 0:e.notes)?void 0:a.marker})),t.bookmarks&&$.push(d.createPluginRegistration(ae,{callbacks:t.bookmarks.callbacks,ui:null==(i=null==(s=t.features)?void 0:s.bookmarks)?void 0:i.marker,hover:null==(n=null==(r=t.features)?void 0:r.bookmarks)?void 0:n.hover})),{plugins:$,uiSchema:S,operationRegistry:x}}({...t,toolbar:t.toolbar??{enabledModes:[]},features:{...je,...t.features,markup:{...je.markup,...null==(e=t.features)?void 0:e.markup},bookmarks:{...je.bookmarks,...null==(a=t.features)?void 0:a.bookmarks},notes:{...je.notes,...null==(s=t.features)?void 0:s.notes},selectionToolbar:{...je.selectionToolbar,...null==(i=t.features)?void 0:i.selectionToolbar},zoom:{...je.zoom,...null==(r=t.features)?void 0:r.zoom}}})}function He(t,e,a){return Math.min(a,Math.max(e,t))}const Ye="chapter-manager",Ke={id:Ye,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}},Xe={kind:"first-wins"};function Ze(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Qe=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const Je=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=Xe,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Xe,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Xe){const a=function(t,e=Xe){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Ze(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Qe(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Je.id="chapter-manager";let ta=Je;const ea={manifest:Ke,create:t=>new ta(Ye,t),reducer:t=>t,initialState:{}},aa="chapter-scroll",sa={id:aa,name:"Chapter Scroll Plugin",version:"0.1.0",provides:["chapter-scroll"],requires:["chapter-manager"],optional:[],defaultConfig:{placeholderPageHeight:1200,placeholderPageWidth:900,bufferSize:2,pageGap:20}},ia={kind:"first-wins"};function ra(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class oa{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}const na=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=ia,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??ia,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=ia){const a=function(t,e=ia){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,ra(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new oa(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};na.id="chapter-manager";let ha=na;const la=class extends d.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=d.createBehaviorEmitter(),this.visibleChange$=d.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(ha.id),this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){if(!this.chapterManager.provides().getChapter(t))return!1;const e=this.documentManager.provides().getDocumentState(t);return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){if(!this.chapterManager.provides().getChapter(t))return;const e=this.documentManager.provides();e.getActiveDocumentId()||e.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){this.chapterManager.provides().getChapter(t)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};la.id="chapter-scroll";let da=la;const ca={manifest:sa,create:t=>new da(aa,t),reducer:t=>t,initialState:{}},ua="note",pa={id:ua,name:"Note Plugin",version:"0.1.0",provides:["note"],requires:["selection","chapter-scroll","chapter-manager"],optional:[],defaultConfig:{callbacks:{onCreateNote:async()=>null,onActivateNote:()=>{}},markerSize:18}},ga={kind:"first-wins"};function fa(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let ma=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const va=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=ga,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??ga,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=ga){const a=function(t,e=ga){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,fa(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new ma(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};va.id="chapter-manager";let ba=va;const Pa={kind:"first-wins"};function wa(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Ia=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const ya=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=Pa,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Pa,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Pa){const a=function(t,e=Pa){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,wa(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Ia(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};ya.id="chapter-manager";let Ca=ya;const Ma=class extends d.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=d.createBehaviorEmitter(),this.visibleChange$=d.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Ca.id),this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){if(!this.chapterManager.provides().getChapter(t))return!1;const e=this.documentManager.provides().getDocumentState(t);return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){if(!this.chapterManager.provides().getChapter(t))return;const e=this.documentManager.provides();e.getActiveDocumentId()||e.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){this.chapterManager.provides().getChapter(t)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};Ma.id="chapter-scroll";let Sa=Ma;const xa=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.notesChange$=d.createBehaviorEmitter([]),this.noteActivated$=d.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(Sa.id),this.chapterManager=this.registry.getPlugin(ba.id),this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,e.callbacks.loadNotes)try{const t=await e.callbacks.loadNotes();for(const e of t)this.notes.set(e.noteId,e);this.notesChange$.emit(this.listAll())}catch(a){this.logger.error(t.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:t=>this.createNoteFromSelection(t),requestCreateFromSelection:t=>this.requestCreateFromSelection(t),registerNote:t=>this.registerNote(t),listNotesForPage:(t,e)=>this.listAll().filter(a=>a.chapterId===t&&a.localPageIndex===e),listAllNotes:()=>this.listAll(),getNote:t=>this.notes.get(t)??null,deleteNote:t=>this.deleteNote(t),updateNoteContent:(t,e)=>this.updateNoteContent(t,e),scrollToNote:t=>this.scrollToNote(t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(t){this.notes.set(t.noteId,t),this.notesChange$.emit(this.listAll())}requestEdit(t){const e=this.notes.get(t);e&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(t,e):this.activateNote(t))}activateNote(t){var e,a;const s=this.notes.get(t);s&&(null==(a=(e=this.config.callbacks).onActivateNote)||a.call(e,t,s),this.noteActivated$.emit({noteId:t,anchor:s}))}listAll(){return Array.from(this.notes.values())}buildDraft(t){return{chapterId:t.chapterId,localPageIndex:t.localPageIndex,globalPageNumber:t.globalPageNumber,globalPageIndex:t.globalPageIndex,rectsPdfCoord:t.rectsPdfCoord,endAnchor:$a(t.rectsPdfCoord),selectedText:t.selectedText,content:t.content}}async requestCreateFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const e=this.buildDraft(t),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:e,complete:async t=>{const a={...e,noteId:t};this.registerNote(a)}}),null):this.createNoteFromSelection(t)}async createNoteFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const a=this.buildDraft(e),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(t.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let i=null;try{i=await s(a)}catch(o){return this.logger.error(t.id,"OnCreateNote","Callback failed",o),null}if(!i)return null;const r={...a,noteId:i.noteId};return this.registerNote(r),r}async deleteNote(e){var a,s;if(this.notes.has(e)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,e))}catch(i){return void this.logger.error(t.id,"OnDeleteNote","Callback failed",i)}this.notes.delete(e),this.notesChange$.emit(this.listAll())}}async updateNoteContent(e,a){var s,i;const r=this.notes.get(e);if(!r)return;const o={...r,content:a};try{await(null==(i=(s=this.config.callbacks).onUpdateNote)?void 0:i.call(s,o))}catch(n){return void this.logger.error(t.id,"OnUpdateNote","Callback failed",n)}this.notes.set(e,o),this.notesChange$.emit(this.listAll())}async scrollToNote(t){var e;const a=this.notes.get(t);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(e=this.documentManager.provides().getDocument(a.chapterId))?void 0:e.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(t){const e=this.chapterScroll.provides(),a=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{i(),a(null)},2500),i=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(s),i(),a(r))})})}};xa.id="note";let La=xa;function $a(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}const Da={manifest:pa,create:t=>new La(ua,t),reducer:t=>t,initialState:{}},ka="paragraph-bookmark",Ta={id:ka,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}},za={kind:"first-wins"};function Ga(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Oa=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const Aa=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=za,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??za,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=za){const a=function(t,e=za){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Ga(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Oa(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Aa.id="chapter-manager";let Na=Aa;const Ea={kind:"first-wins"};function Ra(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class Va{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}const _a=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=Ea,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Ea,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Ea){const a=function(t,e=Ea){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Ra(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Va(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};_a.id="chapter-manager";let Ua=_a;const Fa=class extends d.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=d.createBehaviorEmitter(),this.visibleChange$=d.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Ua.id),this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){if(!this.chapterManager.provides().getChapter(t))return!1;const e=this.documentManager.provides().getDocumentState(t);return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){if(!this.chapterManager.provides().getChapter(t))return;const e=this.documentManager.provides();e.getActiveDocumentId()||e.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){this.chapterManager.provides().getChapter(t)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};Fa.id="chapter-scroll";let qa=Fa;function Ba(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function ja(t,e){const a=t.origin.y,s=t.origin.y+t.size.height,i=e.origin.y,r=e.origin.y+e.size.height,o=Math.max(s,r)-Math.min(a,i);return o<=0?0:Math.max(0,Math.min(s,r)-Math.max(a,i))/o}function Wa(t,e){var a,s;if(t.chapterId!==e.chapterId||t.localPageIndex!==e.localPageIndex)return!1;const i=(null==(a=t.rectsPdfCoord)?void 0:a.length)?t.rectsPdfCoord:[t.rectPdfCoord],r=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],o=t.markerAnchor??Ba(i),n=e.markerAnchor??Ba(r);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const h of i)for(const t of r){if(ja(h,t)<.5)continue;const e=Math.max(h.origin.x,t.origin.x);if(Math.min(h.origin.x+h.size.width,t.origin.x+t.size.width)-e>.25*Math.min(h.size.width,t.size.width))return!0}return!1}const Ha=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.change$=d.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(qa.id),this.chapterManager=this.registry.getPlugin(Na.id),this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(e){var a;if(this.config=e,null==(a=e.callbacks)?void 0:a.load)try{const t=await e.callbacks.load();for(const e of t)this.entries.set(e.id,e);this.change$.emit(this.list())}catch(s){this.logger.error(t.id,"Load","Failed to load paragraph bookmarks",s)}}buildCapability(){return{addBookmark:t=>this.addBookmark(t),removeBookmark:t=>this.removeBookmark(t),updateBookmark:(t,e)=>this.updateBookmark(t,e),listBookmarks:()=>this.list(),getBookmark:t=>this.entries.get(t)??null,scrollToBookmark:t=>this.scrollToBookmark(t),requestRemoveBookmark:t=>this.requestRemoveBookmark(t),onBookmarksChange:this.change$.on}}addBookmark(t){for(const s of this.entries.values())if(Wa(s.anchor,t.anchor))return s;const e=t.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:e,label:t.label,anchor:t.anchor,metadata:t.metadata,createdAt:Date.now()};return this.entries.set(e,a),this.notifyAndPersist(),a}removeBookmark(t){var e,a,s;this.entries.delete(t)&&(this.notifyAndPersist(),null==(s=null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,t))}async requestRemoveBookmark(e){var a,s;const i=this.entries.get(e);if(!i)return!1;const r=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(r)try{if(!(await r(i)))return!1}catch(o){return this.logger.error(t.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(e),!0}updateBookmark(t,e){const a=this.entries.get(t);a&&(this.entries.set(t,{...a,...e}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((t,e)=>t.createdAt-e.createdAt)}notifyAndPersist(){var e,a;const s=this.list();this.change$.emit(s),(null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.persist)&&Promise.resolve(this.config.callbacks.persist(s)).catch(e=>this.logger.error(t.id,"Persist","persist callback rejected",e))}async scrollToBookmark(t){const e=this.entries.get(t);if(!e)return;const a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(e.anchor.chapterId);let s=e.anchor.globalPageIndex;if(void 0===s){const t=this.chapterManager.provides().getVirtualPageMap().toGlobal(e.anchor.chapterId,e.anchor.localPageIndex);if(!t)return;s=t.globalPageIndex}const i=function(t){if(t.markerAnchor)return t.markerAnchor.y;const e=t.rectPdfCoord;return e.origin.y+e.size.height}(e.anchor);await async function(t,e,a){t.scrollToGlobalPageIndex(e),await function(t,e,a=2500){const s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const i=setTimeout(()=>{r(),s(null)},a),r=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(i),r(),s(a))})})}(t,e),t.scrollToGlobalPdfPoint(e,a,{marginTop:80})}(a,s,i)}};Ha.id="paragraph-bookmark";let Ya=Ha;const Ka={manifest:Ta,create:t=>new Ya(ka,t),reducer:t=>t,initialState:{}},Xa={"annotation-toolbar":{id:"annotation-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"],show:["overflow-annotation-tools"]},md:{minWidth:640,hide:["overflow-annotation-tools"],show:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"]}}},permanent:!1,categories:["annotation"],items:[{type:"spacer",id:"spacer-3",flex:!0},{type:"group",id:"annotation-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-highlight",commandId:"annotation:add-highlight",variant:"icon",categories:["annotation","annotation-markup","annotation-highlight"]},{type:"command-button",id:"add-strikeout",commandId:"annotation:add-strikeout",variant:"icon",categories:["annotation","annotation-markup","annotation-strikeout"]},{type:"command-button",id:"add-underline",commandId:"annotation:add-underline",variant:"icon",categories:["annotation","annotation-markup","annotation-underline"]},{type:"command-button",id:"add-squiggly",commandId:"annotation:add-squiggly",variant:"icon",categories:["annotation","annotation-markup","annotation-squiggly"]},{type:"command-button",id:"add-ink",commandId:"annotation:add-ink",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-ink-highlighter",commandId:"annotation:add-ink-highlighter",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-text",commandId:"annotation:add-text",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"add-insert-text",commandId:"annotation:add-insert-text",variant:"icon",categories:["annotation","annotation-markup","annotation-insert-text"]},{type:"command-button",id:"add-replace-text",commandId:"annotation:add-replace-text",variant:"icon",categories:["annotation","annotation-markup","annotation-replace-text"]},{type:"command-button",id:"add-comment",commandId:"annotation:add-comment",variant:"icon",categories:["annotation","annotation-comment-tool"]},{type:"command-button",id:"add-callout",commandId:"annotation:add-callout",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"overflow-annotation-tools",commandId:"annotation:overflow-tools",variant:"icon",categories:["annotation","annotation-overflow"]},{type:"divider",id:"annotation-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"annotation-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-4",flex:!0}]},"shapes-toolbar":{id:"shapes-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-polygon","add-polyline"],show:["overflow-shapes-tools"]},md:{minWidth:640,hide:["overflow-shapes-tools"],show:["add-polygon","add-polyline"]}}},permanent:!1,categories:["annotation","annotation-shape"],items:[{type:"spacer",id:"spacer-5",flex:!0},{type:"group",id:"shapes-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rectangle",commandId:"annotation:add-rectangle",variant:"icon",categories:["annotation","annotation-shape","annotation-rectangle"]},{type:"command-button",id:"add-circle",commandId:"annotation:add-circle",variant:"icon",categories:["annotation","annotation-shape","annotation-circle"]},{type:"command-button",id:"add-line",commandId:"annotation:add-line",variant:"icon",categories:["annotation","annotation-shape","annotation-line"]},{type:"command-button",id:"add-arrow",commandId:"annotation:add-arrow",variant:"icon",categories:["annotation","annotation-shape","annotation-arrow"]},{type:"command-button",id:"add-polygon",commandId:"annotation:add-polygon",variant:"icon",categories:["annotation","annotation-shape","annotation-polygon"]},{type:"command-button",id:"add-polyline",commandId:"annotation:add-polyline",variant:"icon",categories:["annotation","annotation-shape","annotation-polyline"]},{type:"command-button",id:"overflow-shapes-tools",commandId:"annotation:overflow-shapes",variant:"icon",categories:["annotation","annotation-shape","annotation-overflow"]},{type:"divider",id:"shapes-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"shapes-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-6",flex:!0}]},"form-toolbar":{id:"form-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-form-select","add-form-listbox"],show:["overflow-forms-tools"]},md:{minWidth:640,hide:["overflow-forms-tools"],show:["add-form-select","add-form-listbox"]}}},permanent:!1,categories:["form"],items:[{type:"spacer",id:"spacer-form-1",flex:!0},{type:"group",id:"form-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-form-textfield",commandId:"form:add-textfield",variant:"icon",categories:["form","form-textfield"]},{type:"command-button",id:"add-form-checkbox",commandId:"form:add-checkbox",variant:"icon",categories:["form","form-checkbox"]},{type:"command-button",id:"add-form-radio",commandId:"form:add-radio",variant:"icon",categories:["form","form-radio"]},{type:"command-button",id:"add-form-select",commandId:"form:add-select",variant:"icon",categories:["form","form-select"]},{type:"command-button",id:"add-form-listbox",commandId:"form:add-listbox",variant:"icon",categories:["form","form-listbox"]},{type:"command-button",id:"overflow-forms-tools",commandId:"form:overflow-tools",variant:"icon",categories:["form","form-overflow"]},{type:"divider",id:"form-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"command-button",id:"toggle-form-fill-mode",commandId:"form:toggle-fill-mode",variant:"icon",categories:["form","form-fill-mode"]},{type:"divider",id:"form-tools-divider-2",orientation:"vertical"},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-form-2",flex:!0}]},"insert-toolbar":{id:"insert-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["insert"],items:[{type:"spacer",id:"spacer-insert-1",flex:!0},{type:"group",id:"insert-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rubber-stamp",commandId:"insert:add-rubber-stamp",variant:"icon",categories:["insert","insert-rubber-stamp"]},{type:"command-button",id:"add-signature",commandId:"insert:add-signature",variant:"icon",categories:["insert","insert-signature"]},{type:"command-button",id:"add-image",commandId:"insert:add-image",variant:"icon",categories:["insert","insert-image"]},{type:"divider",id:"insert-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"insert-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-insert-2",flex:!0}]},"redaction-toolbar":{id:"redaction-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["redaction"],items:[{type:"spacer",id:"spacer-7",flex:!0},{type:"group",id:"redaction-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"redact",commandId:"redaction:redact",variant:"icon",categories:["redaction","redaction-combined"]},{type:"divider",id:"redaction-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-redaction-panel",commandId:"panel:toggle-redaction",variant:"icon",categories:["panel","panel-redaction"]},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"redaction-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-8",flex:!0}]}};class Za{constructor(){this.specs=[]}register(t){if(this.specs.some(e=>e.id===t.id))throw new Error(`OperationRegistry: duplicate operation id "${t.id}"`);this.specs.push(t)}registerAll(t){for(const e of t)e&&this.register(e)}list(){return this.specs}buildToolbars(){const t=structuredClone(Xa);for(const e of this.specs){const a=t[e.toolbarSlot];if(!a)continue;const s={type:"command-button",id:e.id,commandId:e.commandId,variant:"icon",...e.icon?{icon:e.icon}:{},...e.i18nKey?{labelKey:e.i18nKey}:{},...e.label?{label:e.label}:{},categories:e.categories??[]};a.items=Qa(a.items,s,e.position)}return t}}function Qa(t,e,a){return(null==a?void 0:a.after)||(null==a?void 0:a.before)?function(t,e,a){const s=t=>{const i=[];for(const r of t)"group"!==r.type?a.before&&r.id===a.before?i.push(e,r):(i.push(r),a.after&&r.id===a.after&&i.push(e)):i.push({...r,items:s(r.items)});return i};return s(t)}(t,e,a):(s=e,t.map(t=>"group"===t.type?{...t,items:[...t.items,s]}:t));var s}const Ja={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function ts(t){var e,a,s,i,r,n;const h=t.toolbar??{},c=h.enabledModes??["view","annotate","shapes","insert","form","redact"],u=c.length>0,{schema:S,operationRegistry:x}=function(t={}){var e,a,s,i,r,o;const n=new Set(t.enabledModes??["view","annotate","shapes","insert","form","redact"]),h=new Za;(null==(e=t.customOperations)?void 0:e.length)&&h.registerAll(t.customOperations);const l=h.buildToolbars(),d={};for(const u of n){if("view"===u)continue;const t=Ja[u];l[t]&&(d[t]=l[t])}const c=function(t){if(0===t.size)return null;const e=(t,e,a)=>({type:"command-button",id:`${t}-mode`,commandId:a,variant:"text",label:e,categories:["mode",t]});return{id:"chapter-editor-main-toolbar",position:{placement:"top",slot:"main",order:0},permanent:!0,items:[{type:"spacer",id:"main-spacer-left",flex:!0},{type:"group",id:"mode-group",alignment:"start",gap:2,items:[...t.has("view")?[e("view","View","mode:view")]:[],...t.has("annotate")?[e("annotate","Annotate","mode:annotate")]:[],...t.has("shapes")?[e("shapes","Shapes","mode:shapes")]:[],...t.has("insert")?[e("insert","Insert","mode:insert")]:[],...t.has("form")?[e("form","Form","mode:form")]:[],...t.has("redact")?[e("redact","Redact","mode:redact")]:[]]},{type:"spacer",id:"main-spacer-right",flex:!0}]}}(n);return c&&(d["chapter-editor-main-toolbar"]=c),(null==(a=t.extend)?void 0:a.toolbars)&&Object.assign(d,t.extend.toolbars),{schema:{id:"chapter-pdf-editor-ui",version:"1.0.0",toolbars:d,menus:(null==(s=t.extend)?void 0:s.menus)??{},sidebars:(null==(i=t.extend)?void 0:i.sidebars)??{},modals:(null==(r=t.extend)?void 0:r.modals)??{},selectionMenus:(null==(o=t.extend)?void 0:o.selectionMenus)??{}},operationRegistry:h}}({...h,enabledModes:c}),L={...u?{"mode:view":{id:"mode:view",label:"View",categories:["mode","mode-view"],action:({registry:t,documentId:e})=>{var a,s,i,r;const o=null==(a=t.getPlugin("ui"))?void 0:a.provides(),n=null==(s=t.getPlugin("interaction-manager"))?void 0:s.provides();o&&n&&(null==(i=n.forDocument(e))||i.activateDefaultMode(),o.forDocument(e).closeToolbarSlot("top","secondary"),null==(r=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(e).setLocked(t.getPluginConfig(p.ANNOTATION_PLUGIN_ID).locked??{type:p.LockModeType.None}))},active:({state:t,documentId:e})=>!M.isToolbarOpen(t.plugins,e,"top","secondary")},"mode:annotate":{id:"mode:annotate",label:"Annotate",categories:["mode","mode-annotate","annotation"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","annotation-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","annotation-toolbar")},"mode:shapes":{id:"mode:shapes",label:"Shapes",categories:["mode","mode-shapes","annotation"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","shapes-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","shapes-toolbar")},"mode:insert":{id:"mode:insert",label:"Insert",categories:["mode","mode-insert","insert"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","insert-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","insert-toolbar")},"mode:form":{id:"mode:form",label:"Form",categories:["mode","mode-form","form"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","form-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.None}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","form-toolbar")},"mode:redact":{id:"mode:redact",label:"Redact",categories:["mode","mode-redact","redaction"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","redaction-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","redaction-toolbar")}}:{},...u?es(x.list()):{},...t.commands??{}},$=[d.createPluginRegistration(l.DocumentManagerPluginPackage,{initialDocuments:[]}),d.createPluginRegistration(ea,{manifest:t.manifest,overlapStrategy:t.overlapStrategy,passwordProvider:t.passwordProvider,chapterPdfLoader:t.chapterPdfLoader,prefetchChapters:t.prefetchChapters,unloadTimeoutMs:t.unloadTimeoutMs}),d.createPluginRegistration(ca,{placeholderPageHeight:t.placeholderPageHeight,placeholderPageWidth:t.placeholderPageWidth}),d.createPluginRegistration(g.InteractionManagerPluginPackage),d.createPluginRegistration(f.RenderPluginPackage),d.createPluginRegistration(m.RotatePluginPackage),d.createPluginRegistration(o.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),d.createPluginRegistration(v.HistoryPluginPackage),d.createPluginRegistration(p.AnnotationPluginPackage),d.createPluginRegistration(b.RedactionPluginPackage),d.createPluginRegistration(P.FormPluginPackage),d.createPluginRegistration(w.StampPluginPackage,!1===t.loadDefaultStampLibrary?{manifests:[]}:void 0),d.createPluginRegistration(I.SignaturePluginPackage),...Object.keys(L).length>0?[d.createPluginRegistration(y.CommandsPluginPackage,{commands:L})]:[],...u?[d.createPluginRegistration(C.I18nPluginPackage),d.createPluginRegistration(M.UIPluginPackage,{schema:S})]:[]];return t.notes&&$.push(d.createPluginRegistration(Da,{callbacks:t.notes.callbacks,ui:null==(a=null==(e=t.features)?void 0:e.notes)?void 0:a.marker})),t.bookmarks&&$.push(d.createPluginRegistration(Ka,{callbacks:t.bookmarks.callbacks,ui:null==(i=null==(s=t.features)?void 0:s.bookmarks)?void 0:i.marker,hover:null==(n=null==(r=t.features)?void 0:r.bookmarks)?void 0:n.hover})),{plugins:$,uiSchema:S,operationRegistry:x}}function es(t){const e={};for(const a of t)a.handler&&(e[a.commandId]={id:a.commandId,labelKey:a.i18nKey,label:a.label,icon:a.icon,categories:a.categories,action:({documentId:t})=>{var e;null==(e=a.handler)||e.call(a,{documentId:t,chapterId:t})}});return e}const as={markup:{enabled:!0},bookmarks:{enabled:!0},notes:{enabled:!0},selectionToolbar:{enabled:!0},zoom:{enabled:!0,min:.5,max:3,initial:1}};class ss{constructor(t){this.cb=t}resolvePassword(t,e){return this.cb(t,e)}}const is={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:0},strikeout:{offsetY:0}},rs={highlight:c.PdfAnnotationSubtype.HIGHLIGHT,underline:c.PdfAnnotationSubtype.UNDERLINE,squiggly:c.PdfAnnotationSubtype.SQUIGGLY,strikeout:c.PdfAnnotationSubtype.STRIKEOUT};function os(t,e){return 0===e?t:t.map(t=>({origin:{x:t.origin.x,y:t.origin.y+e},size:{...t.size}}))}function ns(t){let e=1/0,a=1/0,s=-1/0,i=-1/0;for(const r of t)e=Math.min(e,r.origin.x),a=Math.min(a,r.origin.y),s=Math.max(s,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:e,y:a},size:{width:s-e,height:i-a}}}const hs={kind:"first-wins"};function ls(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let ds=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};function cs(t,e=hs){const a=function(t,e=hs){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,ls(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new ds(r)}const us=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=hs,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??hs,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=cs(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));if(t&&this.documentManager.provides().isDocumentOpen(t)){this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus){if("loaded"!==s)continue;e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}if(!o)return void this.updateStatus(e,"password-required");this.updateStatus(e,"loading");this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})}closeChapter(t){const e=this.documentManager.provides();if(e.isDocumentOpen(t)){e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed"))}else this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};us.id="chapter-manager";let ps=us;const gs={kind:"first-wins"};function fs(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class ms{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}function vs(t,e=gs){const a=function(t,e=gs){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,fs(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new ms(r)}const bs=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=gs,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??gs,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=vs(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));if(t&&this.documentManager.provides().isDocumentOpen(t)){this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus){if("loaded"!==s)continue;e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}if(!o)return void this.updateStatus(e,"password-required");this.updateStatus(e,"loading");this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})}closeChapter(t){const e=this.documentManager.provides();if(e.isDocumentOpen(t)){e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed"))}else this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};bs.id="chapter-manager";let Ps=bs;const ws=class extends d.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=d.createBehaviorEmitter(),this.visibleChange$=d.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Ps.id),this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){if(!this.chapterManager.provides().getChapter(t))return!1;const e=this.documentManager.provides().getDocumentState(t);return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){if(!this.chapterManager.provides().getChapter(t))return;const e=this.documentManager.provides();e.getActiveDocumentId()||e.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){this.chapterManager.provides().getChapter(t)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};ws.id="chapter-scroll";let Is=ws;function ys(t){if(0===t.length)throw new Error("unionRects: empty rects");let e=1/0,a=1/0,s=-1/0,i=-1/0;for(const r of t)e=Math.min(e,r.origin.x),a=Math.min(a,r.origin.y),s=Math.max(s,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:e,y:a},size:{width:s-e,height:i-a}}}function Cs(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function Ms(t,e){const a=t.origin.y,s=t.origin.y+t.size.height,i=e.origin.y,r=e.origin.y+e.size.height,o=Math.max(s,r)-Math.min(a,i);if(o<=0)return 0;return Math.max(0,Math.min(s,r)-Math.max(a,i))/o}function Ss(t,e){var a,s;if(t.chapterId!==e.chapterId||t.localPageIndex!==e.localPageIndex)return!1;const i=(null==(a=t.rectsPdfCoord)?void 0:a.length)?t.rectsPdfCoord:[t.rectPdfCoord],r=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],o=t.markerAnchor??Cs(i),n=e.markerAnchor??Cs(r);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const h of i)for(const t of r){if(Ms(h,t)<.5)continue;const e=Math.max(h.origin.x,t.origin.x);if(Math.min(h.origin.x+h.size.width,t.origin.x+t.size.width)-e>.25*Math.min(h.size.width,t.size.width))return!0}return!1}async function xs(t,e,a){t.scrollToGlobalPageIndex(e),await function(t,e,a=2500){const s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const i=setTimeout(()=>{r(),s(null)},a),r=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(i),r(),s(a))})})}(t,e),t.scrollToGlobalPdfPoint(e,a,{marginTop:80})}(class t extends d.BasePlugin{constructor(t,e){super(t,e),this.change$=d.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(Is.id),this.chapterManager=this.registry.getPlugin(ps.id),this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(e){var a;if(this.config=e,null==(a=e.callbacks)?void 0:a.load)try{const t=await e.callbacks.load();for(const e of t)this.entries.set(e.id,e);this.change$.emit(this.list())}catch(s){this.logger.error(t.id,"Load","Failed to load paragraph bookmarks",s)}}buildCapability(){return{addBookmark:t=>this.addBookmark(t),removeBookmark:t=>this.removeBookmark(t),updateBookmark:(t,e)=>this.updateBookmark(t,e),listBookmarks:()=>this.list(),getBookmark:t=>this.entries.get(t)??null,scrollToBookmark:t=>this.scrollToBookmark(t),requestRemoveBookmark:t=>this.requestRemoveBookmark(t),onBookmarksChange:this.change$.on}}addBookmark(t){for(const s of this.entries.values())if(Ss(s.anchor,t.anchor))return s;const e=t.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:e,label:t.label,anchor:t.anchor,metadata:t.metadata,createdAt:Date.now()};return this.entries.set(e,a),this.notifyAndPersist(),a}removeBookmark(t){var e,a,s;this.entries.delete(t)&&(this.notifyAndPersist(),null==(s=null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,t))}async requestRemoveBookmark(e){var a,s;const i=this.entries.get(e);if(!i)return!1;const r=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(r)try{if(!(await r(i)))return!1}catch(o){return this.logger.error(t.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(e),!0}updateBookmark(t,e){const a=this.entries.get(t);a&&(this.entries.set(t,{...a,...e}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((t,e)=>t.createdAt-e.createdAt)}notifyAndPersist(){var e,a;const s=this.list();this.change$.emit(s),(null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.persist)&&Promise.resolve(this.config.callbacks.persist(s)).catch(e=>this.logger.error(t.id,"Persist","persist callback rejected",e))}async scrollToBookmark(t){const e=this.entries.get(t);if(!e)return;const a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(e.anchor.chapterId);let s=e.anchor.globalPageIndex;if(void 0===s){const t=this.chapterManager.provides().getVirtualPageMap().toGlobal(e.anchor.chapterId,e.anchor.localPageIndex);if(!t)return;s=t.globalPageIndex}const i=function(t){if(t.markerAnchor)return t.markerAnchor.y;const e=t.rectPdfCoord;return e.origin.y+e.size.height}(e.anchor);await xs(a,s,i)}}).id="paragraph-bookmark";const Ls={kind:"first-wins"};function $s(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Ds=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};function ks(t,e=Ls){const a=function(t,e=Ls){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,$s(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Ds(r)}const Ts=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=Ls,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Ls,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=ks(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));if(t&&this.documentManager.provides().isDocumentOpen(t)){this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus){if("loaded"!==s)continue;e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}if(!o)return void this.updateStatus(e,"password-required");this.updateStatus(e,"loading");this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})}closeChapter(t){const e=this.documentManager.provides();if(e.isDocumentOpen(t)){e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed"))}else this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Ts.id="chapter-manager";let zs=Ts;const Gs={kind:"first-wins"};function Os(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class As{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}function Ns(t,e=Gs){const a=function(t,e=Gs){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Os(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new As(r)}const Es=class t extends d.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=d.createBehaviorEmitter(),this.manifestChange$=d.createEmitter(),this.overlapStrategy=Gs,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Gs,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=Ns(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));if(t&&this.documentManager.provides().isDocumentOpen(t)){this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus){if("loaded"!==s)continue;e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==c.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}if(!o)return void this.updateStatus(e,"password-required");this.updateStatus(e,"loading");this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})}closeChapter(t){const e=this.documentManager.provides();if(e.isDocumentOpen(t)){e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed"))}else this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Es.id="chapter-manager";let Rs=Es;const Vs=class extends d.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=d.createBehaviorEmitter(),this.visibleChange$=d.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Rs.id),this.documentManager=this.registry.getPlugin(l.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){if(!this.chapterManager.provides().getChapter(t))return!1;const e=this.documentManager.provides().getDocumentState(t);return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){if(!this.chapterManager.provides().getChapter(t))return;const e=this.documentManager.provides();e.getActiveDocumentId()||e.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){this.chapterManager.provides().getChapter(t)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};Vs.id="chapter-scroll";let _s=Vs;const Us={idle:"未加载",loading:"加载中",loaded:"已加载",closed:"已卸载",error:"失败","password-required":"需密码"};function Fs({nodes:e,depth:a,activeChapterId:s,chapterStatus:i,onSelect:r}){return t.jsx("ul",{style:{margin:0,padding:0,listStyle:"none",marginLeft:a>0?12:0},children:e.map(e=>t.jsx(qs,{node:e,depth:a,activeChapterId:s,chapterStatus:i,onSelect:r},e.id))})}function qs({node:a,depth:s,activeChapterId:i,chapterStatus:r,onSelect:o}){const n=a.children??[],h=n.length>0,[l,d]=e.useState(s<1),c=i===a.id,u=r[a.id]??"idle",p=!h;return t.jsxs("li",{children:[t.jsxs("div",{style:{display:"flex",alignItems:"stretch",gap:2},children:[h?t.jsx("button",{type:"button","aria-expanded":l,style:Hs,onClick:()=>d(t=>!t),children:l?"▼":"▶"}):t.jsx("span",{style:{width:16,flexShrink:0},"aria-hidden":!0}),t.jsxs("button",{type:"button",style:{...Ys,background:c?"#1e293b":"transparent",color:c?"#fff":"#334155"},onClick:()=>o(a.id),children:[t.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:a.title}),t.jsxs("div",{style:{marginTop:2,fontSize:10,color:c?"#cbd5e1":"#94a3b8",display:"flex",flexWrap:"wrap",gap:"4px 8px"},children:[t.jsxs("span",{children:["第 ",a.startPage,a.endPage!==a.startPage?`–${a.endPage}`:""," 页"]}),p?t.jsx("span",{children:Us[u]}):null]})]})]}),h&&l?t.jsx(Fs,{nodes:n,depth:s+1,activeChapterId:i,chapterStatus:r,onSelect:o}):null]})}const Bs={display:"flex",flexDirection:"column",width:224,flexShrink:0,borderRadius:8,border:"1px solid #e2e8f0",background:"#fff",overflow:"hidden"},js={margin:0,padding:"8px 12px",fontSize:12,fontWeight:600,color:"#334155",borderBottom:"1px solid #f1f5f9"},Ws={flex:1,overflowY:"auto",padding:4},Hs={flexShrink:0,padding:"0 4px",border:"none",background:"transparent",fontSize:10,color:"#94a3b8",cursor:"pointer"},Ys={minWidth:0,flex:1,border:"none",borderRadius:6,padding:"8px",textAlign:"left",fontSize:13,cursor:"pointer"};Object.defineProperty(exports,"EmbedPDF",{enumerable:!0,get:()=>a.EmbedPDF}),Object.defineProperty(exports,"useCapability",{enumerable:!0,get:()=>a.useCapability}),Object.defineProperty(exports,"usePdfiumEngine",{enumerable:!0,get:()=>S.usePdfiumEngine}),exports.CallbackPasswordProvider=class{constructor(t){this.cb=t}resolvePassword(t,e){return this.cb(t,e)}},exports.ChapterManagerPlugin=zs,exports.ChapterPdfViewer=function({engine:s,editorOptions:i,features:r,className:o,viewportClassName:n,buildSelectionMenu:h,onExtraSelectionAction:l,renderPageOverlay:d,children:c}){var u,p,g,f;const m=e.useMemo(()=>({...je,...r}),[r]),v=e.useMemo(()=>We({...i,features:m}),[i,m]),b=!1!==(null==(u=m.zoom)?void 0:u.enabled),[P,w]=e.useState((null==(p=m.zoom)?void 0:p.initial)??1),I=e.useRef(null);return e.useEffect(()=>{var t,e;if(!b)return;const a=I.current;if(!a)return;const s=a.querySelector("[data-chapter-scroll-viewport]");return s?function({container:t,getScale:e,setScale:a,minZoom:s=.5,maxZoom:i=3}){let r=0,o=1,n=null,h=1,l=1;const d=t=>{(t.ctrlKey||t.metaKey)&&(t.preventDefault(),null===n?(l=e(),h=1):clearTimeout(n),h*=1-.01*t.deltaY,h=He(h,.1,10),a(He(l*h,s,i)),n=setTimeout(()=>{n=null},120))},c=new Map,u=t=>{if(c.set(t.pointerId,{x:t.clientX,y:t.clientY}),2===c.size){const[t,a]=[...c.values()];r=Math.hypot(a.x-t.x,a.y-t.y),o=e()}},p=t=>{if(c.has(t.pointerId)&&(c.set(t.pointerId,{x:t.clientX,y:t.clientY}),2===c.size&&r>0)){t.preventDefault();const[e,n]=[...c.values()],h=Math.hypot(n.x-e.x,n.y-e.y);a(He(o*(h/r),s,i))}},g=t=>{c.delete(t.pointerId),c.size<2&&(r=0)};return t.addEventListener("wheel",d,{passive:!1}),t.addEventListener("pointerdown",u),t.addEventListener("pointermove",p,{passive:!1}),t.addEventListener("pointerup",g),t.addEventListener("pointercancel",g),()=>{t.removeEventListener("wheel",d),t.removeEventListener("pointerdown",u),t.removeEventListener("pointermove",p),t.removeEventListener("pointerup",g),t.removeEventListener("pointercancel",g),n&&clearTimeout(n)}}({container:s,getScale:()=>P,setScale:w,minZoom:(null==(t=m.zoom)?void 0:t.min)??.5,maxZoom:(null==(e=m.zoom)?void 0:e.max)??3}):void 0},[null==(g=m.zoom)?void 0:g.max,null==(f=m.zoom)?void 0:f.min,P,b]),t.jsx("div",{ref:I,className:o??"relative h-full w-full",children:t.jsx(a.EmbedPDF,{engine:s,plugins:v.plugins,children:({pluginsReady:e})=>e?t.jsxs("div",{className:"h-full w-full",style:b?{transform:`scale(${P})`,transformOrigin:"top center"}:void 0,children:[t.jsx(Pe,{className:n,features:m,buildSelectionMenu:h,onExtraSelectionAction:l,renderPageOverlay:d}),c]}):null})})},exports.ChapterScrollPlugin=_s,exports.ChapterTreePanel=function({tree:s,activeChapterId:i,onActiveChapterChange:r}){const{provides:o}=a.useCapability(_s.id),{provides:n}=a.useCapability(zs.id),[h,l]=e.useState({}),d=e.useCallback(()=>{if(!n)return;const t={},e=a=>{var s;for(const i of a)t[i.id]=n.getChapterStatus(i.id),(null==(s=i.children)?void 0:s.length)&&e(i.children)};e(s),l(t)},[n,s]);return e.useEffect(()=>{d()},[d]),e.useEffect(()=>{if(n)return n.onChapterStatusChange(d)},[n,d]),t.jsxs("aside",{style:Bs,children:[t.jsx("h2",{style:js,children:"章节目录"}),t.jsx("nav",{style:Ws,"aria-label":"章节目录",children:t.jsx(Fs,{nodes:s,depth:0,activeChapterId:i,chapterStatus:h,onSelect:t=>{null==r||r(t),null==o||o.scrollToChapter(t)}})})]})},exports.DEFAULT_CHAPTER_VIEWER_FEATURES=as,exports.PdfChapterViewport=Pe,exports.applySelectionMarkup=function(t,e,a,s,i){const r=a.forDocument(t),o=s.forDocument(t);if(!r||!o)return!1;const n="highlight"===e?"highlight":"underline"===e?"underline":"squiggly"===e?"squiggly":"strikeout",h=a.getTool(n);if(!h)return!1;const l=h.defaults,d=function(t,e){return{...is[t],...null==e?void 0:e[t]}}(e,i),u=o.getFormattedSelection();if(0===u.length)return!1;r.setLocked({type:p.LockModeType.Exclude,categories:["markup","shape"]});for(const p of u){const t=c.uuidV4(),a=d.color??l.color??l.strokeColor,s=d.opacity??l.opacity,i=d.thickness??l.strokeWidth,o=d.offsetY??0,n="underline"===e||"squiggly"===e||"strikeout"===e?os(p.segmentRects,o):p.segmentRects,h="underline"===e||"squiggly"===e||"strikeout"===e?ns(n):p.rect;r.createAnnotation(p.pageIndex,{id:t,created:new Date,flags:["print"],type:rs[e],..."highlight"===e?{blendMode:c.PdfBlendMode.Multiply}:{},strokeColor:a,opacity:s,...null!=i?{strokeWidth:i}:{},pageIndex:p.pageIndex,rect:h,segmentRects:n})}return o.clear(),!0},exports.buildParagraphBookmarkAnchor=function(t,e,a,s){const i=a.length>0?a:[];if(0===i.length)throw new Error("buildParagraphBookmarkAnchor: no rects");return{chapterId:t,localPageIndex:e,globalPageIndex:null==s?void 0:s.globalPageIndex,globalPageNumber:null==s?void 0:s.globalPageNumber,rectPdfCoord:ys(i),rectsPdfCoord:i,markerAnchor:Cs(i)}},exports.createChapterViewerEditor=function(t){var e,a,s,i,r;return ts({...t,toolbar:t.toolbar??{enabledModes:[]},features:{...as,...t.features,markup:{...as.markup,...null==(e=t.features)?void 0:e.markup},bookmarks:{...as.bookmarks,...null==(a=t.features)?void 0:a.bookmarks},notes:{...as.notes,...null==(s=t.features)?void 0:s.notes},selectionToolbar:{...as.selectionToolbar,...null==(i=t.features)?void 0:i.selectionToolbar},zoom:{...as.zoom,...null==(r=t.features)?void 0:r.zoom}}})},exports.createChapterViewerEditorOptions=function(t){return{manifest:t.manifest,chapterPdfLoader:t.chapterPdfLoader,overlapStrategy:{kind:"first-wins"},passwordProvider:new ss(async()=>null),prefetchChapters:1,loadDefaultStampLibrary:!1,unloadTimeoutMs:12e4,toolbar:{enabledModes:[]},bookmarks:t.bookmarks,notes:t.notes}},exports.createPdfChapterEditor=ts;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),e=require("react"),a=require("@embedpdf/core/react"),s=require("@embedpdf/plugin-interaction-manager/react"),i=require("@embedpdf/plugin-rotate/react"),r=require("@embedpdf/plugin-selection/react"),o=require("@embedpdf/plugin-selection"),n=require("@embedpdf/plugin-annotation/react"),h=require("@embedpdf/plugin-redaction/react"),l=require("@embedpdf/core"),d=require("@embedpdf/models"),c=require("@embedpdf/plugin-document-manager"),u=require("@embedpdf/plugin-render/react");require("@embedpdf/plugin-tiling/react");const p=require("@embedpdf/plugin-annotation"),g=require("@embedpdf/plugin-interaction-manager"),f=require("@embedpdf/plugin-render"),m=require("@embedpdf/plugin-rotate"),v=require("@embedpdf/plugin-history"),b=require("@embedpdf/plugin-redaction"),P=require("@embedpdf/plugin-form"),w=require("@embedpdf/plugin-stamp"),I=require("@embedpdf/plugin-signature"),y=require("@embedpdf/plugin-commands"),C=require("@embedpdf/plugin-i18n"),M=require("@embedpdf/plugin-ui"),S=require("@embedpdf/engines/react"),x={kind:"first-wins"};function L(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let $=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const k=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=x,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??x,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=x){const a=function(t,e=x){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,L(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new $(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};k.id="chapter-manager";let D=k;const T=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(D.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};T.id="chapter-scroll";let z=T;function O({item:s,renderPage:i,renderPlaceholder:r}){const o=function(t,s){const i=a.useDocumentState(t),r=e.useMemo(()=>!(!i||"loaded"!==i.status||!i.document)&&Boolean(i.document.pages[s]),[i,s]),[o,n]=e.useState(r);return e.useEffect(()=>{n(r)},[r]),e.useEffect(()=>{if(r)return;if(!i||"loaded"!==i.status||!i.document)return;let t=!1,e=0;const a=()=>{var r;t||((null==(r=i.document)?void 0:r.pages[s])?n(!0):++e<120&&requestAnimationFrame(a))};return requestAnimationFrame(a),()=>{t=!0}},[i,s,r]),o}(s.chapterId,s.localPageIndex);return t.jsx("div",{"data-global-page-index":s.globalPageIndex,"data-chapter-id":s.chapterId,"data-local-page-index":s.localPageIndex,style:{position:"absolute",top:`${s.offsetTop}px`,left:"50%",transform:"translateX(-50%)",width:`${s.width}px`,height:`${s.height}px`,backgroundColor:o?"#fff":"#f3f4f6",boxShadow:"0 1px 4px rgba(0,0,0,0.08)"},children:o?i(s):(null==r?void 0:r(s))??t.jsx("div",{style:{display:"flex",width:"100%",height:"100%",alignItems:"center",justifyContent:"center",color:"#9ca3af",fontSize:"12px"},children:"Loading chapter…"})})}function G({renderPage:s,renderPlaceholder:i,className:r,style:o,...n}){const{provides:h}=a.useCapability(z.id),{provides:l}=a.useCapability(c.DocumentManagerPlugin.id),d=e.useRef(null),[u,p]=e.useState(null);e.useEffect(()=>{if(!h)return;const t=d.current;h.registerViewport(t);const e=t=>p(t),a=h.onLayoutChange(e),s=null==l?void 0:l.onDocumentOpened(()=>e(h.getLayout())),i=null==l?void 0:l.onDocumentClosed(()=>e(h.getLayout()));return()=>{a(),null==s||s(),null==i||i(),h.registerViewport(null)}},[h,l]);const g=(null==u?void 0:u.totalHeight)??0,f=(null==u?void 0:u.totalWidth)??0;return t.jsx("div",{...n,ref:d,"data-chapter-scroll-viewport":"",className:r,style:{overflow:"auto",position:"relative",width:"100%",height:"100%",...o},children:t.jsx("div",{style:{position:"relative",width:`${f}px`,height:`${g}px`,margin:"0 auto"},children:null==u?void 0:u.items.map(e=>t.jsx(O,{item:e,renderPage:s,renderPlaceholder:i},e.globalPageIndex))})})}function A({chapterId:e,localPageIndex:a,scale:s,dpr:i,className:r}){return t.jsx(u.RenderLayer,{documentId:e,pageIndex:a,scale:s,dpr:i,className:r,style:{pointerEvents:"none"}})}const N={kind:"first-wins"};function E(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let R=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const V=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=N,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??N,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=N){const a=function(t,e=N){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,E(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new R(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};V.id="chapter-manager";let _=V;const U={kind:"first-wins"};function F(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let q=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const B=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=U,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??U,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=U){const a=function(t,e=U){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,F(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new q(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};B.id="chapter-manager";let j=B;const W=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(j.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};W.id="chapter-scroll";let H=W;const Y=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.notesChange$=l.createBehaviorEmitter([]),this.noteActivated$=l.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(H.id),this.chapterManager=this.registry.getPlugin(_.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,e.callbacks.loadNotes)try{const t=await e.callbacks.loadNotes();for(const e of t)this.notes.set(e.noteId,e);this.notesChange$.emit(this.listAll())}catch(a){this.logger.error(t.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:t=>this.createNoteFromSelection(t),requestCreateFromSelection:t=>this.requestCreateFromSelection(t),registerNote:t=>this.registerNote(t),listNotesForPage:(t,e)=>this.listAll().filter(a=>a.chapterId===t&&a.localPageIndex===e),listAllNotes:()=>this.listAll(),getNote:t=>this.notes.get(t)??null,deleteNote:t=>this.deleteNote(t),updateNoteContent:(t,e)=>this.updateNoteContent(t,e),scrollToNote:t=>this.scrollToNote(t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(t){this.notes.set(t.noteId,t),this.notesChange$.emit(this.listAll())}requestEdit(t){const e=this.notes.get(t);e&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(t,e):this.activateNote(t))}activateNote(t){var e,a;const s=this.notes.get(t);s&&(null==(a=(e=this.config.callbacks).onActivateNote)||a.call(e,t,s),this.noteActivated$.emit({noteId:t,anchor:s}))}listAll(){return Array.from(this.notes.values())}buildDraft(t){return{chapterId:t.chapterId,localPageIndex:t.localPageIndex,globalPageNumber:t.globalPageNumber,globalPageIndex:t.globalPageIndex,rectsPdfCoord:t.rectsPdfCoord,endAnchor:X(t.rectsPdfCoord),selectedText:t.selectedText,content:t.content}}async requestCreateFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const e=this.buildDraft(t),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:e,complete:async t=>{const a={...e,noteId:t};this.registerNote(a)}}),null):this.createNoteFromSelection(t)}async createNoteFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const a=this.buildDraft(e),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(t.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let i=null;try{i=await s(a)}catch(o){return this.logger.error(t.id,"OnCreateNote","Callback failed",o),null}if(!i)return null;const r={...a,noteId:i.noteId};return this.registerNote(r),r}async deleteNote(e){var a,s;if(this.notes.has(e)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,e))}catch(i){return void this.logger.error(t.id,"OnDeleteNote","Callback failed",i)}this.notes.delete(e),this.notesChange$.emit(this.listAll())}}async updateNoteContent(e,a){var s,i;const r=this.notes.get(e);if(!r)return;const o={...r,content:a};try{await(null==(i=(s=this.config.callbacks).onUpdateNote)?void 0:i.call(s,o))}catch(n){return void this.logger.error(t.id,"OnUpdateNote","Callback failed",n)}this.notes.set(e,o),this.notesChange$.emit(this.listAll())}async scrollToNote(t){var e;const a=this.notes.get(t);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(e=this.documentManager.provides().getDocument(a.chapterId))?void 0:e.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(t){const e=this.chapterScroll.provides(),a=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{i(),a(null)},2500),i=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(s),i(),a(r))})})}};Y.id="note";let K=Y;function X(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function Z({chapterId:s,localPageIndex:i,pdfPageWidth:r,pdfPageHeight:o,cssPageWidth:n,cssPageHeight:h,color:l="#f59e0b",ui:d,className:c,style:u}){const{plugin:p}=(()=>{const{registry:t}=a.useRegistry();if(null===t)return{plugin:null,isLoading:!0,ready:new Promise(()=>{})};const e=t.getPlugin(K.id);return{plugin:e,isLoading:!1,ready:(null==e?void 0:e.ready())??Promise.resolve()}})(),{provides:g}=(()=>{const{registry:t}=a.useRegistry();if(null===t)return{provides:null,isLoading:!0,ready:new Promise(()=>{})};const e=t.getPlugin(K.id);return(null==e?void 0:e.provides)?{provides:e.provides(),isLoading:!1,ready:e.ready()}:{provides:null,isLoading:!1,ready:Promise.resolve()}})(),[f,m]=e.useState([]),[v,b]=e.useState(null),[P,w]=e.useState(null);if(e.useEffect(()=>{if(g)return g.onNotesChange(t=>{m(t.filter(t=>t.chapterId===s&&t.localPageIndex===i))})},[g,s,i]),e.useEffect(()=>{if(!P)return;const t=t=>{var e;const a=t.target;(null==(e=a.closest)?void 0:e.call(a,`[data-note-marker-zone="${P}"]`))||(w(null),b(null))};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[P]),!g||0===f.length||!r||!o)return null;const I=n/r,y=h/o,C=(null==d?void 0:d.iconSize)??16,M=(null==d?void 0:d.highlightColor)??"rgba(245, 158, 11, 0.08)";return t.jsx("div",{className:c,style:{position:"absolute",inset:0,pointerEvents:"none",zIndex:25,...u},children:f.map(e=>{const a=v===e.noteId,s=P===e.noteId,i=a||s,{left:r,top:o}=function(t){const{markerPdf:e,lineRects:a,sx:s,sy:i,cssPageWidth:r,iconSize:o,gapPx:n=6}=t,h=(null==a?void 0:a.length)?a[a.length-1]:void 0;let l,d;h?(l=(h.origin.x+h.size.width)*s+n,d=h.origin.y*i+(h.size.height*i-o)/2):(l=e.x*s-o/2,d=e.y*i-o-n);const c=Math.max(0,r-o-2);return l>c&&(l=c),d<0&&(d=0),{left:l,top:d}}({markerPdf:e.endAnchor,lineRects:e.rectsPdfCoord,sx:I,sy:y,cssPageWidth:n,iconSize:C}),h=function(t,e,a){let s=1/0,i=1/0,r=-1/0,o=-1/0;for(const n of t)s=Math.min(s,n.origin.x*e),i=Math.min(i,n.origin.y*a),r=Math.max(r,(n.origin.x+n.size.width)*e),o=Math.max(o,(n.origin.y+n.size.height)*a);return{left:s,top:i,width:r-s,height:o-i}}(e.rectsPdfCoord,I,y),c=s?72:0,u=Math.max(0,Math.min(h.left,r)-8),f=Math.max(0,Math.min(h.top,o)-8),m=Math.min(n,Math.max(h.left+h.width,r+C)+8)-u,S=Math.max(h.top+h.height,o+C+6+c)+8-f;return t.jsxs("div",{children:[e.rectsPdfCoord.map((a,s)=>t.jsx("div",{style:{position:"absolute",left:a.origin.x*I+"px",top:a.origin.y*y+"px",width:a.size.width*I+"px",height:a.size.height*y+"px",background:M,borderRadius:"2px",pointerEvents:"auto",cursor:"default"},onMouseEnter:()=>b(e.noteId)},`${e.noteId}-bg-${s}`)),i&&t.jsxs("div",{"data-note-marker-zone":e.noteId,style:{position:"absolute",left:`${u}px`,top:`${f}px`,width:`${m}px`,height:`${S}px`,pointerEvents:"auto",zIndex:26},onMouseEnter:()=>b(e.noteId),onMouseLeave:()=>{P!==e.noteId&&b(null)},children:[(null==d?void 0:d.renderIcon)?t.jsx("div",{role:"button",tabIndex:0,title:"笔记","aria-label":"笔记",onMouseDown:t=>t.stopPropagation(),onClick:t=>{t.stopPropagation(),w(t=>t===e.noteId?null:e.noteId)},style:{position:"absolute",left:r-u+"px",top:o-f+"px",width:`${C}px`,height:`${C}px`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",padding:0},children:d.renderIcon({note:e})}):t.jsx("button",{type:"button",title:"笔记",onMouseDown:t=>t.stopPropagation(),onClick:t=>{t.stopPropagation(),w(t=>t===e.noteId?null:e.noteId)},style:{position:"absolute",left:r-u+"px",top:o-f+"px",width:`${C}px`,height:`${C}px`,border:"none",borderRadius:"50%",background:l,color:"#fff",cursor:"pointer",boxShadow:"0 2px 6px rgba(0,0,0,0.2)",padding:0,display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",lineHeight:1},"aria-label":"笔记",children:"💬"}),s&&((null==d?void 0:d.renderMenuActions)?t.jsx("div",{style:{position:"absolute",left:r-u+C/2+"px",top:`${o-f+C+6}px`,transform:"translateX(-50%)",zIndex:30,pointerEvents:"auto"},onMouseDown:t=>t.stopPropagation(),children:d.renderMenuActions({note:e,onEdit:()=>{w(null),b(null),null==p||p.requestEdit(e.noteId)},onDelete:()=>{w(null),b(null),g.deleteNote(e.noteId)}})}):t.jsxs("div",{style:{position:"absolute",left:r-u+C/2+"px",top:`${o-f+C+6}px`,transform:"translateX(-50%)",zIndex:30,pointerEvents:"auto",minWidth:"80px",padding:"4px",borderRadius:"6px",background:"#fff",border:"1px solid #e5e7eb",boxShadow:"0 4px 12px rgba(0,0,0,0.12)"},onMouseDown:t=>t.stopPropagation(),children:[t.jsx("button",{type:"button",style:Q,onClick:t=>{t.stopPropagation(),w(null),b(null),null==p||p.requestEdit(e.noteId)},children:"编辑"}),t.jsx("button",{type:"button",style:{...Q,color:"#dc2626"},onClick:t=>{t.stopPropagation(),w(null),b(null),g.deleteNote(e.noteId)},children:"删除"})]}))]})]},e.noteId)})})}const Q={display:"block",width:"100%",padding:"6px 10px",fontSize:"12px",border:"none",borderRadius:"4px",background:"transparent",color:"#334155",cursor:"pointer",textAlign:"left"},J={kind:"first-wins"};function tt(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let et=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const at=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=J,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??J,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=J){const a=function(t,e=J){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,tt(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new et(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};at.id="chapter-manager";let st=at;const it={kind:"first-wins"};function rt(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let ot=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const nt=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=it,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??it,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=it){const a=function(t,e=it){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,rt(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new ot(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};nt.id="chapter-manager";let ht=nt;const lt=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(ht.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};lt.id="chapter-scroll";let dt=lt;function ct(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function ut(t,e){const a=t.origin.y,s=t.origin.y+t.size.height,i=e.origin.y,r=e.origin.y+e.size.height,o=Math.max(s,r)-Math.min(a,i);return o<=0?0:Math.max(0,Math.min(s,r)-Math.max(a,i))/o}function pt(t,e){var a,s;if(t.chapterId!==e.chapterId||t.localPageIndex!==e.localPageIndex)return!1;const i=(null==(a=t.rectsPdfCoord)?void 0:a.length)?t.rectsPdfCoord:[t.rectPdfCoord],r=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],o=t.markerAnchor??ct(i),n=e.markerAnchor??ct(r);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const h of i)for(const t of r){if(ut(h,t)<.5)continue;const e=Math.max(h.origin.x,t.origin.x);if(Math.min(h.origin.x+h.size.width,t.origin.x+t.size.width)-e>.25*Math.min(h.size.width,t.size.width))return!0}return!1}const gt=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.change$=l.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(dt.id),this.chapterManager=this.registry.getPlugin(st.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){var a;if(this.config=e,null==(a=e.callbacks)?void 0:a.load)try{const t=await e.callbacks.load();for(const e of t)this.entries.set(e.id,e);this.change$.emit(this.list())}catch(s){this.logger.error(t.id,"Load","Failed to load paragraph bookmarks",s)}}buildCapability(){return{addBookmark:t=>this.addBookmark(t),removeBookmark:t=>this.removeBookmark(t),updateBookmark:(t,e)=>this.updateBookmark(t,e),listBookmarks:()=>this.list(),getBookmark:t=>this.entries.get(t)??null,scrollToBookmark:t=>this.scrollToBookmark(t),requestRemoveBookmark:t=>this.requestRemoveBookmark(t),onBookmarksChange:this.change$.on}}addBookmark(t){for(const s of this.entries.values())if(pt(s.anchor,t.anchor))return s;const e=t.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:e,label:t.label,anchor:t.anchor,metadata:t.metadata,createdAt:Date.now()};return this.entries.set(e,a),this.notifyAndPersist(),a}removeBookmark(t){var e,a,s;this.entries.delete(t)&&(this.notifyAndPersist(),null==(s=null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,t))}async requestRemoveBookmark(e){var a,s;const i=this.entries.get(e);if(!i)return!1;const r=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(r)try{if(!(await r(i)))return!1}catch(o){return this.logger.error(t.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(e),!0}updateBookmark(t,e){const a=this.entries.get(t);a&&(this.entries.set(t,{...a,...e}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((t,e)=>t.createdAt-e.createdAt)}notifyAndPersist(){var e,a;const s=this.list();this.change$.emit(s),(null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.persist)&&Promise.resolve(this.config.callbacks.persist(s)).catch(e=>this.logger.error(t.id,"Persist","persist callback rejected",e))}async scrollToBookmark(t){const e=this.entries.get(t);if(!e)return;const a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(e.anchor.chapterId);let s=e.anchor.globalPageIndex;if(void 0===s){const t=this.chapterManager.provides().getVirtualPageMap().toGlobal(e.anchor.chapterId,e.anchor.localPageIndex);if(!t)return;s=t.globalPageIndex}const i=function(t){if(t.markerAnchor)return t.markerAnchor.y;const e=t.rectPdfCoord;return e.origin.y+e.size.height}(e.anchor);await async function(t,e,a){t.scrollToGlobalPageIndex(e),await function(t,e,a=2500){const s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const i=setTimeout(()=>{r(),s(null)},a),r=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(i),r(),s(a))})})}(t,e),t.scrollToGlobalPdfPoint(e,a,{marginTop:80})}(a,s,i)}};gt.id="paragraph-bookmark";let ft=gt;function mt({chapterId:s,localPageIndex:i,pdfPageWidth:r,pdfPageHeight:o,cssPageWidth:n,cssPageHeight:h,onBookmarkClick:l,ui:d,className:c,style:u}){const{provides:p}=a.useCapability(ft.id),[g,f]=e.useState([]),[m,v]=e.useState(null),b=e.useRef(null);if(e.useEffect(()=>{if(!p)return;const t=()=>{f(p.listBookmarks().filter(t=>t.anchor.chapterId===s&&t.anchor.localPageIndex===i))};return t(),p.onBookmarksChange(t)},[p,s,i]),e.useEffect(()=>{if(!m)return;const t=t=>{var e;(null==(e=b.current)?void 0:e.contains(t.target))||v(null)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[m]),!p||0===g.length||!r||!o)return null;const P=n/r,w=h/o,I=(null==d?void 0:d.iconSize)??16;return t.jsx("div",{className:c,style:{position:"absolute",inset:0,pointerEvents:"none",...u},children:g.map(e=>{var a;const s=(null==(a=e.anchor.rectsPdfCoord)?void 0:a.length)?e.anchor.rectsPdfCoord:[e.anchor.rectPdfCoord],i=e.anchor.markerAnchor??{x:e.anchor.rectPdfCoord.origin.x+e.anchor.rectPdfCoord.size.width,y:e.anchor.rectPdfCoord.origin.y+e.anchor.rectPdfCoord.size.height},{left:r,top:o}=function(t){const{markerPdf:e,lineRects:a,sx:s,sy:i,cssPageWidth:r,iconSize:o,gapPx:n=6}=t,h=(null==a?void 0:a.length)?a[a.length-1]:void 0;let l,d;h?(l=(h.origin.x+h.size.width)*s+n,d=h.origin.y*i+(h.size.height*i-o)/2):(l=e.x*s-o/2,d=e.y*i-o-n);const c=Math.max(0,r-o-2);return l>c&&(l=c),d<0&&(d=0),{left:l,top:d}}({markerPdf:i,lineRects:s,sx:P,sy:w,cssPageWidth:n,iconSize:I}),h=Math.max(0,r-6),c=Math.max(0,o-6);return t.jsxs("div",{style:{position:"absolute",left:`${h}px`,top:`${c}px`,width:`${I+12}px`,height:`${I+12}px`,pointerEvents:"auto",zIndex:20},onMouseDown:t=>t.stopPropagation(),children:[(null==d?void 0:d.renderIcon)?t.jsx("div",{role:"button",tabIndex:0,title:e.label,"aria-label":`bookmark ${e.label}`,style:{position:"absolute",left:"6px",top:"6px",width:`${I}px`,height:`${I}px`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",padding:0},onClick:t=>{t.stopPropagation(),v(t=>t===e.id?null:e.id),null==l||l(e)},children:d.renderIcon({bookmark:e})}):t.jsx("button",{type:"button",title:e.label,onClick:t=>{t.stopPropagation(),v(t=>t===e.id?null:e.id),null==l||l(e)},style:{position:"absolute",left:"6px",top:"6px",width:`${I}px`,height:`${I}px`,border:"none",borderRadius:"4px",background:"#3b82f6",color:"#fff",cursor:"pointer",boxShadow:"0 2px 6px rgba(37, 99, 235, 0.35)",padding:0,display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",lineHeight:1},"aria-label":`bookmark ${e.label}`,children:"🔖"}),m===e.id&&t.jsx("div",{ref:b,style:{position:"absolute",left:"6px",top:"-36px",zIndex:30,pointerEvents:"auto",minWidth:"88px",padding:"4px",borderRadius:"6px",background:"#fff",border:"1px solid #e5e7eb",boxShadow:"0 4px 12px rgba(0,0,0,0.12)"},onClick:t=>t.stopPropagation(),children:t.jsx("button",{type:"button",style:{width:"100%",padding:"6px 8px",fontSize:"12px",border:"none",borderRadius:"4px",background:"transparent",color:"#dc2626",cursor:"pointer",textAlign:"left"},onClick:()=>{p.requestRemoveBookmark(e.id).then(t=>{t&&v(null)})},children:"删除书签"})})]},e.id)})})}function vt(t){return t.chapterId}function bt(t,e){t.wait(e,()=>{})}const Pt="note",wt={id:Pt,name:"Note Plugin",version:"0.1.0",provides:["note"],requires:["selection","chapter-scroll","chapter-manager"],optional:[],defaultConfig:{callbacks:{onCreateNote:async()=>null,onActivateNote:()=>{}},markerSize:18}},It={kind:"first-wins"};function yt(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Ct=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const Mt=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=It,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??It,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=It){const a=function(t,e=It){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,yt(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Ct(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Mt.id="chapter-manager";let St=Mt;const xt={kind:"first-wins"};function Lt(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let $t=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const kt=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=xt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??xt,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=xt){const a=function(t,e=xt){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Lt(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new $t(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};kt.id="chapter-manager";let Dt=kt;const Tt=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Dt.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};Tt.id="chapter-scroll";let zt=Tt;const Ot=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.notesChange$=l.createBehaviorEmitter([]),this.noteActivated$=l.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(zt.id),this.chapterManager=this.registry.getPlugin(St.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,e.callbacks.loadNotes)try{const t=await e.callbacks.loadNotes();for(const e of t)this.notes.set(e.noteId,e);this.notesChange$.emit(this.listAll())}catch(a){this.logger.error(t.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:t=>this.createNoteFromSelection(t),requestCreateFromSelection:t=>this.requestCreateFromSelection(t),registerNote:t=>this.registerNote(t),listNotesForPage:(t,e)=>this.listAll().filter(a=>a.chapterId===t&&a.localPageIndex===e),listAllNotes:()=>this.listAll(),getNote:t=>this.notes.get(t)??null,deleteNote:t=>this.deleteNote(t),updateNoteContent:(t,e)=>this.updateNoteContent(t,e),scrollToNote:t=>this.scrollToNote(t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(t){this.notes.set(t.noteId,t),this.notesChange$.emit(this.listAll())}requestEdit(t){const e=this.notes.get(t);e&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(t,e):this.activateNote(t))}activateNote(t){var e,a;const s=this.notes.get(t);s&&(null==(a=(e=this.config.callbacks).onActivateNote)||a.call(e,t,s),this.noteActivated$.emit({noteId:t,anchor:s}))}listAll(){return Array.from(this.notes.values())}buildDraft(t){return{chapterId:t.chapterId,localPageIndex:t.localPageIndex,globalPageNumber:t.globalPageNumber,globalPageIndex:t.globalPageIndex,rectsPdfCoord:t.rectsPdfCoord,endAnchor:At(t.rectsPdfCoord),selectedText:t.selectedText,content:t.content}}async requestCreateFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const e=this.buildDraft(t),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:e,complete:async t=>{const a={...e,noteId:t};this.registerNote(a)}}),null):this.createNoteFromSelection(t)}async createNoteFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const a=this.buildDraft(e),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(t.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let i=null;try{i=await s(a)}catch(o){return this.logger.error(t.id,"OnCreateNote","Callback failed",o),null}if(!i)return null;const r={...a,noteId:i.noteId};return this.registerNote(r),r}async deleteNote(e){var a,s;if(this.notes.has(e)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,e))}catch(i){return void this.logger.error(t.id,"OnDeleteNote","Callback failed",i)}this.notes.delete(e),this.notesChange$.emit(this.listAll())}}async updateNoteContent(e,a){var s,i;const r=this.notes.get(e);if(!r)return;const o={...r,content:a};try{await(null==(i=(s=this.config.callbacks).onUpdateNote)?void 0:i.call(s,o))}catch(n){return void this.logger.error(t.id,"OnUpdateNote","Callback failed",n)}this.notes.set(e,o),this.notesChange$.emit(this.listAll())}async scrollToNote(t){var e;const a=this.notes.get(t);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(e=this.documentManager.provides().getDocument(a.chapterId))?void 0:e.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(t){const e=this.chapterScroll.provides(),a=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{i(),a(null)},2500),i=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(s),i(),a(r))})})}};Ot.id="note";let Gt=Ot;function At(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}const Nt={manifest:wt,create:t=>new Gt(Pt,t),reducer:t=>t,initialState:{}},Et="paragraph-bookmark",Rt={id:Et,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}},Vt={kind:"first-wins"};function _t(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Ut=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const Ft=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Vt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Vt,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Vt){const a=function(t,e=Vt){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,_t(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Ut(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Ft.id="chapter-manager";let qt=Ft;const Bt={kind:"first-wins"};function jt(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class Wt{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}const Ht=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Bt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Bt,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Bt){const a=function(t,e=Bt){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,jt(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Wt(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Ht.id="chapter-manager";let Yt=Ht;const Kt=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Yt.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};Kt.id="chapter-scroll";let Xt=Kt;function Zt(t){if(0===t.length)throw new Error("unionRects: empty rects");let e=1/0,a=1/0,s=-1/0,i=-1/0;for(const r of t)e=Math.min(e,r.origin.x),a=Math.min(a,r.origin.y),s=Math.max(s,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:e,y:a},size:{width:s-e,height:i-a}}}function Qt(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function Jt(t,e){const a=t.origin.y,s=t.origin.y+t.size.height,i=e.origin.y,r=e.origin.y+e.size.height,o=Math.max(s,r)-Math.min(a,i);return o<=0?0:Math.max(0,Math.min(s,r)-Math.max(a,i))/o}function te(t,e){var a,s;if(t.chapterId!==e.chapterId||t.localPageIndex!==e.localPageIndex)return!1;const i=(null==(a=t.rectsPdfCoord)?void 0:a.length)?t.rectsPdfCoord:[t.rectPdfCoord],r=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],o=t.markerAnchor??Qt(i),n=e.markerAnchor??Qt(r);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const h of i)for(const t of r){if(Jt(h,t)<.5)continue;const e=Math.max(h.origin.x,t.origin.x);if(Math.min(h.origin.x+h.size.width,t.origin.x+t.size.width)-e>.25*Math.min(h.size.width,t.size.width))return!0}return!1}const ee=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.change$=l.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(Xt.id),this.chapterManager=this.registry.getPlugin(qt.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){var a;if(this.config=e,null==(a=e.callbacks)?void 0:a.load)try{const t=await e.callbacks.load();for(const e of t)this.entries.set(e.id,e);this.change$.emit(this.list())}catch(s){this.logger.error(t.id,"Load","Failed to load paragraph bookmarks",s)}}buildCapability(){return{addBookmark:t=>this.addBookmark(t),removeBookmark:t=>this.removeBookmark(t),updateBookmark:(t,e)=>this.updateBookmark(t,e),listBookmarks:()=>this.list(),getBookmark:t=>this.entries.get(t)??null,scrollToBookmark:t=>this.scrollToBookmark(t),requestRemoveBookmark:t=>this.requestRemoveBookmark(t),onBookmarksChange:this.change$.on}}addBookmark(t){for(const s of this.entries.values())if(te(s.anchor,t.anchor))return s;const e=t.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:e,label:t.label,anchor:t.anchor,metadata:t.metadata,createdAt:Date.now()};return this.entries.set(e,a),this.notifyAndPersist(),a}removeBookmark(t){var e,a,s;this.entries.delete(t)&&(this.notifyAndPersist(),null==(s=null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,t))}async requestRemoveBookmark(e){var a,s;const i=this.entries.get(e);if(!i)return!1;const r=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(r)try{if(!(await r(i)))return!1}catch(o){return this.logger.error(t.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(e),!0}updateBookmark(t,e){const a=this.entries.get(t);a&&(this.entries.set(t,{...a,...e}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((t,e)=>t.createdAt-e.createdAt)}notifyAndPersist(){var e,a;const s=this.list();this.change$.emit(s),(null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.persist)&&Promise.resolve(this.config.callbacks.persist(s)).catch(e=>this.logger.error(t.id,"Persist","persist callback rejected",e))}async scrollToBookmark(t){const e=this.entries.get(t);if(!e)return;const a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(e.anchor.chapterId);let s=e.anchor.globalPageIndex;if(void 0===s){const t=this.chapterManager.provides().getVirtualPageMap().toGlobal(e.anchor.chapterId,e.anchor.localPageIndex);if(!t)return;s=t.globalPageIndex}const i=function(t){if(t.markerAnchor)return t.markerAnchor.y;const e=t.rectPdfCoord;return e.origin.y+e.size.height}(e.anchor);await async function(t,e,a){t.scrollToGlobalPageIndex(e),await function(t,e,a=2500){const s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const i=setTimeout(()=>{r(),s(null)},a),r=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(i),r(),s(a))})})}(t,e),t.scrollToGlobalPdfPoint(e,a,{marginTop:80})}(a,s,i)}};ee.id="paragraph-bookmark";let ae=ee;const se={manifest:Rt,create:t=>new ae(Et,t),reducer:t=>t,initialState:{}};function ie({item:s,pdfPageWidth:i,pdfPageHeight:r,cssPageWidth:n,cssPageHeight:h,hoverUi:l}){const d=vt(s),{provides:c}=a.useCapability(o.SelectionPlugin.id),{provides:u}=a.useCapability(ae.id),p=e.useRef(null),[g,f]=e.useState(null),[m,v]=e.useState(null),[b,P]=e.useState(null),w=(null==l?void 0:l.iconSize)??16;e.useEffect(()=>{if(!c)return;const t=c.forDocument(d),e=()=>{const e=t.getState().geometry[s.localPageIndex];e&&f(e)},a=t.onSelectionChange(e);let i=!1;const r=()=>{if(!i){try{if(e(),t.getState().geometry[s.localPageIndex])return}catch{}requestAnimationFrame(r)}};return r(),()=>{i=!0,a()}},[c,d,s.localPageIndex]);const I=b??m;e.useEffect(()=>{if(!g||!i)return;const t=t=>{if(b)return;if(c)try{if(c.forDocument(d).getState().selecting)return void v(null)}catch{}const e=p.current;if(!e)return;const a=e.getBoundingClientRect();if(t.clientX<a.left||t.clientX>a.right||t.clientY<a.top||t.clientY>a.bottom)return void v(null);const s=function(t,e){const a=o.glyphAt(t,e);if(a<0)return null;const s=o.expandToLineBoundary(t,a);if(!s)return null;const i=o.rectsWithinSlice(t,s.from,s.to);return 0===i.length?null:{lineRects:i,charFrom:s.from,charTo:s.to}}(g,{x:(t.clientX-a.left)/(n/i),y:(t.clientY-a.top)/(h/r)});v((null==s?void 0:s.lineRects)??null)};return document.addEventListener("mousemove",t),()=>document.removeEventListener("mousemove",t)},[g,i,r,n,h,c,d,b]);const y=(null==I?void 0:I.length)?function(t,e,a,s){const i=a.length>0?a:[];if(0===i.length)throw new Error("buildParagraphBookmarkAnchor: no rects");return{chapterId:t,localPageIndex:e,globalPageIndex:null==s?void 0:s.globalPageIndex,globalPageNumber:null==s?void 0:s.globalPageNumber,rectPdfCoord:Zt(i),rectsPdfCoord:i,markerAnchor:Qt(i)}}(s.chapterId,s.localPageIndex,I,{globalPageIndex:s.globalPageIndex,globalPageNumber:s.globalPageNumber}):null,C=y&&(null==u?void 0:u.listBookmarks().some(t=>te(t.anchor,y))),M=e.useCallback(()=>{u&&y&&!C&&(u.addBookmark({label:`书签 ${(new Date).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"})}`,anchor:y}),v(null),P(null))},[u,y,C]);if(!u||!i||!r)return null;const S=n/i,x=h/r,L=null==I?void 0:I[I.length-1],$=L?Math.min((L.origin.x+L.size.width)*S+6,Math.max(0,n-w-2)):0,k=L?L.origin.y*x+(L.size.height*x-w)/2:0,D=L?Math.max(0,(L.origin.x+L.size.width)*S-4):0,T=L?Math.max(0,L.origin.y*x-4):0;return t.jsx("div",{ref:p,style:{position:"absolute",inset:0,zIndex:14,pointerEvents:"none"},children:I&&L&&!C&&t.jsx("div",{style:{position:"absolute",left:`${D}px`,top:`${T}px`,width:`${w+20}px`,height:`${L.size.height*x+w+12}px`,pointerEvents:"auto"},onMouseEnter:()=>P(I),onMouseLeave:()=>P(null),children:(null==l?void 0:l.renderAddIcon)?t.jsx("div",{role:"button",tabIndex:0,title:"添加书签",onClick:t=>{t.stopPropagation(),M()},style:{position:"absolute",left:$-D+"px",top:k-T+"px",width:w,height:w,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",padding:0},children:l.renderAddIcon()}):t.jsx("button",{type:"button",title:"添加书签",onClick:t=>{t.stopPropagation(),M()},style:{position:"absolute",left:$-D+"px",top:k-T+"px",width:`${w}px`,height:`${w}px`,border:"none",borderRadius:"4px",background:"#3b82f6",color:"#fff",cursor:"pointer",boxShadow:"0 2px 8px rgba(37, 99, 235, 0.45)",fontSize:"12px",lineHeight:1,padding:0,display:"flex",alignItems:"center",justifyContent:"center"},children:"🔖"})})})}const re={position:"relative",height:"100%",width:"100%"},oe={height:"100%",width:"100%"},ne={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:0},strikeout:{offsetY:0}},he={highlight:d.PdfAnnotationSubtype.HIGHLIGHT,underline:d.PdfAnnotationSubtype.UNDERLINE,squiggly:d.PdfAnnotationSubtype.SQUIGGLY,strikeout:d.PdfAnnotationSubtype.STRIKEOUT};function le(t,e){return 0===e?t:t.map(t=>({origin:{x:t.origin.x,y:t.origin.y+e},size:{...t.size}}))}function de(t){let e=1/0,a=1/0,s=-1/0,i=-1/0;for(const r of t)e=Math.min(e,r.origin.x),a=Math.min(a,r.origin.y),s=Math.max(s,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:e,y:a},size:{width:s-e,height:i-a}}}const ce=[{id:"highlight",label:"高亮背景",icon:t.jsx(fe,{})},{id:"underline",label:"下划线",icon:t.jsx(me,{})},{id:"squiggly",label:"波浪线",icon:t.jsx(ve,{})},{id:"strikeout",label:"删除线",icon:t.jsx(be,{})},{id:"note",label:"添加笔记",icon:t.jsx(Pe,{})}];function ue({placementAbove:e,anchorHeight:a,onAction:s,hiddenBuiltinActions:i=[],extraActions:r=[]}){const o=new Set(i),n=ce.filter(t=>"note"!==t.id&&!o.has(t.id)),h=ce.find(t=>"note"===t.id),l=h&&!o.has("note"),d=[...r].sort((t,e)=>(t.order??0)-(e.order??0));return t.jsxs("div",{style:{position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:e?void 0:a+10,bottom:e?a+10:void 0,display:"flex",alignItems:"center",gap:2,padding:"6px 8px",borderRadius:10,background:"#ffffff",border:"1px solid rgba(15, 23, 42, 0.08)",boxShadow:"0 4px 6px -1px rgba(15, 23, 42, 0.08), 0 10px 24px -4px rgba(15, 23, 42, 0.12)"},role:"toolbar","aria-label":"选区工具",children:[n.map(e=>t.jsx(pe,{label:e.label,onClick:()=>s(e.id),children:e.icon},e.id)),d.map(e=>t.jsx(pe,{label:e.label,onClick:()=>s(e.id),children:t.jsx("span",{style:{fontSize:11,fontWeight:600},children:e.label.slice(0,2)})},e.id)),l&&t.jsxs(t.Fragment,{children:[t.jsx("span",{style:{width:1,height:28,margin:"0 4px",background:"#e2e8f0",flexShrink:0},"aria-hidden":!0}),t.jsx(pe,{label:h.label,onClick:()=>s("note"),accent:!0,children:h.icon})]})]})}function pe({label:e,onClick:a,accent:s,children:i}){return t.jsx("button",{type:"button",title:e,"aria-label":e,onClick:a,style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,border:"none",borderRadius:8,background:"transparent",color:s?"#b45309":"#334155",cursor:"pointer"},onMouseEnter:t=>{t.currentTarget.style.background=s?"#fffbeb":"#f1f5f9"},onMouseLeave:t=>{t.currentTarget.style.background="transparent"},children:i})}function ge({behind:e,mark:a}){return t.jsxs("svg",{width:"28",height:"28",viewBox:"0 0 28 28",fill:"none","aria-hidden":!0,children:[e,t.jsx("text",{x:"14",y:"19",textAnchor:"middle",fontSize:"15",fontWeight:"700",fontFamily:"system-ui, sans-serif",fill:"#0f172a",children:"A"}),a]})}function fe(){return t.jsx(ge,{behind:t.jsx("rect",{x:"5",y:"4",width:"18",height:"20",rx:"3",fill:"#facc15"})})}function me(){return t.jsx(ge,{mark:t.jsx("path",{d:"M6 22h16",stroke:"#dc2626",strokeWidth:"2.2",strokeLinecap:"round"})})}function ve(){return t.jsx(ge,{mark:t.jsx("path",{d:"M6 22c2-2 3-2 5 0s3 2 5 0 3-2 5 0",stroke:"#dc2626",strokeWidth:"2",strokeLinecap:"round",fill:"none"})})}function be(){return t.jsx(ge,{mark:t.jsx("path",{d:"M5 14h18",stroke:"#dc2626",strokeWidth:"2.2",strokeLinecap:"round"})})}function Pe(){return t.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:[t.jsx("path",{d:"M8 3h8l4 4v14H8V3z",fill:"#fef3c7",stroke:"#d97706",strokeWidth:"1.2",strokeLinejoin:"round"}),t.jsx("path",{d:"M16 3v4h4",stroke:"#d97706",strokeWidth:"1.2"}),t.jsx("path",{d:"M10 12h6M10 16h4",stroke:"#92400e",strokeWidth:"1.2",strokeLinecap:"round"})]})}const we={highlight:"highlight",underline:"underline",squiggly:"squiggly",strikeout:"strikeout"};function Ie(s,i){var r,n,h,l;const c=null==s?void 0:s.selectionToolbar,u=!1!==(null==(r=null==s?void 0:s.markup)?void 0:r.enabled),g=!1!==(null==(n=null==s?void 0:s.notes)?void 0:n.enabled);if(!1===(null==c?void 0:c.enabled))return;if(!u&&!g&&!(null==(h=null==c?void 0:c.extraActions)?void 0:h.length))return;const{provides:f}=a.useCapability(o.SelectionPlugin.id),{provides:m}=a.useCapability(p.AnnotationPlugin.id),{provides:v}=a.useCapability(Gt.id);return e.useMemo(()=>e=>{const a=vt(e.item);return r=>{var o;return t.jsx("div",{...r.menuWrapperProps,children:t.jsx(ue,{placementAbove:!!(null==(o=r.placement)?void 0:o.suggestTop),anchorHeight:r.rect.size.height,onAction:t=>{var r,o;if("highlight"!==t&&"underline"!==t&&"squiggly"!==t&&"strikeout"!==t){if("note"===t){if(!f||!v||!g)return;const t=f.getHighlightRectsForPage(e.item.localPageIndex,a);return void bt(f.getSelectedText(a),a=>{v.requestCreateFromSelection({chapterId:e.item.chapterId,localPageIndex:e.item.localPageIndex,globalPageIndex:e.item.globalPageIndex,globalPageNumber:e.item.globalPageNumber,rectsPdfCoord:t,selectedText:a.join("\n")})})}null==(r=null==i?void 0:i.onExtraAction)||r.call(i,t,e)}else{if(!f||!m||!u)return;!function(t,e,a,s,i){const r=a.forDocument(t),o=s.forDocument(t);if(!r||!o)return!1;const n="highlight"===e?"highlight":"underline"===e?"underline":"squiggly"===e?"squiggly":"strikeout",h=a.getTool(n);if(!h)return!1;const l=h.defaults,c={...ne[g=e],...null==(f=i)?void 0:f[g]},u=o.getFormattedSelection();var g,f;if(0===u.length)return!1;r.setLocked({type:p.LockModeType.Exclude,categories:["markup","shape"]});for(const p of u){const t=d.uuidV4(),a=c.color??l.color??l.strokeColor,s=c.opacity??l.opacity,i=c.thickness??l.strokeWidth,o=c.offsetY??0,n="underline"===e||"squiggly"===e||"strikeout"===e?le(p.segmentRects,o):p.segmentRects,h="underline"===e||"squiggly"===e||"strikeout"===e?de(n):p.rect;r.createAnnotation(p.pageIndex,{id:t,created:new Date,flags:["print"],type:he[e],..."highlight"===e?{blendMode:d.PdfBlendMode.Multiply}:{},strokeColor:a,opacity:s,...null!=i?{strokeWidth:i}:{},pageIndex:p.pageIndex,rect:h,segmentRects:n})}o.clear()}(a,we[t],m,f,null==(o=null==s?void 0:s.markup)?void 0:o.styles)}},hiddenBuiltinActions:null==c?void 0:c.hiddenBuiltinActions,extraActions:null==c?void 0:c.extraActions})})}},[m,null==(l=null==s?void 0:s.markup)?void 0:l.styles,null==i?void 0:i.onExtraAction,u,v,g,f,null==c?void 0:c.extraActions,null==c?void 0:c.hiddenBuiltinActions])}function ye({className:s,buildSelectionMenu:i,annotationSelectionMenu:r,redactionSelectionMenu:o,showNoteMarkers:n=!0,showBookmarkMarkers:h=!0,showRedactionLayer:l=!1,renderPageOverlay:d,features:c,onExtraSelectionAction:u,children:p}){var g,f,m,v;const b=function(){const{registry:t}=a.useRegistry();return e.useMemo(()=>{var e,a;const s=null==(a=null==(e=null==t?void 0:t.getPlugin(Gt.id))?void 0:e.provides)?void 0:a.call(e);return s?t=>s.createNoteFromSelection(t):null},[t])}(),P=function(){const{registry:t}=a.useRegistry();return!!(null==t?void 0:t.getPlugin(Gt.id))}(),w=function(){const{registry:t}=a.useRegistry();return!!(null==t?void 0:t.getPlugin(ae.id))}(),I=n&&P&&!1!==(null==(g=null==c?void 0:c.notes)?void 0:g.enabled),y=h&&w&&!1!==(null==(f=null==c?void 0:c.bookmarks)?void 0:f.enabled),C=w&&!1!==(null==(m=null==c?void 0:c.bookmarks)?void 0:m.enabled),M=Ie(c,{onExtraAction:u}),S=e.useMemo(()=>{if(i||M)return t=>{const e=M?M(t):t.defaultMenu;return i?i({...t,defaultMenu:e}):e}},[i,M]),x=e.useMemo(()=>d||C?e=>{var a;return t.jsxs(t.Fragment,{children:[C&&t.jsx(Ce,{item:e,hoverUi:null==(a=null==c?void 0:c.bookmarks)?void 0:a.hover}),null==d?void 0:d(e)]})}:d,[null==(v=null==c?void 0:c.bookmarks)?void 0:v.hover,C,d]);return t.jsxs("div",{className:s,style:s?void 0:re,children:[t.jsx(G,{renderPage:e=>{var a,s;return t.jsx(Me,{item:e,showNoteMarkers:I,showBookmarkMarkers:y,noteMarkerUi:null==(a=null==c?void 0:c.notes)?void 0:a.marker,bookmarkMarkerUi:null==(s=null==c?void 0:c.bookmarks)?void 0:s.marker,renderPageOverlay:x,buildSelectionMenu:S,createNote:b,annotationSelectionMenu:r,redactionSelectionMenu:o,showRedactionLayer:l})}}),p]})}function Ce({item:e,hoverUi:s}){var i;const r=vt(e),o=a.useDocumentState(r),n=(null==(i=null==o?void 0:o.document)?void 0:i.pages[e.localPageIndex])??null;return n?t.jsx(ie,{item:e,pdfPageWidth:n.size.width,pdfPageHeight:n.size.height,cssPageWidth:e.width,cssPageHeight:e.height,hoverUi:s}):null}function Me({item:l,showNoteMarkers:d,showBookmarkMarkers:u,noteMarkerUi:p,bookmarkMarkerUi:g,renderPageOverlay:f,createNote:m,buildSelectionMenu:v,annotationSelectionMenu:b,redactionSelectionMenu:P,showRedactionLayer:w=!1}){var I;const y=vt(l);!function(t){const{provides:s}=a.useCapability(c.DocumentManagerPlugin.id);e.useEffect(()=>{s&&t&&s.isDocumentOpen(t)&&s.setActiveDocument(t)},[s,t])}(y);const C=a.useDocumentState(y),M=(null==(I=null==C?void 0:C.document)?void 0:I.pages[l.localPageIndex])??null,S=function(s,i){const{provides:r}=a.useCapability(o.SelectionPlugin.id),n=vt(s);return e.useMemo(()=>{if(i)return e=>{var a;const o={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==(a=e.placement)?void 0:a.suggestTop)?-40:e.rect.size.height+8};return t.jsx("div",{...e.menuWrapperProps,children:t.jsx("div",{style:o,children:t.jsx("button",{type:"button",onClick:()=>{if(!r)return;const t=r.getHighlightRectsForPage(s.localPageIndex,n);bt(r.getSelectedText(n),e=>{const a=e.join("\n"),r=function(t,e,a){return{chapterId:t.chapterId,localPageIndex:t.localPageIndex,globalPageIndex:t.globalPageIndex,globalPageNumber:t.globalPageNumber,rectsPdfCoord:e,selectedText:a}}(s,t,a);i(r)})},style:{padding:"6px 10px",fontSize:"12px",border:"1px solid #e5e7eb",borderRadius:"6px",background:"#fff",cursor:"pointer",boxShadow:"0 2px 8px rgba(0,0,0,0.08)"},children:"添加附注"})})})}},[i,n,s,r])}(l,m),x=void 0!==v?v({item:l,defaultMenu:S,createNote:m}):S;return M?t.jsx(s.GlobalPointerProvider,{documentId:y,children:t.jsx(i.Rotate,{documentId:y,pageIndex:l.localPageIndex,style:{backgroundColor:"#fff"},children:t.jsxs(s.PagePointerProvider,{documentId:y,pageIndex:l.localPageIndex,children:[t.jsx(A,{chapterId:y,localPageIndex:l.localPageIndex}),t.jsx(r.SelectionLayer,{documentId:y,pageIndex:l.localPageIndex,selectionMenu:x}),w&&t.jsx(h.RedactionLayer,{documentId:y,pageIndex:l.localPageIndex,selectionMenu:P}),t.jsx(n.AnnotationLayer,{documentId:y,pageIndex:l.localPageIndex,selectionMenu:b}),u&&M&&t.jsx(mt,{chapterId:y,localPageIndex:l.localPageIndex,pdfPageWidth:M.size.width,pdfPageHeight:M.size.height,cssPageWidth:l.width,cssPageHeight:l.height,ui:g}),null==f?void 0:f(l),d&&M&&t.jsx(Z,{chapterId:y,localPageIndex:l.localPageIndex,pdfPageWidth:M.size.width,pdfPageHeight:M.size.height,cssPageWidth:l.width,cssPageHeight:l.height,ui:p})]})})}):null}const Se="chapter-manager",xe={id:Se,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}},Le={kind:"first-wins"};function $e(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let ke=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const De=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Le,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Le,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Le){const a=function(t,e=Le){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,$e(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new ke(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};De.id="chapter-manager";let Te=De;const ze={manifest:xe,create:t=>new Te(Se,t),reducer:t=>t,initialState:{}},Oe="chapter-scroll",Ge={id:Oe,name:"Chapter Scroll Plugin",version:"0.1.0",provides:["chapter-scroll"],requires:["chapter-manager"],optional:[],defaultConfig:{placeholderPageHeight:1200,placeholderPageWidth:900,bufferSize:2,pageGap:20}},Ae={kind:"first-wins"};function Ne(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class Ee{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}const Re=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Ae,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Ae,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Ae){const a=function(t,e=Ae){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Ne(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Ee(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Re.id="chapter-manager";let Ve=Re;const _e=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Ve.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};_e.id="chapter-scroll";let Ue=_e;const Fe={manifest:Ge,create:t=>new Ue(Oe,t),reducer:t=>t,initialState:{}},qe={"annotation-toolbar":{id:"annotation-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"],show:["overflow-annotation-tools"]},md:{minWidth:640,hide:["overflow-annotation-tools"],show:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"]}}},permanent:!1,categories:["annotation"],items:[{type:"spacer",id:"spacer-3",flex:!0},{type:"group",id:"annotation-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-highlight",commandId:"annotation:add-highlight",variant:"icon",categories:["annotation","annotation-markup","annotation-highlight"]},{type:"command-button",id:"add-strikeout",commandId:"annotation:add-strikeout",variant:"icon",categories:["annotation","annotation-markup","annotation-strikeout"]},{type:"command-button",id:"add-underline",commandId:"annotation:add-underline",variant:"icon",categories:["annotation","annotation-markup","annotation-underline"]},{type:"command-button",id:"add-squiggly",commandId:"annotation:add-squiggly",variant:"icon",categories:["annotation","annotation-markup","annotation-squiggly"]},{type:"command-button",id:"add-ink",commandId:"annotation:add-ink",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-ink-highlighter",commandId:"annotation:add-ink-highlighter",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-text",commandId:"annotation:add-text",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"add-insert-text",commandId:"annotation:add-insert-text",variant:"icon",categories:["annotation","annotation-markup","annotation-insert-text"]},{type:"command-button",id:"add-replace-text",commandId:"annotation:add-replace-text",variant:"icon",categories:["annotation","annotation-markup","annotation-replace-text"]},{type:"command-button",id:"add-comment",commandId:"annotation:add-comment",variant:"icon",categories:["annotation","annotation-comment-tool"]},{type:"command-button",id:"add-callout",commandId:"annotation:add-callout",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"overflow-annotation-tools",commandId:"annotation:overflow-tools",variant:"icon",categories:["annotation","annotation-overflow"]},{type:"divider",id:"annotation-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"annotation-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-4",flex:!0}]},"shapes-toolbar":{id:"shapes-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-polygon","add-polyline"],show:["overflow-shapes-tools"]},md:{minWidth:640,hide:["overflow-shapes-tools"],show:["add-polygon","add-polyline"]}}},permanent:!1,categories:["annotation","annotation-shape"],items:[{type:"spacer",id:"spacer-5",flex:!0},{type:"group",id:"shapes-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rectangle",commandId:"annotation:add-rectangle",variant:"icon",categories:["annotation","annotation-shape","annotation-rectangle"]},{type:"command-button",id:"add-circle",commandId:"annotation:add-circle",variant:"icon",categories:["annotation","annotation-shape","annotation-circle"]},{type:"command-button",id:"add-line",commandId:"annotation:add-line",variant:"icon",categories:["annotation","annotation-shape","annotation-line"]},{type:"command-button",id:"add-arrow",commandId:"annotation:add-arrow",variant:"icon",categories:["annotation","annotation-shape","annotation-arrow"]},{type:"command-button",id:"add-polygon",commandId:"annotation:add-polygon",variant:"icon",categories:["annotation","annotation-shape","annotation-polygon"]},{type:"command-button",id:"add-polyline",commandId:"annotation:add-polyline",variant:"icon",categories:["annotation","annotation-shape","annotation-polyline"]},{type:"command-button",id:"overflow-shapes-tools",commandId:"annotation:overflow-shapes",variant:"icon",categories:["annotation","annotation-shape","annotation-overflow"]},{type:"divider",id:"shapes-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"shapes-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-6",flex:!0}]},"form-toolbar":{id:"form-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-form-select","add-form-listbox"],show:["overflow-forms-tools"]},md:{minWidth:640,hide:["overflow-forms-tools"],show:["add-form-select","add-form-listbox"]}}},permanent:!1,categories:["form"],items:[{type:"spacer",id:"spacer-form-1",flex:!0},{type:"group",id:"form-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-form-textfield",commandId:"form:add-textfield",variant:"icon",categories:["form","form-textfield"]},{type:"command-button",id:"add-form-checkbox",commandId:"form:add-checkbox",variant:"icon",categories:["form","form-checkbox"]},{type:"command-button",id:"add-form-radio",commandId:"form:add-radio",variant:"icon",categories:["form","form-radio"]},{type:"command-button",id:"add-form-select",commandId:"form:add-select",variant:"icon",categories:["form","form-select"]},{type:"command-button",id:"add-form-listbox",commandId:"form:add-listbox",variant:"icon",categories:["form","form-listbox"]},{type:"command-button",id:"overflow-forms-tools",commandId:"form:overflow-tools",variant:"icon",categories:["form","form-overflow"]},{type:"divider",id:"form-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"command-button",id:"toggle-form-fill-mode",commandId:"form:toggle-fill-mode",variant:"icon",categories:["form","form-fill-mode"]},{type:"divider",id:"form-tools-divider-2",orientation:"vertical"},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-form-2",flex:!0}]},"insert-toolbar":{id:"insert-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["insert"],items:[{type:"spacer",id:"spacer-insert-1",flex:!0},{type:"group",id:"insert-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rubber-stamp",commandId:"insert:add-rubber-stamp",variant:"icon",categories:["insert","insert-rubber-stamp"]},{type:"command-button",id:"add-signature",commandId:"insert:add-signature",variant:"icon",categories:["insert","insert-signature"]},{type:"command-button",id:"add-image",commandId:"insert:add-image",variant:"icon",categories:["insert","insert-image"]},{type:"divider",id:"insert-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"insert-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-insert-2",flex:!0}]},"redaction-toolbar":{id:"redaction-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["redaction"],items:[{type:"spacer",id:"spacer-7",flex:!0},{type:"group",id:"redaction-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"redact",commandId:"redaction:redact",variant:"icon",categories:["redaction","redaction-combined"]},{type:"divider",id:"redaction-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-redaction-panel",commandId:"panel:toggle-redaction",variant:"icon",categories:["panel","panel-redaction"]},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"redaction-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-8",flex:!0}]}};class Be{constructor(){this.specs=[]}register(t){if(this.specs.some(e=>e.id===t.id))throw new Error(`OperationRegistry: duplicate operation id "${t.id}"`);this.specs.push(t)}registerAll(t){for(const e of t)e&&this.register(e)}list(){return this.specs}buildToolbars(){const t=structuredClone(qe);for(const e of this.specs){const a=t[e.toolbarSlot];if(!a)continue;const s={type:"command-button",id:e.id,commandId:e.commandId,variant:"icon",...e.icon?{icon:e.icon}:{},...e.i18nKey?{labelKey:e.i18nKey}:{},...e.label?{label:e.label}:{},categories:e.categories??[]};a.items=je(a.items,s,e.position)}return t}}function je(t,e,a){return(null==a?void 0:a.after)||(null==a?void 0:a.before)?function(t,e,a){const s=t=>{const i=[];for(const r of t)"group"!==r.type?a.before&&r.id===a.before?i.push(e,r):(i.push(r),a.after&&r.id===a.after&&i.push(e)):i.push({...r,items:s(r.items)});return i};return s(t)}(t,e,a):(s=e,t.map(t=>"group"===t.type?{...t,items:[...t.items,s]}:t));var s}const We={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function He(t){const e={};for(const a of t)a.handler&&(e[a.commandId]={id:a.commandId,labelKey:a.i18nKey,label:a.label,icon:a.icon,categories:a.categories,action:({documentId:t})=>{var e;null==(e=a.handler)||e.call(a,{documentId:t,chapterId:t})}});return e}const Ye={markup:{enabled:!0},bookmarks:{enabled:!0},notes:{enabled:!0},selectionToolbar:{enabled:!0},zoom:{enabled:!0,min:.5,max:3,initial:1}};function Ke(t){var e,a,s,i,r;return function(t){var e,a,s,i,r,n;const h=t.toolbar??{},d=h.enabledModes??["view","annotate","shapes","insert","form","redact"],u=d.length>0,{schema:S,operationRegistry:x}=function(t={}){var e,a,s,i,r,o;const n=new Set(t.enabledModes??["view","annotate","shapes","insert","form","redact"]),h=new Be;(null==(e=t.customOperations)?void 0:e.length)&&h.registerAll(t.customOperations);const l=h.buildToolbars(),d={};for(const u of n){if("view"===u)continue;const t=We[u];l[t]&&(d[t]=l[t])}const c=function(t){if(0===t.size)return null;const e=(t,e,a)=>({type:"command-button",id:`${t}-mode`,commandId:a,variant:"text",label:e,categories:["mode",t]});return{id:"chapter-editor-main-toolbar",position:{placement:"top",slot:"main",order:0},permanent:!0,items:[{type:"spacer",id:"main-spacer-left",flex:!0},{type:"group",id:"mode-group",alignment:"start",gap:2,items:[...t.has("view")?[e("view","View","mode:view")]:[],...t.has("annotate")?[e("annotate","Annotate","mode:annotate")]:[],...t.has("shapes")?[e("shapes","Shapes","mode:shapes")]:[],...t.has("insert")?[e("insert","Insert","mode:insert")]:[],...t.has("form")?[e("form","Form","mode:form")]:[],...t.has("redact")?[e("redact","Redact","mode:redact")]:[]]},{type:"spacer",id:"main-spacer-right",flex:!0}]}}(n);return c&&(d["chapter-editor-main-toolbar"]=c),(null==(a=t.extend)?void 0:a.toolbars)&&Object.assign(d,t.extend.toolbars),{schema:{id:"chapter-pdf-editor-ui",version:"1.0.0",toolbars:d,menus:(null==(s=t.extend)?void 0:s.menus)??{},sidebars:(null==(i=t.extend)?void 0:i.sidebars)??{},modals:(null==(r=t.extend)?void 0:r.modals)??{},selectionMenus:(null==(o=t.extend)?void 0:o.selectionMenus)??{}},operationRegistry:h}}({...h,enabledModes:d}),L={...u?{"mode:view":{id:"mode:view",label:"View",categories:["mode","mode-view"],action:({registry:t,documentId:e})=>{var a,s,i,r;const o=null==(a=t.getPlugin("ui"))?void 0:a.provides(),n=null==(s=t.getPlugin("interaction-manager"))?void 0:s.provides();o&&n&&(null==(i=n.forDocument(e))||i.activateDefaultMode(),o.forDocument(e).closeToolbarSlot("top","secondary"),null==(r=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(e).setLocked(t.getPluginConfig(p.ANNOTATION_PLUGIN_ID).locked??{type:p.LockModeType.None}))},active:({state:t,documentId:e})=>!M.isToolbarOpen(t.plugins,e,"top","secondary")},"mode:annotate":{id:"mode:annotate",label:"Annotate",categories:["mode","mode-annotate","annotation"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","annotation-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","annotation-toolbar")},"mode:shapes":{id:"mode:shapes",label:"Shapes",categories:["mode","mode-shapes","annotation"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","shapes-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","shapes-toolbar")},"mode:insert":{id:"mode:insert",label:"Insert",categories:["mode","mode-insert","insert"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","insert-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","insert-toolbar")},"mode:form":{id:"mode:form",label:"Form",categories:["mode","mode-form","form"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","form-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.None}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","form-toolbar")},"mode:redact":{id:"mode:redact",label:"Redact",categories:["mode","mode-redact","redaction"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","redaction-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","redaction-toolbar")}}:{},...u?He(x.list()):{},...t.commands??{}},$=[l.createPluginRegistration(c.DocumentManagerPluginPackage,{initialDocuments:[]}),l.createPluginRegistration(ze,{manifest:t.manifest,overlapStrategy:t.overlapStrategy,passwordProvider:t.passwordProvider,chapterPdfLoader:t.chapterPdfLoader,prefetchChapters:t.prefetchChapters,unloadTimeoutMs:t.unloadTimeoutMs}),l.createPluginRegistration(Fe,{placeholderPageHeight:t.placeholderPageHeight,placeholderPageWidth:t.placeholderPageWidth}),l.createPluginRegistration(g.InteractionManagerPluginPackage),l.createPluginRegistration(f.RenderPluginPackage),l.createPluginRegistration(m.RotatePluginPackage),l.createPluginRegistration(o.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),l.createPluginRegistration(v.HistoryPluginPackage),l.createPluginRegistration(p.AnnotationPluginPackage),l.createPluginRegistration(b.RedactionPluginPackage),l.createPluginRegistration(P.FormPluginPackage),l.createPluginRegistration(w.StampPluginPackage,!1===t.loadDefaultStampLibrary?{manifests:[]}:void 0),l.createPluginRegistration(I.SignaturePluginPackage),...Object.keys(L).length>0?[l.createPluginRegistration(y.CommandsPluginPackage,{commands:L})]:[],...u?[l.createPluginRegistration(C.I18nPluginPackage),l.createPluginRegistration(M.UIPluginPackage,{schema:S})]:[]];return t.notes&&$.push(l.createPluginRegistration(Nt,{callbacks:t.notes.callbacks,ui:null==(a=null==(e=t.features)?void 0:e.notes)?void 0:a.marker})),t.bookmarks&&$.push(l.createPluginRegistration(se,{callbacks:t.bookmarks.callbacks,ui:null==(i=null==(s=t.features)?void 0:s.bookmarks)?void 0:i.marker,hover:null==(n=null==(r=t.features)?void 0:r.bookmarks)?void 0:n.hover})),{plugins:$,uiSchema:S,operationRegistry:x}}({...t,toolbar:t.toolbar??{enabledModes:[]},features:{...Ye,...t.features,markup:{...Ye.markup,...null==(e=t.features)?void 0:e.markup},bookmarks:{...Ye.bookmarks,...null==(a=t.features)?void 0:a.bookmarks},notes:{...Ye.notes,...null==(s=t.features)?void 0:s.notes},selectionToolbar:{...Ye.selectionToolbar,...null==(i=t.features)?void 0:i.selectionToolbar},zoom:{...Ye.zoom,...null==(r=t.features)?void 0:r.zoom}}})}function Xe(t,e,a){return Math.min(a,Math.max(e,t))}const Ze="chapter-manager",Qe={id:Ze,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}},Je={kind:"first-wins"};function ta(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let ea=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const aa=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Je,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Je,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Je){const a=function(t,e=Je){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,ta(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new ea(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};aa.id="chapter-manager";let sa=aa;const ia={manifest:Qe,create:t=>new sa(Ze,t),reducer:t=>t,initialState:{}},ra="chapter-scroll",oa={id:ra,name:"Chapter Scroll Plugin",version:"0.1.0",provides:["chapter-scroll"],requires:["chapter-manager"],optional:[],defaultConfig:{placeholderPageHeight:1200,placeholderPageWidth:900,bufferSize:2,pageGap:20}},na={kind:"first-wins"};function ha(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class la{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}const da=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=na,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??na,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=na){const a=function(t,e=na){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,ha(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new la(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};da.id="chapter-manager";let ca=da;const ua=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(ca.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};ua.id="chapter-scroll";let pa=ua;const ga={manifest:oa,create:t=>new pa(ra,t),reducer:t=>t,initialState:{}},fa="note",ma={id:fa,name:"Note Plugin",version:"0.1.0",provides:["note"],requires:["selection","chapter-scroll","chapter-manager"],optional:[],defaultConfig:{callbacks:{onCreateNote:async()=>null,onActivateNote:()=>{}},markerSize:18}},va={kind:"first-wins"};function ba(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Pa=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const wa=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=va,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??va,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=va){const a=function(t,e=va){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,ba(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Pa(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};wa.id="chapter-manager";let Ia=wa;const ya={kind:"first-wins"};function Ca(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Ma=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const Sa=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=ya,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??ya,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=ya){const a=function(t,e=ya){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Ca(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Ma(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Sa.id="chapter-manager";let xa=Sa;const La=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(xa.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};La.id="chapter-scroll";let $a=La;const ka=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.notesChange$=l.createBehaviorEmitter([]),this.noteActivated$=l.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin($a.id),this.chapterManager=this.registry.getPlugin(Ia.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,e.callbacks.loadNotes)try{const t=await e.callbacks.loadNotes();for(const e of t)this.notes.set(e.noteId,e);this.notesChange$.emit(this.listAll())}catch(a){this.logger.error(t.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:t=>this.createNoteFromSelection(t),requestCreateFromSelection:t=>this.requestCreateFromSelection(t),registerNote:t=>this.registerNote(t),listNotesForPage:(t,e)=>this.listAll().filter(a=>a.chapterId===t&&a.localPageIndex===e),listAllNotes:()=>this.listAll(),getNote:t=>this.notes.get(t)??null,deleteNote:t=>this.deleteNote(t),updateNoteContent:(t,e)=>this.updateNoteContent(t,e),scrollToNote:t=>this.scrollToNote(t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(t){this.notes.set(t.noteId,t),this.notesChange$.emit(this.listAll())}requestEdit(t){const e=this.notes.get(t);e&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(t,e):this.activateNote(t))}activateNote(t){var e,a;const s=this.notes.get(t);s&&(null==(a=(e=this.config.callbacks).onActivateNote)||a.call(e,t,s),this.noteActivated$.emit({noteId:t,anchor:s}))}listAll(){return Array.from(this.notes.values())}buildDraft(t){return{chapterId:t.chapterId,localPageIndex:t.localPageIndex,globalPageNumber:t.globalPageNumber,globalPageIndex:t.globalPageIndex,rectsPdfCoord:t.rectsPdfCoord,endAnchor:Ta(t.rectsPdfCoord),selectedText:t.selectedText,content:t.content}}async requestCreateFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const e=this.buildDraft(t),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:e,complete:async t=>{const a={...e,noteId:t};this.registerNote(a)}}),null):this.createNoteFromSelection(t)}async createNoteFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const a=this.buildDraft(e),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(t.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let i=null;try{i=await s(a)}catch(o){return this.logger.error(t.id,"OnCreateNote","Callback failed",o),null}if(!i)return null;const r={...a,noteId:i.noteId};return this.registerNote(r),r}async deleteNote(e){var a,s;if(this.notes.has(e)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,e))}catch(i){return void this.logger.error(t.id,"OnDeleteNote","Callback failed",i)}this.notes.delete(e),this.notesChange$.emit(this.listAll())}}async updateNoteContent(e,a){var s,i;const r=this.notes.get(e);if(!r)return;const o={...r,content:a};try{await(null==(i=(s=this.config.callbacks).onUpdateNote)?void 0:i.call(s,o))}catch(n){return void this.logger.error(t.id,"OnUpdateNote","Callback failed",n)}this.notes.set(e,o),this.notesChange$.emit(this.listAll())}async scrollToNote(t){var e;const a=this.notes.get(t);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(e=this.documentManager.provides().getDocument(a.chapterId))?void 0:e.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(t){const e=this.chapterScroll.provides(),a=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{i(),a(null)},2500),i=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(s),i(),a(r))})})}};ka.id="note";let Da=ka;function Ta(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}const za={manifest:ma,create:t=>new Da(fa,t),reducer:t=>t,initialState:{}},Oa="paragraph-bookmark",Ga={id:Oa,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}},Aa={kind:"first-wins"};function Na(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let Ea=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};const Ra=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Aa,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Aa,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=Aa){const a=function(t,e=Aa){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Na(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Ea(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Ra.id="chapter-manager";let Va=Ra;const _a={kind:"first-wins"};function Ua(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class Fa{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}const qa=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=_a,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??_a,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=function(t,e=_a){const a=function(t,e=_a){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Ua(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Fa(r)}(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));t&&this.documentManager.provides().isDocumentOpen(t)&&this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}o?(this.updateStatus(e,"loading"),this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})):this.updateStatus(e,"password-required")}closeChapter(t){const e=this.documentManager.provides();e.isDocumentOpen(t)?e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed")):this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};qa.id="chapter-manager";let Ba=qa;const ja=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Ba.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};ja.id="chapter-scroll";let Wa=ja;function Ha(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function Ya(t,e){const a=t.origin.y,s=t.origin.y+t.size.height,i=e.origin.y,r=e.origin.y+e.size.height,o=Math.max(s,r)-Math.min(a,i);return o<=0?0:Math.max(0,Math.min(s,r)-Math.max(a,i))/o}function Ka(t,e){var a,s;if(t.chapterId!==e.chapterId||t.localPageIndex!==e.localPageIndex)return!1;const i=(null==(a=t.rectsPdfCoord)?void 0:a.length)?t.rectsPdfCoord:[t.rectPdfCoord],r=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],o=t.markerAnchor??Ha(i),n=e.markerAnchor??Ha(r);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const h of i)for(const t of r){if(Ya(h,t)<.5)continue;const e=Math.max(h.origin.x,t.origin.x);if(Math.min(h.origin.x+h.size.width,t.origin.x+t.size.width)-e>.25*Math.min(h.size.width,t.size.width))return!0}return!1}const Xa=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.change$=l.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(Wa.id),this.chapterManager=this.registry.getPlugin(Va.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){var a;if(this.config=e,null==(a=e.callbacks)?void 0:a.load)try{const t=await e.callbacks.load();for(const e of t)this.entries.set(e.id,e);this.change$.emit(this.list())}catch(s){this.logger.error(t.id,"Load","Failed to load paragraph bookmarks",s)}}buildCapability(){return{addBookmark:t=>this.addBookmark(t),removeBookmark:t=>this.removeBookmark(t),updateBookmark:(t,e)=>this.updateBookmark(t,e),listBookmarks:()=>this.list(),getBookmark:t=>this.entries.get(t)??null,scrollToBookmark:t=>this.scrollToBookmark(t),requestRemoveBookmark:t=>this.requestRemoveBookmark(t),onBookmarksChange:this.change$.on}}addBookmark(t){for(const s of this.entries.values())if(Ka(s.anchor,t.anchor))return s;const e=t.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:e,label:t.label,anchor:t.anchor,metadata:t.metadata,createdAt:Date.now()};return this.entries.set(e,a),this.notifyAndPersist(),a}removeBookmark(t){var e,a,s;this.entries.delete(t)&&(this.notifyAndPersist(),null==(s=null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,t))}async requestRemoveBookmark(e){var a,s;const i=this.entries.get(e);if(!i)return!1;const r=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(r)try{if(!(await r(i)))return!1}catch(o){return this.logger.error(t.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(e),!0}updateBookmark(t,e){const a=this.entries.get(t);a&&(this.entries.set(t,{...a,...e}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((t,e)=>t.createdAt-e.createdAt)}notifyAndPersist(){var e,a;const s=this.list();this.change$.emit(s),(null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.persist)&&Promise.resolve(this.config.callbacks.persist(s)).catch(e=>this.logger.error(t.id,"Persist","persist callback rejected",e))}async scrollToBookmark(t){const e=this.entries.get(t);if(!e)return;const a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(e.anchor.chapterId);let s=e.anchor.globalPageIndex;if(void 0===s){const t=this.chapterManager.provides().getVirtualPageMap().toGlobal(e.anchor.chapterId,e.anchor.localPageIndex);if(!t)return;s=t.globalPageIndex}const i=function(t){if(t.markerAnchor)return t.markerAnchor.y;const e=t.rectPdfCoord;return e.origin.y+e.size.height}(e.anchor);await async function(t,e,a){t.scrollToGlobalPageIndex(e),await function(t,e,a=2500){const s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const i=setTimeout(()=>{r(),s(null)},a),r=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(i),r(),s(a))})})}(t,e),t.scrollToGlobalPdfPoint(e,a,{marginTop:80})}(a,s,i)}};Xa.id="paragraph-bookmark";let Za=Xa;const Qa={manifest:Ga,create:t=>new Za(Oa,t),reducer:t=>t,initialState:{}},Ja={"annotation-toolbar":{id:"annotation-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"],show:["overflow-annotation-tools"]},md:{minWidth:640,hide:["overflow-annotation-tools"],show:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"]}}},permanent:!1,categories:["annotation"],items:[{type:"spacer",id:"spacer-3",flex:!0},{type:"group",id:"annotation-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-highlight",commandId:"annotation:add-highlight",variant:"icon",categories:["annotation","annotation-markup","annotation-highlight"]},{type:"command-button",id:"add-strikeout",commandId:"annotation:add-strikeout",variant:"icon",categories:["annotation","annotation-markup","annotation-strikeout"]},{type:"command-button",id:"add-underline",commandId:"annotation:add-underline",variant:"icon",categories:["annotation","annotation-markup","annotation-underline"]},{type:"command-button",id:"add-squiggly",commandId:"annotation:add-squiggly",variant:"icon",categories:["annotation","annotation-markup","annotation-squiggly"]},{type:"command-button",id:"add-ink",commandId:"annotation:add-ink",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-ink-highlighter",commandId:"annotation:add-ink-highlighter",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-text",commandId:"annotation:add-text",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"add-insert-text",commandId:"annotation:add-insert-text",variant:"icon",categories:["annotation","annotation-markup","annotation-insert-text"]},{type:"command-button",id:"add-replace-text",commandId:"annotation:add-replace-text",variant:"icon",categories:["annotation","annotation-markup","annotation-replace-text"]},{type:"command-button",id:"add-comment",commandId:"annotation:add-comment",variant:"icon",categories:["annotation","annotation-comment-tool"]},{type:"command-button",id:"add-callout",commandId:"annotation:add-callout",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"overflow-annotation-tools",commandId:"annotation:overflow-tools",variant:"icon",categories:["annotation","annotation-overflow"]},{type:"divider",id:"annotation-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"annotation-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-4",flex:!0}]},"shapes-toolbar":{id:"shapes-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-polygon","add-polyline"],show:["overflow-shapes-tools"]},md:{minWidth:640,hide:["overflow-shapes-tools"],show:["add-polygon","add-polyline"]}}},permanent:!1,categories:["annotation","annotation-shape"],items:[{type:"spacer",id:"spacer-5",flex:!0},{type:"group",id:"shapes-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rectangle",commandId:"annotation:add-rectangle",variant:"icon",categories:["annotation","annotation-shape","annotation-rectangle"]},{type:"command-button",id:"add-circle",commandId:"annotation:add-circle",variant:"icon",categories:["annotation","annotation-shape","annotation-circle"]},{type:"command-button",id:"add-line",commandId:"annotation:add-line",variant:"icon",categories:["annotation","annotation-shape","annotation-line"]},{type:"command-button",id:"add-arrow",commandId:"annotation:add-arrow",variant:"icon",categories:["annotation","annotation-shape","annotation-arrow"]},{type:"command-button",id:"add-polygon",commandId:"annotation:add-polygon",variant:"icon",categories:["annotation","annotation-shape","annotation-polygon"]},{type:"command-button",id:"add-polyline",commandId:"annotation:add-polyline",variant:"icon",categories:["annotation","annotation-shape","annotation-polyline"]},{type:"command-button",id:"overflow-shapes-tools",commandId:"annotation:overflow-shapes",variant:"icon",categories:["annotation","annotation-shape","annotation-overflow"]},{type:"divider",id:"shapes-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"shapes-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-6",flex:!0}]},"form-toolbar":{id:"form-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-form-select","add-form-listbox"],show:["overflow-forms-tools"]},md:{minWidth:640,hide:["overflow-forms-tools"],show:["add-form-select","add-form-listbox"]}}},permanent:!1,categories:["form"],items:[{type:"spacer",id:"spacer-form-1",flex:!0},{type:"group",id:"form-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-form-textfield",commandId:"form:add-textfield",variant:"icon",categories:["form","form-textfield"]},{type:"command-button",id:"add-form-checkbox",commandId:"form:add-checkbox",variant:"icon",categories:["form","form-checkbox"]},{type:"command-button",id:"add-form-radio",commandId:"form:add-radio",variant:"icon",categories:["form","form-radio"]},{type:"command-button",id:"add-form-select",commandId:"form:add-select",variant:"icon",categories:["form","form-select"]},{type:"command-button",id:"add-form-listbox",commandId:"form:add-listbox",variant:"icon",categories:["form","form-listbox"]},{type:"command-button",id:"overflow-forms-tools",commandId:"form:overflow-tools",variant:"icon",categories:["form","form-overflow"]},{type:"divider",id:"form-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"command-button",id:"toggle-form-fill-mode",commandId:"form:toggle-fill-mode",variant:"icon",categories:["form","form-fill-mode"]},{type:"divider",id:"form-tools-divider-2",orientation:"vertical"},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-form-2",flex:!0}]},"insert-toolbar":{id:"insert-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["insert"],items:[{type:"spacer",id:"spacer-insert-1",flex:!0},{type:"group",id:"insert-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rubber-stamp",commandId:"insert:add-rubber-stamp",variant:"icon",categories:["insert","insert-rubber-stamp"]},{type:"command-button",id:"add-signature",commandId:"insert:add-signature",variant:"icon",categories:["insert","insert-signature"]},{type:"command-button",id:"add-image",commandId:"insert:add-image",variant:"icon",categories:["insert","insert-image"]},{type:"divider",id:"insert-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"insert-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-insert-2",flex:!0}]},"redaction-toolbar":{id:"redaction-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["redaction"],items:[{type:"spacer",id:"spacer-7",flex:!0},{type:"group",id:"redaction-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"redact",commandId:"redaction:redact",variant:"icon",categories:["redaction","redaction-combined"]},{type:"divider",id:"redaction-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-redaction-panel",commandId:"panel:toggle-redaction",variant:"icon",categories:["panel","panel-redaction"]},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"redaction-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-8",flex:!0}]}};class ts{constructor(){this.specs=[]}register(t){if(this.specs.some(e=>e.id===t.id))throw new Error(`OperationRegistry: duplicate operation id "${t.id}"`);this.specs.push(t)}registerAll(t){for(const e of t)e&&this.register(e)}list(){return this.specs}buildToolbars(){const t=structuredClone(Ja);for(const e of this.specs){const a=t[e.toolbarSlot];if(!a)continue;const s={type:"command-button",id:e.id,commandId:e.commandId,variant:"icon",...e.icon?{icon:e.icon}:{},...e.i18nKey?{labelKey:e.i18nKey}:{},...e.label?{label:e.label}:{},categories:e.categories??[]};a.items=es(a.items,s,e.position)}return t}}function es(t,e,a){return(null==a?void 0:a.after)||(null==a?void 0:a.before)?function(t,e,a){const s=t=>{const i=[];for(const r of t)"group"!==r.type?a.before&&r.id===a.before?i.push(e,r):(i.push(r),a.after&&r.id===a.after&&i.push(e)):i.push({...r,items:s(r.items)});return i};return s(t)}(t,e,a):(s=e,t.map(t=>"group"===t.type?{...t,items:[...t.items,s]}:t));var s}const as={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function ss(t){var e,a,s,i,r,n;const h=t.toolbar??{},d=h.enabledModes??["view","annotate","shapes","insert","form","redact"],u=d.length>0,{schema:S,operationRegistry:x}=function(t={}){var e,a,s,i,r,o;const n=new Set(t.enabledModes??["view","annotate","shapes","insert","form","redact"]),h=new ts;(null==(e=t.customOperations)?void 0:e.length)&&h.registerAll(t.customOperations);const l=h.buildToolbars(),d={};for(const u of n){if("view"===u)continue;const t=as[u];l[t]&&(d[t]=l[t])}const c=function(t){if(0===t.size)return null;const e=(t,e,a)=>({type:"command-button",id:`${t}-mode`,commandId:a,variant:"text",label:e,categories:["mode",t]});return{id:"chapter-editor-main-toolbar",position:{placement:"top",slot:"main",order:0},permanent:!0,items:[{type:"spacer",id:"main-spacer-left",flex:!0},{type:"group",id:"mode-group",alignment:"start",gap:2,items:[...t.has("view")?[e("view","View","mode:view")]:[],...t.has("annotate")?[e("annotate","Annotate","mode:annotate")]:[],...t.has("shapes")?[e("shapes","Shapes","mode:shapes")]:[],...t.has("insert")?[e("insert","Insert","mode:insert")]:[],...t.has("form")?[e("form","Form","mode:form")]:[],...t.has("redact")?[e("redact","Redact","mode:redact")]:[]]},{type:"spacer",id:"main-spacer-right",flex:!0}]}}(n);return c&&(d["chapter-editor-main-toolbar"]=c),(null==(a=t.extend)?void 0:a.toolbars)&&Object.assign(d,t.extend.toolbars),{schema:{id:"chapter-pdf-editor-ui",version:"1.0.0",toolbars:d,menus:(null==(s=t.extend)?void 0:s.menus)??{},sidebars:(null==(i=t.extend)?void 0:i.sidebars)??{},modals:(null==(r=t.extend)?void 0:r.modals)??{},selectionMenus:(null==(o=t.extend)?void 0:o.selectionMenus)??{}},operationRegistry:h}}({...h,enabledModes:d}),L={...u?{"mode:view":{id:"mode:view",label:"View",categories:["mode","mode-view"],action:({registry:t,documentId:e})=>{var a,s,i,r;const o=null==(a=t.getPlugin("ui"))?void 0:a.provides(),n=null==(s=t.getPlugin("interaction-manager"))?void 0:s.provides();o&&n&&(null==(i=n.forDocument(e))||i.activateDefaultMode(),o.forDocument(e).closeToolbarSlot("top","secondary"),null==(r=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(e).setLocked(t.getPluginConfig(p.ANNOTATION_PLUGIN_ID).locked??{type:p.LockModeType.None}))},active:({state:t,documentId:e})=>!M.isToolbarOpen(t.plugins,e,"top","secondary")},"mode:annotate":{id:"mode:annotate",label:"Annotate",categories:["mode","mode-annotate","annotation"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","annotation-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","annotation-toolbar")},"mode:shapes":{id:"mode:shapes",label:"Shapes",categories:["mode","mode-shapes","annotation"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","shapes-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","shapes-toolbar")},"mode:insert":{id:"mode:insert",label:"Insert",categories:["mode","mode-insert","insert"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","insert-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","insert-toolbar")},"mode:form":{id:"mode:form",label:"Form",categories:["mode","mode-form","form"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","form-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.None}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","form-toolbar")},"mode:redact":{id:"mode:redact",label:"Redact",categories:["mode","mode-redact","redaction"],action:({registry:t,documentId:e})=>{var a,s;const i=null==(a=t.getPlugin("ui"))?void 0:a.provides();i&&(i.setActiveToolbar("top","secondary","redaction-toolbar",e),null==(s=t.getPlugin(p.ANNOTATION_PLUGIN_ID))||s.provides().forDocument(e).setLocked({type:p.LockModeType.Include,categories:["form"]}))},active:({state:t,documentId:e})=>M.isToolbarOpen(t.plugins,e,"top","secondary","redaction-toolbar")}}:{},...u?is(x.list()):{},...t.commands??{}},$=[l.createPluginRegistration(c.DocumentManagerPluginPackage,{initialDocuments:[]}),l.createPluginRegistration(ia,{manifest:t.manifest,overlapStrategy:t.overlapStrategy,passwordProvider:t.passwordProvider,chapterPdfLoader:t.chapterPdfLoader,prefetchChapters:t.prefetchChapters,unloadTimeoutMs:t.unloadTimeoutMs}),l.createPluginRegistration(ga,{placeholderPageHeight:t.placeholderPageHeight,placeholderPageWidth:t.placeholderPageWidth}),l.createPluginRegistration(g.InteractionManagerPluginPackage),l.createPluginRegistration(f.RenderPluginPackage),l.createPluginRegistration(m.RotatePluginPackage),l.createPluginRegistration(o.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),l.createPluginRegistration(v.HistoryPluginPackage),l.createPluginRegistration(p.AnnotationPluginPackage),l.createPluginRegistration(b.RedactionPluginPackage),l.createPluginRegistration(P.FormPluginPackage),l.createPluginRegistration(w.StampPluginPackage,!1===t.loadDefaultStampLibrary?{manifests:[]}:void 0),l.createPluginRegistration(I.SignaturePluginPackage),...Object.keys(L).length>0?[l.createPluginRegistration(y.CommandsPluginPackage,{commands:L})]:[],...u?[l.createPluginRegistration(C.I18nPluginPackage),l.createPluginRegistration(M.UIPluginPackage,{schema:S})]:[]];return t.notes&&$.push(l.createPluginRegistration(za,{callbacks:t.notes.callbacks,ui:null==(a=null==(e=t.features)?void 0:e.notes)?void 0:a.marker})),t.bookmarks&&$.push(l.createPluginRegistration(Qa,{callbacks:t.bookmarks.callbacks,ui:null==(i=null==(s=t.features)?void 0:s.bookmarks)?void 0:i.marker,hover:null==(n=null==(r=t.features)?void 0:r.bookmarks)?void 0:n.hover})),{plugins:$,uiSchema:S,operationRegistry:x}}function is(t){const e={};for(const a of t)a.handler&&(e[a.commandId]={id:a.commandId,labelKey:a.i18nKey,label:a.label,icon:a.icon,categories:a.categories,action:({documentId:t})=>{var e;null==(e=a.handler)||e.call(a,{documentId:t,chapterId:t})}});return e}const rs={markup:{enabled:!0},bookmarks:{enabled:!0},notes:{enabled:!0},selectionToolbar:{enabled:!0},zoom:{enabled:!0,min:.5,max:3,initial:1}};class os{constructor(t){this.cb=t}resolvePassword(t,e){return this.cb(t,e)}}const ns={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:0},strikeout:{offsetY:0}},hs={highlight:d.PdfAnnotationSubtype.HIGHLIGHT,underline:d.PdfAnnotationSubtype.UNDERLINE,squiggly:d.PdfAnnotationSubtype.SQUIGGLY,strikeout:d.PdfAnnotationSubtype.STRIKEOUT};function ls(t,e){return 0===e?t:t.map(t=>({origin:{x:t.origin.x,y:t.origin.y+e},size:{...t.size}}))}function ds(t){let e=1/0,a=1/0,s=-1/0,i=-1/0;for(const r of t)e=Math.min(e,r.origin.x),a=Math.min(a,r.origin.y),s=Math.max(s,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:e,y:a},size:{width:s-e,height:i-a}}}const cs={kind:"first-wins"};function us(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let ps=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};function gs(t,e=cs){const a=function(t,e=cs){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,us(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new ps(r)}const fs=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=cs,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??cs,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=gs(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));if(t&&this.documentManager.provides().isDocumentOpen(t)){this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus){if("loaded"!==s)continue;e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}if(!o)return void this.updateStatus(e,"password-required");this.updateStatus(e,"loading");this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})}closeChapter(t){const e=this.documentManager.provides();if(e.isDocumentOpen(t)){e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed"))}else this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};fs.id="chapter-manager";let ms=fs;const vs={kind:"first-wins"};function bs(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class Ps{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}function ws(t,e=vs){const a=function(t,e=vs){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,bs(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Ps(r)}const Is=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=vs,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??vs,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=ws(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));if(t&&this.documentManager.provides().isDocumentOpen(t)){this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus){if("loaded"!==s)continue;e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}if(!o)return void this.updateStatus(e,"password-required");this.updateStatus(e,"loading");this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})}closeChapter(t){const e=this.documentManager.provides();if(e.isDocumentOpen(t)){e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed"))}else this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Is.id="chapter-manager";let ys=Is;const Cs=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(ys.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};Cs.id="chapter-scroll";let Ms=Cs;function Ss(t){if(0===t.length)throw new Error("unionRects: empty rects");let e=1/0,a=1/0,s=-1/0,i=-1/0;for(const r of t)e=Math.min(e,r.origin.x),a=Math.min(a,r.origin.y),s=Math.max(s,r.origin.x+r.size.width),i=Math.max(i,r.origin.y+r.size.height);return{origin:{x:e,y:a},size:{width:s-e,height:i-a}}}function xs(t){const e=t[t.length-1];return{x:e.origin.x+e.size.width,y:e.origin.y+e.size.height}}function Ls(t,e){const a=t.origin.y,s=t.origin.y+t.size.height,i=e.origin.y,r=e.origin.y+e.size.height,o=Math.max(s,r)-Math.min(a,i);if(o<=0)return 0;return Math.max(0,Math.min(s,r)-Math.max(a,i))/o}function $s(t,e){var a,s;if(t.chapterId!==e.chapterId||t.localPageIndex!==e.localPageIndex)return!1;const i=(null==(a=t.rectsPdfCoord)?void 0:a.length)?t.rectsPdfCoord:[t.rectPdfCoord],r=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],o=t.markerAnchor??xs(i),n=e.markerAnchor??xs(r);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const h of i)for(const t of r){if(Ls(h,t)<.5)continue;const e=Math.max(h.origin.x,t.origin.x);if(Math.min(h.origin.x+h.size.width,t.origin.x+t.size.width)-e>.25*Math.min(h.size.width,t.size.width))return!0}return!1}async function ks(t,e,a){t.scrollToGlobalPageIndex(e),await function(t,e,a=2500){const s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const i=setTimeout(()=>{r(),s(null)},a),r=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(i),r(),s(a))})})}(t,e),t.scrollToGlobalPdfPoint(e,a,{marginTop:80})}(class t extends l.BasePlugin{constructor(t,e){super(t,e),this.change$=l.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(Ms.id),this.chapterManager=this.registry.getPlugin(ms.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(e){var a;if(this.config=e,null==(a=e.callbacks)?void 0:a.load)try{const t=await e.callbacks.load();for(const e of t)this.entries.set(e.id,e);this.change$.emit(this.list())}catch(s){this.logger.error(t.id,"Load","Failed to load paragraph bookmarks",s)}}buildCapability(){return{addBookmark:t=>this.addBookmark(t),removeBookmark:t=>this.removeBookmark(t),updateBookmark:(t,e)=>this.updateBookmark(t,e),listBookmarks:()=>this.list(),getBookmark:t=>this.entries.get(t)??null,scrollToBookmark:t=>this.scrollToBookmark(t),requestRemoveBookmark:t=>this.requestRemoveBookmark(t),onBookmarksChange:this.change$.on}}addBookmark(t){for(const s of this.entries.values())if($s(s.anchor,t.anchor))return s;const e=t.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:e,label:t.label,anchor:t.anchor,metadata:t.metadata,createdAt:Date.now()};return this.entries.set(e,a),this.notifyAndPersist(),a}removeBookmark(t){var e,a,s;this.entries.delete(t)&&(this.notifyAndPersist(),null==(s=null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,t))}async requestRemoveBookmark(e){var a,s;const i=this.entries.get(e);if(!i)return!1;const r=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(r)try{if(!(await r(i)))return!1}catch(o){return this.logger.error(t.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(e),!0}updateBookmark(t,e){const a=this.entries.get(t);a&&(this.entries.set(t,{...a,...e}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((t,e)=>t.createdAt-e.createdAt)}notifyAndPersist(){var e,a;const s=this.list();this.change$.emit(s),(null==(a=null==(e=this.config)?void 0:e.callbacks)?void 0:a.persist)&&Promise.resolve(this.config.callbacks.persist(s)).catch(e=>this.logger.error(t.id,"Persist","persist callback rejected",e))}async scrollToBookmark(t){const e=this.entries.get(t);if(!e)return;const a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(e.anchor.chapterId);let s=e.anchor.globalPageIndex;if(void 0===s){const t=this.chapterManager.provides().getVirtualPageMap().toGlobal(e.anchor.chapterId,e.anchor.localPageIndex);if(!t)return;s=t.globalPageIndex}const i=function(t){if(t.markerAnchor)return t.markerAnchor.y;const e=t.rectPdfCoord;return e.origin.y+e.size.height}(e.anchor);await ks(a,s,i)}}).id="paragraph-bookmark";const Ds={kind:"first-wins"};function Ts(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}let zs=class{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}};function Os(t,e=Ds){const a=function(t,e=Ds){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Ts(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new zs(r)}const Gs=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Ds,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Ds,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=Os(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));if(t&&this.documentManager.provides().isDocumentOpen(t)){this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus){if("loaded"!==s)continue;e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}if(!o)return void this.updateStatus(e,"password-required");this.updateStatus(e,"loading");this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})}closeChapter(t){const e=this.documentManager.provides();if(e.isDocumentOpen(t)){e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed"))}else this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};Gs.id="chapter-manager";let As=Gs;const Ns={kind:"first-wins"};function Es(t,e,a){if(1===e.length)return e[0].chapterId;switch(a.kind){case"first-wins":return e[0].chapterId;case"last-wins":return e[e.length-1].chapterId;case"explicit":{const a=e.find(e=>{var a;return null==(a=e.ownedGlobalPages)?void 0:a.includes(t)});return a?a.chapterId:e[0].chapterId}case"custom":return a.resolve(t,e)}}class Rs{constructor(t){this._pages=t,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const e of t){this._byGlobalNumber.set(e.globalPageNumber,e);let t=this._byChapter.get(e.chapterId);t||(t=[],this._byChapter.set(e.chapterId,t)),t.push(e)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(t){return this._pages[t]??null}byGlobalNumber(t){return this._byGlobalNumber.get(t)??null}toGlobal(t,e){const a=this._byChapter.get(t);return a?a.find(t=>t.localPageIndex===e)??null:null}pagesOfChapter(t){return this._byChapter.get(t)??[]}firstIndexOfChapter(t){var e;const a=null==(e=this._byChapter.get(t))?void 0:e[0];return a?this._pages.indexOf(a):-1}}function Vs(t,e=Ns){const a=function(t,e=Ns){const a=new Map;for(const i of t.chapters){const[t,e]=i.globalPageRange;for(let s=t;s<=e;s++){const t=a.get(s);t?t.push(i):a.set(s,[i])}}const s=new Map;for(const[i,r]of a)s.set(i,Es(i,r,e));return s}(t,e),s=new Map;for(const n of t.chapters)s.set(n.chapterId,n);const i=Array.from(a.keys()).sort((t,e)=>t-e),r=[];let o=0;for(const n of i){const t=a.get(n),e=s.get(t);if(!e)continue;const[i]=e.globalPageRange,[h]=e.localPageRange,l=h+(n-i);r.push({globalPageIndex:o++,globalPageNumber:n,chapterId:t,localPageIndex:l})}return new Rs(r)}const _s=class t extends l.BasePlugin{constructor(t,e){super(t,e),this.statusChange$=l.createBehaviorEmitter(),this.manifestChange$=l.createEmitter(),this.overlapStrategy=Ns,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,this.passwordProvider=t.passwordProvider,this.overlapStrategy=t.overlapStrategy??Ns,this.setManifestInternal(t.manifest),this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(t=>{this.isOwnedChapter(t.id)&&(this.passwordAttempts.delete(t.id),this.updateStatus(t.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(t=>{this.isOwnedChapter(t)&&this.updateStatus(t,"closed")}),this.documentManager.provides().onDocumentError(t=>{this.isOwnedChapter(t.documentId)&&this.handleDocumentError(t.documentId,t.code,t.message)})),t.unloadTimeoutMs&&t.unloadTimeoutMs>0){const e=Math.max(5e3,Math.floor(t.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),e)}}buildCapability(){return{setManifest:(t,e)=>{e&&(this.overlapStrategy=e),this.setManifestInternal(t)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:t=>this.handleVisibleChange(t),ensureChapterLoaded:t=>this.ensureChapterLoaded(t),getChapterStatus:t=>this.chapterStatus.get(t)??"idle",getChapter:t=>this.findChapter(t),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const t of this.documentManagerUnsubs)t();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(e){const a=function(t){const e=[],a=new Set;for(const s of t.chapters){a.has(s.chapterId)&&e.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[t,i]=s.globalPageRange,[r,o]=s.localPageRange;if(t>i&&e.push(`${s.chapterId}: invalid globalPageRange [${t},${i}]`),r>o&&e.push(`${s.chapterId}: invalid localPageRange [${r},${o}]`),i-t!==o-r&&e.push(`${s.chapterId}: page-count mismatch (global ${i-t+1} vs local ${o-r+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<t||a>i)&&e.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return e}(e);a.length>0&&this.logger.warn(t.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),i=new Set(e.chapters.map(t=>t.chapterId));for(const t of s)i.has(t)||(this.closeChapter(t),this.chapterStatus.delete(t));for(const t of e.chapters)this.chapterStatus.has(t.chapterId)||this.chapterStatus.set(t.chapterId,"idle");this.manifest=e,this.virtualPageMap=Vs(e,this.overlapStrategy),this.manifestChange$.emit({manifest:e,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const t=this.config.prefetchChapters??0;if(t<=0||0===this.manifest.chapters.length)return;const e=Date.now(),a=Math.min(t,this.manifest.chapters.length);for(let s=0;s<a;s++){const t=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(t,e);const a=this.chapterStatus.get(t)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(t)}}findChapter(t){return this.manifest.chapters.find(e=>e.chapterId===t)??null}isOwnedChapter(t){return!!this.findChapter(t)}handleVisibleChange(t){if(!this.virtualPageMap)return;const e=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of t){const t=this.virtualPageMap.atIndex(n);t&&s.add(t.chapterId)}if(0===s.size)return;const i=this.manifest.chapters.map(t=>t.chapterId),r=new Set;for(const n of s){const t=i.indexOf(n);if(-1!==t)for(let e=t-a;e<=t+a;e++)e>=0&&e<i.length&&r.add(e)}const o=new Set;for(const n of r)o.add(i[n]);for(const n of o){this.chapterLastUsed.set(n,e);const t=this.chapterStatus.get(n)??"idle";"idle"!==t&&"closed"!==t&&"error"!==t||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const t=i.find(t=>s.has(t));if(t&&this.documentManager.provides().isDocumentOpen(t)){this.documentManager.provides().getActiveDocumentId()!==t&&this.documentManager.provides().setActiveDocument(t)}}}collectIdleChapters(){const t=this.config.unloadTimeoutMs??6e4;if(t<=0)return;const e=Date.now();for(const[a,s]of this.chapterStatus){if("loaded"!==s)continue;e-(this.chapterLastUsed.get(a)??0)>t&&this.closeChapter(a)}}ensureChapterLoaded(t){const e=this.pendingLoadPromises.get(t);if(e)return e;const a=this.findChapter(t);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const i=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(t)});return this.pendingLoadPromises.set(t,i),i}async resolvePdfPayload(t){const e=t.source;if(e){if("url"in e)return{url:e.url};if("buffer"in e)return{buffer:e.buffer};if("load"in e)return e.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(t);throw new Error(`Chapter "${t.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var e;this.updateStatus(t.chapterId,"loading"),this.chapterLastUsed.set(t.chapterId,Date.now());const a=t.encrypted&&(null==(e=this.passwordProvider)?void 0:e.getCachedPassword)?this.passwordProvider.getCachedPassword(t.chapterId):null,s=await this.resolvePdfPayload(t),i=this.documentManager.provides(),r="url"in s?i.openDocumentUrl({documentId:t.chapterId,url:s.url,name:t.title,password:a??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:t.chapterId,buffer:s.buffer,name:t.title,password:a??void 0,autoActivate:!1});return await new Promise(t=>r.wait(()=>t(),()=>t())),this.waitForTerminalStatus(t.chapterId)}waitForTerminalStatus(t){return new Promise(e=>{const a=t=>{"loaded"!==t&&"error"!==t&&"password-required"!==t&&"closed"!==t||(s(),e(t))},s=this.statusChange$.on(e=>{e.chapterId===t&&a(e.status)});a(this.chapterStatus.get(t)??"idle")})}async handleDocumentError(e,a,s){if(a!==d.PdfErrorCode.Password)return void this.updateStatus(e,"error");if(!this.passwordProvider)return void this.updateStatus(e,"password-required");const i=this.findChapter(e);if(!i)return;const r=(this.passwordAttempts.get(e)??0)+1;this.passwordAttempts.set(e,r);let o=null;try{o=await this.passwordProvider.resolvePassword(i,r-1)}catch(n){this.logger.error(t.id,"PasswordProvider",`Provider rejected for ${e}`,n)}if(!o)return void this.updateStatus(e,"password-required");this.updateStatus(e,"loading");this.documentManager.provides().retryDocument(e,{password:o}).wait(()=>{},()=>{})}closeChapter(t){const e=this.documentManager.provides();if(e.isDocumentOpen(t)){e.closeDocument(t).wait(()=>this.updateStatus(t,"closed"),()=>this.updateStatus(t,"closed"))}else this.updateStatus(t,"closed")}updateStatus(t,e,a){this.chapterStatus.get(t)!==e&&(this.chapterStatus.set(t,e),this.statusChange$.emit({chapterId:t,status:e,..."error"===e&&a?{error:{message:a}}:{}}))}};_s.id="chapter-manager";let Us=_s;const Fs=class extends l.BasePlugin{constructor(t,e){super(t,e),this.layoutChange$=l.createBehaviorEmitter(),this.visibleChange$=l.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Us.id),this.documentManager=this.registry.getPlugin(c.DocumentManagerPlugin.id)}async initialize(t){this.config={placeholderPageHeight:t.placeholderPageHeight??1200,placeholderPageWidth:t.placeholderPageWidth??900,bufferSize:t.bufferSize??2,pageGap:t.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:t})=>{this.virtualPageMap=t,this.pageSizes.clear(),this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()})),this.syncReadyChapterSizes()}isChapterDocumentReady(t){const e=this.coreState.core.documents[t];return!(!e||"loaded"!==e.status||!e.document)&&e.document.pages.length>0}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}syncReadyChapterSizes(){for(const t of this.chapterManager.provides().getManifest().chapters)this.isChapterDocumentReady(t.chapterId)&&this.harvestChapterSizes(t.chapterId);this.refreshLayout()}onDocumentLoaded(t){var e;if(0===((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(t),this.harvestChapterSizes(t),this.refreshLayout()}onDocumentClosed(t){var e;0!==((null==(e=this.virtualPageMap)?void 0:e.pagesOfChapter(t).length)??0)&&(this.dropChapterSizes(t),this.refreshLayout())}buildCapability(){return{registerViewport:t=>this.bindViewport(t),reportChapterPageSizes:(t,e)=>this.applyChapterPageSizes(t,e),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(t,e)=>this.scrollToIndex(t,e),scrollToChapter:(t,e)=>this.scrollToChapter(t,e),scrollToGlobalPageNumber:(t,e)=>this.scrollToGlobalNumber(t,e),scrollToGlobalPdfPoint:(t,e,a)=>this.scrollToGlobalPdfPoint(t,e,a),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var t;super.destroy();for(const e of this.chapterManagerUnsubs)e();this.chapterManagerUnsubs=[],null==(t=this.viewportObservers)||t.unbind(),this.viewportObservers=null,this.viewportEl=null,this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(t){return this.pageSizes.get(t)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const t=this.virtualPageMap.totalPages;this.offsets=new Array(t);let e=0,a=0;for(let s=0;s<t;s++){const{width:t,height:i}=this.getPageSize(s);this.offsets[s]=e,e+=i+this.config.pageGap,t>a&&(a=t)}this.totalHeight=t>0?e-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(t,e){if(!this.virtualPageMap)return;let a=!1;for(const s of e){const e=this.virtualPageMap.toGlobal(t,s.localPageIndex);if(!e)continue;const i=this.pageSizes.get(e.globalPageIndex);i&&i.width===s.width&&i.height===s.height||(this.pageSizes.set(e.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const t=this.currentGlobalPageIndex,e=this.offsets[t]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[t]??0)-e;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(t){var e;return(null==(e=this.coreState.core.documents[t])?void 0:e.scale)??1}harvestChapterSizes(t,e=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(t),i=this.virtualPageMap.pagesOfChapter(t);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===i.length)return void(e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1)));const r=this.getChapterDocumentScale(t),o=[];for(const n of i){const t=s.pages[n.localPageIndex];(null==t?void 0:t.size)&&o.push({localPageIndex:n.localPageIndex,width:t.size.width*r,height:t.size.height*r})}0!==o.length?this.applyChapterPageSizes(t,o):e<60&&requestAnimationFrame(()=>this.harvestChapterSizes(t,e+1))}onScaleChanged(t){const e=this.coreState.core.documents[t];e&&"loaded"===e.status&&this.chapterManager.provides().getChapter(t)&&this.harvestChapterSizes(t)}dropChapterSizes(t){if(!this.virtualPageMap)return;let e=!1;for(const a of this.virtualPageMap.pagesOfChapter(t))this.pageSizes.delete(a.globalPageIndex)&&(e=!0);e&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(t){var e;if(null==(e=this.viewportObservers)||e.unbind(),this.viewportEl=t,this.viewportObservers=null,!t)return;const a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());t.addEventListener("scroll",a,{passive:!0}),s.observe(t),this.viewportObservers={unbind:()=>{t.removeEventListener("scroll",a),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===t.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const t=this.virtualPageMap.totalPages;if(0===t)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const e=this.viewportEl.scrollTop,a=e+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(e);let i=s;for(;i<t;){const t=this.getPageSize(i),e=this.offsets[i];if(t.height,e>=a)break;i++}const r=[];let o=s,n=-1;for(let h=s;h<i;h++){r.push(h);const t=this.offsets[h],s=t+this.getPageSize(h).height,i=Math.max(0,Math.min(s,a)-Math.max(t,e));i>n&&(n=i,o=h)}this.currentVisible=r,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:r,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(r),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(t){let e=0,a=this.offsets.length-1,s=0;for(;e<=a;){const i=e+a>>1;this.offsets[i]<=t?(s=i,e=i+1):a=i-1}return s}computeLayout(){const t=this.config.bufferSize,e=Math.max(0,(this.currentVisible[0]??0)-t),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+t),i=[];if(this.virtualPageMap&&this.offsets.length>0)for(let r=e;r<=s;r++){const t=this.virtualPageMap.atIndex(r);if(!t)continue;const e=this.getPageSize(r),a=!this.isChapterDocumentReady(t.chapterId);i.push({globalPageIndex:r,globalPageNumber:t.globalPageNumber,chapterId:t.chapterId,localPageIndex:t.localPageIndex,width:e.width,height:e.height,offsetTop:this.offsets[r],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:i,pageGap:this.config.pageGap}}scrollToIndex(t,e){if(!this.viewportEl||t<0||t>=this.offsets.length)return;const a=(this.offsets[t]??0)-((null==e?void 0:e.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==e?void 0:e.behavior)??"auto"})}scrollToGlobalPdfPoint(t,e,a){var s;if(!this.viewportEl||t<0||t>=this.offsets.length||!this.virtualPageMap)return;const i=(null==a?void 0:a.marginTop)??80,r=this.virtualPageMap.atIndex(t);if(!r)return void this.scrollToIndex(t,a);const o=this.pageSizes.get(t),n=null==(s=this.documentManager.provides().getDocument(r.chapterId))?void 0:s.pages[r.localPageIndex];if(!o||!n)return void this.scrollToIndex(t,a);const h=o.height/n.size.height,l=(this.offsets[t]??0)+e*h-i;this.viewportEl.scrollTo({top:Math.max(0,l),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(t);a<0||(this.chapterManager.provides().ensureChapterLoaded(t),this.scrollToIndex(a,e))}scrollToGlobalNumber(t,e){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(t);a&&this.scrollToIndex(a.globalPageIndex,e)}};Fs.id="chapter-scroll";let qs=Fs;const Bs={idle:"未加载",loading:"加载中",loaded:"已加载",closed:"已卸载",error:"失败","password-required":"需密码"};function js({nodes:e,depth:a,activeChapterId:s,chapterStatus:i,onSelect:r}){return t.jsx("ul",{style:{margin:0,padding:0,listStyle:"none",marginLeft:a>0?12:0},children:e.map(e=>t.jsx(Ws,{node:e,depth:a,activeChapterId:s,chapterStatus:i,onSelect:r},e.id))})}function Ws({node:a,depth:s,activeChapterId:i,chapterStatus:r,onSelect:o}){const n=a.children??[],h=n.length>0,[l,d]=e.useState(s<1),c=i===a.id,u=r[a.id]??"idle",p=!h;return t.jsxs("li",{children:[t.jsxs("div",{style:{display:"flex",alignItems:"stretch",gap:2},children:[h?t.jsx("button",{type:"button","aria-expanded":l,style:Xs,onClick:()=>d(t=>!t),children:l?"▼":"▶"}):t.jsx("span",{style:{width:16,flexShrink:0},"aria-hidden":!0}),t.jsxs("button",{type:"button",style:{...Zs,background:c?"#1e293b":"transparent",color:c?"#fff":"#334155"},onClick:()=>o(a.id),children:[t.jsx("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:500},children:a.title}),t.jsxs("div",{style:{marginTop:2,fontSize:10,color:c?"#cbd5e1":"#94a3b8",display:"flex",flexWrap:"wrap",gap:"4px 8px"},children:[t.jsxs("span",{children:["第 ",a.startPage,a.endPage!==a.startPage?`–${a.endPage}`:""," 页"]}),p?t.jsx("span",{children:Bs[u]}):null]})]})]}),h&&l?t.jsx(js,{nodes:n,depth:s+1,activeChapterId:i,chapterStatus:r,onSelect:o}):null]})}const Hs={display:"flex",flexDirection:"column",width:224,flexShrink:0,borderRadius:8,border:"1px solid #e2e8f0",background:"#fff",overflow:"hidden"},Ys={margin:0,padding:"8px 12px",fontSize:12,fontWeight:600,color:"#334155",borderBottom:"1px solid #f1f5f9"},Ks={flex:1,overflowY:"auto",padding:4},Xs={flexShrink:0,padding:"0 4px",border:"none",background:"transparent",fontSize:10,color:"#94a3b8",cursor:"pointer"},Zs={minWidth:0,flex:1,border:"none",borderRadius:6,padding:"8px",textAlign:"left",fontSize:13,cursor:"pointer"};Object.defineProperty(exports,"EmbedPDF",{enumerable:!0,get:()=>a.EmbedPDF}),Object.defineProperty(exports,"useCapability",{enumerable:!0,get:()=>a.useCapability}),Object.defineProperty(exports,"usePdfiumEngine",{enumerable:!0,get:()=>S.usePdfiumEngine}),exports.CallbackPasswordProvider=class{constructor(t){this.cb=t}resolvePassword(t,e){return this.cb(t,e)}},exports.ChapterManagerPlugin=As,exports.ChapterPdfViewer=function({engine:s,editorOptions:i,features:r,className:o,viewportClassName:n,buildSelectionMenu:h,onExtraSelectionAction:l,renderPageOverlay:d,children:c}){var u,p,g,f;const m=e.useMemo(()=>({...Ye,...r}),[r]),v=e.useMemo(()=>Ke({...i,features:m}),[i,m]),b=!1!==(null==(u=m.zoom)?void 0:u.enabled),[P,w]=e.useState((null==(p=m.zoom)?void 0:p.initial)??1),I=e.useRef(null);return e.useEffect(()=>{var t,e;if(!b)return;const a=I.current;if(!a)return;const s=a.querySelector("[data-chapter-scroll-viewport]");return s?function({container:t,getScale:e,setScale:a,minZoom:s=.5,maxZoom:i=3}){let r=0,o=1,n=null,h=1,l=1;const d=t=>{(t.ctrlKey||t.metaKey)&&(t.preventDefault(),null===n?(l=e(),h=1):clearTimeout(n),h*=1-.01*t.deltaY,h=Xe(h,.1,10),a(Xe(l*h,s,i)),n=setTimeout(()=>{n=null},120))},c=new Map,u=t=>{if(c.set(t.pointerId,{x:t.clientX,y:t.clientY}),2===c.size){const[t,a]=[...c.values()];r=Math.hypot(a.x-t.x,a.y-t.y),o=e()}},p=t=>{if(c.has(t.pointerId)&&(c.set(t.pointerId,{x:t.clientX,y:t.clientY}),2===c.size&&r>0)){t.preventDefault();const[e,n]=[...c.values()],h=Math.hypot(n.x-e.x,n.y-e.y);a(Xe(o*(h/r),s,i))}},g=t=>{c.delete(t.pointerId),c.size<2&&(r=0)};return t.addEventListener("wheel",d,{passive:!1}),t.addEventListener("pointerdown",u),t.addEventListener("pointermove",p,{passive:!1}),t.addEventListener("pointerup",g),t.addEventListener("pointercancel",g),()=>{t.removeEventListener("wheel",d),t.removeEventListener("pointerdown",u),t.removeEventListener("pointermove",p),t.removeEventListener("pointerup",g),t.removeEventListener("pointercancel",g),n&&clearTimeout(n)}}({container:s,getScale:()=>P,setScale:w,minZoom:(null==(t=m.zoom)?void 0:t.min)??.5,maxZoom:(null==(e=m.zoom)?void 0:e.max)??3}):void 0},[null==(g=m.zoom)?void 0:g.max,null==(f=m.zoom)?void 0:f.min,P,b]),t.jsx("div",{ref:I,className:o,style:o?void 0:re,children:t.jsx(a.EmbedPDF,{engine:s,plugins:v.plugins,children:({pluginsReady:e})=>e?t.jsxs("div",{style:b?{...oe,transform:`scale(${P})`,transformOrigin:"top center"}:oe,children:[t.jsx(ye,{className:n,features:m,buildSelectionMenu:h,onExtraSelectionAction:l,renderPageOverlay:d}),c]}):null})})},exports.ChapterScrollPlugin=qs,exports.ChapterTreePanel=function({tree:s,activeChapterId:i,onActiveChapterChange:r}){const{provides:o}=a.useCapability(qs.id),{provides:n}=a.useCapability(As.id),[h,l]=e.useState({}),d=e.useCallback(()=>{if(!n)return;const t={},e=a=>{var s;for(const i of a)t[i.id]=n.getChapterStatus(i.id),(null==(s=i.children)?void 0:s.length)&&e(i.children)};e(s),l(t)},[n,s]);return e.useEffect(()=>{d()},[d]),e.useEffect(()=>{if(n)return n.onChapterStatusChange(d)},[n,d]),t.jsxs("aside",{style:Hs,children:[t.jsx("h2",{style:Ys,children:"章节目录"}),t.jsx("nav",{style:Ks,"aria-label":"章节目录",children:t.jsx(js,{nodes:s,depth:0,activeChapterId:i,chapterStatus:h,onSelect:t=>{null==r||r(t),null==o||o.scrollToChapter(t)}})})]})},exports.DEFAULT_CHAPTER_VIEWER_FEATURES=rs,exports.PdfChapterViewport=ye,exports.applySelectionMarkup=function(t,e,a,s,i){const r=a.forDocument(t),o=s.forDocument(t);if(!r||!o)return!1;const n="highlight"===e?"highlight":"underline"===e?"underline":"squiggly"===e?"squiggly":"strikeout",h=a.getTool(n);if(!h)return!1;const l=h.defaults,c=function(t,e){return{...ns[t],...null==e?void 0:e[t]}}(e,i),u=o.getFormattedSelection();if(0===u.length)return!1;r.setLocked({type:p.LockModeType.Exclude,categories:["markup","shape"]});for(const p of u){const t=d.uuidV4(),a=c.color??l.color??l.strokeColor,s=c.opacity??l.opacity,i=c.thickness??l.strokeWidth,o=c.offsetY??0,n="underline"===e||"squiggly"===e||"strikeout"===e?ls(p.segmentRects,o):p.segmentRects,h="underline"===e||"squiggly"===e||"strikeout"===e?ds(n):p.rect;r.createAnnotation(p.pageIndex,{id:t,created:new Date,flags:["print"],type:hs[e],..."highlight"===e?{blendMode:d.PdfBlendMode.Multiply}:{},strokeColor:a,opacity:s,...null!=i?{strokeWidth:i}:{},pageIndex:p.pageIndex,rect:h,segmentRects:n})}return o.clear(),!0},exports.buildParagraphBookmarkAnchor=function(t,e,a,s){const i=a.length>0?a:[];if(0===i.length)throw new Error("buildParagraphBookmarkAnchor: no rects");return{chapterId:t,localPageIndex:e,globalPageIndex:null==s?void 0:s.globalPageIndex,globalPageNumber:null==s?void 0:s.globalPageNumber,rectPdfCoord:Ss(i),rectsPdfCoord:i,markerAnchor:xs(i)}},exports.createChapterViewerEditor=function(t){var e,a,s,i,r;return ss({...t,toolbar:t.toolbar??{enabledModes:[]},features:{...rs,...t.features,markup:{...rs.markup,...null==(e=t.features)?void 0:e.markup},bookmarks:{...rs.bookmarks,...null==(a=t.features)?void 0:a.bookmarks},notes:{...rs.notes,...null==(s=t.features)?void 0:s.notes},selectionToolbar:{...rs.selectionToolbar,...null==(i=t.features)?void 0:i.selectionToolbar},zoom:{...rs.zoom,...null==(r=t.features)?void 0:r.zoom}}})},exports.createChapterViewerEditorOptions=function(t){return{manifest:t.manifest,chapterPdfLoader:t.chapterPdfLoader,overlapStrategy:{kind:"first-wins"},passwordProvider:new os(async()=>null),prefetchChapters:1,loadDefaultStampLibrary:!1,unloadTimeoutMs:12e4,toolbar:{enabledModes:[]},bookmarks:t.bookmarks,notes:t.notes}},exports.createPdfChapterEditor=ss;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|