@embedpdf-editor/vue3-chapter-viewer 1.0.8 → 1.0.9-beta.2
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/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +290 -251
- package/dist/index.js.map +1 -1
- package/package.json +7 -7
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),t=require("@embedpdf/core/vue"),s=require("@embedpdf/plugin-annotation"),r=require("@embedpdf/models"),n=require("@embedpdf/core"),a=require("@embedpdf/plugin-document-manager"),i=require("@embedpdf/plugin-interaction-manager"),o=require("@embedpdf/plugin-render"),l=require("@embedpdf/plugin-rotate"),h=require("@embedpdf/plugin-selection"),d=require("@embedpdf/plugin-history"),c=require("@embedpdf/plugin-redaction"),u=require("@embedpdf/plugin-form"),p=require("@embedpdf/plugin-stamp"),g=require("@embedpdf/plugin-signature"),m=require("@embedpdf/plugin-commands"),f=require("@embedpdf/plugin-i18n"),v=require("@embedpdf/plugin-ui"),P=require("@embedpdf/plugin-interaction-manager/vue"),I=require("@embedpdf/plugin-rotate/vue"),b=require("@embedpdf/plugin-selection/vue"),S=require("@embedpdf/plugin-annotation/vue"),C=require("@embedpdf/plugin-redaction/vue"),w=require("@embedpdf/plugin-render/vue"),y=require("@embedpdf/engines/vue"),M={position:"relative",height:"100%",width:"100%"},x={userSelect:"none",WebkitUserSelect:"none"};function L(){var e;"undefined"!=typeof window&&(null==(e=window.getSelection())||e.removeAllRanges())}const $="#f1f5f9",k={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:4},strikeout:{offsetY:0}},D={highlight:r.PdfAnnotationSubtype.HIGHLIGHT,underline:r.PdfAnnotationSubtype.UNDERLINE,squiggly:r.PdfAnnotationSubtype.SQUIGGLY,strikeout:r.PdfAnnotationSubtype.STRIKEOUT};function U(e,t){return 0===t?e:e.map(e=>({origin:{x:e.origin.x,y:e.origin.y+t},size:{...e.size}}))}function E(e){let t=1/0,s=1/0,r=-1/0,n=-1/0;for(const a of e)t=Math.min(t,a.origin.x),s=Math.min(s,a.origin.y),r=Math.max(r,a.origin.x+a.size.width),n=Math.max(n,a.origin.y+a.size.height);return{origin:{x:t,y:s},size:{width:r-t,height:n-s}}}function V(e,t,n,a,i){const o=n.forDocument(e),l=a.forDocument(e);if(!o||!l)return!1;const h="highlight"===t?"highlight":"underline"===t?"underline":"squiggly"===t?"squiggly":"strikeout",d=n.getTool(h);if(!d)return!1;const c=d.defaults,u={...k[g=t],...null==(m=i)?void 0:m[g]},p=l.getFormattedSelection();var g,m;if(0===p.length)return!1;o.setLocked({type:s.LockModeType.Exclude,categories:["markup","shape"]});for(const s of p){const e=r.uuidV4(),n=u.color??c.color??c.strokeColor,a=u.opacity??c.opacity,i=u.thickness??c.strokeWidth,l=u.offsetY??0,h="underline"===t||"squiggly"===t||"strikeout"===t?U(s.segmentRects,l):s.segmentRects,d="underline"===t||"squiggly"===t||"strikeout"===t?E(h):s.rect;o.createAnnotation(s.pageIndex,{id:e,created:new Date,flags:["print"],type:D[t],..."highlight"===t?{blendMode:r.PdfBlendMode.Multiply}:{},strokeColor:n,opacity:a,...null!=i?{strokeWidth:i}:{},pageIndex:s.pageIndex,rect:d,segmentRects:h})}return l.clear(),!0}const N=new Set([r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT]);function T(e,t){const s=e;return!1===e?{...t,enabled:!1}:!0===e||void 0===e?{...t,enabled:t.enabled??!0}:{...t,...s,enabled:!1!==(null==s?void 0:s.enabled)}}function F(e){var t;const s=T(null==e?void 0:e.markup,{enabled:!0}),r=T(null==e?void 0:e.bookmarks,{enabled:!0}),n=T(null==e?void 0:e.notes,{enabled:!0}),a=T(null==e?void 0:e.zoom,{enabled:!0,min:.5,max:3,initial:1}),i=T(void 0===(null==e?void 0:e.selectionToolbar)?!1!==s.enabled||!1!==n.enabled:e.selectionToolbar,{enabled:!0});return{markup:s,bookmarks:r,notes:n,zoom:a,scrollViewport:{background:(null==(t=null==e?void 0:e.scrollViewport)?void 0:t.background)??$},selectionToolbar:i}}function A(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function O(e,t){return`${e}#s${t}`}function R(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return A(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=A(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:O(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}let B=class{constructor(e){this.cb=e}resolvePassword(e,t){return this.cb(e,t)}};const G="chapter-manager",z={id:G,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,maxConcurrentSegmentLoads:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}};function _(e){const[t,s]=e.localPageRange;return s-t+1}function q(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function W(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return q(t)?t.segmentPageThreshold:null}function H(e,t){return`${e}#s${t}`}function K(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function j(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function X(e){const t=W(e);if(!t)return null;const s=_(e),r=j(s,t),n=q(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:H(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Y(e,t){const s=X(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Z(e,t){const s=X(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function J(e){var t;const s=W(e);if(!s)return[];const r=[],{chapterId:n}=e,a=_(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!q(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=j(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Q={kind:"first-wins"};function ee(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let te=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const se=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Q,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Q,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=K(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=K(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=K(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Y(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?X(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...J(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Q){const s=function(e,t=Q){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,ee(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new te(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?X(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Z(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(q(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=X(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=[];for(const n of t){const e=`${n.chapterId}:${n.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(n.chapterId,n.segmentIndex)||r.push({chapterId:n.chapterId,segmentIndex:n.segmentIndex}))}this.visibleSegmentBacklog=r,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=X(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Z(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);if(l){const e=this.findChapter(l.chapterId);if(e){const t=Z(e,l.localPageIndex);o(l.chapterId,t+1)}}for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Z(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Y(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=X(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(q(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=W(t);if(a){const r=j(_(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(q(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=K(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?X(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};se.id="chapter-manager";let re=se;const ne={manifest:z,create:e=>new re(G,e),reducer:e=>e,initialState:{}},ae="chapter-scroll",ie={id:ae,name:"Chapter Scroll Plugin",version:"0.1.0",provides:["chapter-scroll"],requires:["chapter-manager"],optional:[],defaultConfig:{placeholderPageHeight:1200,placeholderPageWidth:900,bufferSize:2,pageGap:20}};function oe(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function le(e,t){return`${e}#s${t}`}function he(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function de(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return oe(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=oe(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:le(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function ce(e,t){const s=de(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function ue(e){const[t,s]=e.localPageRange;return s-t+1}function pe(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ge(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return pe(t)?t.segmentPageThreshold:null}function me(e,t){return`${e}#s${t}`}function fe(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function ve(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Pe(e){const t=ge(e);if(!t)return null;const s=ue(e),r=ve(s,t),n=pe(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:me(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Ie(e,t){const s=Pe(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function be(e,t){const s=Pe(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Se(e){var t;const s=ge(e);if(!s)return[];const r=[],{chapterId:n}=e,a=ue(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!pe(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=ve(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Ce={kind:"first-wins"};function we(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let ye=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const Me=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Ce,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Ce,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=fe(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=fe(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=fe(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Ie(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Pe(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Se(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Ce){const s=function(e,t=Ce){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,we(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new ye(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Pe(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=be(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(pe(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Pe(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=[];for(const n of t){const e=`${n.chapterId}:${n.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(n.chapterId,n.segmentIndex)||r.push({chapterId:n.chapterId,segmentIndex:n.segmentIndex}))}this.visibleSegmentBacklog=r,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Pe(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=be(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);if(l){const e=this.findChapter(l.chapterId);if(e){const t=be(e,l.localPageIndex);o(l.chapterId,t+1)}}for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=be(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Ie(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Pe(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(pe(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=ge(t);if(a){const r=ve(ue(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(pe(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=fe(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Pe(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Me.id="chapter-manager";let xe=Me;function Le(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const $e=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,Le),this.visibleChange$=n.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.lastLoadIndicesKey="",this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(xe.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.lastLoadIndicesKey="",this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=ce(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===e.length)return;const t=this.chapterManager.provides(),s=t.visibleRangeNeedsSegmentLoad(e),r=e.join(",");(r!==this.lastLoadIndicesKey||s)&&(this.lastLoadIndicesKey=r,t.setVisibleGlobalPages(e))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=he(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=he(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}if(s){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),r=s.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!r||0===n.length)return;const a=de(r),i=this.documentManager.provides(),o=[],l=(e,t,s,r)=>{var n;const a=i.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let i=0;i<r;i++){const e=a.pages[s+i];(null==e?void 0:e.size)&&o.push({localPageIndex:t+i,width:e.size.width*l,height:e.size.height*l})}return o.length>0};if(a)for(const h of a.segments){if(!s.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=he(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),r=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,r=this.findFirstVisibleIndex(t);let n=r;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=s)break;n++}const a=[];let i=r,o=-1;for(let l=r;l<n;l++){a.push(l);const e=this.offsets[l],r=e+this.getPageSize(l).height,n=Math.max(0,Math.min(r,s)-Math.max(e,t));n>o&&(o=n,i=l)}this.currentVisible=a,this.currentGlobalPageIndex=i,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:i}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);if(s<0)return;const r=this.chapterManager.provides(),n=r.getChapter(e),a=this.virtualPageMap.atIndex(s);if(n&&a){const t=ce(n,a.localPageIndex);r.ensureSegmentLoaded(e,t)}else r.ensureChapterLoaded(e);this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};$e.id="chapter-scroll";let ke=$e;const De={manifest:ie,create:e=>new ke(ae,e),reducer:e=>e,initialState:{}},Ue="note",Ee={id:Ue,name:"Note Plugin",version:"0.1.0",provides:["note"],requires:["selection","chapter-scroll","chapter-manager"],optional:[],defaultConfig:{callbacks:{onCreateNote:async()=>null,onActivateNote:()=>{}},markerSize:18}};function Ve(e){const[t,s]=e.localPageRange;return s-t+1}function Ne(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Te(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ne(t)?t.segmentPageThreshold:null}function Fe(e,t){return`${e}#s${t}`}function Ae(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Oe(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Re(e){const t=Te(e);if(!t)return null;const s=Ve(e),r=Oe(s,t),n=Ne(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Fe(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Be(e,t){const s=Re(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Ge(e,t){const s=Re(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function ze(e){var t;const s=Te(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Ve(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Ne(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Oe(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const _e={kind:"first-wins"};function qe(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let We=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const He=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=_e,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??_e,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Ae(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Ae(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Ae(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Be(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Re(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...ze(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=_e){const s=function(e,t=_e){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,qe(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new We(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Re(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Ge(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Ne(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Re(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=[];for(const n of t){const e=`${n.chapterId}:${n.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(n.chapterId,n.segmentIndex)||r.push({chapterId:n.chapterId,segmentIndex:n.segmentIndex}))}this.visibleSegmentBacklog=r,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Re(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Ge(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);if(l){const e=this.findChapter(l.chapterId);if(e){const t=Ge(e,l.localPageIndex);o(l.chapterId,t+1)}}for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Ge(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Be(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Re(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Ne(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Te(t);if(a){const r=Oe(Ve(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Ne(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Ae(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Re(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};He.id="chapter-manager";let Ke=He;function je(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Xe(e,t){return`${e}#s${t}`}function Ye(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Ze(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return je(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=je(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:Xe(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Je(e,t){const s=Ze(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Qe(e){const[t,s]=e.localPageRange;return s-t+1}function et(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function tt(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return et(t)?t.segmentPageThreshold:null}function st(e,t){return`${e}#s${t}`}function rt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function nt(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function at(e){const t=tt(e);if(!t)return null;const s=Qe(e),r=nt(s,t),n=et(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:st(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function it(e,t){const s=at(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function ot(e,t){const s=at(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function lt(e){var t;const s=tt(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Qe(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!et(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=nt(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const ht={kind:"first-wins"};function dt(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let ct=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const ut=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ht,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ht,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=rt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=rt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=rt(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?it(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?at(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...lt(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=ht){const s=function(e,t=ht){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,dt(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new ct(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?at(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=ot(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(et(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=at(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=[];for(const n of t){const e=`${n.chapterId}:${n.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(n.chapterId,n.segmentIndex)||r.push({chapterId:n.chapterId,segmentIndex:n.segmentIndex}))}this.visibleSegmentBacklog=r,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=at(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=ot(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);if(l){const e=this.findChapter(l.chapterId);if(e){const t=ot(e,l.localPageIndex);o(l.chapterId,t+1)}}for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=ot(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=it(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=at(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(et(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=tt(t);if(a){const r=nt(Qe(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(et(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=rt(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?at(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};ut.id="chapter-manager";let pt=ut;function gt(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const mt=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,gt),this.visibleChange$=n.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.lastLoadIndicesKey="",this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(pt.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.lastLoadIndicesKey="",this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=Je(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===e.length)return;const t=this.chapterManager.provides(),s=t.visibleRangeNeedsSegmentLoad(e),r=e.join(",");(r!==this.lastLoadIndicesKey||s)&&(this.lastLoadIndicesKey=r,t.setVisibleGlobalPages(e))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Ye(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Ye(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}if(s){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),r=s.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!r||0===n.length)return;const a=Ze(r),i=this.documentManager.provides(),o=[],l=(e,t,s,r)=>{var n;const a=i.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let i=0;i<r;i++){const e=a.pages[s+i];(null==e?void 0:e.size)&&o.push({localPageIndex:t+i,width:e.size.width*l,height:e.size.height*l})}return o.length>0};if(a)for(const h of a.segments){if(!s.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=Ye(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),r=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,r=this.findFirstVisibleIndex(t);let n=r;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=s)break;n++}const a=[];let i=r,o=-1;for(let l=r;l<n;l++){a.push(l);const e=this.offsets[l],r=e+this.getPageSize(l).height,n=Math.max(0,Math.min(r,s)-Math.max(e,t));n>o&&(o=n,i=l)}this.currentVisible=a,this.currentGlobalPageIndex=i,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:i}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);if(s<0)return;const r=this.chapterManager.provides(),n=r.getChapter(e),a=this.virtualPageMap.atIndex(s);if(n&&a){const t=Je(n,a.localPageIndex);r.ensureSegmentLoaded(e,t)}else r.ensureChapterLoaded(e);this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};mt.id="chapter-scroll";let ft=mt;const vt=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=n.createBehaviorEmitter([]),this.noteActivated$=n.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(ft.id),this.chapterManager=this.registry.getPlugin(Ke.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,t.callbacks.loadNotes)try{const e=await t.callbacks.loadNotes();for(const t of e)this.notes.set(t.noteId,t);this.notesChange$.emit(this.listAll())}catch(s){this.logger.error(e.id,"LoadNotes","Failed to load notes",s)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(s=>s.chapterId===e&&s.localPageIndex===t),listAllNotes:()=>this.listAll(),getNote:e=>this.notes.get(e)??null,deleteNote:e=>this.deleteNote(e),updateNoteContent:(e,t)=>this.updateNoteContent(e,t),scrollToNote:e=>this.scrollToNote(e),listNotesForChapter:e=>this.listNotesForChapter(e),replaceNotesForChapter:(e,t)=>this.replaceNotesForChapter(e,t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(e){this.notes.set(e.noteId,e),this.notesChange$.emit(this.listAll())}requestEdit(e){const t=this.notes.get(e);t&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(e,t):this.activateNote(e))}activateNote(e){var t,s;const r=this.notes.get(e);r&&(null==(s=(t=this.config.callbacks).onActivateNote)||s.call(t,e,r),this.noteActivated$.emit({noteId:e,anchor:r}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[s,r]of this.notes.entries())r.chapterId===e&&this.notes.delete(s);for(const s of t)s.chapterId===e&&this.notes.set(s.noteId,s);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:It(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:s,onCreateNote:r}=this.config.callbacks;return s?(s({draft:t,complete:async e=>{const s={...t,noteId:e};this.registerNote(s)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const s=this.buildDraft(t),r=this.config.callbacks.onCreateNote;if(!r)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await r(s)}catch(i){return this.logger.error(e.id,"OnCreateNote","Callback failed",i),null}if(!n)return null;const a={...s,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var s,r;if(this.notes.has(t)){try{await(null==(r=(s=this.config.callbacks).onDeleteNote)?void 0:r.call(s,t))}catch(n){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",n)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,s){var r,n;const a=this.notes.get(t);if(!a)return;const i={...a,content:s};try{await(null==(n=(r=this.config.callbacks).onUpdateNote)?void 0:n.call(r,i))}catch(o){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",o)}this.notes.set(t,i),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const s=this.notes.get(e);if(!s)return;const r=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(s.chapterId);const a=n.resolvePageDocument(s.chapterId,s.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(r.scrollToGlobalPageIndex(s.globalPageIndex),await this.waitForPageInLayout(s.globalPageIndex),r.scrollToGlobalPdfPoint(s.globalPageIndex,s.endAnchor.y,{marginTop:80})):r.scrollToGlobalPageIndex(s.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const r=setTimeout(()=>{n(),s(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(r),n(),s(a))})})}};vt.id="note";let Pt=vt;function It(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}const bt={manifest:Ee,create:e=>new Pt(Ue,e),reducer:e=>e,initialState:{}},St="paragraph-bookmark",Ct={id:St,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}};function wt(e){const[t,s]=e.localPageRange;return s-t+1}function yt(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Mt(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return yt(t)?t.segmentPageThreshold:null}function xt(e,t){return`${e}#s${t}`}function Lt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function $t(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function kt(e){const t=Mt(e);if(!t)return null;const s=wt(e),r=$t(s,t),n=yt(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:xt(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Dt(e,t){const s=kt(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Ut(e,t){const s=kt(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Et(e){var t;const s=Mt(e);if(!s)return[];const r=[],{chapterId:n}=e,a=wt(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!yt(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=$t(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Vt={kind:"first-wins"};function Nt(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let Tt=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const Ft=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Vt,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Vt,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Lt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Lt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Lt(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Dt(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?kt(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Et(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Vt){const s=function(e,t=Vt){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Nt(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Tt(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?kt(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Ut(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(yt(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=kt(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=[];for(const n of t){const e=`${n.chapterId}:${n.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(n.chapterId,n.segmentIndex)||r.push({chapterId:n.chapterId,segmentIndex:n.segmentIndex}))}this.visibleSegmentBacklog=r,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=kt(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Ut(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);if(l){const e=this.findChapter(l.chapterId);if(e){const t=Ut(e,l.localPageIndex);o(l.chapterId,t+1)}}for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Ut(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Dt(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=kt(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(yt(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Mt(t);if(a){const r=$t(wt(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(yt(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Lt(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?kt(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Ft.id="chapter-manager";let At=Ft;function Ot(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Rt(e,t){return`${e}#s${t}`}function Bt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Gt(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ot(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=Ot(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:Rt(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function zt(e,t){const s=Gt(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function _t(e){const[t,s]=e.localPageRange;return s-t+1}function qt(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Wt(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return qt(t)?t.segmentPageThreshold:null}function Ht(e,t){return`${e}#s${t}`}function Kt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function jt(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Xt(e){const t=Wt(e);if(!t)return null;const s=_t(e),r=jt(s,t),n=qt(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Ht(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Yt(e,t){const s=Xt(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Zt(e,t){const s=Xt(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Jt(e){var t;const s=Wt(e);if(!s)return[];const r=[],{chapterId:n}=e,a=_t(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!qt(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=jt(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Qt={kind:"first-wins"};function es(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let ts=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const ss=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Qt,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Qt,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Kt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Kt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Kt(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Yt(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Xt(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Jt(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Qt){const s=function(e,t=Qt){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,es(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new ts(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Xt(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Zt(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(qt(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Xt(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=[];for(const n of t){const e=`${n.chapterId}:${n.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(n.chapterId,n.segmentIndex)||r.push({chapterId:n.chapterId,segmentIndex:n.segmentIndex}))}this.visibleSegmentBacklog=r,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Xt(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Zt(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);if(l){const e=this.findChapter(l.chapterId);if(e){const t=Zt(e,l.localPageIndex);o(l.chapterId,t+1)}}for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Zt(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Yt(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Xt(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(qt(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Wt(t);if(a){const r=jt(_t(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(qt(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Kt(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Xt(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};ss.id="chapter-manager";let rs=ss;function ns(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const as=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,ns),this.visibleChange$=n.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.lastLoadIndicesKey="",this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(rs.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.lastLoadIndicesKey="",this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=zt(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===e.length)return;const t=this.chapterManager.provides(),s=t.visibleRangeNeedsSegmentLoad(e),r=e.join(",");(r!==this.lastLoadIndicesKey||s)&&(this.lastLoadIndicesKey=r,t.setVisibleGlobalPages(e))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Bt(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Bt(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}if(s){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),r=s.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!r||0===n.length)return;const a=Gt(r),i=this.documentManager.provides(),o=[],l=(e,t,s,r)=>{var n;const a=i.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let i=0;i<r;i++){const e=a.pages[s+i];(null==e?void 0:e.size)&&o.push({localPageIndex:t+i,width:e.size.width*l,height:e.size.height*l})}return o.length>0};if(a)for(const h of a.segments){if(!s.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=Bt(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),r=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,r=this.findFirstVisibleIndex(t);let n=r;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=s)break;n++}const a=[];let i=r,o=-1;for(let l=r;l<n;l++){a.push(l);const e=this.offsets[l],r=e+this.getPageSize(l).height,n=Math.max(0,Math.min(r,s)-Math.max(e,t));n>o&&(o=n,i=l)}this.currentVisible=a,this.currentGlobalPageIndex=i,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:i}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);if(s<0)return;const r=this.chapterManager.provides(),n=r.getChapter(e),a=this.virtualPageMap.atIndex(s);if(n&&a){const t=zt(n,a.localPageIndex);r.ensureSegmentLoaded(e,t)}else r.ensureChapterLoaded(e);this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};as.id="chapter-scroll";let is=as;function os(e){if(0===e.length)throw new Error("unionRects: empty rects");let t=1/0,s=1/0,r=-1/0,n=-1/0;for(const a of e)t=Math.min(t,a.origin.x),s=Math.min(s,a.origin.y),r=Math.max(r,a.origin.x+a.size.width),n=Math.max(n,a.origin.y+a.size.height);return{origin:{x:t,y:s},size:{width:r-t,height:n-s}}}function ls(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function hs(e,t){const s=e.origin.y,r=e.origin.y+e.size.height,n=t.origin.y,a=t.origin.y+t.size.height,i=Math.max(r,a)-Math.min(s,n);return i<=0?0:Math.max(0,Math.min(r,a)-Math.max(s,n))/i}function ds(e,t){var s,r;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const n=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],a=(null==(r=t.rectsPdfCoord)?void 0:r.length)?t.rectsPdfCoord:[t.rectPdfCoord],i=e.markerAnchor??ls(n),o=t.markerAnchor??ls(a);if(Math.hypot(i.x-o.x,i.y-o.y)<=6)return!0;for(const l of n)for(const e of a){if(hs(l,e)<.5)continue;const t=Math.max(l.origin.x,e.origin.x);if(Math.min(l.origin.x+l.size.width,e.origin.x+e.size.width)-t>.25*Math.min(l.size.width,e.size.width))return!0}return!1}function cs(e,t,s,r){const n=s.length>0?s:[];if(0===n.length)throw new Error("buildParagraphBookmarkAnchor: no rects");return{chapterId:e,localPageIndex:t,globalPageIndex:null==r?void 0:r.globalPageIndex,globalPageNumber:null==r?void 0:r.globalPageNumber,rectPdfCoord:os(n),rectsPdfCoord:n,markerAnchor:ls(n)}}const us=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.change$=n.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(is.id),this.chapterManager=this.registry.getPlugin(At.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){var s;if(this.config=t,null==(s=t.callbacks)?void 0:s.load)try{const e=await t.callbacks.load();for(const t of e)this.entries.set(t.id,t);this.change$.emit(this.list())}catch(r){this.logger.error(e.id,"Load","Failed to load paragraph bookmarks",r)}}buildCapability(){return{addBookmark:e=>this.addBookmark(e),removeBookmark:e=>this.removeBookmark(e),updateBookmark:(e,t)=>this.updateBookmark(e,t),listBookmarks:()=>this.list(),getBookmark:e=>this.entries.get(e)??null,scrollToBookmark:e=>this.scrollToBookmark(e),requestRemoveBookmark:e=>this.requestRemoveBookmark(e),listBookmarksForChapter:e=>this.listBookmarksForChapter(e),replaceBookmarksForChapter:(e,t)=>this.replaceBookmarksForChapter(e,t),onBookmarksChange:this.change$.on}}addBookmark(e){for(const r of this.entries.values())if(ds(r.anchor,e.anchor))return r;const t=e.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s={id:t,label:e.label,anchor:e.anchor,metadata:e.metadata,createdAt:Date.now()};return this.entries.set(t,s),this.notifyAndPersist(),s}removeBookmark(e){var t,s,r;this.entries.delete(e)&&(this.notifyAndPersist(),null==(r=null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.onRemoveSuccess)||r.call(s,e))}async requestRemoveBookmark(t){var s,r;const n=this.entries.get(t);if(!n)return!1;const a=null==(r=null==(s=this.config)?void 0:s.callbacks)?void 0:r.onRequestRemove;if(a)try{if(!(await a(n)))return!1}catch(i){return this.logger.error(e.id,"RequestRemove","callback failed",i),!1}return this.removeBookmark(t),!0}updateBookmark(e,t){const s=this.entries.get(e);s&&(this.entries.set(e,{...s,...t}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((e,t)=>e.createdAt-t.createdAt)}listBookmarksForChapter(e){return this.list().filter(t=>t.anchor.chapterId===e)}replaceBookmarksForChapter(e,t){for(const[s,r]of this.entries.entries())r.anchor.chapterId===e&&this.entries.delete(s);for(const s of t)s.anchor.chapterId===e&&this.entries.set(s.id,s);this.notifyAndPersist()}notifyAndPersist(){var t,s;const r=this.list();this.change$.emit(r),(null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.persist)&&Promise.resolve(this.config.callbacks.persist(r)).catch(t=>this.logger.error(e.id,"Persist","persist callback rejected",t))}async scrollToBookmark(e){const t=this.entries.get(e);if(!t)return;const s=this.chapterScroll.provides(),r=this.chapterManager.provides();await r.ensureAllSegmentsLoaded(t.anchor.chapterId);let n=t.anchor.globalPageIndex;if(void 0===n){const e=this.chapterManager.provides().getVirtualPageMap().toGlobal(t.anchor.chapterId,t.anchor.localPageIndex);if(!e)return;n=e.globalPageIndex}const a=function(e){if(e.markerAnchor)return e.markerAnchor.y;const t=e.rectPdfCoord;return t.origin.y+t.size.height}(t.anchor);await async function(e,t,s){e.scrollToGlobalPageIndex(t),await function(e,t,s=2500){const r=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return r?Promise.resolve(r):new Promise(r=>{const n=setTimeout(()=>{a(),r(null)},s),a=e.onLayoutChange(e=>{const s=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);s&&(clearTimeout(n),a(),r(s))})})}(e,t),e.scrollToGlobalPdfPoint(t,s,{marginTop:80})}(s,n,a)}};us.id="paragraph-bookmark";let ps=us;const gs={manifest:Ct,create:e=>new ps(St,e),reducer:e=>e,initialState:{}},ms={"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 fs{constructor(){this.specs=[]}register(e){if(this.specs.some(t=>t.id===e.id))throw new Error(`OperationRegistry: duplicate operation id "${e.id}"`);this.specs.push(e)}registerAll(e){for(const t of e)t&&this.register(t)}list(){return this.specs}buildToolbars(){const e=structuredClone(ms);for(const t of this.specs){const s=e[t.toolbarSlot];if(!s)continue;const r={type:"command-button",id:t.id,commandId:t.commandId,variant:"icon",...t.icon?{icon:t.icon}:{},...t.i18nKey?{labelKey:t.i18nKey}:{},...t.label?{label:t.label}:{},categories:t.categories??[]};s.items=vs(s.items,r,t.position)}return e}}function vs(e,t,s){return(null==s?void 0:s.after)||(null==s?void 0:s.before)?function(e,t,s){const r=e=>{const n=[];for(const a of e)"group"!==a.type?s.before&&a.id===s.before?n.push(t,a):(n.push(a),s.after&&a.id===s.after&&n.push(t)):n.push({...a,items:r(a.items)});return n};return r(e)}(e,t,s):(r=t,e.map(e=>"group"===e.type?{...e,items:[...e.items,r]}:e));var r}const Ps={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function Is(e){var t,r,P,I,b,S;const C=e.toolbar??{},w=C.enabledModes??["view","annotate","shapes","insert","form","redact"],y=w.length>0,{schema:M,operationRegistry:x}=function(e={}){var t,s,r,n,a,i;const o=new Set(e.enabledModes??["view","annotate","shapes","insert","form","redact"]),l=new fs;(null==(t=e.customOperations)?void 0:t.length)&&l.registerAll(e.customOperations);const h=l.buildToolbars(),d={};for(const u of o){if("view"===u)continue;const e=Ps[u];h[e]&&(d[e]=h[e])}const c=function(e){if(0===e.size)return null;const t=(e,t,s)=>({type:"command-button",id:`${e}-mode`,commandId:s,variant:"text",label:t,categories:["mode",e]});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:[...e.has("view")?[t("view","View","mode:view")]:[],...e.has("annotate")?[t("annotate","Annotate","mode:annotate")]:[],...e.has("shapes")?[t("shapes","Shapes","mode:shapes")]:[],...e.has("insert")?[t("insert","Insert","mode:insert")]:[],...e.has("form")?[t("form","Form","mode:form")]:[],...e.has("redact")?[t("redact","Redact","mode:redact")]:[]]},{type:"spacer",id:"main-spacer-right",flex:!0}]}}(o);return c&&(d["chapter-editor-main-toolbar"]=c),(null==(s=e.extend)?void 0:s.toolbars)&&Object.assign(d,e.extend.toolbars),{schema:{id:"chapter-pdf-editor-ui",version:"1.0.0",toolbars:d,menus:(null==(r=e.extend)?void 0:r.menus)??{},sidebars:(null==(n=e.extend)?void 0:n.sidebars)??{},modals:(null==(a=e.extend)?void 0:a.modals)??{},selectionMenus:(null==(i=e.extend)?void 0:i.selectionMenus)??{}},operationRegistry:l}}({...C,enabledModes:w}),L={...y?{"mode:view":{id:"mode:view",label:"View",categories:["mode","mode-view"],action:({registry:e,documentId:t})=>{var r,n,a,i;const o=null==(r=e.getPlugin("ui"))?void 0:r.provides(),l=null==(n=e.getPlugin("interaction-manager"))?void 0:n.provides();o&&l&&(null==(a=l.forDocument(t))||a.activateDefaultMode(),o.forDocument(t).closeToolbarSlot("top","secondary"),null==(i=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||i.provides().forDocument(t).setLocked(e.getPluginConfig(s.ANNOTATION_PLUGIN_ID).locked??{type:s.LockModeType.None}))},active:({state:e,documentId:t})=>!v.isToolbarOpen(e.plugins,t,"top","secondary")},"mode:annotate":{id:"mode:annotate",label:"Annotate",categories:["mode","mode-annotate","annotation"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","annotation-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","annotation-toolbar")},"mode:shapes":{id:"mode:shapes",label:"Shapes",categories:["mode","mode-shapes","annotation"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","shapes-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","shapes-toolbar")},"mode:insert":{id:"mode:insert",label:"Insert",categories:["mode","mode-insert","insert"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","insert-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","insert-toolbar")},"mode:form":{id:"mode:form",label:"Form",categories:["mode","mode-form","form"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","form-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.None}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","form-toolbar")},"mode:redact":{id:"mode:redact",label:"Redact",categories:["mode","mode-redact","redaction"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","redaction-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","redaction-toolbar")}}:{},...y?bs(x.list()):{},...e.commands??{}},$=[n.createPluginRegistration(a.DocumentManagerPluginPackage,{initialDocuments:[]}),n.createPluginRegistration(ne,{manifest:e.manifest,overlapStrategy:e.overlapStrategy,passwordProvider:e.passwordProvider,chapterPdfLoader:e.chapterPdfLoader,prefetchChapters:e.prefetchChapters,maxConcurrentSegmentLoads:e.maxConcurrentSegmentLoads,unloadTimeoutMs:e.unloadTimeoutMs}),n.createPluginRegistration(De,{placeholderPageHeight:e.placeholderPageHeight,placeholderPageWidth:e.placeholderPageWidth}),n.createPluginRegistration(i.InteractionManagerPluginPackage),n.createPluginRegistration(o.RenderPluginPackage),n.createPluginRegistration(l.RotatePluginPackage),n.createPluginRegistration(h.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),n.createPluginRegistration(d.HistoryPluginPackage),n.createPluginRegistration(s.AnnotationPluginPackage),n.createPluginRegistration(c.RedactionPluginPackage),n.createPluginRegistration(u.FormPluginPackage),n.createPluginRegistration(p.StampPluginPackage,!1===e.loadDefaultStampLibrary?{manifests:[]}:void 0),n.createPluginRegistration(g.SignaturePluginPackage),...Object.keys(L).length>0?[n.createPluginRegistration(m.CommandsPluginPackage,{commands:L})]:[],...y?[n.createPluginRegistration(f.I18nPluginPackage),n.createPluginRegistration(v.UIPluginPackage,{schema:M})]:[]];return e.notes&&$.push(n.createPluginRegistration(bt,{callbacks:e.notes.callbacks,ui:null==(r=null==(t=e.features)?void 0:t.notes)?void 0:r.marker})),e.bookmarks&&$.push(n.createPluginRegistration(gs,{callbacks:e.bookmarks.callbacks,ui:null==(I=null==(P=e.features)?void 0:P.bookmarks)?void 0:I.marker,hover:null==(S=null==(b=e.features)?void 0:b.bookmarks)?void 0:S.hover})),{plugins:$,uiSchema:M,operationRegistry:x}}function bs(e){const t={};for(const s of e)s.handler&&(t[s.commandId]={id:s.commandId,labelKey:s.i18nKey,label:s.label,icon:s.icon,categories:s.categories,action:({documentId:e})=>{var t;null==(t=s.handler)||t.call(s,{documentId:e,chapterId:e})}});return t}const Ss=F();function Cs(e){return Is({...e,toolbar:e.toolbar??{enabledModes:[]},features:F(e.features)})}const ws={overlapStrategy:{kind:"first-wins"},passwordProvider:new B(async()=>null),prefetchChapters:1,maxConcurrentSegmentLoads:1,loadDefaultStampLibrary:!1,unloadTimeoutMs:12e4,toolbar:{enabledModes:[]}};function ys(e){return"callbacks"in e.notes?{manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,notes:e.notes.callbacks,bookmarks:e.bookmarks.callbacks}:e}function Ms(e){return{...ws,manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,overlapStrategy:e.overlapStrategy??ws.overlapStrategy,prefetchChapters:e.prefetchChapters??ws.prefetchChapters,maxConcurrentSegmentLoads:e.maxConcurrentSegmentLoads??ws.maxConcurrentSegmentLoads,unloadTimeoutMs:e.unloadTimeoutMs??ws.unloadTimeoutMs,notes:{callbacks:e.notes},bookmarks:{callbacks:e.bookmarks},features:F(e.features)}}function xs(e){const t=Ms(ys(e)),{plugins:s}=Cs(t);return{plugins:s,features:t.features,editorOptions:t}}function Ls(e,t=.5,s=3){return Math.min(s,Math.max(t,e))}function $s(e,t){var s;if(t<=0)return 1;let r=0;for(const n of e.pages){const e=(null==(s=null==n?void 0:n.size)?void 0:s.width)??0;e>r&&(r=e)}return r<=0?1:t/r}function ks(e,t){return e<=0?t??0:null==t||t<=0?e:Math.min(t,e)}function Ds(e,t,s,r){const n=ks(t,s);if(n<=0)return r;const a=$s(e,n);return Math.min(r,a)}function Us(e,t,s){const r=R(t);if(r){for(const t of r.segments){const r=e.getDocument(t.documentId);r&&s(r,t.documentId)}return}const n=e.getDocument(t.chapterId);n&&s(n,t.chapterId)}function Es(e){return e instanceof HTMLElement?e.clientWidth:0}function Vs(e,t,s){return Math.min(s,Math.max(t,e))}const Ns={chapters:[]};function Ts(s){const r=e.ref(null),{provides:i}=t.useCapability(re.id),o=e.computed(()=>{var e;return(null==(e=i.value)?void 0:e.getManifest())??Ns}),l=e.computed(()=>{var e;return null==(e=s.value)?void 0:e.zoom}),{scale:h,setScale:d,zoomEnabled:c,minZoom:u,maxZoom:p}=function(s,r,i){const o=e.isRef(s)?s:e.computed(()=>s),{registry:l}=t.useRegistry(),{provides:h}=t.useCapability(a.DocumentManagerPlugin.id),{provides:d}=t.useCapability(re.id),c=e.ref(v()),u=e.ref(c.value),p=e.ref(0),g=e.ref(!1),m=()=>{var e;return null==(e=r.value)?void 0:e.pageWidth},f=()=>{return null!=(e=m())&&e>0;var e},v=()=>{var e;return(null==(e=r.value)?void 0:e.initial)??1},P=e.computed(()=>{var e;return function(e,t,s,r,n){if(!e||s<=0)return n;let a=n;for(const i of t.chapters)Us(e,i,e=>{a=Math.min(a,Ds(e,s,r,n))});return a}(h.value,o.value,p.value,m(),(null==(e=r.value)?void 0:e.max)??3)}),I=e.computed(()=>{var e;return Math.min((null==(e=r.value)?void 0:e.min)??.5,P.value)});let b;function S(e){const t=P.value,s=I.value,r=Ls(e,s,t);u.value=r,c.value=r,function(e,t,s,r=.5,a=3){const i=null==e?void 0:e.getStore();if(!i)return;const o=Ls(s,r,a);i.dispatchToCore(n.setDefaultScale(o));for(const l of t.chapters){const e=R(l);if(e)for(const t of e.segments)i.getState().core.documents[t.documentId]&&i.dispatchToCore(n.setScale(o,t.documentId));else i.getState().core.documents[l.chapterId]&&i.dispatchToCore(n.setScale(o,l.chapterId))}}(l.value,o.value,r,s,t)}function C(e){if(!h.value||!d.value)return;const t=d.value.resolvePageDocument(e,0),s=h.value.getDocument(t.documentId);if(!s)return;const r=ks(p.value,m());r<=0||S($s(s,r))}function w(e){if(!g.value)return f()?C(e):S(v()),void(g.value=!0);S(u.value)}return e.watch(()=>null==i?void 0:i.value,e=>{null==b||b(),b=e?function(e,t){if(!e||"undefined"==typeof ResizeObserver)return()=>{};let s=null;const r=new ResizeObserver(()=>{t(Es(s))}),n=()=>{const n=e.querySelector("[data-chapter-scroll-viewport]");n!==s?(s&&r.unobserve(s),s=n,s?(r.observe(s),t(Es(s))):t(0)):t(Es(s))};n();const a=new MutationObserver(n);a.observe(e,{childList:!0,subtree:!0});const i=requestAnimationFrame(n);return()=>{cancelAnimationFrame(i),a.disconnect(),s&&r.unobserve(s),r.disconnect()}}(e,e=>{p.value=e}):void 0},{immediate:!0}),e.onBeforeUnmount(()=>null==b?void 0:b()),e.watch([l,()=>v(),()=>f()],()=>{l.value&&(f()||S(v()))},{immediate:!0}),e.watch(P,e=>{u.value>e&&S(e)}),e.watch([d,o,()=>f(),()=>v()],()=>{const e=d.value;if(e){for(const t of o.value.chapters)"loaded"===e.getChapterStatus(t.chapterId)&&w(t.chapterId);return e.onChapterStatusChange(e=>{"loaded"===e.status&&w(e.chapterId)})}},{immediate:!0}),e.watch(h,(e,t,s)=>{e&&s(e.onDocumentOpened(()=>{g.value&&S(u.value)}))}),e.watch([p,()=>f(),d,o],()=>{if(f()&&!(p.value<=0)&&d.value&&!g.value)for(const e of o.value.chapters)if("loaded"===d.value.getChapterStatus(e.chapterId)){C(e.chapterId),g.value=!0;break}}),{scale:c,setScale:S,zoomEnabled:()=>{var e;return!1!==(null==(e=r.value)?void 0:e.enabled)},minZoom:I,maxZoom:P}}(o,l,r);return function(t,s){let r=null;e.watch([t,s],()=>{null==r||r();const e=s.value;r=function(e,t){if(!e||!1===t.enabled)return()=>{};let s=null,r=null,n=0;const a=()=>{const r=e.querySelector("[data-chapter-scroll-viewport]");return!!r&&(null==s||s(),s=function({container:e,getScale:t,setScale:s,minZoom:r=.5,maxZoom:n=3}){let a=0,i=1,o=null,l=1,h=1;const d=e=>{(e.ctrlKey||e.metaKey)&&(e.preventDefault(),null===o?(h=t(),l=1):clearTimeout(o),l*=1-.01*e.deltaY,l=Vs(l,.1,10),s(Vs(h*l,r,n)),o=setTimeout(()=>{o=null},120))},c=new Map,u=e=>{if(c.set(e.pointerId,{x:e.clientX,y:e.clientY}),2===c.size){const[e,s]=[...c.values()];a=Math.hypot(s.x-e.x,s.y-e.y),i=t()}},p=e=>{if(c.has(e.pointerId)&&(c.set(e.pointerId,{x:e.clientX,y:e.clientY}),2===c.size&&a>0)){e.preventDefault();const[t,o]=[...c.values()],l=Math.hypot(o.x-t.x,o.y-t.y);s(Vs(i*(l/a),r,n))}},g=e=>{c.delete(e.pointerId),c.size<2&&(a=0)};return e.addEventListener("wheel",d,{passive:!1}),e.addEventListener("pointerdown",u),e.addEventListener("pointermove",p,{passive:!1}),e.addEventListener("pointerup",g),e.addEventListener("pointercancel",g),()=>{e.removeEventListener("wheel",d),e.removeEventListener("pointerdown",u),e.removeEventListener("pointermove",p),e.removeEventListener("pointerup",g),e.removeEventListener("pointercancel",g),o&&clearTimeout(o)}}({container:r,getScale:t.getScale,setScale:t.setScale,minZoom:t.minZoom,maxZoom:t.maxZoom}),!0)};return a()||(r=new MutationObserver(()=>{a()&&(null==r||r.disconnect(),r=null)}),r.observe(e,{childList:!0,subtree:!0}),n=requestAnimationFrame(()=>a())),()=>{n&&cancelAnimationFrame(n),null==r||r.disconnect(),null==s||s()}}(t.value??null,{enabled:e.enabled,getScale:e.getScale,setScale:e.setScale,minZoom:e.minZoom,maxZoom:e.maxZoom})},{deep:!0,flush:"post"}),e.onBeforeUnmount(()=>null==r?void 0:r())}(r,e.computed(()=>({enabled:c(),getScale:()=>h.value,setScale:d,minZoom:u.value,maxZoom:p.value}))),{hostRef:r,scale:h,setScale:d,zoomEnabled:c}}function Fs(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function As(e,t){return`${e}#s${t}`}function Os(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Rs(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Fs(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=Fs(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:As(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Bs(e,t){const s=Rs(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Gs(e){const[t,s]=e.localPageRange;return s-t+1}function zs(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function _s(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return zs(t)?t.segmentPageThreshold:null}function qs(e,t){return`${e}#s${t}`}function Ws(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Hs(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ks(e){const t=_s(e);if(!t)return null;const s=Gs(e),r=Hs(s,t),n=zs(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:qs(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function js(e,t){const s=Ks(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Xs(e,t){const s=Ks(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Ys(e){var t;const s=_s(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Gs(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!zs(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Hs(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Zs={kind:"first-wins"};function Js(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class Qs{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}const er=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Zs,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Zs,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Ws(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Ws(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Ws(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?js(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ks(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Ys(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Zs){const s=function(e,t=Zs){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Js(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Qs(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ks(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Xs(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(zs(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Ks(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=[];for(const n of t){const e=`${n.chapterId}:${n.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(n.chapterId,n.segmentIndex)||r.push({chapterId:n.chapterId,segmentIndex:n.segmentIndex}))}this.visibleSegmentBacklog=r,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Ks(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Xs(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);if(l){const e=this.findChapter(l.chapterId);if(e){const t=Xs(e,l.localPageIndex);o(l.chapterId,t+1)}}for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Xs(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=js(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Ks(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(zs(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=_s(t);if(a){const r=Hs(Gs(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(zs(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Ws(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Ks(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};er.id="chapter-manager";let tr=er;function sr(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const rr=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,sr),this.visibleChange$=n.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.lastLoadIndicesKey="",this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(tr.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.lastLoadIndicesKey="",this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=Bs(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===e.length)return;const t=this.chapterManager.provides(),s=t.visibleRangeNeedsSegmentLoad(e),r=e.join(",");(r!==this.lastLoadIndicesKey||s)&&(this.lastLoadIndicesKey=r,t.setVisibleGlobalPages(e))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Os(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Os(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}if(s){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),r=s.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!r||0===n.length)return;const a=Rs(r),i=this.documentManager.provides(),o=[],l=(e,t,s,r)=>{var n;const a=i.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let i=0;i<r;i++){const e=a.pages[s+i];(null==e?void 0:e.size)&&o.push({localPageIndex:t+i,width:e.size.width*l,height:e.size.height*l})}return o.length>0};if(a)for(const h of a.segments){if(!s.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=Os(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),r=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,r=this.findFirstVisibleIndex(t);let n=r;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=s)break;n++}const a=[];let i=r,o=-1;for(let l=r;l<n;l++){a.push(l);const e=this.offsets[l],r=e+this.getPageSize(l).height,n=Math.max(0,Math.min(r,s)-Math.max(e,t));n>o&&(o=n,i=l)}this.currentVisible=a,this.currentGlobalPageIndex=i,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:i}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);if(s<0)return;const r=this.chapterManager.provides(),n=r.getChapter(e),a=this.virtualPageMap.atIndex(s);if(n&&a){const t=Bs(n,a.localPageIndex);r.ensureSegmentLoaded(e,t)}else r.ensureChapterLoaded(e);this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};rr.id="chapter-scroll";let nr=rr;const ar=["data-global-page-index","data-chapter-id","data-local-page-index"],ir=(e=>{const t=e.__vccOpts||e;for(const[s,r]of[["__scopeId","data-v-e9ab4da3"]])t[s]=r;return t})(e.defineComponent({__name:"ChapterScroller",props:{class:{},style:{}},setup(s){const{provides:r}=t.useCapability(nr.id),n=e.ref(null),a=e.ref(null);let i=null;const o=()=>{null==i||i(),i=null,r.value&&(r.value.registerViewport(n.value),i=r.value.onLayoutChange(e=>{a.value=e}))};return e.onMounted(o),e.onBeforeUnmount(()=>{var e;null==i||i(),null==(e=r.value)||e.registerViewport(null)}),e.watch(r,o),(t,s)=>{var r,i,o;return e.openBlock(),e.createElementBlock("div",{ref_key:"containerRef",ref:n,"data-chapter-scroll-viewport":"",class:e.normalizeClass(t.$props.class),style:e.normalizeStyle({overflow:"auto",overflowX:"hidden",position:"relative",width:"100%",height:"100%",...t.$props.style})},[e.createElementVNode("div",{style:e.normalizeStyle({position:"relative",width:`${(null==(r=a.value)?void 0:r.totalWidth)??0}px`,height:`${(null==(i=a.value)?void 0:i.totalHeight)??0}px`,margin:"0 auto"})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList((null==(o=a.value)?void 0:o.items)??[],r=>(e.openBlock(),e.createElementBlock("div",{key:r.globalPageIndex,"data-global-page-index":r.globalPageIndex,"data-chapter-id":r.chapterId,"data-local-page-index":r.localPageIndex,style:e.normalizeStyle({position:"absolute",top:`${r.offsetTop}px`,left:"50%",transform:"translateX(-50%)",width:`${r.width}px`,height:`${r.height}px`,backgroundColor:r.isPlaceholder?"#f3f4f6":"#fff",boxShadow:"0 1px 4px rgba(0,0,0,0.08)"})},[r.isPlaceholder?e.renderSlot(t.$slots,"placeholder",{key:0,item:r},()=>[s[0]||(s[0]=e.createElementVNode("div",{class:"chapter-scroll-placeholder"},"Loading chapter…",-1))],!0):e.renderSlot(t.$slots,"page",{key:1,item:r},void 0,!0)],12,ar))),128))],4)],6)}}})),or=e.defineComponent({__name:"ChapterRenderLayer",props:{chapterId:{},localPageIndex:{},pdfDocumentId:{},pdfPageIndex:{},scale:{},dpr:{},class:{}},setup(t){const s=t;return(r,n)=>(e.openBlock(),e.createBlock(e.unref(w.RenderLayer),{"document-id":s.pdfDocumentId??s.chapterId,"page-index":s.pdfPageIndex??s.localPageIndex,scale:t.scale,dpr:t.dpr,class:e.normalizeClass(t.class),style:{pointerEvents:"none"}},null,8,["document-id","page-index","scale","dpr","class"]))}});function lr(e){const[t,s]=e.localPageRange;return s-t+1}function hr(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function dr(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return hr(t)?t.segmentPageThreshold:null}function cr(e,t){return`${e}#s${t}`}function ur(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function pr(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function gr(e){const t=dr(e);if(!t)return null;const s=lr(e),r=pr(s,t),n=hr(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:cr(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function mr(e,t){const s=gr(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function fr(e,t){const s=gr(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function vr(e){var t;const s=dr(e);if(!s)return[];const r=[],{chapterId:n}=e,a=lr(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!hr(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=pr(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Pr={kind:"first-wins"};function Ir(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let br=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const Sr=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Pr,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Pr,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=ur(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=ur(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=ur(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?mr(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?gr(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...vr(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Pr){const s=function(e,t=Pr){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Ir(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new br(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?gr(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=fr(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(hr(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=gr(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=[];for(const n of t){const e=`${n.chapterId}:${n.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(n.chapterId,n.segmentIndex)||r.push({chapterId:n.chapterId,segmentIndex:n.segmentIndex}))}this.visibleSegmentBacklog=r,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=gr(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=fr(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);if(l){const e=this.findChapter(l.chapterId);if(e){const t=fr(e,l.localPageIndex);o(l.chapterId,t+1)}}for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=fr(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=mr(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=gr(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(hr(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=dr(t);if(a){const r=pr(lr(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(hr(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=ur(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?gr(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Sr.id="chapter-manager";let Cr=Sr;function wr(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function yr(e,t){return`${e}#s${t}`}function Mr(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function xr(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return wr(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=wr(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:yr(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Lr(e,t){const s=xr(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function $r(e){const[t,s]=e.localPageRange;return s-t+1}function kr(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Dr(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return kr(t)?t.segmentPageThreshold:null}function Ur(e,t){return`${e}#s${t}`}function Er(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Vr(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Nr(e){const t=Dr(e);if(!t)return null;const s=$r(e),r=Vr(s,t),n=kr(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Ur(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Tr(e,t){const s=Nr(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Fr(e,t){const s=Nr(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Ar(e){var t;const s=Dr(e);if(!s)return[];const r=[],{chapterId:n}=e,a=$r(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!kr(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Vr(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Or={kind:"first-wins"};function Rr(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class Br{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}const Gr=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Or,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Or,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Er(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Er(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Er(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Tr(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Nr(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Ar(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Or){const s=function(e,t=Or){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Rr(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Br(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Nr(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Fr(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(kr(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Nr(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=[];for(const n of t){const e=`${n.chapterId}:${n.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(n.chapterId,n.segmentIndex)||r.push({chapterId:n.chapterId,segmentIndex:n.segmentIndex}))}this.visibleSegmentBacklog=r,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Nr(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Fr(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);if(l){const e=this.findChapter(l.chapterId);if(e){const t=Fr(e,l.localPageIndex);o(l.chapterId,t+1)}}for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Fr(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Tr(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Nr(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(kr(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Dr(t);if(a){const r=Vr($r(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(kr(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Er(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Nr(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Gr.id="chapter-manager";let zr=Gr;function _r(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const qr=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,_r),this.visibleChange$=n.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.lastLoadIndicesKey="",this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(zr.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.lastLoadIndicesKey="",this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=Lr(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===e.length)return;const t=this.chapterManager.provides(),s=t.visibleRangeNeedsSegmentLoad(e),r=e.join(",");(r!==this.lastLoadIndicesKey||s)&&(this.lastLoadIndicesKey=r,t.setVisibleGlobalPages(e))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Mr(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Mr(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}if(s){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),r=s.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!r||0===n.length)return;const a=xr(r),i=this.documentManager.provides(),o=[],l=(e,t,s,r)=>{var n;const a=i.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let i=0;i<r;i++){const e=a.pages[s+i];(null==e?void 0:e.size)&&o.push({localPageIndex:t+i,width:e.size.width*l,height:e.size.height*l})}return o.length>0};if(a)for(const h of a.segments){if(!s.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=Mr(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),r=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,r=this.findFirstVisibleIndex(t);let n=r;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=s)break;n++}const a=[];let i=r,o=-1;for(let l=r;l<n;l++){a.push(l);const e=this.offsets[l],r=e+this.getPageSize(l).height,n=Math.max(0,Math.min(r,s)-Math.max(e,t));n>o&&(o=n,i=l)}this.currentVisible=a,this.currentGlobalPageIndex=i,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:i}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);if(s<0)return;const r=this.chapterManager.provides(),n=r.getChapter(e),a=this.virtualPageMap.atIndex(s);if(n&&a){const t=Lr(n,a.localPageIndex);r.ensureSegmentLoaded(e,t)}else r.ensureChapterLoaded(e);this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};qr.id="chapter-scroll";let Wr=qr;const Hr=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=n.createBehaviorEmitter([]),this.noteActivated$=n.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(Wr.id),this.chapterManager=this.registry.getPlugin(Cr.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,t.callbacks.loadNotes)try{const e=await t.callbacks.loadNotes();for(const t of e)this.notes.set(t.noteId,t);this.notesChange$.emit(this.listAll())}catch(s){this.logger.error(e.id,"LoadNotes","Failed to load notes",s)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(s=>s.chapterId===e&&s.localPageIndex===t),listAllNotes:()=>this.listAll(),getNote:e=>this.notes.get(e)??null,deleteNote:e=>this.deleteNote(e),updateNoteContent:(e,t)=>this.updateNoteContent(e,t),scrollToNote:e=>this.scrollToNote(e),listNotesForChapter:e=>this.listNotesForChapter(e),replaceNotesForChapter:(e,t)=>this.replaceNotesForChapter(e,t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(e){this.notes.set(e.noteId,e),this.notesChange$.emit(this.listAll())}requestEdit(e){const t=this.notes.get(e);t&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(e,t):this.activateNote(e))}activateNote(e){var t,s;const r=this.notes.get(e);r&&(null==(s=(t=this.config.callbacks).onActivateNote)||s.call(t,e,r),this.noteActivated$.emit({noteId:e,anchor:r}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[s,r]of this.notes.entries())r.chapterId===e&&this.notes.delete(s);for(const s of t)s.chapterId===e&&this.notes.set(s.noteId,s);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:jr(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:s,onCreateNote:r}=this.config.callbacks;return s?(s({draft:t,complete:async e=>{const s={...t,noteId:e};this.registerNote(s)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const s=this.buildDraft(t),r=this.config.callbacks.onCreateNote;if(!r)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await r(s)}catch(i){return this.logger.error(e.id,"OnCreateNote","Callback failed",i),null}if(!n)return null;const a={...s,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var s,r;if(this.notes.has(t)){try{await(null==(r=(s=this.config.callbacks).onDeleteNote)?void 0:r.call(s,t))}catch(n){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",n)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,s){var r,n;const a=this.notes.get(t);if(!a)return;const i={...a,content:s};try{await(null==(n=(r=this.config.callbacks).onUpdateNote)?void 0:n.call(r,i))}catch(o){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",o)}this.notes.set(t,i),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const s=this.notes.get(e);if(!s)return;const r=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(s.chapterId);const a=n.resolvePageDocument(s.chapterId,s.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(r.scrollToGlobalPageIndex(s.globalPageIndex),await this.waitForPageInLayout(s.globalPageIndex),r.scrollToGlobalPdfPoint(s.globalPageIndex,s.endAnchor.y,{marginTop:80})):r.scrollToGlobalPageIndex(s.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const r=setTimeout(()=>{n(),s(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(r),n(),s(a))})})}};Hr.id="note";let Kr=Hr;function jr(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Xr(e){const{markerPdf:t,lineRects:s,sx:r,sy:n,cssPageWidth:a,iconSize:i,gapPx:o=6}=e,l=(null==s?void 0:s.length)?s[s.length-1]:void 0;let h,d;l?(h=(l.origin.x+l.size.width)*r+o,d=l.origin.y*n+(l.size.height*n-i)/2):(h=t.x*r-i/2,d=t.y*n-i-o);const c=Math.max(0,a-i-2);return h>c&&(h=c),d<0&&(d=0),{left:h,top:d}}const Yr={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none",zIndex:25}},Zr=["onMouseenter"],Jr=["data-note-marker-zone","onMouseenter","onMouseleave"],Qr=["onClick"],en=["onClick"],tn=["onClick"],sn=e.defineComponent({__name:"NoteMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(s){const r=s,{provides:n}=t.useCapability(Kr.id),a=e.ref([]),i=e.ref(null),o=e.ref(null);e.watch(n,e=>{if(e)return e.onNotesChange(e=>{a.value=e.filter(e=>e.chapterId===r.chapterId&&e.localPageIndex===r.localPageIndex)})},{immediate:!0});let l=null;e.watch(o,e=>{l&&(document.removeEventListener("mousedown",l),l=null),e&&(l=t=>{var s;const r=t.target;(null==(s=r.closest)?void 0:s.call(r,`[data-note-marker-zone="${e}"]`))||(o.value=null,i.value=null)},document.addEventListener("mousedown",l))}),e.onBeforeUnmount(()=>{l&&document.removeEventListener("mousedown",l)});const h=e.computed(()=>{var e;return(null==(e=r.ui)?void 0:e.iconSize)??16}),d=e.computed(()=>{var e;return(null==(e=r.ui)?void 0:e.highlightColor)??"rgba(245, 158, 11, 0.08)"});function c(e){const t=r.cssPageWidth/r.pdfPageWidth,s=r.cssPageHeight/r.pdfPageHeight,n=h.value,{left:a,top:i}=Xr({markerPdf:e.endAnchor,lineRects:e.rectsPdfCoord,sx:t,sy:s,cssPageWidth:r.cssPageWidth,iconSize:n}),l=function(e,t,s){let r=1/0,n=1/0,a=-1/0,i=-1/0;for(const o of e)r=Math.min(r,o.origin.x*t),n=Math.min(n,o.origin.y*s),a=Math.max(a,(o.origin.x+o.size.width)*t),i=Math.max(i,(o.origin.y+o.size.height)*s);return{left:r,top:n,width:a-r,height:i-n}}(e.rectsPdfCoord,t,s),d=o.value===e.noteId?72:0,c=Math.max(0,Math.min(l.left,a)-8),u=Math.max(0,Math.min(l.top,i)-8);return{zoneLeft:c,zoneTop:u,zoneW:Math.min(r.cssPageWidth,Math.max(l.left+l.width,a+n)+8)-c,zoneH:Math.max(l.top+l.height,i+n+6+d)+8-u,iconLeft:a,iconTop:i,sx:t,sy:s}}return(t,r)=>e.unref(n)&&a.value.length&&s.pdfPageWidth&&s.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",Yr,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(a.value,t=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:t.noteId},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.rectsPdfCoord,(s,r)=>(e.openBlock(),e.createElementBlock("div",{key:`${t.noteId}-bg-${r}`,style:e.normalizeStyle({position:"absolute",left:s.origin.x*c(t).sx+"px",top:s.origin.y*c(t).sy+"px",width:s.size.width*c(t).sx+"px",height:s.size.height*c(t).sy+"px",background:d.value,borderRadius:"2px",pointerEvents:"auto"}),onMouseenter:e=>i.value=t.noteId},null,44,Zr))),128)),i.value===t.noteId||o.value===t.noteId?(e.openBlock(),e.createElementBlock("div",{key:0,"data-note-marker-zone":t.noteId,style:e.normalizeStyle({position:"absolute",left:`${c(t).zoneLeft}px`,top:`${c(t).zoneTop}px`,width:`${c(t).zoneW}px`,height:`${c(t).zoneH}px`,pointerEvents:"auto",zIndex:26}),onMouseenter:e=>i.value=t.noteId,onMouseleave:e=>o.value!==t.noteId&&(i.value=null)},[e.createElementVNode("button",{type:"button",title:"笔记",style:e.normalizeStyle({position:"absolute",left:c(t).iconLeft-c(t).zoneLeft+"px",top:c(t).iconTop-c(t).zoneTop+"px",width:`${h.value}px`,height:`${h.value}px`,border:"none",borderRadius:"50%",background:"#f59e0b",color:"#fff",cursor:"pointer",fontSize:"11px",padding:0}),onMousedown:r[0]||(r[0]=e.withModifiers(()=>{},["stop"])),onClick:e.withModifiers(e=>o.value=o.value===t.noteId?null:t.noteId,["stop"])}," 💬 ",44,Qr),o.value===t.noteId?(e.openBlock(),e.createElementBlock("div",{key:0,style:e.normalizeStyle({position:"absolute",left:c(t).iconLeft-c(t).zoneLeft+"px",top:`${c(t).iconTop-c(t).zoneTop+h.value+4}px`,minWidth:"120px",padding:"6px",borderRadius:"8px",background:"#fff",border:"1px solid #e5e7eb",boxShadow:"0 4px 12px rgba(0,0,0,0.12)",zIndex:30}),onMousedown:r[1]||(r[1]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",style:{display:"block",width:"100%",padding:"6px 8px","font-size":"12px",border:"none","border-radius":"4px",background:"transparent",color:"#334155",cursor:"pointer","text-align":"left"},onClick:e=>{return s=t,void(null==(r=n.value)||r.requestEditNote(s.noteId,s));var s,r}}," 编辑 ",8,en),e.createElementVNode("button",{type:"button",style:{display:"block",width:"100%",padding:"6px 8px","font-size":"12px",border:"none","border-radius":"4px",background:"transparent",color:"#dc2626",cursor:"pointer","text-align":"left"},onClick:e=>{var s,r;return r=t.noteId,null==(s=n.value)||s.requestDeleteNote(r),void(o.value=null)}}," 删除 ",8,tn)],36)):e.createCommentVNode("",!0)],44,Jr)):e.createCommentVNode("",!0)],64))),128))])):e.createCommentVNode("",!0)}}),rn={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none"}},nn=["title","onClick"],an=["onClick"],on=e.defineComponent({__name:"BookmarkMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(s){const r=s,{provides:n}=t.useCapability(ps.id),a=e.ref([]),i=e.ref(null),o=e.ref(null);function l(){const e=n.value;e&&(a.value=e.listBookmarks().filter(e=>e.anchor.chapterId===r.chapterId&&e.anchor.localPageIndex===r.localPageIndex))}e.watch(n,e=>{if(e)return l(),e.onBookmarksChange(l)},{immediate:!0});let h=null;e.watch(i,e=>{h&&(document.removeEventListener("mousedown",h),h=null),e&&(h=e=>{var t;(null==(t=o.value)?void 0:t.contains(e.target))||(i.value=null)},document.addEventListener("mousedown",h))}),e.onBeforeUnmount(()=>{h&&document.removeEventListener("mousedown",h)});const d=e.computed(()=>{var e;return(null==(e=r.ui)?void 0:e.iconSize)??16});function c(e){const{left:t,top:s}=function(e){var t;const s=r.cssPageWidth/r.pdfPageWidth,n=r.cssPageHeight/r.pdfPageHeight,a=(null==(t=e.anchor.rectsPdfCoord)?void 0:t.length)?e.anchor.rectsPdfCoord:[e.anchor.rectPdfCoord];return Xr({markerPdf: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},lineRects:a,sx:s,sy:n,cssPageWidth:r.cssPageWidth,iconSize:d.value})}(e);return{position:"absolute",left:`${Math.max(0,t-6)}px`,top:`${Math.max(0,s-6)}px`,width:`${d.value+12}px`,height:`${d.value+12}px`,pointerEvents:"auto",zIndex:20}}return(t,r)=>e.unref(n)&&a.value.length&&s.pdfPageWidth&&s.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",rn,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(a.value,t=>(e.openBlock(),e.createElementBlock("div",{key:t.id,style:e.normalizeStyle(c(t)),onMousedown:r[1]||(r[1]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",title:t.label,style:e.normalizeStyle({position:"absolute",left:"6px",top:"6px",width:`${d.value}px`,height:`${d.value}px`,border:"none",borderRadius:"4px",background:"#3b82f6",color:"#fff",cursor:"pointer",boxShadow:"0 2px 6px rgba(37, 99, 235, 0.35)",fontSize:"11px",padding:0}),onClick:e.withModifiers(e=>i.value=i.value===t.id?null:t.id,["stop"])}," 🔖 ",12,nn),i.value===t.id?(e.openBlock(),e.createElementBlock("div",{key:0,ref_for:!0,ref_key:"deleteMenuRef",ref:o,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:r[0]||(r[0]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",style:{width:"100%",padding:"6px 8px","font-size":"12px",border:"none","border-radius":"4px",background:"transparent",color:"#dc2626",cursor:"pointer","text-align":"left"},onClick:e=>async function(e){const t=n.value;t&&await t.requestRemoveBookmark(e)&&(i.value=null)}(t.id)}," 删除书签 ",8,an)],512)):e.createCommentVNode("",!0)],36))),128))])):e.createCommentVNode("",!0)}});function ln(e){return e.pdfDocumentId??e.chapterId}function hn(e){return e.pdfPageIndex??e.localPageIndex}function dn(e,t){e.wait(t,()=>{})}const cn={display:"flex",alignItems:"center",justifyContent:"center",padding:"4px 8px",borderRadius:"8px",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)"},un={padding:"6px 12px",fontSize:"12px",fontWeight:"500",border:"none",borderRadius:"6px",background:"transparent",color:"#dc2626",cursor:"pointer"};const pn=e.defineComponent({__name:"ChapterPageSurface",props:{item:{},features:{},showNoteMarkers:{type:Boolean},showBookmarkMarkers:{type:Boolean},showRedactionLayer:{type:Boolean},noteMarkerUi:{},bookmarkMarkerUi:{},buildSelectionMenu:{type:Function},createNote:{},annotationSelectionMenu:{},redactionSelectionMenu:{},renderPageOverlay:{type:Function}},setup(s){const r=s,n=e.computed(()=>ln(r.item)),i=e.computed(()=>hn(r.item));!function(s){const{provides:r}=t.useCapability(a.DocumentManagerPlugin.id);e.watch([r,s],([e,t])=>{e&&t&&e.isDocumentOpen(t)&&e.setActiveDocument(t)},{immediate:!0})}(n);const{provides:o}=t.useCapability(a.DocumentManagerPlugin.id),{provides:l}=t.useCapability(h.SelectionPlugin.id),d=e.computed(()=>{var e,t;return null==(t=null==(e=o.value)?void 0:e.getDocument(n.value))?void 0:t.pages[i.value]});function c(t,s){var n,a,i,o;const h=r.createNote.value;if(h&&!1!==(null==(a=null==(n=r.features)?void 0:n.notes)?void 0:a.enabled)&&!1!==(null==(o=null==(i=r.features)?void 0:i.selectionToolbar)?void 0:o.enabled))return r=>{var n;const a={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==(n=r.placement)?void 0:n.suggestTop)?-40:r.rect.size.height+8};return e.h("div",r.menuWrapperProps,[e.h("div",{style:a},e.h("button",{type:"button",style:{padding:"6px 10px",fontSize:"12px",border:"1px solid #e2e8f0",borderRadius:"6px",background:"#fff",cursor:"pointer"},onClick:()=>{if(!l.value)return;const e=l.value.getHighlightRectsForPage(hn(t),s);dn(l.value.getSelectedText(s),s=>{var r,n,a;h((r=t,n=e,a=s.join("\n"),{chapterId:r.chapterId,localPageIndex:r.localPageIndex,globalPageIndex:r.globalPageIndex,globalPageNumber:r.globalPageNumber,rectsPdfCoord:n,selectedText:a}))})}},"添加附注"))])}}const u=e.computed(()=>{const e=r.buildSelectionMenu,t={item:r.item,defaultMenu:c(r.item,n.value),createNote:r.createNote.value};if(e){const s=e(t);if(s)return s}return t.defaultMenu}),p=function(t,s){var r,n;const{provides:a}=S.useAnnotationCapability(),i=null==(r=null==s?void 0:s.markup)?void 0:r.annotationMenu,o=!1!==(null==(n=null==s?void 0:s.markup)?void 0:n.enabled),l=!1!==(null==i?void 0:i.enabled);return e.computed(()=>{const s="string"==typeof t?t:t.value;if(o&&l&&a.value)return t=>{const{context:r,rect:n,placement:o,menuWrapperProps:l,selected:h}=t;if(!h||"annotation"!==r.type)return e.h("span",l);if(r.structurallyLocked)return e.h("span",l);if(d=r.annotation.object.type,!N.has(d))return e.h("span",l);var d;const c=a.value.forDocument(s),{pageIndex:u,id:p}=r.annotation.object,g=()=>{null==c||c.deleteAnnotation(u,p)},m={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==o?void 0:o.suggestTop)?void 0:`${n.size.height+8}px`,bottom:(null==o?void 0:o.suggestTop)?`${n.size.height+8}px`:void 0},f=(null==i?void 0:i.renderMenu)?i.renderMenu({pageIndex:u,annotationId:p,onDelete:g}):e.h("button",{type:"button",style:un,onClick:g},"删除");return e.h("div",l,[e.h("div",{style:m},[e.h("div",{style:cn,role:"toolbar","aria-label":"划线标注"},[f])])])}})}(n,r.features),g=e.computed(()=>function(e,t){if(e||t)return s=>{if(e){const t=e(s);if(null!=t)return t}return(null==t?void 0:t(s))??null}}(r.annotationSelectionMenu,p.value)),m=e.computed(()=>{var e;return null==(e=r.renderPageOverlay)?void 0:e.call(r,r.item)}),f=e.computed(()=>{var e;return function(e){const t=null==e?void 0:e.selectionBackground;if(t)return{background:t}}(null==(e=r.features)?void 0:e.selectionToolbar)});return(t,r)=>s.item.isPlaceholder?e.createCommentVNode("",!0):(e.openBlock(),e.createBlock(e.unref(P.GlobalPointerProvider),{key:0,"document-id":n.value},{default:e.withCtx(()=>[e.createVNode(e.unref(I.Rotate),{"document-id":n.value,"page-index":i.value,style:{backgroundColor:"#fff"}},{default:e.withCtx(()=>[e.createVNode(e.unref(P.PagePointerProvider),{"document-id":n.value,"page-index":i.value,style:e.normalizeStyle(e.unref(x)),onPointerdown:e.unref(L)},{default:e.withCtx(()=>[e.createVNode(e.unref(or),{"chapter-id":s.item.chapterId,"local-page-index":s.item.localPageIndex,"pdf-document-id":n.value,"pdf-page-index":i.value},null,8,["chapter-id","local-page-index","pdf-document-id","pdf-page-index"]),e.createVNode(e.unref(b.SelectionLayer),{"document-id":n.value,"page-index":i.value,"text-style":f.value,"selection-menu":u.value},null,8,["document-id","page-index","text-style","selection-menu"]),s.showRedactionLayer?(e.openBlock(),e.createBlock(e.unref(C.RedactionLayer),{key:0,"document-id":n.value,"page-index":i.value,"selection-menu":s.redactionSelectionMenu},null,8,["document-id","page-index","selection-menu"])):e.createCommentVNode("",!0),e.createVNode(e.unref(S.AnnotationLayer),{"document-id":n.value,"page-index":i.value,"selection-menu":g.value},null,8,["document-id","page-index","selection-menu"]),s.showBookmarkMarkers&&d.value?(e.openBlock(),e.createBlock(on,{key:1,"chapter-id":s.item.chapterId,"local-page-index":s.item.localPageIndex,"pdf-page-width":d.value.size.width,"pdf-page-height":d.value.size.height,"css-page-width":s.item.width,"css-page-height":s.item.height,ui:s.bookmarkMarkerUi},null,8,["chapter-id","local-page-index","pdf-page-width","pdf-page-height","css-page-width","css-page-height","ui"])):e.createCommentVNode("",!0),m.value?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(m.value),{key:2})):e.createCommentVNode("",!0),s.showNoteMarkers&&d.value?(e.openBlock(),e.createBlock(sn,{key:3,"chapter-id":s.item.chapterId,"local-page-index":s.item.localPageIndex,"pdf-page-width":d.value.size.width,"pdf-page-height":d.value.size.height,"css-page-width":s.item.width,"css-page-height":s.item.height,ui:s.noteMarkerUi},null,8,["chapter-id","local-page-index","pdf-page-width","pdf-page-height","css-page-width","css-page-height","ui"])):e.createCommentVNode("",!0),e.renderSlot(t.$slots,"default")]),_:3},8,["document-id","page-index","style","onPointerdown"])]),_:3},8,["document-id","page-index"])]),_:3},8,["document-id"]))}}),gn=e.defineComponent({__name:"HoverBookmarkLayer",props:{item:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},hoverUi:{}},setup(s){const r=s,n=e.computed(()=>ln(r.item)),{provides:a}=t.useCapability(h.SelectionPlugin.id),{provides:i}=t.useCapability(ps.id),o=e.ref(null),l=e.ref(null),d=e.ref(null),c=e.ref(null),u=e.computed(()=>{var e;return(null==(e=r.hoverUi)?void 0:e.iconSize)??16}),p=e.computed(()=>c.value??d.value);let g=null,m=0;function f(){const e=a.value;if(!e)return;const t=e.forDocument(n.value).getState().geometry[r.item.localPageIndex];t&&(l.value=t)}e.watch([a,n,()=>r.item.localPageIndex],([e])=>{if(null==g||g(),g=null,cancelAnimationFrame(m),l.value=null,!e)return;const t=e.forDocument(n.value);g=t.onSelectionChange(f);let s=!1;const a=()=>{if(!s){try{if(f(),t.getState().geometry[r.item.localPageIndex])return}catch{}m=requestAnimationFrame(a)}};return a(),()=>{s=!0,cancelAnimationFrame(m),null==g||g(),g=null}},{immediate:!0});let v=null;e.watch([l,()=>r.pdfPageWidth,c,a],()=>{v&&(document.removeEventListener("mousemove",v),v=null),l.value&&r.pdfPageWidth&&(v=e=>{if(c.value)return;const t=a.value;if(t)try{if(t.forDocument(n.value).getState().selecting)return void(d.value=null)}catch{}const s=o.value;if(!s)return;const i=s.getBoundingClientRect();if(e.clientX<i.left||e.clientX>i.right||e.clientY<i.top||e.clientY>i.bottom)return void(d.value=null);const u=function(e,t){const s=h.glyphAt(e,t);if(s<0)return null;const r=h.expandToLineBoundary(e,s);if(!r)return null;const n=h.rectsWithinSlice(e,r.from,r.to);return 0===n.length?null:{lineRects:n,charFrom:r.from,charTo:r.to}}(l.value,{x:(e.clientX-i.left)/(r.cssPageWidth/r.pdfPageWidth),y:(e.clientY-i.top)/(r.cssPageHeight/r.pdfPageHeight)});d.value=(null==u?void 0:u.lineRects)??null},document.addEventListener("mousemove",v))},{immediate:!0}),e.onBeforeUnmount(()=>{v&&document.removeEventListener("mousemove",v),cancelAnimationFrame(m),null==g||g()});const P=e.computed(()=>{const e=p.value;return(null==e?void 0:e.length)?cs(r.item.chapterId,r.item.localPageIndex,e,{globalPageIndex:r.item.globalPageIndex,globalPageNumber:r.item.globalPageNumber}):null}),I=e.computed(()=>{const e=P.value,t=i.value;return!(!e||!t)&&t.listBookmarks().some(t=>ds(t.anchor,e))});function b(){const e=i.value,t=P.value;e&&t&&!I.value&&(e.addBookmark({label:`书签 ${(new Date).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"})}`,anchor:t}),d.value=null,c.value=null)}const S=e.computed(()=>{const e=p.value,t=null==e?void 0:e[e.length-1];if(!t||!r.pdfPageWidth)return null;const s=r.cssPageWidth/r.pdfPageWidth,n=r.cssPageHeight/r.pdfPageHeight,a=u.value;return{iconLeft:Math.min((t.origin.x+t.size.width)*s+6,Math.max(0,r.cssPageWidth-a-2)),iconTop:t.origin.y*n+(t.size.height*n-a)/2,zoneLeft:Math.max(0,(t.origin.x+t.size.width)*s-4),zoneTop:Math.max(0,t.origin.y*n-4),size:a}});return(t,r)=>{var n;return e.unref(i)&&s.pdfPageWidth&&s.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",{key:0,ref_key:"rootRef",ref:o,style:{position:"absolute",inset:"0",zIndex:14,pointerEvents:"none"}},[S.value&&p.value&&!I.value?(e.openBlock(),e.createElementBlock("div",{key:0,style:e.normalizeStyle({position:"absolute",left:`${S.value.zoneLeft}px`,top:`${S.value.zoneTop}px`,width:`${S.value.size+20}px`,height:`${((null==(n=p.value[p.value.length-1])?void 0:n.size.height)??0)*(s.cssPageHeight/s.pdfPageHeight)+S.value.size+12}px`,pointerEvents:"auto"}),onMouseenter:r[0]||(r[0]=e=>c.value=p.value),onMouseleave:r[1]||(r[1]=e=>c.value=null)},[e.createElementVNode("button",{type:"button",title:"添加书签",style:e.normalizeStyle({position:"absolute",left:S.value.iconLeft-S.value.zoneLeft+"px",top:S.value.iconTop-S.value.zoneTop+"px",width:`${S.value.size}px`,height:`${S.value.size}px`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",background:"#3b82f6",color:"#fff",border:"none",borderRadius:"4px",boxShadow:"0 2px 8px rgba(37, 99, 235, 0.45)",fontSize:"12px",padding:0}),onClick:e.withModifiers(b,["stop"])}," 🔖 ",4)],36)):e.createCommentVNode("",!0)],512)):e.createCommentVNode("",!0)}}}),mn={key:0,width:"20",height:"20",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},fn={key:1,width:"24",height:"24",viewBox:"0 0 28 28",fill:"none","aria-hidden":""},vn={key:0,x:"5",y:"4",width:"18",height:"20",rx:"3",fill:"#fde047"},Pn={key:1,d:"M6 22h16",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},In={key:2,d:"M6 22c2-2 3-2 5 0s3 2 5 0 3-2 5 0",stroke:"#dc2626","stroke-width":"2","stroke-linecap":"round",fill:"none"},bn={key:3,d:"M5 14h18",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},Sn={key:2,width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},Cn=e.defineComponent({__name:"SelectionToolbarIcons",props:{kind:{}},setup:t=>(s,r)=>"copy"===t.kind?(e.openBlock(),e.createElementBlock("svg",mn,[...r[0]||(r[0]=[e.createElementVNode("rect",{x:"8.5",y:"8.5",width:"11",height:"13",rx:"2.25",fill:"#f1f5f9",stroke:"#94a3b8","stroke-width":"1.35"},null,-1),e.createElementVNode("rect",{x:"4.5",y:"3.5",width:"11",height:"13",rx:"2.25",fill:"#ffffff",stroke:"#334155","stroke-width":"1.5"},null,-1),e.createElementVNode("path",{d:"M7.5 7h5.5a1.5 1.5 0 0 1 1.5 1.5V14",stroke:"#64748b","stroke-width":"1.2","stroke-linecap":"round"},null,-1)])])):"note"!==t.kind?(e.openBlock(),e.createElementBlock("svg",fn,["highlight"===t.kind?(e.openBlock(),e.createElementBlock("rect",vn)):e.createCommentVNode("",!0),r[1]||(r[1]=e.createElementVNode("text",{x:"14",y:"19","text-anchor":"middle","font-size":"15","font-weight":"700","font-family":"system-ui, -apple-system, sans-serif",fill:"#0f172a"}," A ",-1)),"underline"===t.kind?(e.openBlock(),e.createElementBlock("path",Pn)):"squiggly"===t.kind?(e.openBlock(),e.createElementBlock("path",In)):"strikeout"===t.kind?(e.openBlock(),e.createElementBlock("path",bn)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("svg",Sn,[...r[2]||(r[2]=[e.createElementVNode("path",{d:"M8 3h8l4 4v14H8V3z",fill:"#fef3c7",stroke:"#d97706","stroke-width":"1.2","stroke-linejoin":"round"},null,-1),e.createElementVNode("path",{d:"M16 3v4h4",stroke:"#d97706","stroke-width":"1.2"},null,-1),e.createElementVNode("path",{d:"M10 12h6M10 16h4",stroke:"#92400e","stroke-width":"1.2","stroke-linecap":"round"},null,-1)])]))}),wn=["title","aria-label","onMouseenter","onClick"],yn=["title","onMouseenter","onClick"],Mn={style:{"font-size":"11px","font-weight":"600"}},xn=e.defineComponent({__name:"SelectionToolbarCard",props:{placementAbove:{type:Boolean},anchorHeight:{},hiddenBuiltinActions:{},extraActions:{},renderCopyIcon:{type:Function}},emits:["action"],setup(t,{emit:s}){const r=t,n=s,a=[{id:"highlight",label:"高亮背景"},{id:"underline",label:"下划线"},{id:"squiggly",label:"波浪线"},{id:"strikeout",label:"删除线"}],i=e.computed(()=>new Set(r.hiddenBuiltinActions??[])),o=e.computed(()=>!i.value.has("copy")),l=e.computed(()=>a.filter(e=>!i.value.has(e.id))),h=e.computed(()=>!i.value.has("note")),d=e.computed(()=>[...r.extraActions??[]].sort((e,t)=>(e.order??0)-(t.order??0))),c=e.computed(()=>l.value.length>0||d.value.length>0),u=e.ref(null),p=e.computed(()=>({position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:r.placementAbove?void 0:`${r.anchorHeight+10}px`,bottom:r.placementAbove?`${r.anchorHeight+10}px`:void 0,display:"flex",alignItems:"center",gap:"2px",padding:"4px 6px",borderRadius:"12px",background:"rgba(255, 255, 255, 0.96)",border:"1px solid rgba(15, 23, 42, 0.06)",boxShadow:"0 2px 8px rgba(15, 23, 42, 0.08), 0 12px 32px rgba(15, 23, 42, 0.1)",backdropFilter:"blur(10px)",WebkitBackdropFilter:"blur(10px)"}));function g(e,t=!1){return{display:"flex",alignItems:"center",justifyContent:"center",width:"32px",height:"32px",padding:0,margin:0,border:"none",borderRadius:"8px",background:u.value===e?t?"#fffbeb":"#f1f5f9":"transparent",color:t?"#b45309":"#334155",cursor:"pointer",flexShrink:0,WebkitAppearance:"none",appearance:"none"}}const m={width:"1px",height:"20px",margin:"0 4px",background:"rgba(15, 23, 42, 0.1)",flexShrink:0};return(s,r)=>(e.openBlock(),e.createElementBlock("div",{role:"toolbar","aria-label":"选区工具",style:e.normalizeStyle(p.value)},[o.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createElementVNode("button",{type:"button",title:"复制","aria-label":"复制",style:e.normalizeStyle(g("copy")),onMouseenter:r[0]||(r[0]=e=>u.value="copy"),onMouseleave:r[1]||(r[1]=e=>u.value=null),onClick:r[2]||(r[2]=e=>n("action","copy"))},[t.renderCopyIcon?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(t.renderCopyIcon),{key:0})):(e.openBlock(),e.createBlock(Cn,{key:1,kind:"copy"}))],36),c.value?(e.openBlock(),e.createElementBlock("span",{key:0,style:m,"aria-hidden":""})):e.createCommentVNode("",!0)],64)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(l.value,t=>(e.openBlock(),e.createElementBlock("button",{key:t.id,type:"button",title:t.label,"aria-label":t.label,style:e.normalizeStyle(g(t.id)),onMouseenter:e=>u.value=t.id,onMouseleave:r[3]||(r[3]=e=>u.value=null),onClick:e=>n("action",t.id)},[e.createVNode(Cn,{kind:t.id},null,8,["kind"])],44,wn))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(d.value,t=>(e.openBlock(),e.createElementBlock("button",{key:t.id,type:"button",title:t.label,style:e.normalizeStyle(g(t.id)),onMouseenter:e=>u.value=t.id,onMouseleave:r[4]||(r[4]=e=>u.value=null),onClick:e=>n("action",t.id)},[e.createElementVNode("span",Mn,e.toDisplayString(t.label.slice(0,2)),1)],44,yn))),128)),h.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[c.value||o.value?(e.openBlock(),e.createElementBlock("span",{key:0,style:m,"aria-hidden":""})):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",title:"添加笔记","aria-label":"添加笔记",style:e.normalizeStyle(g("note",!0)),onMouseenter:r[5]||(r[5]=e=>u.value="note"),onMouseleave:r[6]||(r[6]=e=>u.value=null),onClick:r[7]||(r[7]=e=>n("action","note"))},[e.createVNode(Cn,{kind:"note"})],36)],64)):e.createCommentVNode("",!0)],4))}}),Ln={highlight:"highlight",underline:"underline",squiggly:"squiggly",strikeout:"strikeout"},$n=e.defineComponent({__name:"PdfChapterViewport",props:{className:{},features:{},buildSelectionMenu:{},annotationSelectionMenu:{},redactionSelectionMenu:{},showNoteMarkers:{type:Boolean,default:!0},showBookmarkMarkers:{type:Boolean,default:!0},showRedactionLayer:{type:Boolean,default:!1},renderPageOverlay:{},onExtraSelectionAction:{}},setup(r){const n=r,i=e.computed(()=>n.features),{hostRef:o}=Ts(i),l=e.computed(()=>{var e,t;return{background:(null==(t=null==(e=n.features)?void 0:e.scrollViewport)?void 0:t.background)??$}}),d=function(){const{registry:s}=t.useRegistry();return e.computed(()=>{var e,t,r;const n=null==(r=null==(t=null==(e=s.value)?void 0:e.getPlugin(Pt.id))?void 0:t.provides)?void 0:r.call(t);return n?e=>n.createNoteFromSelection(e):null})}(),c=function(){const{registry:s}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=s.value)?void 0:e.getPlugin(Pt.id))})}(),u=function(){const{registry:s}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=s.value)?void 0:e.getPlugin(ps.id))})}(),p=e.computed(()=>{var e,t;return n.showNoteMarkers&&c.value&&!1!==(null==(t=null==(e=n.features)?void 0:e.notes)?void 0:t.enabled)}),g=e.computed(()=>{var e,t;return n.showBookmarkMarkers&&u.value&&!1!==(null==(t=null==(e=n.features)?void 0:e.bookmarks)?void 0:t.enabled)}),m=e.computed(()=>{var e,t;return u.value&&!1!==(null==(t=null==(e=n.features)?void 0:e.bookmarks)?void 0:t.enabled)}),f=function(r,n){const a=e.computed(()=>{var e;return null==(e=r())?void 0:e.selectionToolbar}),i=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=r())?void 0:e.markup)?void 0:t.enabled)}),o=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=r())?void 0:e.notes)?void 0:t.enabled)}),l=e.computed(()=>{var e,t;return!(null==(t=null==(e=a.value)?void 0:e.hiddenBuiltinActions)?void 0:t.includes("copy"))}),{provides:d}=t.useCapability(h.SelectionPlugin.id),{provides:c}=t.useCapability(s.AnnotationPlugin.id),{provides:u}=t.useCapability(Pt.id);return e.computed(()=>{var t,s,h;if(!1!==(null==(t=a.value)?void 0:t.enabled)&&(i.value||o.value||l.value||(null==(h=null==(s=a.value)?void 0:s.extraActions)?void 0:h.length)))return t=>{const s=ln(t.item),h=hn(t.item);return p=>{var g,m,f,v;return e.h("div",p.menuWrapperProps,e.h(xn,{placementAbove:!!(null==(g=p.placement)?void 0:g.suggestTop),anchorHeight:p.rect.size.height,hiddenBuiltinActions:null==(m=a.value)?void 0:m.hiddenBuiltinActions,extraActions:null==(f=a.value)?void 0:f.extraActions,renderCopyIcon:null==(v=a.value)?void 0:v.renderCopyIcon,onAction:e=>{var a,p,g;if("copy"!==e)if("highlight"!==e&&"underline"!==e&&"squiggly"!==e&&"strikeout"!==e){if("note"===e){if(!d.value||!u.value||!o.value)return;const e=d.value.getHighlightRectsForPage(h,s);return void dn(d.value.getSelectedText(s),s=>{var r;null==(r=u.value)||r.requestCreateFromSelection({chapterId:t.item.chapterId,localPageIndex:t.item.localPageIndex,globalPageIndex:t.item.globalPageIndex,globalPageNumber:t.item.globalPageNumber,rectsPdfCoord:e,selectedText:s.join("\n")})})}null==(a=null==n?void 0:n.onExtraAction)||a.call(n,e,t)}else{if(!d.value||!c.value||!i.value)return;V(s,Ln[e],c.value,d.value,null==(g=null==(p=r())?void 0:p.markup)?void 0:g.styles)}else{if(!d.value||!l.value)return;dn(d.value.getSelectedText(s),e=>{!async function(e){var t;const s=e.trim();if(!s)return!1;try{if("undefined"!=typeof navigator&&(null==(t=navigator.clipboard)?void 0:t.writeText))return await navigator.clipboard.writeText(s),!0}catch{}if("undefined"==typeof document)return!1;try{const e=document.createElement("textarea");e.value=s,e.setAttribute("readonly",""),e.style.position="fixed",e.style.left="-9999px",document.body.appendChild(e),e.select();const t=document.execCommand("copy");return document.body.removeChild(e),t}catch{return!1}}(e.join("\n"))})}}}))}}})}(()=>n.features,{onExtraAction:n.onExtraSelectionAction}),v=e.computed(()=>{if(n.buildSelectionMenu||f.value)return e=>{const t=f.value?f.value(e):e.defaultMenu;return n.buildSelectionMenu?n.buildSelectionMenu({...e,defaultMenu:t}):t}}),{provides:P}=t.useCapability(a.DocumentManagerPlugin.id);function I(t){var s;const r=[];if(m.value){const s=function(t){var s,r,a,i;const o=ln(t),l=hn(t),h=null==(r=null==(s=P.value)?void 0:s.getDocument(o))?void 0:r.pages[l];return t.isPlaceholder||!h?null:e.h(gn,{item:t,pdfPageWidth:h.size.width,pdfPageHeight:h.size.height,cssPageWidth:t.width,cssPageHeight:t.height,hoverUi:null==(i=null==(a=n.features)?void 0:a.bookmarks)?void 0:i.hover})}(t);s&&r.push(s)}const a=null==(s=n.renderPageOverlay)?void 0:s.call(n,t);if(a&&r.push(a),r.length)return e.h("div",r)}return(t,s)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"hostRef",ref:o,class:e.normalizeClass(r.className),style:e.normalizeStyle(r.className?void 0:e.unref(M))},[e.createVNode(e.unref(ir),{class:e.normalizeClass(r.className),style:e.normalizeStyle(l.value)},{page:e.withCtx(({item:t})=>{var s,n,a,i;return[e.createVNode(pn,{item:t,features:r.features,"show-note-markers":p.value,"show-bookmark-markers":g.value,"show-redaction-layer":r.showRedactionLayer,"note-marker-ui":null==(n=null==(s=r.features)?void 0:s.notes)?void 0:n.marker,"bookmark-marker-ui":null==(i=null==(a=r.features)?void 0:a.bookmarks)?void 0:i.marker,"build-selection-menu":v.value,"create-note":e.unref(d),"annotation-selection-menu":r.annotationSelectionMenu,"redaction-selection-menu":r.redactionSelectionMenu,"render-page-overlay":I},null,8,["item","features","show-note-markers","show-bookmark-markers","show-redaction-layer","note-marker-ui","bookmark-marker-ui","build-selection-menu","create-note","annotation-selection-menu","redaction-selection-menu"])]}),_:1},8,["class","style"]),e.renderSlot(t.$slots,"default")],6))}}),kn={key:0,style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,width:"100%"}},Dn=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{},onExtraSelectionAction:{type:Function}},setup(s){const r=s,n=e.computed(()=>function(e){if(e.options)return xs(e.options);if(!e.editorOptions)throw new Error("ChapterPdfViewer: 请传入 `options`(推荐),或同时传入 `editorOptions` 与 `features`");const t=F(e.features),{plugins:s}=Cs({...e.editorOptions,features:t});return{plugins:s,features:t,editorOptions:{...e.editorOptions,features:t}}}({engine:r.engine,options:r.options,editorOptions:r.editorOptions,features:r.features}));return(r,a)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(s.className),style:e.normalizeStyle(s.className?void 0:e.unref(M))},[e.createVNode(e.unref(t.EmbedPDF),{engine:s.engine,plugins:n.value.plugins},{default:e.withCtx(({pluginsReady:t})=>[t?(e.openBlock(),e.createElementBlock("div",kn,[e.renderSlot(r.$slots,"prepend"),e.createVNode($n,{class:e.normalizeClass(s.viewportClassName),style:{flex:1,minHeight:0},features:n.value.features,"on-extra-selection-action":s.onExtraSelectionAction},null,8,["class","features","on-extra-selection-action"]),e.renderSlot(r.$slots,"default")])):e.createCommentVNode("",!0)]),_:3},8,["engine","plugins"])],6))}}),Un={class:"chapter-tree-row"},En=["aria-expanded"],Vn={key:1,class:"chapter-tree-toggle-spacer","aria-hidden":""},Nn={class:"chapter-tree-label"},Tn={class:"chapter-tree-meta"},Fn={key:0},An=(e,t)=>{const s=e.__vccOpts||e;for(const[r,n]of t)s[r]=n;return s},On=An(e.defineComponent({__name:"ChapterTreeItem",props:{node:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup(t){const s={idle:"未加载",loading:"加载中",loaded:"已加载",closed:"已卸载",error:"失败","password-required":"需密码"},r=t,n=e.computed(()=>r.node.children??[]),a=e.computed(()=>n.value.length>0),i=e.ref(r.depth<1),o=e.computed(()=>r.activeChapterId===r.node.id),l=e.computed(()=>r.chapterStatus[r.node.id]??"idle"),h=e.computed(()=>!a.value);return(r,d)=>(e.openBlock(),e.createElementBlock("li",null,[e.createElementVNode("div",Un,[a.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"chapter-tree-toggle","aria-expanded":i.value,onClick:d[0]||(d[0]=e=>i.value=!i.value)},e.toDisplayString(i.value?"▼":"▶"),9,En)):(e.openBlock(),e.createElementBlock("span",Vn)),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["chapter-tree-btn",{"chapter-tree-btn-active":o.value}]),onClick:d[1]||(d[1]=e=>r.$emit("select",t.node.id))},[e.createElementVNode("div",Nn,e.toDisplayString(t.node.title),1),e.createElementVNode("div",Tn,[e.createElementVNode("span",null," 第 "+e.toDisplayString(t.node.startPage)+e.toDisplayString(t.node.endPage!==t.node.startPage?`–${t.node.endPage}`:"")+" 页 ",1),h.value?(e.openBlock(),e.createElementBlock("span",Fn,e.toDisplayString(s[l.value]),1)):e.createCommentVNode("",!0)])],2)]),a.value&&i.value?(e.openBlock(),e.createBlock(Rn,{key:0,nodes:n.value,depth:t.depth+1,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:d[2]||(d[2]=e=>r.$emit("select",e))},null,8,["nodes","depth","active-chapter-id","chapter-status"])):e.createCommentVNode("",!0)]))}}),[["__scopeId","data-v-315bbf7a"]]),Rn=An(e.defineComponent({__name:"ChapterTreeList",props:{nodes:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup:t=>(s,r)=>(e.openBlock(),e.createElementBlock("ul",{class:"chapter-tree-list",style:e.normalizeStyle({marginLeft:t.depth>0?"12px":"0"})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.nodes,n=>(e.openBlock(),e.createBlock(On,{key:n.id,node:n,depth:t.depth,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:r[0]||(r[0]=e=>s.$emit("select",e))},null,8,["node","depth","active-chapter-id","chapter-status"]))),128))],4))}),[["__scopeId","data-v-eb742e4f"]]),Bn={class:"chapter-tree"},Gn={class:"chapter-tree-nav","aria-label":"章节目录"},zn=An(e.defineComponent({__name:"ChapterTreePanel",props:{tree:{},activeChapterId:{}},emits:["active-chapter-change"],setup(s,{emit:r}){const n=s,a=r,{provides:i}=t.useCapability(ke.id),{provides:o}=t.useCapability(re.id),l=e.ref({});function h(){if(!o.value)return;const e={},t=s=>{var r;for(const n of s)e[n.id]=o.value.getChapterStatus(n.id),(null==(r=n.children)?void 0:r.length)&&t(n.children)};t(n.tree),l.value=e}e.watch([o,()=>n.tree],h,{immediate:!0});let d=null;function c(e){var t;a("active-chapter-change",e),null==(t=i.value)||t.scrollToChapter(e)}return e.watch(o,e=>{null==d||d(),d=e?e.onChapterStatusChange(h):null},{immediate:!0}),e.onBeforeUnmount(()=>null==d?void 0:d()),(t,r)=>(e.openBlock(),e.createElementBlock("aside",Bn,[r[0]||(r[0]=e.createElementVNode("h2",{class:"chapter-tree-title"},"章节目录",-1)),e.createElementVNode("nav",Gn,[e.createVNode(Rn,{nodes:s.tree,depth:0,"active-chapter-id":s.activeChapterId,"chapter-status":l.value,onSelect:c},null,8,["nodes","active-chapter-id","chapter-status"])])]))}}),[["__scopeId","data-v-d7a0838d"]]),_n=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{}},setup:t=>(t,s)=>(e.openBlock(),e.createBlock(e.unref(Dn),e.normalizeProps(e.guardReactiveProps(t.$props)),e.createSlots({default:e.withCtx(()=>[e.renderSlot(t.$slots,"default")]),_:2},[t.$slots.prepend?{name:"prepend",fn:e.withCtx(()=>[e.renderSlot(t.$slots,"prepend")]),key:"0"}:void 0]),1040))});function qn(e){const[t,s]=e.localPageRange;return s-t+1}function Wn(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Hn(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Wn(t)?t.segmentPageThreshold:null}function Kn(e,t){return`${e}#s${t}`}function jn(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Xn(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Yn(e){const t=Hn(e);if(!t)return null;const s=qn(e),r=Xn(s,t),n=Wn(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Kn(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Zn(e,t){const s=Yn(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Jn(e,t){const s=Yn(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Qn(e){var t;const s=Hn(e);if(!s)return[];const r=[],{chapterId:n}=e,a=qn(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Wn(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Xn(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const ea={kind:"first-wins"};function ta(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let sa=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const ra=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ea,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ea,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=jn(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=jn(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=jn(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Zn(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Yn(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Qn(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=ea){const s=function(e,t=ea){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,ta(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new sa(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Yn(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Jn(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Wn(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Yn(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=[];for(const n of t){const e=`${n.chapterId}:${n.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(n.chapterId,n.segmentIndex)||r.push({chapterId:n.chapterId,segmentIndex:n.segmentIndex}))}this.visibleSegmentBacklog=r,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Yn(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Jn(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);if(l){const e=this.findChapter(l.chapterId);if(e){const t=Jn(e,l.localPageIndex);o(l.chapterId,t+1)}}for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Jn(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Zn(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Yn(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Wn(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Hn(t);if(a){const r=Xn(qn(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Wn(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=jn(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Yn(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};ra.id="chapter-manager";let na=ra;function aa(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ia(e,t){return`${e}#s${t}`}function oa(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function la(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return aa(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=aa(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:ia(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function ha(e,t){const s=la(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function da(e){const[t,s]=e.localPageRange;return s-t+1}function ca(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ua(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ca(t)?t.segmentPageThreshold:null}function pa(e,t){return`${e}#s${t}`}function ga(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function ma(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function fa(e){const t=ua(e);if(!t)return null;const s=da(e),r=ma(s,t),n=ca(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:pa(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function va(e,t){const s=fa(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Pa(e,t){const s=fa(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Ia(e){var t;const s=ua(e);if(!s)return[];const r=[],{chapterId:n}=e,a=da(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!ca(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=ma(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const ba={kind:"first-wins"};function Sa(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class Ca{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}const wa=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ba,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ba,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=ga(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=ga(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=ga(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?va(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?fa(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Ia(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=ba){const s=function(e,t=ba){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Sa(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Ca(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?fa(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Pa(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(ca(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=fa(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=[];for(const n of t){const e=`${n.chapterId}:${n.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(n.chapterId,n.segmentIndex)||r.push({chapterId:n.chapterId,segmentIndex:n.segmentIndex}))}this.visibleSegmentBacklog=r,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=fa(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Pa(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);if(l){const e=this.findChapter(l.chapterId);if(e){const t=Pa(e,l.localPageIndex);o(l.chapterId,t+1)}}for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Pa(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=va(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=fa(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(ca(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=ua(t);if(a){const r=ma(da(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(ca(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=ga(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?fa(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};wa.id="chapter-manager";let ya=wa;function Ma(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}function xa(e){const[t,s]=e.localPageRange;return s-t+1}function La(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function $a(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return La(t)?t.segmentPageThreshold:null}function ka(e,t){return`${e}#s${t}`}function Da(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Ua(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ea(e){const t=$a(e);if(!t)return null;const s=xa(e),r=Ua(s,t),n=La(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:ka(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Va(e,t){const s=Ea(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Na(e,t){const s=Ea(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Ta(e){var t;const s=$a(e);if(!s)return[];const r=[],{chapterId:n}=e,a=xa(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!La(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Ua(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}(class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,Ma),this.visibleChange$=n.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.lastLoadIndicesKey="",this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(ya.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.lastLoadIndicesKey="",this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=ha(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===e.length)return;const t=this.chapterManager.provides(),s=t.visibleRangeNeedsSegmentLoad(e),r=e.join(",");(r!==this.lastLoadIndicesKey||s)&&(this.lastLoadIndicesKey=r,t.setVisibleGlobalPages(e))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=oa(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=oa(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}if(s){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),r=s.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!r||0===n.length)return;const a=la(r),i=this.documentManager.provides(),o=[],l=(e,t,s,r)=>{var n;const a=i.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let i=0;i<r;i++){const e=a.pages[s+i];(null==e?void 0:e.size)&&o.push({localPageIndex:t+i,width:e.size.width*l,height:e.size.height*l})}return o.length>0};if(a)for(const h of a.segments){if(!s.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=oa(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),r=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,r=this.findFirstVisibleIndex(t);let n=r;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=s)break;n++}const a=[];let i=r,o=-1;for(let l=r;l<n;l++){a.push(l);const e=this.offsets[l],r=e+this.getPageSize(l).height,n=Math.max(0,Math.min(r,s)-Math.max(e,t));n>o&&(o=n,i=l)}this.currentVisible=a,this.currentGlobalPageIndex=i,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:i}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);if(s<0)return;const r=this.chapterManager.provides(),n=r.getChapter(e),a=this.virtualPageMap.atIndex(s);if(n&&a){const t=ha(n,a.localPageIndex);r.ensureSegmentLoaded(e,t)}else r.ensureChapterLoaded(e);this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}}).id="chapter-scroll";const Fa={kind:"first-wins"};function Aa(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let Oa=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const Ra=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Fa,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Fa,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Da(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Da(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Da(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Va(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ea(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Ta(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Fa){const s=function(e,t=Fa){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Aa(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Oa(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ea(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Na(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(La(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Ea(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=[];for(const n of t){const e=`${n.chapterId}:${n.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(n.chapterId,n.segmentIndex)||r.push({chapterId:n.chapterId,segmentIndex:n.segmentIndex}))}this.visibleSegmentBacklog=r,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Ea(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Na(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);if(l){const e=this.findChapter(l.chapterId);if(e){const t=Na(e,l.localPageIndex);o(l.chapterId,t+1)}}for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Na(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Va(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Ea(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(La(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=$a(t);if(a){const r=Ua(xa(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(La(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Da(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Ea(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Ra.id="chapter-manager";let Ba=Ra;function Ga(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function za(e,t){return`${e}#s${t}`}function _a(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function qa(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ga(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=Ga(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:za(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Wa(e,t){const s=qa(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Ha(e){const[t,s]=e.localPageRange;return s-t+1}function Ka(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ja(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ka(t)?t.segmentPageThreshold:null}function Xa(e,t){return`${e}#s${t}`}function Ya(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Za(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ja(e){const t=ja(e);if(!t)return null;const s=Ha(e),r=Za(s,t),n=Ka(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Xa(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Qa(e,t){const s=Ja(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function ei(e,t){const s=Ja(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function ti(e){var t;const s=ja(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Ha(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Ka(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Za(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const si={kind:"first-wins"};function ri(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let ni=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const ai=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=si,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??si,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Ya(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Ya(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Ya(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Qa(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ja(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...ti(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=si){const s=function(e,t=si){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,ri(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new ni(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ja(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=ei(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Ka(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Ja(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=[];for(const n of t){const e=`${n.chapterId}:${n.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(n.chapterId,n.segmentIndex)||r.push({chapterId:n.chapterId,segmentIndex:n.segmentIndex}))}this.visibleSegmentBacklog=r,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Ja(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=ei(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);if(l){const e=this.findChapter(l.chapterId);if(e){const t=ei(e,l.localPageIndex);o(l.chapterId,t+1)}}for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=ei(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Qa(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Ja(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Ka(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=ja(t);if(a){const r=Za(Ha(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Ka(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Ya(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Ja(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};ai.id="chapter-manager";let ii=ai;function oi(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const li=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,oi),this.visibleChange$=n.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.lastLoadIndicesKey="",this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(ii.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.lastLoadIndicesKey="",this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=Wa(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===e.length)return;const t=this.chapterManager.provides(),s=t.visibleRangeNeedsSegmentLoad(e),r=e.join(",");(r!==this.lastLoadIndicesKey||s)&&(this.lastLoadIndicesKey=r,t.setVisibleGlobalPages(e))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=_a(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=_a(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}if(s){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),r=s.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!r||0===n.length)return;const a=qa(r),i=this.documentManager.provides(),o=[],l=(e,t,s,r)=>{var n;const a=i.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let i=0;i<r;i++){const e=a.pages[s+i];(null==e?void 0:e.size)&&o.push({localPageIndex:t+i,width:e.size.width*l,height:e.size.height*l})}return o.length>0};if(a)for(const h of a.segments){if(!s.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=_a(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),r=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,r=this.findFirstVisibleIndex(t);let n=r;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=s)break;n++}const a=[];let i=r,o=-1;for(let l=r;l<n;l++){a.push(l);const e=this.offsets[l],r=e+this.getPageSize(l).height,n=Math.max(0,Math.min(r,s)-Math.max(e,t));n>o&&(o=n,i=l)}this.currentVisible=a,this.currentGlobalPageIndex=i,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:i}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);if(s<0)return;const r=this.chapterManager.provides(),n=r.getChapter(e),a=this.virtualPageMap.atIndex(s);if(n&&a){const t=Wa(n,a.localPageIndex);r.ensureSegmentLoaded(e,t)}else r.ensureChapterLoaded(e);this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};li.id="chapter-scroll";let hi=li;const di=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=n.createBehaviorEmitter([]),this.noteActivated$=n.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(hi.id),this.chapterManager=this.registry.getPlugin(Ba.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,t.callbacks.loadNotes)try{const e=await t.callbacks.loadNotes();for(const t of e)this.notes.set(t.noteId,t);this.notesChange$.emit(this.listAll())}catch(s){this.logger.error(e.id,"LoadNotes","Failed to load notes",s)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(s=>s.chapterId===e&&s.localPageIndex===t),listAllNotes:()=>this.listAll(),getNote:e=>this.notes.get(e)??null,deleteNote:e=>this.deleteNote(e),updateNoteContent:(e,t)=>this.updateNoteContent(e,t),scrollToNote:e=>this.scrollToNote(e),listNotesForChapter:e=>this.listNotesForChapter(e),replaceNotesForChapter:(e,t)=>this.replaceNotesForChapter(e,t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(e){this.notes.set(e.noteId,e),this.notesChange$.emit(this.listAll())}requestEdit(e){const t=this.notes.get(e);t&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(e,t):this.activateNote(e))}activateNote(e){var t,s;const r=this.notes.get(e);r&&(null==(s=(t=this.config.callbacks).onActivateNote)||s.call(t,e,r),this.noteActivated$.emit({noteId:e,anchor:r}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[s,r]of this.notes.entries())r.chapterId===e&&this.notes.delete(s);for(const s of t)s.chapterId===e&&this.notes.set(s.noteId,s);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:ui(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:s,onCreateNote:r}=this.config.callbacks;return s?(s({draft:t,complete:async e=>{const s={...t,noteId:e};this.registerNote(s)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const s=this.buildDraft(t),r=this.config.callbacks.onCreateNote;if(!r)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await r(s)}catch(i){return this.logger.error(e.id,"OnCreateNote","Callback failed",i),null}if(!n)return null;const a={...s,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var s,r;if(this.notes.has(t)){try{await(null==(r=(s=this.config.callbacks).onDeleteNote)?void 0:r.call(s,t))}catch(n){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",n)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,s){var r,n;const a=this.notes.get(t);if(!a)return;const i={...a,content:s};try{await(null==(n=(r=this.config.callbacks).onUpdateNote)?void 0:n.call(r,i))}catch(o){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",o)}this.notes.set(t,i),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const s=this.notes.get(e);if(!s)return;const r=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(s.chapterId);const a=n.resolvePageDocument(s.chapterId,s.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(r.scrollToGlobalPageIndex(s.globalPageIndex),await this.waitForPageInLayout(s.globalPageIndex),r.scrollToGlobalPdfPoint(s.globalPageIndex,s.endAnchor.y,{marginTop:80})):r.scrollToGlobalPageIndex(s.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const r=setTimeout(()=>{n(),s(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(r),n(),s(a))})})}};di.id="note";let ci=di;function ui(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function pi(e){const[t,s]=e.localPageRange;return s-t+1}function gi(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function mi(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return gi(t)?t.segmentPageThreshold:null}function fi(e,t){return`${e}#s${t}`}function vi(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Pi(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ii(e){const t=mi(e);if(!t)return null;const s=pi(e),r=Pi(s,t),n=gi(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:fi(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function bi(e,t){const s=Ii(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Si(e,t){const s=Ii(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Ci(e){var t;const s=mi(e);if(!s)return[];const r=[],{chapterId:n}=e,a=pi(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!gi(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Pi(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const wi={kind:"first-wins"};function yi(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let Mi=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const xi=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=wi,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??wi,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=vi(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=vi(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=vi(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?bi(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ii(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Ci(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=wi){const s=function(e,t=wi){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,yi(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Mi(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ii(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Si(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(gi(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Ii(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=[];for(const n of t){const e=`${n.chapterId}:${n.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(n.chapterId,n.segmentIndex)||r.push({chapterId:n.chapterId,segmentIndex:n.segmentIndex}))}this.visibleSegmentBacklog=r,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Ii(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Si(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);if(l){const e=this.findChapter(l.chapterId);if(e){const t=Si(e,l.localPageIndex);o(l.chapterId,t+1)}}for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Si(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=bi(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Ii(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(gi(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=mi(t);if(a){const r=Pi(pi(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(gi(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=vi(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Ii(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};xi.id="chapter-manager";let Li=xi;function $i(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ki(e,t){return`${e}#s${t}`}function Di(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Ui(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return $i(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=$i(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:ki(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Ei(e,t){const s=Ui(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Vi(e){const[t,s]=e.localPageRange;return s-t+1}function Ni(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ti(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ni(t)?t.segmentPageThreshold:null}function Fi(e,t){return`${e}#s${t}`}function Ai(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Oi(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ri(e){const t=Ti(e);if(!t)return null;const s=Vi(e),r=Oi(s,t),n=Ni(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Fi(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Bi(e,t){const s=Ri(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Gi(e,t){const s=Ri(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function zi(e){var t;const s=Ti(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Vi(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Ni(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Oi(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const _i={kind:"first-wins"};function qi(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class Wi{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}const Hi=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=_i,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??_i,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Ai(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Ai(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Ai(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Bi(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ri(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...zi(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=_i){const s=function(e,t=_i){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,qi(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Wi(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ri(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Gi(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Ni(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Ri(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=[];for(const n of t){const e=`${n.chapterId}:${n.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(n.chapterId,n.segmentIndex)||r.push({chapterId:n.chapterId,segmentIndex:n.segmentIndex}))}this.visibleSegmentBacklog=r,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Ri(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Gi(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);if(l){const e=this.findChapter(l.chapterId);if(e){const t=Gi(e,l.localPageIndex);o(l.chapterId,t+1)}}for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Gi(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Bi(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Ri(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Ni(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Ti(t);if(a){const r=Oi(Vi(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Ni(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Ai(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Ri(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Hi.id="chapter-manager";let Ki=Hi;function ji(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const Xi=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,ji),this.visibleChange$=n.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.lastLoadIndicesKey="",this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Ki.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.lastLoadIndicesKey="",this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=Ei(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===e.length)return;const t=this.chapterManager.provides(),s=t.visibleRangeNeedsSegmentLoad(e),r=e.join(",");(r!==this.lastLoadIndicesKey||s)&&(this.lastLoadIndicesKey=r,t.setVisibleGlobalPages(e))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Di(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Di(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}if(s){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),r=s.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!r||0===n.length)return;const a=Ui(r),i=this.documentManager.provides(),o=[],l=(e,t,s,r)=>{var n;const a=i.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let i=0;i<r;i++){const e=a.pages[s+i];(null==e?void 0:e.size)&&o.push({localPageIndex:t+i,width:e.size.width*l,height:e.size.height*l})}return o.length>0};if(a)for(const h of a.segments){if(!s.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=Di(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),r=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,r=this.findFirstVisibleIndex(t);let n=r;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=s)break;n++}const a=[];let i=r,o=-1;for(let l=r;l<n;l++){a.push(l);const e=this.offsets[l],r=e+this.getPageSize(l).height,n=Math.max(0,Math.min(r,s)-Math.max(e,t));n>o&&(o=n,i=l)}this.currentVisible=a,this.currentGlobalPageIndex=i,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:i}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);if(s<0)return;const r=this.chapterManager.provides(),n=r.getChapter(e),a=this.virtualPageMap.atIndex(s);if(n&&a){const t=Ei(n,a.localPageIndex);r.ensureSegmentLoaded(e,t)}else r.ensureChapterLoaded(e);this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};Xi.id="chapter-scroll";let Yi=Xi;function Zi(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Ji(e,t){const s=e.origin.y,r=e.origin.y+e.size.height,n=t.origin.y,a=t.origin.y+t.size.height,i=Math.max(r,a)-Math.min(s,n);return i<=0?0:Math.max(0,Math.min(r,a)-Math.max(s,n))/i}function Qi(e,t){var s,r;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const n=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],a=(null==(r=t.rectsPdfCoord)?void 0:r.length)?t.rectsPdfCoord:[t.rectPdfCoord],i=e.markerAnchor??Zi(n),o=t.markerAnchor??Zi(a);if(Math.hypot(i.x-o.x,i.y-o.y)<=6)return!0;for(const l of n)for(const e of a){if(Ji(l,e)<.5)continue;const t=Math.max(l.origin.x,e.origin.x);if(Math.min(l.origin.x+l.size.width,e.origin.x+e.size.width)-t>.25*Math.min(l.size.width,e.size.width))return!0}return!1}const eo=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.change$=n.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(Yi.id),this.chapterManager=this.registry.getPlugin(Li.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){var s;if(this.config=t,null==(s=t.callbacks)?void 0:s.load)try{const e=await t.callbacks.load();for(const t of e)this.entries.set(t.id,t);this.change$.emit(this.list())}catch(r){this.logger.error(e.id,"Load","Failed to load paragraph bookmarks",r)}}buildCapability(){return{addBookmark:e=>this.addBookmark(e),removeBookmark:e=>this.removeBookmark(e),updateBookmark:(e,t)=>this.updateBookmark(e,t),listBookmarks:()=>this.list(),getBookmark:e=>this.entries.get(e)??null,scrollToBookmark:e=>this.scrollToBookmark(e),requestRemoveBookmark:e=>this.requestRemoveBookmark(e),listBookmarksForChapter:e=>this.listBookmarksForChapter(e),replaceBookmarksForChapter:(e,t)=>this.replaceBookmarksForChapter(e,t),onBookmarksChange:this.change$.on}}addBookmark(e){for(const r of this.entries.values())if(Qi(r.anchor,e.anchor))return r;const t=e.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s={id:t,label:e.label,anchor:e.anchor,metadata:e.metadata,createdAt:Date.now()};return this.entries.set(t,s),this.notifyAndPersist(),s}removeBookmark(e){var t,s,r;this.entries.delete(e)&&(this.notifyAndPersist(),null==(r=null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.onRemoveSuccess)||r.call(s,e))}async requestRemoveBookmark(t){var s,r;const n=this.entries.get(t);if(!n)return!1;const a=null==(r=null==(s=this.config)?void 0:s.callbacks)?void 0:r.onRequestRemove;if(a)try{if(!(await a(n)))return!1}catch(i){return this.logger.error(e.id,"RequestRemove","callback failed",i),!1}return this.removeBookmark(t),!0}updateBookmark(e,t){const s=this.entries.get(e);s&&(this.entries.set(e,{...s,...t}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((e,t)=>e.createdAt-t.createdAt)}listBookmarksForChapter(e){return this.list().filter(t=>t.anchor.chapterId===e)}replaceBookmarksForChapter(e,t){for(const[s,r]of this.entries.entries())r.anchor.chapterId===e&&this.entries.delete(s);for(const s of t)s.anchor.chapterId===e&&this.entries.set(s.id,s);this.notifyAndPersist()}notifyAndPersist(){var t,s;const r=this.list();this.change$.emit(r),(null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.persist)&&Promise.resolve(this.config.callbacks.persist(r)).catch(t=>this.logger.error(e.id,"Persist","persist callback rejected",t))}async scrollToBookmark(e){const t=this.entries.get(e);if(!t)return;const s=this.chapterScroll.provides(),r=this.chapterManager.provides();await r.ensureAllSegmentsLoaded(t.anchor.chapterId);let n=t.anchor.globalPageIndex;if(void 0===n){const e=this.chapterManager.provides().getVirtualPageMap().toGlobal(t.anchor.chapterId,t.anchor.localPageIndex);if(!e)return;n=e.globalPageIndex}const a=function(e){if(e.markerAnchor)return e.markerAnchor.y;const t=e.rectPdfCoord;return t.origin.y+t.size.height}(t.anchor);await async function(e,t,s){e.scrollToGlobalPageIndex(t),await function(e,t,s=2500){const r=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return r?Promise.resolve(r):new Promise(r=>{const n=setTimeout(()=>{a(),r(null)},s),a=e.onLayoutChange(e=>{const s=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);s&&(clearTimeout(n),a(),r(s))})})}(e,t),e.scrollToGlobalPdfPoint(t,s,{marginTop:80})}(s,n,a)}};eo.id="paragraph-bookmark";let to=eo;function so(e,t){const s=e;return!1===e?{...t,enabled:!1}:!0===e||void 0===e?{...t,enabled:t.enabled??!0}:{...t,...s,enabled:!1!==(null==s?void 0:s.enabled)}}function ro(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function no(e,t){return`${e}#s${t}`}function ao(e,t){const s=function(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ro(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=ro(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:no(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT,r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT,function(){const e=so(void 0,{enabled:!0}),t=so(void 0,{enabled:!0}),s=so(void 0,{enabled:!0}),r=so(void 0,{enabled:!0,min:.5,max:3,initial:1}),n=so(!1!==e.enabled||!1!==s.enabled,{enabled:!0});null==void 0||(void 0).background}();function io(e){const t=new Uint8Array(e);let s="";for(let r=0;r<t.length;r++)s+=String.fromCharCode(t[r]);return btoa(s)}function oo(e){return{bookmarks:!1!==(null==e?void 0:e.bookmarks),notes:!1!==(null==e?void 0:e.notes),markup:!1!==(null==e?void 0:e.markup)}}function lo(e){return new Promise((t,s)=>{e.wait(e=>t(e),e=>s(e))})}function ho(e){var t,r,n,a;return{annotation:null==(t=e.getPlugin(s.AnnotationPlugin.id))?void 0:t.provides(),note:null==(r=e.getPlugin(ci.id))?void 0:r.provides(),bookmark:null==(n=e.getPlugin(to.id))?void 0:n.provides(),chapterManager:null==(a=e.getPlugin(na.id))?void 0:a.provides()}}async function co(e,t,s){if(!s||!e)return;const r=e.getSegmentPlan(t)?await e.ensureAllSegmentsLoaded(t):await e.ensureChapterLoaded(t);if("loaded"!==r)throw new Error(`章节 ${t} 未加载成功(${r}),无法导入/导出划线`)}async function uo(e,t,s){const r=oo(s),{annotation:n,note:a,bookmark:i,chapterManager:o}=ho(e),l={chapterId:t};if(r.bookmarks){if(!i)throw new Error("paragraph-bookmark 插件未注册");l.bookmarks=i.listBookmarksForChapter(t)}if(r.notes){if(!a)throw new Error("note 插件未注册");l.notes=a.listNotesForChapter(t)}if(r.markup){if(!n)throw new Error("annotation 插件未注册");await co(o,t,!1!==(null==s?void 0:s.ensureChapterLoaded));const e=await async function(e,t,s){const r=t.getSegmentPlan(s);if(!r)return lo(e.forDocument(s).exportAnnotations());const n=[];for(const a of r.segments){if(!t.isSegmentLoaded(s,a.index))continue;const r=await lo(e.forDocument(a.documentId).exportAnnotations());for(const e of r){const t=e.annotation.pageIndex;n.push({...e,annotation:{...e.annotation,pageIndex:t+a.localPageStart}})}}return n}(n,o,t);l.markup=function(e){return e.map(e=>{if(!(e.ctx&&"data"in e.ctx&&e.ctx.data instanceof ArrayBuffer))return{annotation:e.annotation};const t=e.ctx;return{annotation:e.annotation,ctx:{dataBase64:io(t.data),mimeType:t.mimeType}}})}(e)}return l}async function po(e,t,s){const r=oo(s),n=(null==s?void 0:s.mode)??"replace",{annotation:a,note:i,bookmark:o,chapterManager:l}=ho(e),h=t.chapterId;if(r.bookmarks&&t.bookmarks){if(!o)throw new Error("paragraph-bookmark 插件未注册");if("replace"===n)o.replaceBookmarksForChapter(h,t.bookmarks);else for(const e of t.bookmarks)o.addBookmark(e)}if(r.notes&&t.notes){if(!i)throw new Error("note 插件未注册");if("replace"===n)i.replaceNotesForChapter(h,t.notes);else for(const e of t.notes)i.registerNote(e)}if(r.markup&&t.markup){if(!a)throw new Error("annotation 插件未注册");await co(l,h,!1!==(null==s?void 0:s.ensureChapterLoaded)),function(e,t,s,r,n){const a=t.getSegmentPlan(s);if(!a){const t=e.forDocument(s);return"replace"===n&&t.deleteAllAnnotations(),void t.importAnnotations(r)}const i=t.getChapter(s);if(!i)return;const o=new Map;for(const l of r){const e=l.annotation.pageIndex,t=ao(i,e),s=a.segments[t];if(!s)continue;const r=o.get(t)??[];r.push({...l,annotation:{...l.annotation,pageIndex:e-s.localPageStart}}),o.set(t,r)}for(const l of a.segments){const t=e.forDocument(l.documentId),s=o.get(l.index)??[];"replace"===n&&t.deleteAllAnnotations(),s.length>0&&t.importAnnotations(s)}}(a,l,h,function(e){return e.map(e=>{var t;if(!(null==(t=e.ctx)?void 0:t.dataBase64))return{annotation:e.annotation};const s=function(e){const t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return s.buffer}(e.ctx.dataBase64);return{annotation:e.annotation,ctx:{data:s,...e.ctx.mimeType?{mimeType:e.ctx.mimeType}:{}}}})}(t.markup),n)}(null==s?void 0:s.persistNotes)&&i&&await s.persistNotes(i.listAllNotes()),(null==s?void 0:s.persistBookmarks)&&o&&await s.persistBookmarks(o.listBookmarks())}function go(e){return JSON.stringify(e,null,2)}function mo(e){return JSON.stringify(e,null,2)}function fo(e,t){const s=new Blob([t],{type:"application/json;charset=utf-8"}),r=URL.createObjectURL(s),n=document.createElement("a");n.href=r,n.download=e,n.click(),URL.revokeObjectURL(r)}r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT,r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT;function vo(e){const[t,s]=e.localPageRange;return s-t+1}function Po(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Io(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Po(t)?t.segmentPageThreshold:null}function bo(e,t){return`${e}#s${t}`}function So(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Co(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function wo(e){const t=Io(e);if(!t)return null;const s=vo(e),r=Co(s,t),n=Po(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:bo(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function yo(e,t){const s=wo(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Mo(e,t){const s=wo(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function xo(e){var t;const s=Io(e);if(!s)return[];const r=[],{chapterId:n}=e,a=vo(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Po(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Co(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Lo={kind:"first-wins"};function $o(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class ko{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}function Do(e,t=Lo){const s=function(e,t=Lo){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,$o(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new ko(a)}const Uo=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Lo,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Lo,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=So(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=So(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=So(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?yo(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?wo(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...xo(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=Do(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?wo(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!!s&&(!!this.pendingSegmentLoadPromises.has(s)||!(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Mo(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&("error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e))}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!Po(s)&&((!s||!("url"in s||"buffer"in s||"load"in s))&&!!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||(!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1))}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=wo(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);if(i)return i.globalPageIndex;return 1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=[];for(const n of t){const e=`${n.chapterId}:${n.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(n.chapterId,n.segmentIndex)||r.push({chapterId:n.chapterId,segmentIndex:n.segmentIndex}))}this.visibleSegmentBacklog=r,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=wo(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Mo(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);if(l){const e=this.findChapter(l.chapterId);if(e){const t=Mo(e,l.localPageIndex);o(l.chapterId,t+1)}}for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Mo(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=yo(this.findChapter(e.chapterId),e.localPageIndex);if(this.documentManager.provides().isDocumentOpen(t.documentId)){this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus){if("loaded"!==r)continue;t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=wo(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Po(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Io(t);if(a){const r=Co(vo(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Po(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=So(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}if(!l)return void this.updateStatus(s,"password-required");this.updateStatus(s,"loading");this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?wo(t):null,n=e=>{if(s.isDocumentOpen(e)){s.closeDocument(e).wait(()=>{},()=>{})}};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Uo.id="chapter-manager";let Eo=Uo;function Vo(e){const t=e.endPage-e.startPage+1;return{chapterId:e.chapterId,title:e.title,globalPageRange:[e.startPage,e.endPage],localPageRange:[0,t-1],...e.source?{source:e.source}:{},...null!=e.segmentPageThreshold?{segmentPageThreshold:e.segmentPageThreshold}:{},...e.encrypted?{encrypted:e.encrypted}:{}}}function No(e){const t=[],s=e=>{var r;for(const n of e)t.push(Vo(n)),(null==(r=n.children)?void 0:r.length)&&s(n.children)};return s(e),t}function To(e){return e.map(e=>{var t;return{id:e.chapterId,title:e.title,startPage:e.startPage,endPage:e.endPage,children:(null==(t=e.children)?void 0:t.length)?To(e.children):void 0}})}Object.defineProperty(exports,"EmbedPDF",{enumerable:!0,get:()=>t.EmbedPDF}),Object.defineProperty(exports,"useCapability",{enumerable:!0,get:()=>t.useCapability}),Object.defineProperty(exports,"useRegistry",{enumerable:!0,get:()=>t.useRegistry}),Object.defineProperty(exports,"usePdfiumEngine",{enumerable:!0,get:()=>y.usePdfiumEngine}),exports.CHAPTER_ANNOTATIONS_ARCHIVE_VERSION=1,exports.CallbackPasswordProvider=B,exports.ChapterManagerPlugin=Eo,exports.ChapterPdfViewer=_n,exports.ChapterTreePanel=zn,exports.DEFAULT_CHAPTER_TEXT_SELECTION_BACKGROUND="rgba(33, 150, 243)",exports.DEFAULT_CHAPTER_VIEWER_CONFIG={},exports.DEFAULT_CHAPTER_VIEWER_FEATURES=Ss,exports.PdfChapterViewport=$n,exports.applySelectionMarkup=V,exports.buildChapterViewerCatalog=function(e){return{tree:To(e),manifest:{chapters:No(e)}}},exports.buildParagraphBookmarkAnchor=cs,exports.chapterAnnotationsArchiveToJson=go,exports.chapterAnnotationsSnapshotToJson=mo,exports.chapterDescriptorFromTreeNode=Vo,exports.copyTextToClipboard=async function(e){var t;const s=e.trim();if(!s)return!1;try{if("undefined"!=typeof navigator&&(null==(t=navigator.clipboard)?void 0:t.writeText))return await navigator.clipboard.writeText(s),!0}catch{}if("undefined"==typeof document)return!1;try{const e=document.createElement("textarea");e.value=s,e.setAttribute("readonly",""),e.style.position="fixed",e.style.left="-9999px",document.body.appendChild(e),e.select();const t=document.execCommand("copy");return document.body.removeChild(e),t}catch{return!1}},exports.createChapterViewerBundle=xs,exports.createChapterViewerEditor=Cs,exports.createChapterViewerEditorOptions=function(e){const{features:t,...s}=Ms(ys(e));return s},exports.createPdfChapterEditor=Is,exports.defaultOverlapStrategy={kind:"first-wins"},exports.downloadChapterAnnotationsArchive=function(e,t="chapter-annotations.json"){fo(t,go(e))},exports.downloadChapterAnnotationsSnapshot=function(e,t){fo(t??`chapter-annotations-${e.chapterId}.json`,mo(e))},exports.downloadJsonFile=fo,exports.exportAllChapterAnnotations=async function(e,t,s){const r={};for(const n of t.chapters){const t=await uo(e,n.chapterId,s),{chapterId:a,...i}=t;r[n.chapterId]=i}return{version:1,exportedAt:(new Date).toISOString(),chapters:r}},exports.exportChapterAnnotations=uo,exports.flattenChapterTree=No,exports.importChapterAnnotations=po,exports.importChapterAnnotationsArchive=async function(e,t,s){if(1!==t.version)throw new Error(`不支持的归档版本 ${t.version},当前为 1`);for(const[r,n]of Object.entries(t.chapters))await po(e,{chapterId:r,...n},s)},exports.overlapStrategyForSamePageOwner=function(e){return"last"===e?{kind:"last-wins"}:{kind:"first-wins"}},exports.parseChapterAnnotationsArchiveJson=function(e){const t=JSON.parse(e);if(!t||"object"!=typeof t||!t.chapters)throw new Error("无效的章节标注 JSON");return t},exports.parseChapterAnnotationsSnapshotJson=function(e){const t=JSON.parse(e);if(!(null==t?void 0:t.chapterId))throw new Error("无效的章节标注 JSON:缺少 chapterId");return t},exports.toChapterTreeNodes=To;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),t=require("@embedpdf/core/vue"),s=require("@embedpdf/plugin-annotation"),r=require("@embedpdf/models"),n=require("@embedpdf/core"),a=require("@embedpdf/plugin-document-manager"),i=require("@embedpdf/plugin-interaction-manager"),o=require("@embedpdf/plugin-render"),l=require("@embedpdf/plugin-rotate"),h=require("@embedpdf/plugin-selection"),d=require("@embedpdf/plugin-history"),c=require("@embedpdf/plugin-redaction"),u=require("@embedpdf/plugin-form"),p=require("@embedpdf/plugin-stamp"),g=require("@embedpdf/plugin-signature"),m=require("@embedpdf/plugin-commands"),f=require("@embedpdf/plugin-i18n"),v=require("@embedpdf/plugin-ui"),P=require("@embedpdf/plugin-interaction-manager/vue"),I=require("@embedpdf/plugin-rotate/vue"),b=require("@embedpdf/plugin-selection/vue"),S=require("@embedpdf/plugin-annotation/vue"),C=require("@embedpdf/plugin-redaction/vue"),w=require("@embedpdf/plugin-render/vue"),y=require("@embedpdf/engines/vue"),M={position:"relative",height:"100%",width:"100%"},x={userSelect:"none",WebkitUserSelect:"none"};function L(){var e;"undefined"!=typeof window&&(null==(e=window.getSelection())||e.removeAllRanges())}const $="#f1f5f9",k={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:4},strikeout:{offsetY:0}},D={highlight:r.PdfAnnotationSubtype.HIGHLIGHT,underline:r.PdfAnnotationSubtype.UNDERLINE,squiggly:r.PdfAnnotationSubtype.SQUIGGLY,strikeout:r.PdfAnnotationSubtype.STRIKEOUT};function U(e,t){return 0===t?e:e.map(e=>({origin:{x:e.origin.x,y:e.origin.y+t},size:{...e.size}}))}function E(e){let t=1/0,s=1/0,r=-1/0,n=-1/0;for(const a of e)t=Math.min(t,a.origin.x),s=Math.min(s,a.origin.y),r=Math.max(r,a.origin.x+a.size.width),n=Math.max(n,a.origin.y+a.size.height);return{origin:{x:t,y:s},size:{width:r-t,height:n-s}}}function V(e,t,n,a,i){const o=n.forDocument(e),l=a.forDocument(e);if(!o||!l)return!1;const h="highlight"===t?"highlight":"underline"===t?"underline":"squiggly"===t?"squiggly":"strikeout",d=n.getTool(h);if(!d)return!1;const c=d.defaults,u={...k[g=t],...null==(m=i)?void 0:m[g]},p=l.getFormattedSelection();var g,m;if(0===p.length)return!1;o.setLocked({type:s.LockModeType.Exclude,categories:["markup","shape"]});for(const s of p){const e=r.uuidV4(),n=u.color??c.color??c.strokeColor,a=u.opacity??c.opacity,i=u.thickness??c.strokeWidth,l=u.offsetY??0,h="underline"===t||"squiggly"===t||"strikeout"===t?U(s.segmentRects,l):s.segmentRects,d="underline"===t||"squiggly"===t||"strikeout"===t?E(h):s.rect;o.createAnnotation(s.pageIndex,{id:e,created:new Date,flags:["print"],type:D[t],..."highlight"===t?{blendMode:r.PdfBlendMode.Multiply}:{},strokeColor:n,opacity:a,...null!=i?{strokeWidth:i}:{},pageIndex:s.pageIndex,rect:d,segmentRects:h})}return l.clear(),!0}const N=new Set([r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT]);function T(e,t){const s=e;return!1===e?{...t,enabled:!1}:!0===e||void 0===e?{...t,enabled:t.enabled??!0}:{...t,...s,enabled:!1!==(null==s?void 0:s.enabled)}}function F(e){var t;const s=T(null==e?void 0:e.markup,{enabled:!0}),r=T(null==e?void 0:e.bookmarks,{enabled:!0}),n=T(null==e?void 0:e.notes,{enabled:!0}),a=T(null==e?void 0:e.zoom,{enabled:!0,min:.5,max:3,initial:1}),i=T(void 0===(null==e?void 0:e.selectionToolbar)?!1!==s.enabled||!1!==n.enabled:e.selectionToolbar,{enabled:!0});return{markup:s,bookmarks:r,notes:n,zoom:a,scrollViewport:{background:(null==(t=null==e?void 0:e.scrollViewport)?void 0:t.background)??$},selectionToolbar:i}}function A(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function O(e,t){return`${e}#s${t}`}function R(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return A(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=A(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:O(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}let B=class{constructor(e){this.cb=e}resolvePassword(e,t){return this.cb(e,t)}};const G="chapter-manager",z={id:G,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,maxConcurrentSegmentLoads:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}};function _(e){const[t,s]=e.localPageRange;return s-t+1}function q(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function W(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return q(t)?t.segmentPageThreshold:null}function H(e,t){return`${e}#s${t}`}function K(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function j(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function X(e){const t=W(e);if(!t)return null;const s=_(e),r=j(s,t),n=q(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:H(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Y(e,t){const s=X(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Z(e,t){const s=X(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function J(e){var t;const s=W(e);if(!s)return[];const r=[],{chapterId:n}=e,a=_(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!q(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=j(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Q={kind:"first-wins"};function ee(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let te=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const se=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Q,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Q,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=K(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=K(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=K(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Y(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?X(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...J(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Q){const s=function(e,t=Q){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,ee(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new te(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?X(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Z(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(q(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=X(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=X(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Z(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Z(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Y(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=X(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(q(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=W(t);if(a){const r=j(_(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(q(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=K(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?X(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};se.id="chapter-manager";let re=se;const ne={manifest:z,create:e=>new re(G,e),reducer:e=>e,initialState:{}},ae="chapter-scroll",ie={id:ae,name:"Chapter Scroll Plugin",version:"0.1.0",provides:["chapter-scroll"],requires:["chapter-manager"],optional:[],defaultConfig:{placeholderPageHeight:1200,placeholderPageWidth:900,bufferSize:2,pageGap:20}};function oe(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function le(e,t){return`${e}#s${t}`}function he(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function de(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return oe(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=oe(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:le(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function ce(e,t){const s=de(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function ue(e){const[t,s]=e.localPageRange;return s-t+1}function pe(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ge(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return pe(t)?t.segmentPageThreshold:null}function me(e,t){return`${e}#s${t}`}function fe(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function ve(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Pe(e){const t=ge(e);if(!t)return null;const s=ue(e),r=ve(s,t),n=pe(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:me(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Ie(e,t){const s=Pe(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function be(e,t){const s=Pe(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Se(e){var t;const s=ge(e);if(!s)return[];const r=[],{chapterId:n}=e,a=ue(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!pe(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=ve(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Ce={kind:"first-wins"};function we(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let ye=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const Me=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Ce,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Ce,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=fe(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=fe(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=fe(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Ie(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Pe(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Se(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Ce){const s=function(e,t=Ce){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,we(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new ye(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Pe(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=be(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(pe(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Pe(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Pe(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=be(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=be(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Ie(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Pe(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(pe(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=ge(t);if(a){const r=ve(ue(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(pe(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=fe(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Pe(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Me.id="chapter-manager";let xe=Me;function Le(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const $e=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,Le),this.visibleChange$=n.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.lastLoadIndicesKey="",this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(xe.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.lastLoadIndicesKey="",this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=ce(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===e.length)return;const t=this.chapterManager.provides(),s=t.visibleRangeNeedsSegmentLoad(e),r=e.join(",");(r!==this.lastLoadIndicesKey||s)&&(this.lastLoadIndicesKey=r,t.setVisibleGlobalPages(e))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=he(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=he(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}if(s){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),r=s.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!r||0===n.length)return;const a=de(r),i=this.documentManager.provides(),o=[],l=(e,t,s,r)=>{var n;const a=i.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let i=0;i<r;i++){const e=a.pages[s+i];(null==e?void 0:e.size)&&o.push({localPageIndex:t+i,width:e.size.width*l,height:e.size.height*l})}return o.length>0};if(a)for(const h of a.segments){if(!s.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=he(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),r=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,r=this.findFirstVisibleIndex(t);let n=r;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=s)break;n++}const a=[];let i=r,o=-1;for(let l=r;l<n;l++){a.push(l);const e=this.offsets[l],r=e+this.getPageSize(l).height,n=Math.max(0,Math.min(r,s)-Math.max(e,t));n>o&&(o=n,i=l)}this.currentVisible=a,this.currentGlobalPageIndex=i,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:i}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);if(s<0)return;const r=this.chapterManager.provides(),n=r.getChapter(e),a=this.virtualPageMap.atIndex(s);if(n&&a){const t=ce(n,a.localPageIndex);r.ensureSegmentLoaded(e,t)}else r.ensureChapterLoaded(e);this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};$e.id="chapter-scroll";let ke=$e;const De={manifest:ie,create:e=>new ke(ae,e),reducer:e=>e,initialState:{}},Ue="note",Ee={id:Ue,name:"Note Plugin",version:"0.1.0",provides:["note"],requires:["selection","chapter-scroll","chapter-manager"],optional:[],defaultConfig:{callbacks:{onCreateNote:async()=>null,onActivateNote:()=>{}},markerSize:18}};function Ve(e){const[t,s]=e.localPageRange;return s-t+1}function Ne(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Te(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ne(t)?t.segmentPageThreshold:null}function Fe(e,t){return`${e}#s${t}`}function Ae(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Oe(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Re(e){const t=Te(e);if(!t)return null;const s=Ve(e),r=Oe(s,t),n=Ne(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Fe(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Be(e,t){const s=Re(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Ge(e,t){const s=Re(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function ze(e){var t;const s=Te(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Ve(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Ne(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Oe(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const _e={kind:"first-wins"};function qe(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let We=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const He=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=_e,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??_e,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Ae(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Ae(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Ae(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Be(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Re(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...ze(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=_e){const s=function(e,t=_e){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,qe(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new We(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Re(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Ge(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Ne(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Re(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Re(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Ge(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Ge(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Be(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Re(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Ne(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Te(t);if(a){const r=Oe(Ve(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Ne(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Ae(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Re(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};He.id="chapter-manager";let Ke=He;function je(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Xe(e,t){return`${e}#s${t}`}function Ye(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Ze(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return je(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=je(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:Xe(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Je(e,t){const s=Ze(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Qe(e){const[t,s]=e.localPageRange;return s-t+1}function et(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function tt(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return et(t)?t.segmentPageThreshold:null}function st(e,t){return`${e}#s${t}`}function rt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function nt(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function at(e){const t=tt(e);if(!t)return null;const s=Qe(e),r=nt(s,t),n=et(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:st(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function it(e,t){const s=at(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function ot(e,t){const s=at(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function lt(e){var t;const s=tt(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Qe(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!et(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=nt(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const ht={kind:"first-wins"};function dt(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let ct=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const ut=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ht,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ht,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=rt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=rt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=rt(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?it(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?at(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...lt(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=ht){const s=function(e,t=ht){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,dt(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new ct(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?at(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=ot(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(et(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=at(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=at(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=ot(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=ot(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=it(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=at(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(et(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=tt(t);if(a){const r=nt(Qe(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(et(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=rt(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?at(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};ut.id="chapter-manager";let pt=ut;function gt(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const mt=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,gt),this.visibleChange$=n.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.lastLoadIndicesKey="",this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(pt.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.lastLoadIndicesKey="",this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=Je(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===e.length)return;const t=this.chapterManager.provides(),s=t.visibleRangeNeedsSegmentLoad(e),r=e.join(",");(r!==this.lastLoadIndicesKey||s)&&(this.lastLoadIndicesKey=r,t.setVisibleGlobalPages(e))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Ye(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Ye(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}if(s){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),r=s.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!r||0===n.length)return;const a=Ze(r),i=this.documentManager.provides(),o=[],l=(e,t,s,r)=>{var n;const a=i.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let i=0;i<r;i++){const e=a.pages[s+i];(null==e?void 0:e.size)&&o.push({localPageIndex:t+i,width:e.size.width*l,height:e.size.height*l})}return o.length>0};if(a)for(const h of a.segments){if(!s.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=Ye(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),r=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,r=this.findFirstVisibleIndex(t);let n=r;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=s)break;n++}const a=[];let i=r,o=-1;for(let l=r;l<n;l++){a.push(l);const e=this.offsets[l],r=e+this.getPageSize(l).height,n=Math.max(0,Math.min(r,s)-Math.max(e,t));n>o&&(o=n,i=l)}this.currentVisible=a,this.currentGlobalPageIndex=i,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:i}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);if(s<0)return;const r=this.chapterManager.provides(),n=r.getChapter(e),a=this.virtualPageMap.atIndex(s);if(n&&a){const t=Je(n,a.localPageIndex);r.ensureSegmentLoaded(e,t)}else r.ensureChapterLoaded(e);this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};mt.id="chapter-scroll";let ft=mt;const vt=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=n.createBehaviorEmitter([]),this.noteActivated$=n.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(ft.id),this.chapterManager=this.registry.getPlugin(Ke.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,t.callbacks.loadNotes)try{const e=await t.callbacks.loadNotes();for(const t of e)this.notes.set(t.noteId,t);this.notesChange$.emit(this.listAll())}catch(s){this.logger.error(e.id,"LoadNotes","Failed to load notes",s)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(s=>s.chapterId===e&&s.localPageIndex===t),listAllNotes:()=>this.listAll(),getNote:e=>this.notes.get(e)??null,deleteNote:e=>this.deleteNote(e),updateNoteContent:(e,t)=>this.updateNoteContent(e,t),scrollToNote:e=>this.scrollToNote(e),listNotesForChapter:e=>this.listNotesForChapter(e),replaceNotesForChapter:(e,t)=>this.replaceNotesForChapter(e,t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(e){this.notes.set(e.noteId,e),this.notesChange$.emit(this.listAll())}requestEdit(e){const t=this.notes.get(e);t&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(e,t):this.activateNote(e))}activateNote(e){var t,s;const r=this.notes.get(e);r&&(null==(s=(t=this.config.callbacks).onActivateNote)||s.call(t,e,r),this.noteActivated$.emit({noteId:e,anchor:r}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[s,r]of this.notes.entries())r.chapterId===e&&this.notes.delete(s);for(const s of t)s.chapterId===e&&this.notes.set(s.noteId,s);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:It(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:s,onCreateNote:r}=this.config.callbacks;return s?(s({draft:t,complete:async e=>{const s={...t,noteId:e};this.registerNote(s)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const s=this.buildDraft(t),r=this.config.callbacks.onCreateNote;if(!r)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await r(s)}catch(i){return this.logger.error(e.id,"OnCreateNote","Callback failed",i),null}if(!n)return null;const a={...s,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var s,r;if(this.notes.has(t)){try{await(null==(r=(s=this.config.callbacks).onDeleteNote)?void 0:r.call(s,t))}catch(n){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",n)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,s){var r,n;const a=this.notes.get(t);if(!a)return;const i={...a,content:s};try{await(null==(n=(r=this.config.callbacks).onUpdateNote)?void 0:n.call(r,i))}catch(o){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",o)}this.notes.set(t,i),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const s=this.notes.get(e);if(!s)return;const r=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(s.chapterId);const a=n.resolvePageDocument(s.chapterId,s.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(r.scrollToGlobalPageIndex(s.globalPageIndex),await this.waitForPageInLayout(s.globalPageIndex),r.scrollToGlobalPdfPoint(s.globalPageIndex,s.endAnchor.y,{marginTop:80})):r.scrollToGlobalPageIndex(s.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const r=setTimeout(()=>{n(),s(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(r),n(),s(a))})})}};vt.id="note";let Pt=vt;function It(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}const bt={manifest:Ee,create:e=>new Pt(Ue,e),reducer:e=>e,initialState:{}},St="paragraph-bookmark",Ct={id:St,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}};function wt(e){const[t,s]=e.localPageRange;return s-t+1}function yt(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Mt(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return yt(t)?t.segmentPageThreshold:null}function xt(e,t){return`${e}#s${t}`}function Lt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function $t(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function kt(e){const t=Mt(e);if(!t)return null;const s=wt(e),r=$t(s,t),n=yt(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:xt(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Dt(e,t){const s=kt(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Ut(e,t){const s=kt(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Et(e){var t;const s=Mt(e);if(!s)return[];const r=[],{chapterId:n}=e,a=wt(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!yt(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=$t(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Vt={kind:"first-wins"};function Nt(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let Tt=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const Ft=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Vt,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Vt,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Lt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Lt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Lt(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Dt(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?kt(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Et(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Vt){const s=function(e,t=Vt){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Nt(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Tt(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?kt(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Ut(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(yt(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=kt(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=kt(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Ut(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Ut(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Dt(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=kt(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(yt(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Mt(t);if(a){const r=$t(wt(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(yt(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Lt(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?kt(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Ft.id="chapter-manager";let At=Ft;function Ot(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Rt(e,t){return`${e}#s${t}`}function Bt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Gt(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ot(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=Ot(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:Rt(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function zt(e,t){const s=Gt(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function _t(e){const[t,s]=e.localPageRange;return s-t+1}function qt(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Wt(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return qt(t)?t.segmentPageThreshold:null}function Ht(e,t){return`${e}#s${t}`}function Kt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function jt(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Xt(e){const t=Wt(e);if(!t)return null;const s=_t(e),r=jt(s,t),n=qt(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Ht(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Yt(e,t){const s=Xt(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Zt(e,t){const s=Xt(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Jt(e){var t;const s=Wt(e);if(!s)return[];const r=[],{chapterId:n}=e,a=_t(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!qt(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=jt(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Qt={kind:"first-wins"};function es(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let ts=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const ss=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Qt,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Qt,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Kt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Kt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Kt(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Yt(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Xt(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Jt(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Qt){const s=function(e,t=Qt){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,es(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new ts(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Xt(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Zt(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(qt(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Xt(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Xt(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Zt(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Zt(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Yt(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Xt(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(qt(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Wt(t);if(a){const r=jt(_t(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(qt(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Kt(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Xt(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};ss.id="chapter-manager";let rs=ss;function ns(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const as=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,ns),this.visibleChange$=n.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.lastLoadIndicesKey="",this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(rs.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.lastLoadIndicesKey="",this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=zt(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===e.length)return;const t=this.chapterManager.provides(),s=t.visibleRangeNeedsSegmentLoad(e),r=e.join(",");(r!==this.lastLoadIndicesKey||s)&&(this.lastLoadIndicesKey=r,t.setVisibleGlobalPages(e))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Bt(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Bt(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}if(s){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),r=s.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!r||0===n.length)return;const a=Gt(r),i=this.documentManager.provides(),o=[],l=(e,t,s,r)=>{var n;const a=i.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let i=0;i<r;i++){const e=a.pages[s+i];(null==e?void 0:e.size)&&o.push({localPageIndex:t+i,width:e.size.width*l,height:e.size.height*l})}return o.length>0};if(a)for(const h of a.segments){if(!s.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=Bt(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),r=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,r=this.findFirstVisibleIndex(t);let n=r;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=s)break;n++}const a=[];let i=r,o=-1;for(let l=r;l<n;l++){a.push(l);const e=this.offsets[l],r=e+this.getPageSize(l).height,n=Math.max(0,Math.min(r,s)-Math.max(e,t));n>o&&(o=n,i=l)}this.currentVisible=a,this.currentGlobalPageIndex=i,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:i}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);if(s<0)return;const r=this.chapterManager.provides(),n=r.getChapter(e),a=this.virtualPageMap.atIndex(s);if(n&&a){const t=zt(n,a.localPageIndex);r.ensureSegmentLoaded(e,t)}else r.ensureChapterLoaded(e);this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};as.id="chapter-scroll";let is=as;function os(e){if(0===e.length)throw new Error("unionRects: empty rects");let t=1/0,s=1/0,r=-1/0,n=-1/0;for(const a of e)t=Math.min(t,a.origin.x),s=Math.min(s,a.origin.y),r=Math.max(r,a.origin.x+a.size.width),n=Math.max(n,a.origin.y+a.size.height);return{origin:{x:t,y:s},size:{width:r-t,height:n-s}}}function ls(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function hs(e,t){const s=e.origin.y,r=e.origin.y+e.size.height,n=t.origin.y,a=t.origin.y+t.size.height,i=Math.max(r,a)-Math.min(s,n);return i<=0?0:Math.max(0,Math.min(r,a)-Math.max(s,n))/i}function ds(e,t){var s,r;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const n=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],a=(null==(r=t.rectsPdfCoord)?void 0:r.length)?t.rectsPdfCoord:[t.rectPdfCoord],i=e.markerAnchor??ls(n),o=t.markerAnchor??ls(a);if(Math.hypot(i.x-o.x,i.y-o.y)<=6)return!0;for(const l of n)for(const e of a){if(hs(l,e)<.5)continue;const t=Math.max(l.origin.x,e.origin.x);if(Math.min(l.origin.x+l.size.width,e.origin.x+e.size.width)-t>.25*Math.min(l.size.width,e.size.width))return!0}return!1}function cs(e,t,s,r){const n=s.length>0?s:[];if(0===n.length)throw new Error("buildParagraphBookmarkAnchor: no rects");return{chapterId:e,localPageIndex:t,globalPageIndex:null==r?void 0:r.globalPageIndex,globalPageNumber:null==r?void 0:r.globalPageNumber,rectPdfCoord:os(n),rectsPdfCoord:n,markerAnchor:ls(n)}}const us=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.change$=n.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(is.id),this.chapterManager=this.registry.getPlugin(At.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){var s;if(this.config=t,null==(s=t.callbacks)?void 0:s.load)try{const e=await t.callbacks.load();for(const t of e)this.entries.set(t.id,t);this.change$.emit(this.list())}catch(r){this.logger.error(e.id,"Load","Failed to load paragraph bookmarks",r)}}buildCapability(){return{addBookmark:e=>this.addBookmark(e),removeBookmark:e=>this.removeBookmark(e),updateBookmark:(e,t)=>this.updateBookmark(e,t),listBookmarks:()=>this.list(),getBookmark:e=>this.entries.get(e)??null,scrollToBookmark:e=>this.scrollToBookmark(e),requestRemoveBookmark:e=>this.requestRemoveBookmark(e),listBookmarksForChapter:e=>this.listBookmarksForChapter(e),replaceBookmarksForChapter:(e,t)=>this.replaceBookmarksForChapter(e,t),onBookmarksChange:this.change$.on}}addBookmark(e){for(const r of this.entries.values())if(ds(r.anchor,e.anchor))return r;const t=e.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s={id:t,label:e.label,anchor:e.anchor,metadata:e.metadata,createdAt:Date.now()};return this.entries.set(t,s),this.notifyAndPersist(),s}removeBookmark(e){var t,s,r;this.entries.delete(e)&&(this.notifyAndPersist(),null==(r=null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.onRemoveSuccess)||r.call(s,e))}async requestRemoveBookmark(t){var s,r;const n=this.entries.get(t);if(!n)return!1;const a=null==(r=null==(s=this.config)?void 0:s.callbacks)?void 0:r.onRequestRemove;if(a)try{if(!(await a(n)))return!1}catch(i){return this.logger.error(e.id,"RequestRemove","callback failed",i),!1}return this.removeBookmark(t),!0}updateBookmark(e,t){const s=this.entries.get(e);s&&(this.entries.set(e,{...s,...t}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((e,t)=>e.createdAt-t.createdAt)}listBookmarksForChapter(e){return this.list().filter(t=>t.anchor.chapterId===e)}replaceBookmarksForChapter(e,t){for(const[s,r]of this.entries.entries())r.anchor.chapterId===e&&this.entries.delete(s);for(const s of t)s.anchor.chapterId===e&&this.entries.set(s.id,s);this.notifyAndPersist()}notifyAndPersist(){var t,s;const r=this.list();this.change$.emit(r),(null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.persist)&&Promise.resolve(this.config.callbacks.persist(r)).catch(t=>this.logger.error(e.id,"Persist","persist callback rejected",t))}async scrollToBookmark(e){const t=this.entries.get(e);if(!t)return;const s=this.chapterScroll.provides(),r=this.chapterManager.provides();await r.ensureAllSegmentsLoaded(t.anchor.chapterId);let n=t.anchor.globalPageIndex;if(void 0===n){const e=this.chapterManager.provides().getVirtualPageMap().toGlobal(t.anchor.chapterId,t.anchor.localPageIndex);if(!e)return;n=e.globalPageIndex}const a=function(e){if(e.markerAnchor)return e.markerAnchor.y;const t=e.rectPdfCoord;return t.origin.y+t.size.height}(t.anchor);await async function(e,t,s){e.scrollToGlobalPageIndex(t),await function(e,t,s=2500){const r=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return r?Promise.resolve(r):new Promise(r=>{const n=setTimeout(()=>{a(),r(null)},s),a=e.onLayoutChange(e=>{const s=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);s&&(clearTimeout(n),a(),r(s))})})}(e,t),e.scrollToGlobalPdfPoint(t,s,{marginTop:80})}(s,n,a)}};us.id="paragraph-bookmark";let ps=us;const gs={manifest:Ct,create:e=>new ps(St,e),reducer:e=>e,initialState:{}},ms={"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 fs{constructor(){this.specs=[]}register(e){if(this.specs.some(t=>t.id===e.id))throw new Error(`OperationRegistry: duplicate operation id "${e.id}"`);this.specs.push(e)}registerAll(e){for(const t of e)t&&this.register(t)}list(){return this.specs}buildToolbars(){const e=structuredClone(ms);for(const t of this.specs){const s=e[t.toolbarSlot];if(!s)continue;const r={type:"command-button",id:t.id,commandId:t.commandId,variant:"icon",...t.icon?{icon:t.icon}:{},...t.i18nKey?{labelKey:t.i18nKey}:{},...t.label?{label:t.label}:{},categories:t.categories??[]};s.items=vs(s.items,r,t.position)}return e}}function vs(e,t,s){return(null==s?void 0:s.after)||(null==s?void 0:s.before)?function(e,t,s){const r=e=>{const n=[];for(const a of e)"group"!==a.type?s.before&&a.id===s.before?n.push(t,a):(n.push(a),s.after&&a.id===s.after&&n.push(t)):n.push({...a,items:r(a.items)});return n};return r(e)}(e,t,s):(r=t,e.map(e=>"group"===e.type?{...e,items:[...e.items,r]}:e));var r}const Ps={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function Is(e){var t,r,P,I,b,S;const C=e.toolbar??{},w=C.enabledModes??["view","annotate","shapes","insert","form","redact"],y=w.length>0,{schema:M,operationRegistry:x}=function(e={}){var t,s,r,n,a,i;const o=new Set(e.enabledModes??["view","annotate","shapes","insert","form","redact"]),l=new fs;(null==(t=e.customOperations)?void 0:t.length)&&l.registerAll(e.customOperations);const h=l.buildToolbars(),d={};for(const u of o){if("view"===u)continue;const e=Ps[u];h[e]&&(d[e]=h[e])}const c=function(e){if(0===e.size)return null;const t=(e,t,s)=>({type:"command-button",id:`${e}-mode`,commandId:s,variant:"text",label:t,categories:["mode",e]});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:[...e.has("view")?[t("view","View","mode:view")]:[],...e.has("annotate")?[t("annotate","Annotate","mode:annotate")]:[],...e.has("shapes")?[t("shapes","Shapes","mode:shapes")]:[],...e.has("insert")?[t("insert","Insert","mode:insert")]:[],...e.has("form")?[t("form","Form","mode:form")]:[],...e.has("redact")?[t("redact","Redact","mode:redact")]:[]]},{type:"spacer",id:"main-spacer-right",flex:!0}]}}(o);return c&&(d["chapter-editor-main-toolbar"]=c),(null==(s=e.extend)?void 0:s.toolbars)&&Object.assign(d,e.extend.toolbars),{schema:{id:"chapter-pdf-editor-ui",version:"1.0.0",toolbars:d,menus:(null==(r=e.extend)?void 0:r.menus)??{},sidebars:(null==(n=e.extend)?void 0:n.sidebars)??{},modals:(null==(a=e.extend)?void 0:a.modals)??{},selectionMenus:(null==(i=e.extend)?void 0:i.selectionMenus)??{}},operationRegistry:l}}({...C,enabledModes:w}),L={...y?{"mode:view":{id:"mode:view",label:"View",categories:["mode","mode-view"],action:({registry:e,documentId:t})=>{var r,n,a,i;const o=null==(r=e.getPlugin("ui"))?void 0:r.provides(),l=null==(n=e.getPlugin("interaction-manager"))?void 0:n.provides();o&&l&&(null==(a=l.forDocument(t))||a.activateDefaultMode(),o.forDocument(t).closeToolbarSlot("top","secondary"),null==(i=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||i.provides().forDocument(t).setLocked(e.getPluginConfig(s.ANNOTATION_PLUGIN_ID).locked??{type:s.LockModeType.None}))},active:({state:e,documentId:t})=>!v.isToolbarOpen(e.plugins,t,"top","secondary")},"mode:annotate":{id:"mode:annotate",label:"Annotate",categories:["mode","mode-annotate","annotation"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","annotation-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","annotation-toolbar")},"mode:shapes":{id:"mode:shapes",label:"Shapes",categories:["mode","mode-shapes","annotation"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","shapes-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","shapes-toolbar")},"mode:insert":{id:"mode:insert",label:"Insert",categories:["mode","mode-insert","insert"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","insert-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","insert-toolbar")},"mode:form":{id:"mode:form",label:"Form",categories:["mode","mode-form","form"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","form-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.None}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","form-toolbar")},"mode:redact":{id:"mode:redact",label:"Redact",categories:["mode","mode-redact","redaction"],action:({registry:e,documentId:t})=>{var r,n;const a=null==(r=e.getPlugin("ui"))?void 0:r.provides();a&&(a.setActiveToolbar("top","secondary","redaction-toolbar",t),null==(n=e.getPlugin(s.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:s.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","redaction-toolbar")}}:{},...y?bs(x.list()):{},...e.commands??{}},$=[n.createPluginRegistration(a.DocumentManagerPluginPackage,{initialDocuments:[]}),n.createPluginRegistration(ne,{manifest:e.manifest,overlapStrategy:e.overlapStrategy,passwordProvider:e.passwordProvider,chapterPdfLoader:e.chapterPdfLoader,prefetchChapters:e.prefetchChapters,maxConcurrentSegmentLoads:e.maxConcurrentSegmentLoads,unloadTimeoutMs:e.unloadTimeoutMs}),n.createPluginRegistration(De,{placeholderPageHeight:e.placeholderPageHeight,placeholderPageWidth:e.placeholderPageWidth}),n.createPluginRegistration(i.InteractionManagerPluginPackage),n.createPluginRegistration(o.RenderPluginPackage),n.createPluginRegistration(l.RotatePluginPackage),n.createPluginRegistration(h.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),n.createPluginRegistration(d.HistoryPluginPackage),n.createPluginRegistration(s.AnnotationPluginPackage),n.createPluginRegistration(c.RedactionPluginPackage),n.createPluginRegistration(u.FormPluginPackage),n.createPluginRegistration(p.StampPluginPackage,!1===e.loadDefaultStampLibrary?{manifests:[]}:void 0),n.createPluginRegistration(g.SignaturePluginPackage),...Object.keys(L).length>0?[n.createPluginRegistration(m.CommandsPluginPackage,{commands:L})]:[],...y?[n.createPluginRegistration(f.I18nPluginPackage),n.createPluginRegistration(v.UIPluginPackage,{schema:M})]:[]];return e.notes&&$.push(n.createPluginRegistration(bt,{callbacks:e.notes.callbacks,ui:null==(r=null==(t=e.features)?void 0:t.notes)?void 0:r.marker})),e.bookmarks&&$.push(n.createPluginRegistration(gs,{callbacks:e.bookmarks.callbacks,ui:null==(I=null==(P=e.features)?void 0:P.bookmarks)?void 0:I.marker,hover:null==(S=null==(b=e.features)?void 0:b.bookmarks)?void 0:S.hover})),{plugins:$,uiSchema:M,operationRegistry:x}}function bs(e){const t={};for(const s of e)s.handler&&(t[s.commandId]={id:s.commandId,labelKey:s.i18nKey,label:s.label,icon:s.icon,categories:s.categories,action:({documentId:e})=>{var t;null==(t=s.handler)||t.call(s,{documentId:e,chapterId:e})}});return t}const Ss=F();function Cs(e){return Is({...e,toolbar:e.toolbar??{enabledModes:[]},features:F(e.features)})}const ws={overlapStrategy:{kind:"first-wins"},passwordProvider:new B(async()=>null),prefetchChapters:1,maxConcurrentSegmentLoads:1,loadDefaultStampLibrary:!1,unloadTimeoutMs:12e4,toolbar:{enabledModes:[]}};function ys(e){return"callbacks"in e.notes?{manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,notes:e.notes.callbacks,bookmarks:e.bookmarks.callbacks}:e}function Ms(e){return{...ws,manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,overlapStrategy:e.overlapStrategy??ws.overlapStrategy,prefetchChapters:e.prefetchChapters??ws.prefetchChapters,maxConcurrentSegmentLoads:e.maxConcurrentSegmentLoads??ws.maxConcurrentSegmentLoads,unloadTimeoutMs:e.unloadTimeoutMs??ws.unloadTimeoutMs,notes:{callbacks:e.notes},bookmarks:{callbacks:e.bookmarks},features:F(e.features)}}function xs(e){const t=Ms(ys(e)),{plugins:s}=Cs(t);return{plugins:s,features:t.features,editorOptions:t}}function Ls(e,t=.5,s=3){return Math.min(s,Math.max(t,e))}function $s(e,t){var s;if(t<=0)return 1;let r=0;for(const n of e.pages){const e=(null==(s=null==n?void 0:n.size)?void 0:s.width)??0;e>r&&(r=e)}return r<=0?1:t/r}function ks(e,t){return e<=0?t??0:null==t||t<=0?e:Math.min(t,e)}function Ds(e,t,s,r){const n=ks(t,s);if(n<=0)return r;const a=$s(e,n);return Math.min(r,a)}function Us(e,t,s){const r=R(t);if(r){for(const t of r.segments){const r=e.getDocument(t.documentId);r&&s(r,t.documentId)}return}const n=e.getDocument(t.chapterId);n&&s(n,t.chapterId)}function Es(e){return e instanceof HTMLElement?e.clientWidth:0}function Vs(e,t,s){return Math.min(s,Math.max(t,e))}const Ns={chapters:[]};function Ts(s){const r=e.ref(null),{provides:i}=t.useCapability(re.id),o=e.computed(()=>{var e;return(null==(e=i.value)?void 0:e.getManifest())??Ns}),l=e.computed(()=>{var e;return null==(e=s.value)?void 0:e.zoom}),{scale:h,setScale:d,zoomEnabled:c,minZoom:u,maxZoom:p}=function(s,r,i){const o=e.isRef(s)?s:e.computed(()=>s),{registry:l}=t.useRegistry(),{provides:h}=t.useCapability(a.DocumentManagerPlugin.id),{provides:d}=t.useCapability(re.id),c=e.ref(v()),u=e.ref(c.value),p=e.ref(0),g=e.ref(!1),m=()=>{var e;return null==(e=r.value)?void 0:e.pageWidth},f=()=>{return null!=(e=m())&&e>0;var e},v=()=>{var e;return(null==(e=r.value)?void 0:e.initial)??1},P=e.computed(()=>{var e;return function(e,t,s,r,n){if(!e||s<=0)return n;let a=n;for(const i of t.chapters)Us(e,i,e=>{a=Math.min(a,Ds(e,s,r,n))});return a}(h.value,o.value,p.value,m(),(null==(e=r.value)?void 0:e.max)??3)}),I=e.computed(()=>{var e;return Math.min((null==(e=r.value)?void 0:e.min)??.5,P.value)});let b;function S(e){const t=P.value,s=I.value,r=Ls(e,s,t);u.value=r,c.value=r,function(e,t,s,r=.5,a=3){const i=null==e?void 0:e.getStore();if(!i)return;const o=Ls(s,r,a);i.dispatchToCore(n.setDefaultScale(o));for(const l of t.chapters){const e=R(l);if(e)for(const t of e.segments)i.getState().core.documents[t.documentId]&&i.dispatchToCore(n.setScale(o,t.documentId));else i.getState().core.documents[l.chapterId]&&i.dispatchToCore(n.setScale(o,l.chapterId))}}(l.value,o.value,r,s,t)}function C(e){if(!h.value||!d.value)return;const t=d.value.resolvePageDocument(e,0),s=h.value.getDocument(t.documentId);if(!s)return;const r=ks(p.value,m());r<=0||S($s(s,r))}function w(e){if(!g.value)return f()?C(e):S(v()),void(g.value=!0);S(u.value)}return e.watch(()=>null==i?void 0:i.value,e=>{null==b||b(),b=e?function(e,t){if(!e||"undefined"==typeof ResizeObserver)return()=>{};let s=null;const r=new ResizeObserver(()=>{t(Es(s))}),n=()=>{const n=e.querySelector("[data-chapter-scroll-viewport]");n!==s?(s&&r.unobserve(s),s=n,s?(r.observe(s),t(Es(s))):t(0)):t(Es(s))};n();const a=new MutationObserver(n);a.observe(e,{childList:!0,subtree:!0});const i=requestAnimationFrame(n);return()=>{cancelAnimationFrame(i),a.disconnect(),s&&r.unobserve(s),r.disconnect()}}(e,e=>{p.value=e}):void 0},{immediate:!0}),e.onBeforeUnmount(()=>null==b?void 0:b()),e.watch([l,()=>v(),()=>f()],()=>{l.value&&(f()||S(v()))},{immediate:!0}),e.watch(P,e=>{u.value>e&&S(e)}),e.watch([d,o,()=>f(),()=>v()],()=>{const e=d.value;if(e){for(const t of o.value.chapters)"loaded"===e.getChapterStatus(t.chapterId)&&w(t.chapterId);return e.onChapterStatusChange(e=>{"loaded"===e.status&&w(e.chapterId)})}},{immediate:!0}),e.watch(h,(e,t,s)=>{e&&s(e.onDocumentOpened(()=>{g.value&&S(u.value)}))}),e.watch([p,()=>f(),d,o],()=>{if(f()&&!(p.value<=0)&&d.value&&!g.value)for(const e of o.value.chapters)if("loaded"===d.value.getChapterStatus(e.chapterId)){C(e.chapterId),g.value=!0;break}}),{scale:c,setScale:S,zoomEnabled:()=>{var e;return!1!==(null==(e=r.value)?void 0:e.enabled)},minZoom:I,maxZoom:P}}(o,l,r);return function(t,s){let r=null;e.watch([t,s],()=>{null==r||r();const e=s.value;r=function(e,t){if(!e||!1===t.enabled)return()=>{};let s=null,r=null,n=0;const a=()=>{const r=e.querySelector("[data-chapter-scroll-viewport]");return!!r&&(null==s||s(),s=function({container:e,getScale:t,setScale:s,minZoom:r=.5,maxZoom:n=3}){let a=0,i=1,o=null,l=1,h=1;const d=e=>{(e.ctrlKey||e.metaKey)&&(e.preventDefault(),null===o?(h=t(),l=1):clearTimeout(o),l*=1-.01*e.deltaY,l=Vs(l,.1,10),s(Vs(h*l,r,n)),o=setTimeout(()=>{o=null},120))},c=new Map,u=e=>{if(c.set(e.pointerId,{x:e.clientX,y:e.clientY}),2===c.size){const[e,s]=[...c.values()];a=Math.hypot(s.x-e.x,s.y-e.y),i=t()}},p=e=>{if(c.has(e.pointerId)&&(c.set(e.pointerId,{x:e.clientX,y:e.clientY}),2===c.size&&a>0)){e.preventDefault();const[t,o]=[...c.values()],l=Math.hypot(o.x-t.x,o.y-t.y);s(Vs(i*(l/a),r,n))}},g=e=>{c.delete(e.pointerId),c.size<2&&(a=0)};return e.addEventListener("wheel",d,{passive:!1}),e.addEventListener("pointerdown",u),e.addEventListener("pointermove",p,{passive:!1}),e.addEventListener("pointerup",g),e.addEventListener("pointercancel",g),()=>{e.removeEventListener("wheel",d),e.removeEventListener("pointerdown",u),e.removeEventListener("pointermove",p),e.removeEventListener("pointerup",g),e.removeEventListener("pointercancel",g),o&&clearTimeout(o)}}({container:r,getScale:t.getScale,setScale:t.setScale,minZoom:t.minZoom,maxZoom:t.maxZoom}),!0)};return a()||(r=new MutationObserver(()=>{a()&&(null==r||r.disconnect(),r=null)}),r.observe(e,{childList:!0,subtree:!0}),n=requestAnimationFrame(()=>a())),()=>{n&&cancelAnimationFrame(n),null==r||r.disconnect(),null==s||s()}}(t.value??null,{enabled:e.enabled,getScale:e.getScale,setScale:e.setScale,minZoom:e.minZoom,maxZoom:e.maxZoom})},{deep:!0,flush:"post"}),e.onBeforeUnmount(()=>null==r?void 0:r())}(r,e.computed(()=>({enabled:c(),getScale:()=>h.value,setScale:d,minZoom:u.value,maxZoom:p.value}))),{hostRef:r,scale:h,setScale:d,zoomEnabled:c}}function Fs(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function As(e,t){return`${e}#s${t}`}function Os(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Rs(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Fs(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=Fs(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:As(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Bs(e,t){const s=Rs(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Gs(e){const[t,s]=e.localPageRange;return s-t+1}function zs(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function _s(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return zs(t)?t.segmentPageThreshold:null}function qs(e,t){return`${e}#s${t}`}function Ws(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Hs(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ks(e){const t=_s(e);if(!t)return null;const s=Gs(e),r=Hs(s,t),n=zs(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:qs(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function js(e,t){const s=Ks(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Xs(e,t){const s=Ks(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Ys(e){var t;const s=_s(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Gs(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!zs(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Hs(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Zs={kind:"first-wins"};function Js(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class Qs{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}const er=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Zs,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Zs,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Ws(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Ws(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Ws(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?js(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ks(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Ys(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Zs){const s=function(e,t=Zs){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Js(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Qs(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ks(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Xs(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(zs(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Ks(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Ks(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Xs(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Xs(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=js(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Ks(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(zs(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=_s(t);if(a){const r=Hs(Gs(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(zs(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Ws(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Ks(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};er.id="chapter-manager";let tr=er;function sr(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const rr=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,sr),this.visibleChange$=n.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.lastLoadIndicesKey="",this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(tr.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.lastLoadIndicesKey="",this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=Bs(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===e.length)return;const t=this.chapterManager.provides(),s=t.visibleRangeNeedsSegmentLoad(e),r=e.join(",");(r!==this.lastLoadIndicesKey||s)&&(this.lastLoadIndicesKey=r,t.setVisibleGlobalPages(e))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Os(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Os(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}if(s){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),r=s.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!r||0===n.length)return;const a=Rs(r),i=this.documentManager.provides(),o=[],l=(e,t,s,r)=>{var n;const a=i.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let i=0;i<r;i++){const e=a.pages[s+i];(null==e?void 0:e.size)&&o.push({localPageIndex:t+i,width:e.size.width*l,height:e.size.height*l})}return o.length>0};if(a)for(const h of a.segments){if(!s.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=Os(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),r=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,r=this.findFirstVisibleIndex(t);let n=r;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=s)break;n++}const a=[];let i=r,o=-1;for(let l=r;l<n;l++){a.push(l);const e=this.offsets[l],r=e+this.getPageSize(l).height,n=Math.max(0,Math.min(r,s)-Math.max(e,t));n>o&&(o=n,i=l)}this.currentVisible=a,this.currentGlobalPageIndex=i,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:i}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);if(s<0)return;const r=this.chapterManager.provides(),n=r.getChapter(e),a=this.virtualPageMap.atIndex(s);if(n&&a){const t=Bs(n,a.localPageIndex);r.ensureSegmentLoaded(e,t)}else r.ensureChapterLoaded(e);this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};rr.id="chapter-scroll";let nr=rr;const ar=["data-global-page-index","data-chapter-id","data-local-page-index"],ir=(e=>{const t=e.__vccOpts||e;for(const[s,r]of[["__scopeId","data-v-e9ab4da3"]])t[s]=r;return t})(e.defineComponent({__name:"ChapterScroller",props:{class:{},style:{}},setup(s){const{provides:r}=t.useCapability(nr.id),n=e.ref(null),a=e.ref(null);let i=null;const o=()=>{null==i||i(),i=null,r.value&&(r.value.registerViewport(n.value),i=r.value.onLayoutChange(e=>{a.value=e}))};return e.onMounted(o),e.onBeforeUnmount(()=>{var e;null==i||i(),null==(e=r.value)||e.registerViewport(null)}),e.watch(r,o),(t,s)=>{var r,i,o;return e.openBlock(),e.createElementBlock("div",{ref_key:"containerRef",ref:n,"data-chapter-scroll-viewport":"",class:e.normalizeClass(t.$props.class),style:e.normalizeStyle({overflow:"auto",overflowX:"hidden",position:"relative",width:"100%",height:"100%",...t.$props.style})},[e.createElementVNode("div",{style:e.normalizeStyle({position:"relative",width:`${(null==(r=a.value)?void 0:r.totalWidth)??0}px`,height:`${(null==(i=a.value)?void 0:i.totalHeight)??0}px`,margin:"0 auto"})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList((null==(o=a.value)?void 0:o.items)??[],r=>(e.openBlock(),e.createElementBlock("div",{key:r.globalPageIndex,"data-global-page-index":r.globalPageIndex,"data-chapter-id":r.chapterId,"data-local-page-index":r.localPageIndex,style:e.normalizeStyle({position:"absolute",top:`${r.offsetTop}px`,left:"50%",transform:"translateX(-50%)",width:`${r.width}px`,height:`${r.height}px`,backgroundColor:r.isPlaceholder?"#f3f4f6":"#fff",boxShadow:"0 1px 4px rgba(0,0,0,0.08)"})},[r.isPlaceholder?e.renderSlot(t.$slots,"placeholder",{key:0,item:r},()=>[s[0]||(s[0]=e.createElementVNode("div",{class:"chapter-scroll-placeholder"},"Loading chapter…",-1))],!0):e.renderSlot(t.$slots,"page",{key:1,item:r},void 0,!0)],12,ar))),128))],4)],6)}}})),or=e.defineComponent({__name:"ChapterRenderLayer",props:{chapterId:{},localPageIndex:{},pdfDocumentId:{},pdfPageIndex:{},scale:{},dpr:{},class:{}},setup(t){const s=t;return(r,n)=>(e.openBlock(),e.createBlock(e.unref(w.RenderLayer),{"document-id":s.pdfDocumentId??s.chapterId,"page-index":s.pdfPageIndex??s.localPageIndex,scale:t.scale,dpr:t.dpr,class:e.normalizeClass(t.class),style:{pointerEvents:"none"}},null,8,["document-id","page-index","scale","dpr","class"]))}});function lr(e){const[t,s]=e.localPageRange;return s-t+1}function hr(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function dr(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return hr(t)?t.segmentPageThreshold:null}function cr(e,t){return`${e}#s${t}`}function ur(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function pr(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function gr(e){const t=dr(e);if(!t)return null;const s=lr(e),r=pr(s,t),n=hr(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:cr(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function mr(e,t){const s=gr(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function fr(e,t){const s=gr(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function vr(e){var t;const s=dr(e);if(!s)return[];const r=[],{chapterId:n}=e,a=lr(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!hr(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=pr(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Pr={kind:"first-wins"};function Ir(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let br=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const Sr=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Pr,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Pr,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=ur(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=ur(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=ur(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?mr(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?gr(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...vr(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Pr){const s=function(e,t=Pr){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Ir(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new br(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?gr(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=fr(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(hr(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=gr(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=gr(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=fr(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=fr(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=mr(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=gr(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(hr(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=dr(t);if(a){const r=pr(lr(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(hr(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=ur(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?gr(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Sr.id="chapter-manager";let Cr=Sr;function wr(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function yr(e,t){return`${e}#s${t}`}function Mr(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function xr(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return wr(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=wr(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:yr(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Lr(e,t){const s=xr(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function $r(e){const[t,s]=e.localPageRange;return s-t+1}function kr(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Dr(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return kr(t)?t.segmentPageThreshold:null}function Ur(e,t){return`${e}#s${t}`}function Er(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Vr(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Nr(e){const t=Dr(e);if(!t)return null;const s=$r(e),r=Vr(s,t),n=kr(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Ur(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Tr(e,t){const s=Nr(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Fr(e,t){const s=Nr(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Ar(e){var t;const s=Dr(e);if(!s)return[];const r=[],{chapterId:n}=e,a=$r(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!kr(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Vr(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Or={kind:"first-wins"};function Rr(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class Br{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}const Gr=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Or,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Or,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Er(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Er(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Er(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Tr(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Nr(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Ar(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Or){const s=function(e,t=Or){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Rr(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Br(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Nr(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Fr(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(kr(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Nr(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Nr(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Fr(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Fr(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Tr(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Nr(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(kr(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Dr(t);if(a){const r=Vr($r(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(kr(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Er(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Nr(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Gr.id="chapter-manager";let zr=Gr;function _r(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const qr=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,_r),this.visibleChange$=n.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.lastLoadIndicesKey="",this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(zr.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.lastLoadIndicesKey="",this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=Lr(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===e.length)return;const t=this.chapterManager.provides(),s=t.visibleRangeNeedsSegmentLoad(e),r=e.join(",");(r!==this.lastLoadIndicesKey||s)&&(this.lastLoadIndicesKey=r,t.setVisibleGlobalPages(e))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Mr(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Mr(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}if(s){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),r=s.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!r||0===n.length)return;const a=xr(r),i=this.documentManager.provides(),o=[],l=(e,t,s,r)=>{var n;const a=i.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let i=0;i<r;i++){const e=a.pages[s+i];(null==e?void 0:e.size)&&o.push({localPageIndex:t+i,width:e.size.width*l,height:e.size.height*l})}return o.length>0};if(a)for(const h of a.segments){if(!s.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=Mr(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),r=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,r=this.findFirstVisibleIndex(t);let n=r;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=s)break;n++}const a=[];let i=r,o=-1;for(let l=r;l<n;l++){a.push(l);const e=this.offsets[l],r=e+this.getPageSize(l).height,n=Math.max(0,Math.min(r,s)-Math.max(e,t));n>o&&(o=n,i=l)}this.currentVisible=a,this.currentGlobalPageIndex=i,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:i}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);if(s<0)return;const r=this.chapterManager.provides(),n=r.getChapter(e),a=this.virtualPageMap.atIndex(s);if(n&&a){const t=Lr(n,a.localPageIndex);r.ensureSegmentLoaded(e,t)}else r.ensureChapterLoaded(e);this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};qr.id="chapter-scroll";let Wr=qr;const Hr=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=n.createBehaviorEmitter([]),this.noteActivated$=n.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(Wr.id),this.chapterManager=this.registry.getPlugin(Cr.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,t.callbacks.loadNotes)try{const e=await t.callbacks.loadNotes();for(const t of e)this.notes.set(t.noteId,t);this.notesChange$.emit(this.listAll())}catch(s){this.logger.error(e.id,"LoadNotes","Failed to load notes",s)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(s=>s.chapterId===e&&s.localPageIndex===t),listAllNotes:()=>this.listAll(),getNote:e=>this.notes.get(e)??null,deleteNote:e=>this.deleteNote(e),updateNoteContent:(e,t)=>this.updateNoteContent(e,t),scrollToNote:e=>this.scrollToNote(e),listNotesForChapter:e=>this.listNotesForChapter(e),replaceNotesForChapter:(e,t)=>this.replaceNotesForChapter(e,t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(e){this.notes.set(e.noteId,e),this.notesChange$.emit(this.listAll())}requestEdit(e){const t=this.notes.get(e);t&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(e,t):this.activateNote(e))}activateNote(e){var t,s;const r=this.notes.get(e);r&&(null==(s=(t=this.config.callbacks).onActivateNote)||s.call(t,e,r),this.noteActivated$.emit({noteId:e,anchor:r}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[s,r]of this.notes.entries())r.chapterId===e&&this.notes.delete(s);for(const s of t)s.chapterId===e&&this.notes.set(s.noteId,s);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:jr(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:s,onCreateNote:r}=this.config.callbacks;return s?(s({draft:t,complete:async e=>{const s={...t,noteId:e};this.registerNote(s)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const s=this.buildDraft(t),r=this.config.callbacks.onCreateNote;if(!r)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await r(s)}catch(i){return this.logger.error(e.id,"OnCreateNote","Callback failed",i),null}if(!n)return null;const a={...s,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var s,r;if(this.notes.has(t)){try{await(null==(r=(s=this.config.callbacks).onDeleteNote)?void 0:r.call(s,t))}catch(n){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",n)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,s){var r,n;const a=this.notes.get(t);if(!a)return;const i={...a,content:s};try{await(null==(n=(r=this.config.callbacks).onUpdateNote)?void 0:n.call(r,i))}catch(o){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",o)}this.notes.set(t,i),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const s=this.notes.get(e);if(!s)return;const r=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(s.chapterId);const a=n.resolvePageDocument(s.chapterId,s.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(r.scrollToGlobalPageIndex(s.globalPageIndex),await this.waitForPageInLayout(s.globalPageIndex),r.scrollToGlobalPdfPoint(s.globalPageIndex,s.endAnchor.y,{marginTop:80})):r.scrollToGlobalPageIndex(s.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const r=setTimeout(()=>{n(),s(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(r),n(),s(a))})})}};Hr.id="note";let Kr=Hr;function jr(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Xr(e){const{markerPdf:t,lineRects:s,sx:r,sy:n,cssPageWidth:a,iconSize:i,gapPx:o=6}=e,l=(null==s?void 0:s.length)?s[s.length-1]:void 0;let h,d;l?(h=(l.origin.x+l.size.width)*r+o,d=l.origin.y*n+(l.size.height*n-i)/2):(h=t.x*r-i/2,d=t.y*n-i-o);const c=Math.max(0,a-i-2);return h>c&&(h=c),d<0&&(d=0),{left:h,top:d}}const Yr={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none",zIndex:25}},Zr=["onMouseenter"],Jr=["data-note-marker-zone","onMouseenter","onMouseleave"],Qr=["onClick"],en=["onClick"],tn=["onClick"],sn=e.defineComponent({__name:"NoteMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(s){const r=s,{provides:n}=t.useCapability(Kr.id),a=e.ref([]),i=e.ref(null),o=e.ref(null);e.watch(n,e=>{if(e)return e.onNotesChange(e=>{a.value=e.filter(e=>e.chapterId===r.chapterId&&e.localPageIndex===r.localPageIndex)})},{immediate:!0});let l=null;e.watch(o,e=>{l&&(document.removeEventListener("mousedown",l),l=null),e&&(l=t=>{var s;const r=t.target;(null==(s=r.closest)?void 0:s.call(r,`[data-note-marker-zone="${e}"]`))||(o.value=null,i.value=null)},document.addEventListener("mousedown",l))}),e.onBeforeUnmount(()=>{l&&document.removeEventListener("mousedown",l)});const h=e.computed(()=>{var e;return(null==(e=r.ui)?void 0:e.iconSize)??16}),d=e.computed(()=>{var e;return(null==(e=r.ui)?void 0:e.highlightColor)??"rgba(245, 158, 11, 0.08)"});function c(e){const t=r.cssPageWidth/r.pdfPageWidth,s=r.cssPageHeight/r.pdfPageHeight,n=h.value,{left:a,top:i}=Xr({markerPdf:e.endAnchor,lineRects:e.rectsPdfCoord,sx:t,sy:s,cssPageWidth:r.cssPageWidth,iconSize:n}),l=function(e,t,s){let r=1/0,n=1/0,a=-1/0,i=-1/0;for(const o of e)r=Math.min(r,o.origin.x*t),n=Math.min(n,o.origin.y*s),a=Math.max(a,(o.origin.x+o.size.width)*t),i=Math.max(i,(o.origin.y+o.size.height)*s);return{left:r,top:n,width:a-r,height:i-n}}(e.rectsPdfCoord,t,s),d=o.value===e.noteId?72:0,c=Math.max(0,Math.min(l.left,a)-8),u=Math.max(0,Math.min(l.top,i)-8);return{zoneLeft:c,zoneTop:u,zoneW:Math.min(r.cssPageWidth,Math.max(l.left+l.width,a+n)+8)-c,zoneH:Math.max(l.top+l.height,i+n+6+d)+8-u,iconLeft:a,iconTop:i,sx:t,sy:s}}return(t,r)=>e.unref(n)&&a.value.length&&s.pdfPageWidth&&s.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",Yr,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(a.value,t=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:t.noteId},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.rectsPdfCoord,(s,r)=>(e.openBlock(),e.createElementBlock("div",{key:`${t.noteId}-bg-${r}`,style:e.normalizeStyle({position:"absolute",left:s.origin.x*c(t).sx+"px",top:s.origin.y*c(t).sy+"px",width:s.size.width*c(t).sx+"px",height:s.size.height*c(t).sy+"px",background:d.value,borderRadius:"2px",pointerEvents:"auto"}),onMouseenter:e=>i.value=t.noteId},null,44,Zr))),128)),i.value===t.noteId||o.value===t.noteId?(e.openBlock(),e.createElementBlock("div",{key:0,"data-note-marker-zone":t.noteId,style:e.normalizeStyle({position:"absolute",left:`${c(t).zoneLeft}px`,top:`${c(t).zoneTop}px`,width:`${c(t).zoneW}px`,height:`${c(t).zoneH}px`,pointerEvents:"auto",zIndex:26}),onMouseenter:e=>i.value=t.noteId,onMouseleave:e=>o.value!==t.noteId&&(i.value=null)},[e.createElementVNode("button",{type:"button",title:"笔记",style:e.normalizeStyle({position:"absolute",left:c(t).iconLeft-c(t).zoneLeft+"px",top:c(t).iconTop-c(t).zoneTop+"px",width:`${h.value}px`,height:`${h.value}px`,border:"none",borderRadius:"50%",background:"#f59e0b",color:"#fff",cursor:"pointer",fontSize:"11px",padding:0}),onMousedown:r[0]||(r[0]=e.withModifiers(()=>{},["stop"])),onClick:e.withModifiers(e=>o.value=o.value===t.noteId?null:t.noteId,["stop"])}," 💬 ",44,Qr),o.value===t.noteId?(e.openBlock(),e.createElementBlock("div",{key:0,style:e.normalizeStyle({position:"absolute",left:c(t).iconLeft-c(t).zoneLeft+"px",top:`${c(t).iconTop-c(t).zoneTop+h.value+4}px`,minWidth:"120px",padding:"6px",borderRadius:"8px",background:"#fff",border:"1px solid #e5e7eb",boxShadow:"0 4px 12px rgba(0,0,0,0.12)",zIndex:30}),onMousedown:r[1]||(r[1]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",style:{display:"block",width:"100%",padding:"6px 8px","font-size":"12px",border:"none","border-radius":"4px",background:"transparent",color:"#334155",cursor:"pointer","text-align":"left"},onClick:e=>{return s=t,void(null==(r=n.value)||r.requestEditNote(s.noteId,s));var s,r}}," 编辑 ",8,en),e.createElementVNode("button",{type:"button",style:{display:"block",width:"100%",padding:"6px 8px","font-size":"12px",border:"none","border-radius":"4px",background:"transparent",color:"#dc2626",cursor:"pointer","text-align":"left"},onClick:e=>{var s,r;return r=t.noteId,null==(s=n.value)||s.requestDeleteNote(r),void(o.value=null)}}," 删除 ",8,tn)],36)):e.createCommentVNode("",!0)],44,Jr)):e.createCommentVNode("",!0)],64))),128))])):e.createCommentVNode("",!0)}}),rn={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none"}},nn=["title","onClick"],an=["onClick"],on=e.defineComponent({__name:"BookmarkMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(s){const r=s,{provides:n}=t.useCapability(ps.id),a=e.ref([]),i=e.ref(null),o=e.ref(null);function l(){const e=n.value;e&&(a.value=e.listBookmarks().filter(e=>e.anchor.chapterId===r.chapterId&&e.anchor.localPageIndex===r.localPageIndex))}e.watch(n,e=>{if(e)return l(),e.onBookmarksChange(l)},{immediate:!0});let h=null;e.watch(i,e=>{h&&(document.removeEventListener("mousedown",h),h=null),e&&(h=e=>{var t;(null==(t=o.value)?void 0:t.contains(e.target))||(i.value=null)},document.addEventListener("mousedown",h))}),e.onBeforeUnmount(()=>{h&&document.removeEventListener("mousedown",h)});const d=e.computed(()=>{var e;return(null==(e=r.ui)?void 0:e.iconSize)??16});function c(e){const{left:t,top:s}=function(e){var t;const s=r.cssPageWidth/r.pdfPageWidth,n=r.cssPageHeight/r.pdfPageHeight,a=(null==(t=e.anchor.rectsPdfCoord)?void 0:t.length)?e.anchor.rectsPdfCoord:[e.anchor.rectPdfCoord];return Xr({markerPdf: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},lineRects:a,sx:s,sy:n,cssPageWidth:r.cssPageWidth,iconSize:d.value})}(e);return{position:"absolute",left:`${Math.max(0,t-6)}px`,top:`${Math.max(0,s-6)}px`,width:`${d.value+12}px`,height:`${d.value+12}px`,pointerEvents:"auto",zIndex:20}}return(t,r)=>e.unref(n)&&a.value.length&&s.pdfPageWidth&&s.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",rn,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(a.value,t=>(e.openBlock(),e.createElementBlock("div",{key:t.id,style:e.normalizeStyle(c(t)),onMousedown:r[1]||(r[1]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",title:t.label,style:e.normalizeStyle({position:"absolute",left:"6px",top:"6px",width:`${d.value}px`,height:`${d.value}px`,border:"none",borderRadius:"4px",background:"#3b82f6",color:"#fff",cursor:"pointer",boxShadow:"0 2px 6px rgba(37, 99, 235, 0.35)",fontSize:"11px",padding:0}),onClick:e.withModifiers(e=>i.value=i.value===t.id?null:t.id,["stop"])}," 🔖 ",12,nn),i.value===t.id?(e.openBlock(),e.createElementBlock("div",{key:0,ref_for:!0,ref_key:"deleteMenuRef",ref:o,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:r[0]||(r[0]=e.withModifiers(()=>{},["stop"]))},[e.createElementVNode("button",{type:"button",style:{width:"100%",padding:"6px 8px","font-size":"12px",border:"none","border-radius":"4px",background:"transparent",color:"#dc2626",cursor:"pointer","text-align":"left"},onClick:e=>async function(e){const t=n.value;t&&await t.requestRemoveBookmark(e)&&(i.value=null)}(t.id)}," 删除书签 ",8,an)],512)):e.createCommentVNode("",!0)],36))),128))])):e.createCommentVNode("",!0)}});function ln(e){return e.pdfDocumentId??e.chapterId}function hn(e){return e.pdfPageIndex??e.localPageIndex}function dn(e,t){e.wait(t,()=>{})}const cn={display:"flex",alignItems:"center",justifyContent:"center",padding:"4px 8px",borderRadius:"8px",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)"},un={padding:"6px 12px",fontSize:"12px",fontWeight:"500",border:"none",borderRadius:"6px",background:"transparent",color:"#dc2626",cursor:"pointer"};const pn=e.defineComponent({__name:"ChapterPageSurface",props:{item:{},features:{},showNoteMarkers:{type:Boolean},showBookmarkMarkers:{type:Boolean},showRedactionLayer:{type:Boolean},noteMarkerUi:{},bookmarkMarkerUi:{},buildSelectionMenu:{type:Function},createNote:{},annotationSelectionMenu:{},redactionSelectionMenu:{},renderPageOverlay:{type:Function}},setup(s){const r=s,n=e.computed(()=>ln(r.item)),i=e.computed(()=>hn(r.item));!function(s){const{provides:r}=t.useCapability(a.DocumentManagerPlugin.id);e.watch([r,s],([e,t])=>{e&&t&&e.isDocumentOpen(t)&&e.setActiveDocument(t)},{immediate:!0})}(n);const{provides:o}=t.useCapability(a.DocumentManagerPlugin.id),{provides:l}=t.useCapability(h.SelectionPlugin.id),d=e.computed(()=>{var e,t;return null==(t=null==(e=o.value)?void 0:e.getDocument(n.value))?void 0:t.pages[i.value]});function c(t,s){var n,a,i,o;const h=r.createNote.value;if(h&&!1!==(null==(a=null==(n=r.features)?void 0:n.notes)?void 0:a.enabled)&&!1!==(null==(o=null==(i=r.features)?void 0:i.selectionToolbar)?void 0:o.enabled))return r=>{var n;const a={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==(n=r.placement)?void 0:n.suggestTop)?-40:r.rect.size.height+8};return e.h("div",r.menuWrapperProps,[e.h("div",{style:a},e.h("button",{type:"button",style:{padding:"6px 10px",fontSize:"12px",border:"1px solid #e2e8f0",borderRadius:"6px",background:"#fff",cursor:"pointer"},onClick:()=>{if(!l.value)return;const e=l.value.getHighlightRectsForPage(hn(t),s);dn(l.value.getSelectedText(s),s=>{var r,n,a;h((r=t,n=e,a=s.join("\n"),{chapterId:r.chapterId,localPageIndex:r.localPageIndex,globalPageIndex:r.globalPageIndex,globalPageNumber:r.globalPageNumber,rectsPdfCoord:n,selectedText:a}))})}},"添加附注"))])}}const u=e.computed(()=>{const e=r.buildSelectionMenu,t={item:r.item,defaultMenu:c(r.item,n.value),createNote:r.createNote.value};if(e){const s=e(t);if(s)return s}return t.defaultMenu}),p=function(t,s){var r,n;const{provides:a}=S.useAnnotationCapability(),i=null==(r=null==s?void 0:s.markup)?void 0:r.annotationMenu,o=!1!==(null==(n=null==s?void 0:s.markup)?void 0:n.enabled),l=!1!==(null==i?void 0:i.enabled);return e.computed(()=>{const s="string"==typeof t?t:t.value;if(o&&l&&a.value)return t=>{const{context:r,rect:n,placement:o,menuWrapperProps:l,selected:h}=t;if(!h||"annotation"!==r.type)return e.h("span",l);if(r.structurallyLocked)return e.h("span",l);if(d=r.annotation.object.type,!N.has(d))return e.h("span",l);var d;const c=a.value.forDocument(s),{pageIndex:u,id:p}=r.annotation.object,g=()=>{null==c||c.deleteAnnotation(u,p)},m={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==o?void 0:o.suggestTop)?void 0:`${n.size.height+8}px`,bottom:(null==o?void 0:o.suggestTop)?`${n.size.height+8}px`:void 0},f=(null==i?void 0:i.renderMenu)?i.renderMenu({pageIndex:u,annotationId:p,onDelete:g}):e.h("button",{type:"button",style:un,onClick:g},"删除");return e.h("div",l,[e.h("div",{style:m},[e.h("div",{style:cn,role:"toolbar","aria-label":"划线标注"},[f])])])}})}(n,r.features),g=e.computed(()=>function(e,t){if(e||t)return s=>{if(e){const t=e(s);if(null!=t)return t}return(null==t?void 0:t(s))??null}}(r.annotationSelectionMenu,p.value)),m=e.computed(()=>{var e;return null==(e=r.renderPageOverlay)?void 0:e.call(r,r.item)}),f=e.computed(()=>{var e;return function(e){const t=null==e?void 0:e.selectionBackground;if(t)return{background:t}}(null==(e=r.features)?void 0:e.selectionToolbar)});return(t,r)=>s.item.isPlaceholder?e.createCommentVNode("",!0):(e.openBlock(),e.createBlock(e.unref(P.GlobalPointerProvider),{key:0,"document-id":n.value},{default:e.withCtx(()=>[e.createVNode(e.unref(I.Rotate),{"document-id":n.value,"page-index":i.value,style:{backgroundColor:"#fff"}},{default:e.withCtx(()=>[e.createVNode(e.unref(P.PagePointerProvider),{"document-id":n.value,"page-index":i.value,style:e.normalizeStyle(e.unref(x)),onPointerdown:e.unref(L)},{default:e.withCtx(()=>[e.createVNode(e.unref(or),{"chapter-id":s.item.chapterId,"local-page-index":s.item.localPageIndex,"pdf-document-id":n.value,"pdf-page-index":i.value},null,8,["chapter-id","local-page-index","pdf-document-id","pdf-page-index"]),e.createVNode(e.unref(b.SelectionLayer),{"document-id":n.value,"page-index":i.value,"text-style":f.value,"selection-menu":u.value},null,8,["document-id","page-index","text-style","selection-menu"]),s.showRedactionLayer?(e.openBlock(),e.createBlock(e.unref(C.RedactionLayer),{key:0,"document-id":n.value,"page-index":i.value,"selection-menu":s.redactionSelectionMenu},null,8,["document-id","page-index","selection-menu"])):e.createCommentVNode("",!0),e.createVNode(e.unref(S.AnnotationLayer),{"document-id":n.value,"page-index":i.value,"selection-menu":g.value},null,8,["document-id","page-index","selection-menu"]),s.showBookmarkMarkers&&d.value?(e.openBlock(),e.createBlock(on,{key:1,"chapter-id":s.item.chapterId,"local-page-index":s.item.localPageIndex,"pdf-page-width":d.value.size.width,"pdf-page-height":d.value.size.height,"css-page-width":s.item.width,"css-page-height":s.item.height,ui:s.bookmarkMarkerUi},null,8,["chapter-id","local-page-index","pdf-page-width","pdf-page-height","css-page-width","css-page-height","ui"])):e.createCommentVNode("",!0),m.value?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(m.value),{key:2})):e.createCommentVNode("",!0),s.showNoteMarkers&&d.value?(e.openBlock(),e.createBlock(sn,{key:3,"chapter-id":s.item.chapterId,"local-page-index":s.item.localPageIndex,"pdf-page-width":d.value.size.width,"pdf-page-height":d.value.size.height,"css-page-width":s.item.width,"css-page-height":s.item.height,ui:s.noteMarkerUi},null,8,["chapter-id","local-page-index","pdf-page-width","pdf-page-height","css-page-width","css-page-height","ui"])):e.createCommentVNode("",!0),e.renderSlot(t.$slots,"default")]),_:3},8,["document-id","page-index","style","onPointerdown"])]),_:3},8,["document-id","page-index"])]),_:3},8,["document-id"]))}}),gn=e.defineComponent({__name:"HoverBookmarkLayer",props:{item:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},hoverUi:{}},setup(s){const r=s,n=e.computed(()=>ln(r.item)),{provides:a}=t.useCapability(h.SelectionPlugin.id),{provides:i}=t.useCapability(ps.id),o=e.ref(null),l=e.ref(null),d=e.ref(null),c=e.ref(null),u=e.computed(()=>{var e;return(null==(e=r.hoverUi)?void 0:e.iconSize)??16}),p=e.computed(()=>c.value??d.value);let g=null,m=0;function f(){const e=a.value;if(!e)return;const t=e.forDocument(n.value).getState().geometry[r.item.localPageIndex];t&&(l.value=t)}e.watch([a,n,()=>r.item.localPageIndex],([e])=>{if(null==g||g(),g=null,cancelAnimationFrame(m),l.value=null,!e)return;const t=e.forDocument(n.value);g=t.onSelectionChange(f);let s=!1;const a=()=>{if(!s){try{if(f(),t.getState().geometry[r.item.localPageIndex])return}catch{}m=requestAnimationFrame(a)}};return a(),()=>{s=!0,cancelAnimationFrame(m),null==g||g(),g=null}},{immediate:!0});let v=null;e.watch([l,()=>r.pdfPageWidth,c,a],()=>{v&&(document.removeEventListener("mousemove",v),v=null),l.value&&r.pdfPageWidth&&(v=e=>{if(c.value)return;const t=a.value;if(t)try{if(t.forDocument(n.value).getState().selecting)return void(d.value=null)}catch{}const s=o.value;if(!s)return;const i=s.getBoundingClientRect();if(e.clientX<i.left||e.clientX>i.right||e.clientY<i.top||e.clientY>i.bottom)return void(d.value=null);const u=function(e,t){const s=h.glyphAt(e,t);if(s<0)return null;const r=h.expandToLineBoundary(e,s);if(!r)return null;const n=h.rectsWithinSlice(e,r.from,r.to);return 0===n.length?null:{lineRects:n,charFrom:r.from,charTo:r.to}}(l.value,{x:(e.clientX-i.left)/(r.cssPageWidth/r.pdfPageWidth),y:(e.clientY-i.top)/(r.cssPageHeight/r.pdfPageHeight)});d.value=(null==u?void 0:u.lineRects)??null},document.addEventListener("mousemove",v))},{immediate:!0}),e.onBeforeUnmount(()=>{v&&document.removeEventListener("mousemove",v),cancelAnimationFrame(m),null==g||g()});const P=e.computed(()=>{const e=p.value;return(null==e?void 0:e.length)?cs(r.item.chapterId,r.item.localPageIndex,e,{globalPageIndex:r.item.globalPageIndex,globalPageNumber:r.item.globalPageNumber}):null}),I=e.computed(()=>{const e=P.value,t=i.value;return!(!e||!t)&&t.listBookmarks().some(t=>ds(t.anchor,e))});function b(){const e=i.value,t=P.value;e&&t&&!I.value&&(e.addBookmark({label:`书签 ${(new Date).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"})}`,anchor:t}),d.value=null,c.value=null)}const S=e.computed(()=>{const e=p.value,t=null==e?void 0:e[e.length-1];if(!t||!r.pdfPageWidth)return null;const s=r.cssPageWidth/r.pdfPageWidth,n=r.cssPageHeight/r.pdfPageHeight,a=u.value;return{iconLeft:Math.min((t.origin.x+t.size.width)*s+6,Math.max(0,r.cssPageWidth-a-2)),iconTop:t.origin.y*n+(t.size.height*n-a)/2,zoneLeft:Math.max(0,(t.origin.x+t.size.width)*s-4),zoneTop:Math.max(0,t.origin.y*n-4),size:a}});return(t,r)=>{var n;return e.unref(i)&&s.pdfPageWidth&&s.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",{key:0,ref_key:"rootRef",ref:o,style:{position:"absolute",inset:"0",zIndex:14,pointerEvents:"none"}},[S.value&&p.value&&!I.value?(e.openBlock(),e.createElementBlock("div",{key:0,style:e.normalizeStyle({position:"absolute",left:`${S.value.zoneLeft}px`,top:`${S.value.zoneTop}px`,width:`${S.value.size+20}px`,height:`${((null==(n=p.value[p.value.length-1])?void 0:n.size.height)??0)*(s.cssPageHeight/s.pdfPageHeight)+S.value.size+12}px`,pointerEvents:"auto"}),onMouseenter:r[0]||(r[0]=e=>c.value=p.value),onMouseleave:r[1]||(r[1]=e=>c.value=null)},[e.createElementVNode("button",{type:"button",title:"添加书签",style:e.normalizeStyle({position:"absolute",left:S.value.iconLeft-S.value.zoneLeft+"px",top:S.value.iconTop-S.value.zoneTop+"px",width:`${S.value.size}px`,height:`${S.value.size}px`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",background:"#3b82f6",color:"#fff",border:"none",borderRadius:"4px",boxShadow:"0 2px 8px rgba(37, 99, 235, 0.45)",fontSize:"12px",padding:0}),onClick:e.withModifiers(b,["stop"])}," 🔖 ",4)],36)):e.createCommentVNode("",!0)],512)):e.createCommentVNode("",!0)}}}),mn={key:0,width:"20",height:"20",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},fn={key:1,width:"24",height:"24",viewBox:"0 0 28 28",fill:"none","aria-hidden":""},vn={key:0,x:"5",y:"4",width:"18",height:"20",rx:"3",fill:"#fde047"},Pn={key:1,d:"M6 22h16",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},In={key:2,d:"M6 22c2-2 3-2 5 0s3 2 5 0 3-2 5 0",stroke:"#dc2626","stroke-width":"2","stroke-linecap":"round",fill:"none"},bn={key:3,d:"M5 14h18",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},Sn={key:2,width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},Cn=e.defineComponent({__name:"SelectionToolbarIcons",props:{kind:{}},setup:t=>(s,r)=>"copy"===t.kind?(e.openBlock(),e.createElementBlock("svg",mn,[...r[0]||(r[0]=[e.createElementVNode("rect",{x:"8.5",y:"8.5",width:"11",height:"13",rx:"2.25",fill:"#f1f5f9",stroke:"#94a3b8","stroke-width":"1.35"},null,-1),e.createElementVNode("rect",{x:"4.5",y:"3.5",width:"11",height:"13",rx:"2.25",fill:"#ffffff",stroke:"#334155","stroke-width":"1.5"},null,-1),e.createElementVNode("path",{d:"M7.5 7h5.5a1.5 1.5 0 0 1 1.5 1.5V14",stroke:"#64748b","stroke-width":"1.2","stroke-linecap":"round"},null,-1)])])):"note"!==t.kind?(e.openBlock(),e.createElementBlock("svg",fn,["highlight"===t.kind?(e.openBlock(),e.createElementBlock("rect",vn)):e.createCommentVNode("",!0),r[1]||(r[1]=e.createElementVNode("text",{x:"14",y:"19","text-anchor":"middle","font-size":"15","font-weight":"700","font-family":"system-ui, -apple-system, sans-serif",fill:"#0f172a"}," A ",-1)),"underline"===t.kind?(e.openBlock(),e.createElementBlock("path",Pn)):"squiggly"===t.kind?(e.openBlock(),e.createElementBlock("path",In)):"strikeout"===t.kind?(e.openBlock(),e.createElementBlock("path",bn)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("svg",Sn,[...r[2]||(r[2]=[e.createElementVNode("path",{d:"M8 3h8l4 4v14H8V3z",fill:"#fef3c7",stroke:"#d97706","stroke-width":"1.2","stroke-linejoin":"round"},null,-1),e.createElementVNode("path",{d:"M16 3v4h4",stroke:"#d97706","stroke-width":"1.2"},null,-1),e.createElementVNode("path",{d:"M10 12h6M10 16h4",stroke:"#92400e","stroke-width":"1.2","stroke-linecap":"round"},null,-1)])]))}),wn=["title","aria-label","onMouseenter","onClick"],yn=["title","onMouseenter","onClick"],Mn={style:{"font-size":"11px","font-weight":"600"}},xn=e.defineComponent({__name:"SelectionToolbarCard",props:{placementAbove:{type:Boolean},anchorHeight:{},hiddenBuiltinActions:{},extraActions:{},renderCopyIcon:{type:Function}},emits:["action"],setup(t,{emit:s}){const r=t,n=s,a=[{id:"highlight",label:"高亮背景"},{id:"underline",label:"下划线"},{id:"squiggly",label:"波浪线"},{id:"strikeout",label:"删除线"}],i=e.computed(()=>new Set(r.hiddenBuiltinActions??[])),o=e.computed(()=>!i.value.has("copy")),l=e.computed(()=>a.filter(e=>!i.value.has(e.id))),h=e.computed(()=>!i.value.has("note")),d=e.computed(()=>[...r.extraActions??[]].sort((e,t)=>(e.order??0)-(t.order??0))),c=e.computed(()=>l.value.length>0||d.value.length>0),u=e.ref(null),p=e.computed(()=>({position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:r.placementAbove?void 0:`${r.anchorHeight+10}px`,bottom:r.placementAbove?`${r.anchorHeight+10}px`:void 0,display:"flex",alignItems:"center",gap:"2px",padding:"4px 6px",borderRadius:"12px",background:"rgba(255, 255, 255, 0.96)",border:"1px solid rgba(15, 23, 42, 0.06)",boxShadow:"0 2px 8px rgba(15, 23, 42, 0.08), 0 12px 32px rgba(15, 23, 42, 0.1)",backdropFilter:"blur(10px)",WebkitBackdropFilter:"blur(10px)"}));function g(e,t=!1){return{display:"flex",alignItems:"center",justifyContent:"center",width:"32px",height:"32px",padding:0,margin:0,border:"none",borderRadius:"8px",background:u.value===e?t?"#fffbeb":"#f1f5f9":"transparent",color:t?"#b45309":"#334155",cursor:"pointer",flexShrink:0,WebkitAppearance:"none",appearance:"none"}}const m={width:"1px",height:"20px",margin:"0 4px",background:"rgba(15, 23, 42, 0.1)",flexShrink:0};return(s,r)=>(e.openBlock(),e.createElementBlock("div",{role:"toolbar","aria-label":"选区工具",style:e.normalizeStyle(p.value)},[o.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createElementVNode("button",{type:"button",title:"复制","aria-label":"复制",style:e.normalizeStyle(g("copy")),onMouseenter:r[0]||(r[0]=e=>u.value="copy"),onMouseleave:r[1]||(r[1]=e=>u.value=null),onClick:r[2]||(r[2]=e=>n("action","copy"))},[t.renderCopyIcon?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(t.renderCopyIcon),{key:0})):(e.openBlock(),e.createBlock(Cn,{key:1,kind:"copy"}))],36),c.value?(e.openBlock(),e.createElementBlock("span",{key:0,style:m,"aria-hidden":""})):e.createCommentVNode("",!0)],64)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(l.value,t=>(e.openBlock(),e.createElementBlock("button",{key:t.id,type:"button",title:t.label,"aria-label":t.label,style:e.normalizeStyle(g(t.id)),onMouseenter:e=>u.value=t.id,onMouseleave:r[3]||(r[3]=e=>u.value=null),onClick:e=>n("action",t.id)},[e.createVNode(Cn,{kind:t.id},null,8,["kind"])],44,wn))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(d.value,t=>(e.openBlock(),e.createElementBlock("button",{key:t.id,type:"button",title:t.label,style:e.normalizeStyle(g(t.id)),onMouseenter:e=>u.value=t.id,onMouseleave:r[4]||(r[4]=e=>u.value=null),onClick:e=>n("action",t.id)},[e.createElementVNode("span",Mn,e.toDisplayString(t.label.slice(0,2)),1)],44,yn))),128)),h.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[c.value||o.value?(e.openBlock(),e.createElementBlock("span",{key:0,style:m,"aria-hidden":""})):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",title:"添加笔记","aria-label":"添加笔记",style:e.normalizeStyle(g("note",!0)),onMouseenter:r[5]||(r[5]=e=>u.value="note"),onMouseleave:r[6]||(r[6]=e=>u.value=null),onClick:r[7]||(r[7]=e=>n("action","note"))},[e.createVNode(Cn,{kind:"note"})],36)],64)):e.createCommentVNode("",!0)],4))}}),Ln={highlight:"highlight",underline:"underline",squiggly:"squiggly",strikeout:"strikeout"},$n=e.defineComponent({__name:"PdfChapterViewport",props:{className:{},features:{},buildSelectionMenu:{},annotationSelectionMenu:{},redactionSelectionMenu:{},showNoteMarkers:{type:Boolean,default:!0},showBookmarkMarkers:{type:Boolean,default:!0},showRedactionLayer:{type:Boolean,default:!1},renderPageOverlay:{},onExtraSelectionAction:{}},setup(r){const n=r,i=e.computed(()=>n.features),{hostRef:o}=Ts(i),l=e.computed(()=>{var e,t;return{background:(null==(t=null==(e=n.features)?void 0:e.scrollViewport)?void 0:t.background)??$}}),d=function(){const{registry:s}=t.useRegistry();return e.computed(()=>{var e,t,r;const n=null==(r=null==(t=null==(e=s.value)?void 0:e.getPlugin(Pt.id))?void 0:t.provides)?void 0:r.call(t);return n?e=>n.createNoteFromSelection(e):null})}(),c=function(){const{registry:s}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=s.value)?void 0:e.getPlugin(Pt.id))})}(),u=function(){const{registry:s}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=s.value)?void 0:e.getPlugin(ps.id))})}(),p=e.computed(()=>{var e,t;return n.showNoteMarkers&&c.value&&!1!==(null==(t=null==(e=n.features)?void 0:e.notes)?void 0:t.enabled)}),g=e.computed(()=>{var e,t;return n.showBookmarkMarkers&&u.value&&!1!==(null==(t=null==(e=n.features)?void 0:e.bookmarks)?void 0:t.enabled)}),m=e.computed(()=>{var e,t;return u.value&&!1!==(null==(t=null==(e=n.features)?void 0:e.bookmarks)?void 0:t.enabled)}),f=function(r,n){const a=e.computed(()=>{var e;return null==(e=r())?void 0:e.selectionToolbar}),i=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=r())?void 0:e.markup)?void 0:t.enabled)}),o=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=r())?void 0:e.notes)?void 0:t.enabled)}),l=e.computed(()=>{var e,t;return!(null==(t=null==(e=a.value)?void 0:e.hiddenBuiltinActions)?void 0:t.includes("copy"))}),{provides:d}=t.useCapability(h.SelectionPlugin.id),{provides:c}=t.useCapability(s.AnnotationPlugin.id),{provides:u}=t.useCapability(Pt.id);return e.computed(()=>{var t,s,h;if(!1!==(null==(t=a.value)?void 0:t.enabled)&&(i.value||o.value||l.value||(null==(h=null==(s=a.value)?void 0:s.extraActions)?void 0:h.length)))return t=>{const s=ln(t.item),h=hn(t.item);return p=>{var g,m,f,v;return e.h("div",p.menuWrapperProps,e.h(xn,{placementAbove:!!(null==(g=p.placement)?void 0:g.suggestTop),anchorHeight:p.rect.size.height,hiddenBuiltinActions:null==(m=a.value)?void 0:m.hiddenBuiltinActions,extraActions:null==(f=a.value)?void 0:f.extraActions,renderCopyIcon:null==(v=a.value)?void 0:v.renderCopyIcon,onAction:e=>{var a,p,g;if("copy"!==e)if("highlight"!==e&&"underline"!==e&&"squiggly"!==e&&"strikeout"!==e){if("note"===e){if(!d.value||!u.value||!o.value)return;const e=d.value.getHighlightRectsForPage(h,s);return void dn(d.value.getSelectedText(s),s=>{var r;null==(r=u.value)||r.requestCreateFromSelection({chapterId:t.item.chapterId,localPageIndex:t.item.localPageIndex,globalPageIndex:t.item.globalPageIndex,globalPageNumber:t.item.globalPageNumber,rectsPdfCoord:e,selectedText:s.join("\n")})})}null==(a=null==n?void 0:n.onExtraAction)||a.call(n,e,t)}else{if(!d.value||!c.value||!i.value)return;V(s,Ln[e],c.value,d.value,null==(g=null==(p=r())?void 0:p.markup)?void 0:g.styles)}else{if(!d.value||!l.value)return;dn(d.value.getSelectedText(s),e=>{!async function(e){var t;const s=e.trim();if(!s)return!1;try{if("undefined"!=typeof navigator&&(null==(t=navigator.clipboard)?void 0:t.writeText))return await navigator.clipboard.writeText(s),!0}catch{}if("undefined"==typeof document)return!1;try{const e=document.createElement("textarea");e.value=s,e.setAttribute("readonly",""),e.style.position="fixed",e.style.left="-9999px",document.body.appendChild(e),e.select();const t=document.execCommand("copy");return document.body.removeChild(e),t}catch{return!1}}(e.join("\n"))})}}}))}}})}(()=>n.features,{onExtraAction:n.onExtraSelectionAction}),v=e.computed(()=>{if(n.buildSelectionMenu||f.value)return e=>{const t=f.value?f.value(e):e.defaultMenu;return n.buildSelectionMenu?n.buildSelectionMenu({...e,defaultMenu:t}):t}}),{provides:P}=t.useCapability(a.DocumentManagerPlugin.id);function I(t){var s;const r=[];if(m.value){const s=function(t){var s,r,a,i;const o=ln(t),l=hn(t),h=null==(r=null==(s=P.value)?void 0:s.getDocument(o))?void 0:r.pages[l];return t.isPlaceholder||!h?null:e.h(gn,{item:t,pdfPageWidth:h.size.width,pdfPageHeight:h.size.height,cssPageWidth:t.width,cssPageHeight:t.height,hoverUi:null==(i=null==(a=n.features)?void 0:a.bookmarks)?void 0:i.hover})}(t);s&&r.push(s)}const a=null==(s=n.renderPageOverlay)?void 0:s.call(n,t);if(a&&r.push(a),r.length)return e.h("div",r)}return(t,s)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"hostRef",ref:o,class:e.normalizeClass(r.className),style:e.normalizeStyle(r.className?void 0:e.unref(M))},[e.createVNode(e.unref(ir),{class:e.normalizeClass(r.className),style:e.normalizeStyle(l.value)},{page:e.withCtx(({item:t})=>{var s,n,a,i;return[e.createVNode(pn,{item:t,features:r.features,"show-note-markers":p.value,"show-bookmark-markers":g.value,"show-redaction-layer":r.showRedactionLayer,"note-marker-ui":null==(n=null==(s=r.features)?void 0:s.notes)?void 0:n.marker,"bookmark-marker-ui":null==(i=null==(a=r.features)?void 0:a.bookmarks)?void 0:i.marker,"build-selection-menu":v.value,"create-note":e.unref(d),"annotation-selection-menu":r.annotationSelectionMenu,"redaction-selection-menu":r.redactionSelectionMenu,"render-page-overlay":I},null,8,["item","features","show-note-markers","show-bookmark-markers","show-redaction-layer","note-marker-ui","bookmark-marker-ui","build-selection-menu","create-note","annotation-selection-menu","redaction-selection-menu"])]}),_:1},8,["class","style"]),e.renderSlot(t.$slots,"default")],6))}}),kn={key:0,style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,width:"100%"}},Dn=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{},onExtraSelectionAction:{type:Function}},setup(s){const r=s,n=e.computed(()=>function(e){if(e.options)return xs(e.options);if(!e.editorOptions)throw new Error("ChapterPdfViewer: 请传入 `options`(推荐),或同时传入 `editorOptions` 与 `features`");const t=F(e.features),{plugins:s}=Cs({...e.editorOptions,features:t});return{plugins:s,features:t,editorOptions:{...e.editorOptions,features:t}}}({engine:r.engine,options:r.options,editorOptions:r.editorOptions,features:r.features}));return(r,a)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(s.className),style:e.normalizeStyle(s.className?void 0:e.unref(M))},[e.createVNode(e.unref(t.EmbedPDF),{engine:s.engine,plugins:n.value.plugins},{default:e.withCtx(({pluginsReady:t})=>[t?(e.openBlock(),e.createElementBlock("div",kn,[e.renderSlot(r.$slots,"prepend"),e.createVNode($n,{class:e.normalizeClass(s.viewportClassName),style:{flex:1,minHeight:0},features:n.value.features,"on-extra-selection-action":s.onExtraSelectionAction},null,8,["class","features","on-extra-selection-action"]),e.renderSlot(r.$slots,"default")])):e.createCommentVNode("",!0)]),_:3},8,["engine","plugins"])],6))}}),Un={class:"chapter-tree-row"},En=["aria-expanded"],Vn={key:1,class:"chapter-tree-toggle-spacer","aria-hidden":""},Nn={class:"chapter-tree-label"},Tn={class:"chapter-tree-meta"},Fn={key:0},An=(e,t)=>{const s=e.__vccOpts||e;for(const[r,n]of t)s[r]=n;return s},On=An(e.defineComponent({__name:"ChapterTreeItem",props:{node:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup(t){const s={idle:"未加载",loading:"加载中",loaded:"已加载",closed:"已卸载",error:"失败","password-required":"需密码"},r=t,n=e.computed(()=>r.node.children??[]),a=e.computed(()=>n.value.length>0),i=e.ref(r.depth<1),o=e.computed(()=>r.activeChapterId===r.node.id),l=e.computed(()=>r.chapterStatus[r.node.id]??"idle"),h=e.computed(()=>!a.value);return(r,d)=>(e.openBlock(),e.createElementBlock("li",null,[e.createElementVNode("div",Un,[a.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"chapter-tree-toggle","aria-expanded":i.value,onClick:d[0]||(d[0]=e=>i.value=!i.value)},e.toDisplayString(i.value?"▼":"▶"),9,En)):(e.openBlock(),e.createElementBlock("span",Vn)),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["chapter-tree-btn",{"chapter-tree-btn-active":o.value}]),onClick:d[1]||(d[1]=e=>r.$emit("select",t.node.id))},[e.createElementVNode("div",Nn,e.toDisplayString(t.node.title),1),e.createElementVNode("div",Tn,[e.createElementVNode("span",null," 第 "+e.toDisplayString(t.node.startPage)+e.toDisplayString(t.node.endPage!==t.node.startPage?`–${t.node.endPage}`:"")+" 页 ",1),h.value?(e.openBlock(),e.createElementBlock("span",Fn,e.toDisplayString(s[l.value]),1)):e.createCommentVNode("",!0)])],2)]),a.value&&i.value?(e.openBlock(),e.createBlock(Rn,{key:0,nodes:n.value,depth:t.depth+1,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:d[2]||(d[2]=e=>r.$emit("select",e))},null,8,["nodes","depth","active-chapter-id","chapter-status"])):e.createCommentVNode("",!0)]))}}),[["__scopeId","data-v-315bbf7a"]]),Rn=An(e.defineComponent({__name:"ChapterTreeList",props:{nodes:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup:t=>(s,r)=>(e.openBlock(),e.createElementBlock("ul",{class:"chapter-tree-list",style:e.normalizeStyle({marginLeft:t.depth>0?"12px":"0"})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.nodes,n=>(e.openBlock(),e.createBlock(On,{key:n.id,node:n,depth:t.depth,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:r[0]||(r[0]=e=>s.$emit("select",e))},null,8,["node","depth","active-chapter-id","chapter-status"]))),128))],4))}),[["__scopeId","data-v-eb742e4f"]]),Bn={class:"chapter-tree"},Gn={class:"chapter-tree-nav","aria-label":"章节目录"},zn=An(e.defineComponent({__name:"ChapterTreePanel",props:{tree:{},activeChapterId:{}},emits:["active-chapter-change"],setup(s,{emit:r}){const n=s,a=r,{provides:i}=t.useCapability(ke.id),{provides:o}=t.useCapability(re.id),l=e.ref({});function h(){if(!o.value)return;const e={},t=s=>{var r;for(const n of s)e[n.id]=o.value.getChapterStatus(n.id),(null==(r=n.children)?void 0:r.length)&&t(n.children)};t(n.tree),l.value=e}e.watch([o,()=>n.tree],h,{immediate:!0});let d=null;function c(e){var t;a("active-chapter-change",e),null==(t=i.value)||t.scrollToChapter(e)}return e.watch(o,e=>{null==d||d(),d=e?e.onChapterStatusChange(h):null},{immediate:!0}),e.onBeforeUnmount(()=>null==d?void 0:d()),(t,r)=>(e.openBlock(),e.createElementBlock("aside",Bn,[r[0]||(r[0]=e.createElementVNode("h2",{class:"chapter-tree-title"},"章节目录",-1)),e.createElementVNode("nav",Gn,[e.createVNode(Rn,{nodes:s.tree,depth:0,"active-chapter-id":s.activeChapterId,"chapter-status":l.value,onSelect:c},null,8,["nodes","active-chapter-id","chapter-status"])])]))}}),[["__scopeId","data-v-d7a0838d"]]),_n=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{}},setup:t=>(t,s)=>(e.openBlock(),e.createBlock(e.unref(Dn),e.normalizeProps(e.guardReactiveProps(t.$props)),e.createSlots({default:e.withCtx(()=>[e.renderSlot(t.$slots,"default")]),_:2},[t.$slots.prepend?{name:"prepend",fn:e.withCtx(()=>[e.renderSlot(t.$slots,"prepend")]),key:"0"}:void 0]),1040))});function qn(e){const[t,s]=e.localPageRange;return s-t+1}function Wn(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Hn(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Wn(t)?t.segmentPageThreshold:null}function Kn(e,t){return`${e}#s${t}`}function jn(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Xn(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Yn(e){const t=Hn(e);if(!t)return null;const s=qn(e),r=Xn(s,t),n=Wn(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Kn(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Zn(e,t){const s=Yn(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Jn(e,t){const s=Yn(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Qn(e){var t;const s=Hn(e);if(!s)return[];const r=[],{chapterId:n}=e,a=qn(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Wn(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Xn(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const ea={kind:"first-wins"};function ta(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let sa=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const ra=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ea,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ea,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=jn(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=jn(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=jn(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Zn(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Yn(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Qn(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=ea){const s=function(e,t=ea){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,ta(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new sa(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Yn(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Jn(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Wn(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Yn(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Yn(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Jn(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Jn(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Zn(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Yn(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Wn(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Hn(t);if(a){const r=Xn(qn(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Wn(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=jn(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Yn(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};ra.id="chapter-manager";let na=ra;function aa(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ia(e,t){return`${e}#s${t}`}function oa(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function la(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return aa(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=aa(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:ia(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function ha(e,t){const s=la(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function da(e){const[t,s]=e.localPageRange;return s-t+1}function ca(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ua(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ca(t)?t.segmentPageThreshold:null}function pa(e,t){return`${e}#s${t}`}function ga(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function ma(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function fa(e){const t=ua(e);if(!t)return null;const s=da(e),r=ma(s,t),n=ca(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:pa(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function va(e,t){const s=fa(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Pa(e,t){const s=fa(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Ia(e){var t;const s=ua(e);if(!s)return[];const r=[],{chapterId:n}=e,a=da(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!ca(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=ma(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const ba={kind:"first-wins"};function Sa(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class Ca{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}const wa=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ba,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ba,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=ga(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=ga(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=ga(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?va(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?fa(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Ia(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=ba){const s=function(e,t=ba){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Sa(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Ca(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?fa(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Pa(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(ca(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=fa(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=fa(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Pa(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Pa(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=va(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=fa(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(ca(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=ua(t);if(a){const r=ma(da(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(ca(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=ga(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?fa(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};wa.id="chapter-manager";let ya=wa;function Ma(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}function xa(e){const[t,s]=e.localPageRange;return s-t+1}function La(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function $a(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return La(t)?t.segmentPageThreshold:null}function ka(e,t){return`${e}#s${t}`}function Da(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Ua(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ea(e){const t=$a(e);if(!t)return null;const s=xa(e),r=Ua(s,t),n=La(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:ka(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Va(e,t){const s=Ea(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Na(e,t){const s=Ea(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Ta(e){var t;const s=$a(e);if(!s)return[];const r=[],{chapterId:n}=e,a=xa(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!La(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Ua(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}(class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,Ma),this.visibleChange$=n.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.lastLoadIndicesKey="",this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(ya.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.lastLoadIndicesKey="",this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=ha(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===e.length)return;const t=this.chapterManager.provides(),s=t.visibleRangeNeedsSegmentLoad(e),r=e.join(",");(r!==this.lastLoadIndicesKey||s)&&(this.lastLoadIndicesKey=r,t.setVisibleGlobalPages(e))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=oa(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=oa(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}if(s){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),r=s.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!r||0===n.length)return;const a=la(r),i=this.documentManager.provides(),o=[],l=(e,t,s,r)=>{var n;const a=i.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let i=0;i<r;i++){const e=a.pages[s+i];(null==e?void 0:e.size)&&o.push({localPageIndex:t+i,width:e.size.width*l,height:e.size.height*l})}return o.length>0};if(a)for(const h of a.segments){if(!s.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=oa(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),r=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,r=this.findFirstVisibleIndex(t);let n=r;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=s)break;n++}const a=[];let i=r,o=-1;for(let l=r;l<n;l++){a.push(l);const e=this.offsets[l],r=e+this.getPageSize(l).height,n=Math.max(0,Math.min(r,s)-Math.max(e,t));n>o&&(o=n,i=l)}this.currentVisible=a,this.currentGlobalPageIndex=i,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:i}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);if(s<0)return;const r=this.chapterManager.provides(),n=r.getChapter(e),a=this.virtualPageMap.atIndex(s);if(n&&a){const t=ha(n,a.localPageIndex);r.ensureSegmentLoaded(e,t)}else r.ensureChapterLoaded(e);this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}}).id="chapter-scroll";const Fa={kind:"first-wins"};function Aa(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let Oa=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const Ra=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Fa,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Fa,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Da(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Da(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Da(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Va(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ea(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Ta(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=Fa){const s=function(e,t=Fa){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,Aa(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Oa(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ea(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Na(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(La(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Ea(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Ea(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Na(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Na(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Va(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Ea(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(La(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=$a(t);if(a){const r=Ua(xa(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(La(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Da(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Ea(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Ra.id="chapter-manager";let Ba=Ra;function Ga(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function za(e,t){return`${e}#s${t}`}function _a(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function qa(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ga(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=Ga(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:za(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Wa(e,t){const s=qa(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Ha(e){const[t,s]=e.localPageRange;return s-t+1}function Ka(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ja(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ka(t)?t.segmentPageThreshold:null}function Xa(e,t){return`${e}#s${t}`}function Ya(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Za(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ja(e){const t=ja(e);if(!t)return null;const s=Ha(e),r=Za(s,t),n=Ka(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Xa(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Qa(e,t){const s=Ja(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function ei(e,t){const s=Ja(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function ti(e){var t;const s=ja(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Ha(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Ka(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Za(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const si={kind:"first-wins"};function ri(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let ni=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const ai=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=si,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??si,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Ya(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Ya(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Ya(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Qa(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ja(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...ti(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=si){const s=function(e,t=si){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,ri(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new ni(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ja(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=ei(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Ka(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Ja(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Ja(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=ei(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=ei(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Qa(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Ja(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Ka(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=ja(t);if(a){const r=Za(Ha(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Ka(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Ya(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Ja(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};ai.id="chapter-manager";let ii=ai;function oi(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const li=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,oi),this.visibleChange$=n.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.lastLoadIndicesKey="",this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(ii.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.lastLoadIndicesKey="",this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=Wa(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===e.length)return;const t=this.chapterManager.provides(),s=t.visibleRangeNeedsSegmentLoad(e),r=e.join(",");(r!==this.lastLoadIndicesKey||s)&&(this.lastLoadIndicesKey=r,t.setVisibleGlobalPages(e))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=_a(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=_a(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}if(s){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),r=s.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!r||0===n.length)return;const a=qa(r),i=this.documentManager.provides(),o=[],l=(e,t,s,r)=>{var n;const a=i.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let i=0;i<r;i++){const e=a.pages[s+i];(null==e?void 0:e.size)&&o.push({localPageIndex:t+i,width:e.size.width*l,height:e.size.height*l})}return o.length>0};if(a)for(const h of a.segments){if(!s.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=_a(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),r=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,r=this.findFirstVisibleIndex(t);let n=r;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=s)break;n++}const a=[];let i=r,o=-1;for(let l=r;l<n;l++){a.push(l);const e=this.offsets[l],r=e+this.getPageSize(l).height,n=Math.max(0,Math.min(r,s)-Math.max(e,t));n>o&&(o=n,i=l)}this.currentVisible=a,this.currentGlobalPageIndex=i,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:i}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);if(s<0)return;const r=this.chapterManager.provides(),n=r.getChapter(e),a=this.virtualPageMap.atIndex(s);if(n&&a){const t=Wa(n,a.localPageIndex);r.ensureSegmentLoaded(e,t)}else r.ensureChapterLoaded(e);this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};li.id="chapter-scroll";let hi=li;const di=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=n.createBehaviorEmitter([]),this.noteActivated$=n.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(hi.id),this.chapterManager=this.registry.getPlugin(Ba.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){if(this.config=t,t.callbacks.loadNotes)try{const e=await t.callbacks.loadNotes();for(const t of e)this.notes.set(t.noteId,t);this.notesChange$.emit(this.listAll())}catch(s){this.logger.error(e.id,"LoadNotes","Failed to load notes",s)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(s=>s.chapterId===e&&s.localPageIndex===t),listAllNotes:()=>this.listAll(),getNote:e=>this.notes.get(e)??null,deleteNote:e=>this.deleteNote(e),updateNoteContent:(e,t)=>this.updateNoteContent(e,t),scrollToNote:e=>this.scrollToNote(e),listNotesForChapter:e=>this.listNotesForChapter(e),replaceNotesForChapter:(e,t)=>this.replaceNotesForChapter(e,t),onNotesChange:this.notesChange$.on,onNoteActivated:this.noteActivated$.on}}registerNote(e){this.notes.set(e.noteId,e),this.notesChange$.emit(this.listAll())}requestEdit(e){const t=this.notes.get(e);t&&(this.config.callbacks.onRequestEditNote?this.config.callbacks.onRequestEditNote(e,t):this.activateNote(e))}activateNote(e){var t,s;const r=this.notes.get(e);r&&(null==(s=(t=this.config.callbacks).onActivateNote)||s.call(t,e,r),this.noteActivated$.emit({noteId:e,anchor:r}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[s,r]of this.notes.entries())r.chapterId===e&&this.notes.delete(s);for(const s of t)s.chapterId===e&&this.notes.set(s.noteId,s);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:ui(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:s,onCreateNote:r}=this.config.callbacks;return s?(s({draft:t,complete:async e=>{const s={...t,noteId:e};this.registerNote(s)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const s=this.buildDraft(t),r=this.config.callbacks.onCreateNote;if(!r)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await r(s)}catch(i){return this.logger.error(e.id,"OnCreateNote","Callback failed",i),null}if(!n)return null;const a={...s,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var s,r;if(this.notes.has(t)){try{await(null==(r=(s=this.config.callbacks).onDeleteNote)?void 0:r.call(s,t))}catch(n){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",n)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,s){var r,n;const a=this.notes.get(t);if(!a)return;const i={...a,content:s};try{await(null==(n=(r=this.config.callbacks).onUpdateNote)?void 0:n.call(r,i))}catch(o){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",o)}this.notes.set(t,i),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const s=this.notes.get(e);if(!s)return;const r=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(s.chapterId);const a=n.resolvePageDocument(s.chapterId,s.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(r.scrollToGlobalPageIndex(s.globalPageIndex),await this.waitForPageInLayout(s.globalPageIndex),r.scrollToGlobalPdfPoint(s.globalPageIndex,s.endAnchor.y,{marginTop:80})):r.scrollToGlobalPageIndex(s.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),s=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const r=setTimeout(()=>{n(),s(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(r),n(),s(a))})})}};di.id="note";let ci=di;function ui(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function pi(e){const[t,s]=e.localPageRange;return s-t+1}function gi(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function mi(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return gi(t)?t.segmentPageThreshold:null}function fi(e,t){return`${e}#s${t}`}function vi(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Pi(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ii(e){const t=mi(e);if(!t)return null;const s=pi(e),r=Pi(s,t),n=gi(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:fi(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function bi(e,t){const s=Ii(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Si(e,t){const s=Ii(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Ci(e){var t;const s=mi(e);if(!s)return[];const r=[],{chapterId:n}=e,a=pi(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!gi(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Pi(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const wi={kind:"first-wins"};function yi(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}let Mi=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}};const xi=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=wi,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??wi,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=vi(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=vi(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=vi(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?bi(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ii(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...Ci(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=wi){const s=function(e,t=wi){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,yi(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Mi(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ii(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Si(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(gi(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Ii(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Ii(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Si(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Si(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=bi(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Ii(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(gi(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=mi(t);if(a){const r=Pi(pi(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(gi(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=vi(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Ii(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};xi.id="chapter-manager";let Li=xi;function $i(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ki(e,t){return`${e}#s${t}`}function Di(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Ui(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return $i(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=$i(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:ki(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Ei(e,t){const s=Ui(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function Vi(e){const[t,s]=e.localPageRange;return s-t+1}function Ni(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ti(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ni(t)?t.segmentPageThreshold:null}function Fi(e,t){return`${e}#s${t}`}function Ai(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Oi(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ri(e){const t=Ti(e);if(!t)return null;const s=Vi(e),r=Oi(s,t),n=Ni(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:Fi(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function Bi(e,t){const s=Ri(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Gi(e,t){const s=Ri(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function zi(e){var t;const s=Ti(e);if(!s)return[];const r=[],{chapterId:n}=e,a=Vi(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Ni(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Oi(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const _i={kind:"first-wins"};function qi(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class Wi{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}const Hi=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=_i,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??_i,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Ai(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Ai(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Ai(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?Bi(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ri(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...zi(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=function(e,t=_i){const s=function(e,t=_i){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,qi(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new Wi(a)}(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ri(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!(!s||!this.pendingSegmentLoadPromises.has(s)&&(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Gi(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&"error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e)}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!(Ni(s)||s&&("url"in s||"buffer"in s||"load"in s)||!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1)}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=Ri(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);return i?i.globalPageIndex:1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=Ri(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Gi(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Gi(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=Bi(this.findChapter(e.chapterId),e.localPageIndex);this.documentManager.provides().isDocumentOpen(t.documentId)&&this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus)"loaded"===r&&t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=Ri(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Ni(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Ti(t);if(a){const r=Oi(Vi(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Ni(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=Ai(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}l?(this.updateStatus(s,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(s,"password-required")}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?Ri(t):null,n=e=>{s.isDocumentOpen(e)&&s.closeDocument(e).wait(()=>{},()=>{})};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Hi.id="chapter-manager";let Ki=Hi;function ji(e,t){if(e===t)return!0;if(e.totalHeight!==t.totalHeight||e.totalWidth!==t.totalWidth||e.pageGap!==t.pageGap||e.items.length!==t.items.length)return!1;for(let s=0;s<e.items.length;s++){const r=e.items[s],n=t.items[s];if(r.globalPageIndex!==n.globalPageIndex||r.isPlaceholder!==n.isPlaceholder||r.chapterId!==n.chapterId||r.localPageIndex!==n.localPageIndex||r.pdfDocumentId!==n.pdfDocumentId||r.pdfPageIndex!==n.pdfPageIndex||r.offsetTop!==n.offsetTop||r.width!==n.width||r.height!==n.height)return!1}return!0}const Xi=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,ji),this.visibleChange$=n.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.lastLoadIndicesKey="",this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Ki.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){this.config={placeholderPageHeight:e.placeholderPageHeight??1200,placeholderPageWidth:e.placeholderPageWidth??900,bufferSize:e.bufferSize??2,pageGap:e.pageGap??20},this.virtualPageMap=this.chapterManager.provides().getVirtualPageMap(),this.rebuildOffsets(),this.chapterManagerUnsubs.push(this.chapterManager.provides().onManifestChange(({map:e})=>{this.virtualPageMap=e,this.pageSizes.clear(),this.lastLoadIndicesKey="",this.rebuildOffsets(),this.syncReadyChapterSizes(),this.recomputeVisible()}),this.chapterManager.provides().onChapterStatusChange(e=>{"loaded"===e.status&&this.harvestChapterSizes(e.chapterId),"loaded"!==e.status&&"closed"!==e.status&&"error"!==e.status&&"password-required"!==e.status||(this.refreshLayout(),"loaded"===e.status&&this.viewportEl&&(this.lastLoadIndicesKey="",this.pushVisibleLoads()))})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const s=this.chapterManager.provides(),r=s.getChapter(e);if(!r)return!0;const n=Ei(r,t);return!s.isSegmentLoaded(e,n)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);if(0===e.length)return;const t=this.chapterManager.provides(),s=t.visibleRangeNeedsSegmentLoad(e),r=e.join(",");(r!==this.lastLoadIndicesKey||s)&&(this.lastLoadIndicesKey=r,t.setVisibleGlobalPages(e))}syncReadyChapterSizes(){for(const e of this.chapterManager.provides().getManifest().chapters)("loaded"===this.chapterManager.provides().getChapterStatus(e.chapterId)||this.isChapterDocumentReady(e.chapterId))&&this.harvestChapterSizes(e.chapterId);this.refreshLayout()}onDocumentLoaded(e){var t;const{chapterId:s}=Di(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0))return;const r=this.documentManager.provides();r.getActiveDocumentId()||r.setActiveDocument(e),this.harvestChapterSizes(s),this.refreshLayout(),this.lastLoadIndicesKey="",this.pushVisibleLoads()}onDocumentClosed(e){var t;const{chapterId:s}=Di(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(s).length)??0)&&(this.dropChapterSizes(s),this.refreshLayout())}buildCapability(){return{registerViewport:e=>this.bindViewport(e),reportChapterPageSizes:(e,t)=>this.applyChapterPageSizes(e,t),getLayout:()=>this.computeLayout(),getCurrentGlobalPageIndex:()=>this.currentGlobalPageIndex,getVisibleGlobalPageIndices:()=>this.currentVisible.slice(),scrollToGlobalPageIndex:(e,t)=>this.scrollToIndex(e,t),scrollToChapter:(e,t)=>this.scrollToChapter(e,t),scrollToGlobalPageNumber:(e,t)=>this.scrollToGlobalNumber(e,t),scrollToGlobalPdfPoint:(e,t,s)=>this.scrollToGlobalPdfPoint(e,t,s),onLayoutChange:this.layoutChange$.on,onVisibleChange:this.visibleChange$.on}}destroy(){var e;super.destroy();for(const t of this.chapterManagerUnsubs)t();this.chapterManagerUnsubs=[],null==(e=this.viewportObservers)||e.unbind(),this.viewportObservers=null,this.viewportEl=null,this.lastLoadIndicesKey="",this.layoutChange$.clear(),this.visibleChange$.clear()}getPageSize(e){return this.pageSizes.get(e)??{width:this.config.placeholderPageWidth,height:this.config.placeholderPageHeight}}rebuildOffsets(){if(!this.virtualPageMap)return this.offsets=[],this.totalHeight=0,void(this.totalWidth=0);const e=this.virtualPageMap.totalPages;this.offsets=new Array(e);let t=0,s=0;for(let r=0;r<e;r++){const{width:e,height:n}=this.getPageSize(r);this.offsets[r]=t,t+=n+this.config.pageGap,e>s&&(s=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=s,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let s=!1;for(const r of t){const t=this.virtualPageMap.toGlobal(e,r.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===r.width&&n.height===r.height||(this.pageSizes.set(t.globalPageIndex,{width:r.width,height:r.height}),s=!0)}if(s){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const s=(this.offsets[e]??0)-t;0!==s&&(this.viewportEl.scrollTop+=s)}this.recomputeVisible()}}getDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){if(!this.virtualPageMap)return;const s=this.chapterManager.provides(),r=s.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!r||0===n.length)return;const a=Ui(r),i=this.documentManager.provides(),o=[],l=(e,t,s,r)=>{var n;const a=i.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let i=0;i<r;i++){const e=a.pages[s+i];(null==e?void 0:e.size)&&o.push({localPageIndex:t+i,width:e.size.width*l,height:e.size.height*l})}return o.length>0};if(a)for(const h of a.segments){if(!s.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else s.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];if(!t||"loaded"!==t.status)return;const{chapterId:s}=Di(e);this.chapterManager.provides().getChapter(s)&&this.harvestChapterSizes(s)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const s of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(s.globalPageIndex)&&(t=!0);t&&(this.rebuildOffsets(),this.recomputeVisible())}bindViewport(e){var t;if(null==(t=this.viewportObservers)||t.unbind(),this.viewportEl=e,this.viewportObservers=null,!e)return;const s=()=>this.recomputeVisible(),r=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",s,{passive:!0}),r.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",s),r.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const s=this.config.bufferSize,r=Math.max(0,e[0]-s),n=Math.min(t-1,e[e.length-1]+s),a=[];for(let i=r;i<=n;i++)a.push(i);return a}recomputeVisible(){if(!this.viewportEl||!this.virtualPageMap)return;const e=this.virtualPageMap.totalPages;if(0===e)return this.currentVisible=[],this.currentGlobalPageIndex=0,void this.layoutChange$.emit(this.computeLayout());const t=this.viewportEl.scrollTop,s=t+this.viewportEl.clientHeight,r=this.findFirstVisibleIndex(t);let n=r;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=s)break;n++}const a=[];let i=r,o=-1;for(let l=r;l<n;l++){a.push(l);const e=this.offsets[l],r=e+this.getPageSize(l).height,n=Math.max(0,Math.min(r,s)-Math.max(e,t));n>o&&(o=n,i=l)}this.currentVisible=a,this.currentGlobalPageIndex=i,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:i}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,s=this.offsets.length-1,r=0;for(;t<=s;){const n=t+s>>1;this.offsets[n]<=e?(r=n,t=n+1):s=n-1}return r}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),s=this.currentVisible[this.currentVisible.length-1]??-1,r=Math.min(this.offsets.length-1,(s>=0?s:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=r;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),s=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),r=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==s?void 0:s.documentId,pdfPageIndex:null==s?void 0:s.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:r})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:n,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const s=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:s,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,s){var r;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==s?void 0:s.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,s);const i=this.pageSizes.get(e),o=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=o?null==(r=this.documentManager.provides().getDocument(o.documentId))?void 0:r.pages[o.pageIndex]:void 0;if(!i||!l)return void this.scrollToIndex(e,s);const h=i.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==s?void 0:s.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.firstIndexOfChapter(e);if(s<0)return;const r=this.chapterManager.provides(),n=r.getChapter(e),a=this.virtualPageMap.atIndex(s);if(n&&a){const t=Ei(n,a.localPageIndex);r.ensureSegmentLoaded(e,t)}else r.ensureChapterLoaded(e);this.scrollToIndex(s,t)}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const s=this.virtualPageMap.byGlobalNumber(e);s&&this.scrollToIndex(s.globalPageIndex,t)}};Xi.id="chapter-scroll";let Yi=Xi;function Zi(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Ji(e,t){const s=e.origin.y,r=e.origin.y+e.size.height,n=t.origin.y,a=t.origin.y+t.size.height,i=Math.max(r,a)-Math.min(s,n);return i<=0?0:Math.max(0,Math.min(r,a)-Math.max(s,n))/i}function Qi(e,t){var s,r;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const n=(null==(s=e.rectsPdfCoord)?void 0:s.length)?e.rectsPdfCoord:[e.rectPdfCoord],a=(null==(r=t.rectsPdfCoord)?void 0:r.length)?t.rectsPdfCoord:[t.rectPdfCoord],i=e.markerAnchor??Zi(n),o=t.markerAnchor??Zi(a);if(Math.hypot(i.x-o.x,i.y-o.y)<=6)return!0;for(const l of n)for(const e of a){if(Ji(l,e)<.5)continue;const t=Math.max(l.origin.x,e.origin.x);if(Math.min(l.origin.x+l.size.width,e.origin.x+e.size.width)-t>.25*Math.min(l.size.width,e.size.width))return!0}return!1}const eo=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.change$=n.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(Yi.id),this.chapterManager=this.registry.getPlugin(Li.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){var s;if(this.config=t,null==(s=t.callbacks)?void 0:s.load)try{const e=await t.callbacks.load();for(const t of e)this.entries.set(t.id,t);this.change$.emit(this.list())}catch(r){this.logger.error(e.id,"Load","Failed to load paragraph bookmarks",r)}}buildCapability(){return{addBookmark:e=>this.addBookmark(e),removeBookmark:e=>this.removeBookmark(e),updateBookmark:(e,t)=>this.updateBookmark(e,t),listBookmarks:()=>this.list(),getBookmark:e=>this.entries.get(e)??null,scrollToBookmark:e=>this.scrollToBookmark(e),requestRemoveBookmark:e=>this.requestRemoveBookmark(e),listBookmarksForChapter:e=>this.listBookmarksForChapter(e),replaceBookmarksForChapter:(e,t)=>this.replaceBookmarksForChapter(e,t),onBookmarksChange:this.change$.on}}addBookmark(e){for(const r of this.entries.values())if(Qi(r.anchor,e.anchor))return r;const t=e.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s={id:t,label:e.label,anchor:e.anchor,metadata:e.metadata,createdAt:Date.now()};return this.entries.set(t,s),this.notifyAndPersist(),s}removeBookmark(e){var t,s,r;this.entries.delete(e)&&(this.notifyAndPersist(),null==(r=null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.onRemoveSuccess)||r.call(s,e))}async requestRemoveBookmark(t){var s,r;const n=this.entries.get(t);if(!n)return!1;const a=null==(r=null==(s=this.config)?void 0:s.callbacks)?void 0:r.onRequestRemove;if(a)try{if(!(await a(n)))return!1}catch(i){return this.logger.error(e.id,"RequestRemove","callback failed",i),!1}return this.removeBookmark(t),!0}updateBookmark(e,t){const s=this.entries.get(e);s&&(this.entries.set(e,{...s,...t}),this.notifyAndPersist())}list(){return Array.from(this.entries.values()).sort((e,t)=>e.createdAt-t.createdAt)}listBookmarksForChapter(e){return this.list().filter(t=>t.anchor.chapterId===e)}replaceBookmarksForChapter(e,t){for(const[s,r]of this.entries.entries())r.anchor.chapterId===e&&this.entries.delete(s);for(const s of t)s.anchor.chapterId===e&&this.entries.set(s.id,s);this.notifyAndPersist()}notifyAndPersist(){var t,s;const r=this.list();this.change$.emit(r),(null==(s=null==(t=this.config)?void 0:t.callbacks)?void 0:s.persist)&&Promise.resolve(this.config.callbacks.persist(r)).catch(t=>this.logger.error(e.id,"Persist","persist callback rejected",t))}async scrollToBookmark(e){const t=this.entries.get(e);if(!t)return;const s=this.chapterScroll.provides(),r=this.chapterManager.provides();await r.ensureAllSegmentsLoaded(t.anchor.chapterId);let n=t.anchor.globalPageIndex;if(void 0===n){const e=this.chapterManager.provides().getVirtualPageMap().toGlobal(t.anchor.chapterId,t.anchor.localPageIndex);if(!e)return;n=e.globalPageIndex}const a=function(e){if(e.markerAnchor)return e.markerAnchor.y;const t=e.rectPdfCoord;return t.origin.y+t.size.height}(t.anchor);await async function(e,t,s){e.scrollToGlobalPageIndex(t),await function(e,t,s=2500){const r=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return r?Promise.resolve(r):new Promise(r=>{const n=setTimeout(()=>{a(),r(null)},s),a=e.onLayoutChange(e=>{const s=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);s&&(clearTimeout(n),a(),r(s))})})}(e,t),e.scrollToGlobalPdfPoint(t,s,{marginTop:80})}(s,n,a)}};eo.id="paragraph-bookmark";let to=eo;function so(e,t){const s=e;return!1===e?{...t,enabled:!1}:!0===e||void 0===e?{...t,enabled:t.enabled??!0}:{...t,...s,enabled:!1!==(null==s?void 0:s.enabled)}}function ro(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function no(e,t){return`${e}#s${t}`}function ao(e,t){const s=function(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ro(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const s=function(e){const[t,s]=e.localPageRange;return s-t+1}(e),r=(o=t,(i=s)<=0||o<=0?0:Math.ceil(i/o)),n=ro(e.source)?e.source.urls:void 0,a=[];var i,o;for(let l=0;l<r;l++){const r=l*t,i=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:r,localPageEnd:i,documentId:no(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT,r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT,function(){const e=so(void 0,{enabled:!0}),t=so(void 0,{enabled:!0}),s=so(void 0,{enabled:!0}),r=so(void 0,{enabled:!0,min:.5,max:3,initial:1}),n=so(!1!==e.enabled||!1!==s.enabled,{enabled:!0});null==void 0||(void 0).background}();function io(e){const t=new Uint8Array(e);let s="";for(let r=0;r<t.length;r++)s+=String.fromCharCode(t[r]);return btoa(s)}function oo(e){return{bookmarks:!1!==(null==e?void 0:e.bookmarks),notes:!1!==(null==e?void 0:e.notes),markup:!1!==(null==e?void 0:e.markup)}}function lo(e){return new Promise((t,s)=>{e.wait(e=>t(e),e=>s(e))})}function ho(e){var t,r,n,a;return{annotation:null==(t=e.getPlugin(s.AnnotationPlugin.id))?void 0:t.provides(),note:null==(r=e.getPlugin(ci.id))?void 0:r.provides(),bookmark:null==(n=e.getPlugin(to.id))?void 0:n.provides(),chapterManager:null==(a=e.getPlugin(na.id))?void 0:a.provides()}}async function co(e,t,s){if(!s||!e)return;const r=e.getSegmentPlan(t)?await e.ensureAllSegmentsLoaded(t):await e.ensureChapterLoaded(t);if("loaded"!==r)throw new Error(`章节 ${t} 未加载成功(${r}),无法导入/导出划线`)}async function uo(e,t,s){const r=oo(s),{annotation:n,note:a,bookmark:i,chapterManager:o}=ho(e),l={chapterId:t};if(r.bookmarks){if(!i)throw new Error("paragraph-bookmark 插件未注册");l.bookmarks=i.listBookmarksForChapter(t)}if(r.notes){if(!a)throw new Error("note 插件未注册");l.notes=a.listNotesForChapter(t)}if(r.markup){if(!n)throw new Error("annotation 插件未注册");await co(o,t,!1!==(null==s?void 0:s.ensureChapterLoaded));const e=await async function(e,t,s){const r=t.getSegmentPlan(s);if(!r)return lo(e.forDocument(s).exportAnnotations());const n=[];for(const a of r.segments){if(!t.isSegmentLoaded(s,a.index))continue;const r=await lo(e.forDocument(a.documentId).exportAnnotations());for(const e of r){const t=e.annotation.pageIndex;n.push({...e,annotation:{...e.annotation,pageIndex:t+a.localPageStart}})}}return n}(n,o,t);l.markup=function(e){return e.map(e=>{if(!(e.ctx&&"data"in e.ctx&&e.ctx.data instanceof ArrayBuffer))return{annotation:e.annotation};const t=e.ctx;return{annotation:e.annotation,ctx:{dataBase64:io(t.data),mimeType:t.mimeType}}})}(e)}return l}async function po(e,t,s){const r=oo(s),n=(null==s?void 0:s.mode)??"replace",{annotation:a,note:i,bookmark:o,chapterManager:l}=ho(e),h=t.chapterId;if(r.bookmarks&&t.bookmarks){if(!o)throw new Error("paragraph-bookmark 插件未注册");if("replace"===n)o.replaceBookmarksForChapter(h,t.bookmarks);else for(const e of t.bookmarks)o.addBookmark(e)}if(r.notes&&t.notes){if(!i)throw new Error("note 插件未注册");if("replace"===n)i.replaceNotesForChapter(h,t.notes);else for(const e of t.notes)i.registerNote(e)}if(r.markup&&t.markup){if(!a)throw new Error("annotation 插件未注册");await co(l,h,!1!==(null==s?void 0:s.ensureChapterLoaded)),function(e,t,s,r,n){const a=t.getSegmentPlan(s);if(!a){const t=e.forDocument(s);return"replace"===n&&t.deleteAllAnnotations(),void t.importAnnotations(r)}const i=t.getChapter(s);if(!i)return;const o=new Map;for(const l of r){const e=l.annotation.pageIndex,t=ao(i,e),s=a.segments[t];if(!s)continue;const r=o.get(t)??[];r.push({...l,annotation:{...l.annotation,pageIndex:e-s.localPageStart}}),o.set(t,r)}for(const l of a.segments){const t=e.forDocument(l.documentId),s=o.get(l.index)??[];"replace"===n&&t.deleteAllAnnotations(),s.length>0&&t.importAnnotations(s)}}(a,l,h,function(e){return e.map(e=>{var t;if(!(null==(t=e.ctx)?void 0:t.dataBase64))return{annotation:e.annotation};const s=function(e){const t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return s.buffer}(e.ctx.dataBase64);return{annotation:e.annotation,ctx:{data:s,...e.ctx.mimeType?{mimeType:e.ctx.mimeType}:{}}}})}(t.markup),n)}(null==s?void 0:s.persistNotes)&&i&&await s.persistNotes(i.listAllNotes()),(null==s?void 0:s.persistBookmarks)&&o&&await s.persistBookmarks(o.listBookmarks())}function go(e){return JSON.stringify(e,null,2)}function mo(e){return JSON.stringify(e,null,2)}function fo(e,t){const s=new Blob([t],{type:"application/json;charset=utf-8"}),r=URL.createObjectURL(s),n=document.createElement("a");n.href=r,n.download=e,n.click(),URL.revokeObjectURL(r)}r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT,r.PdfAnnotationSubtype.HIGHLIGHT,r.PdfAnnotationSubtype.UNDERLINE,r.PdfAnnotationSubtype.SQUIGGLY,r.PdfAnnotationSubtype.STRIKEOUT;function vo(e){const[t,s]=e.localPageRange;return s-t+1}function Po(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Io(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Po(t)?t.segmentPageThreshold:null}function bo(e,t){return`${e}#s${t}`}function So(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const s=e.slice(0,t),r=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(r)||r<0?{chapterId:e,segmentIndex:null}:{chapterId:s,segmentIndex:r}}function Co(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function wo(e){const t=Io(e);if(!t)return null;const s=vo(e),r=Co(s,t),n=Po(e.source)?e.source.urls:void 0,a=[];for(let i=0;i<r;i++){const r=i*t,o=Math.min(r+t-1,s-1);if(r>=s)break;a.push({index:i,url:(null==n?void 0:n[i])??"",localPageStart:r,localPageEnd:o,documentId:bo(e.chapterId,i)})}return{chapterId:e.chapterId,threshold:t,pageCount:s,segments:a}}function yo(e,t){const s=wo(e);if(!s)return{documentId:e.chapterId,pageIndex:t};const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!r){const r=s.segments[s.segments.length-1];return r?{documentId:r.documentId,pageIndex:t-r.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:r.documentId,pageIndex:t-r.localPageStart}}function Mo(e,t){const s=wo(e);if(!s)return 0;const r=s.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==r?void 0:r.index)??Math.floor(t/s.threshold)}function xo(e){var t;const s=Io(e);if(!s)return[];const r=[],{chapterId:n}=e,a=vo(e);s<=0&&r.push(`${n}: segmentPageThreshold must be > 0`);const i=e.source;if(!Po(i))return r;0===i.urls.length&&r.push(`${n}: source.urls must not be empty`);const o=Co(a,s);i.urls.length!==o&&r.push(`${n}: source.urls.length (${i.urls.length}) must equal ceil(pageCount/threshold) (${o})`);for(let l=0;l<i.urls.length;l++)(null==(t=i.urls[l])?void 0:t.trim())||r.push(`${n}: source.urls[${l}] is empty`);return r}const Lo={kind:"first-wins"};function $o(e,t,s){if(1===t.length)return t[0].chapterId;switch(s.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const s=t.find(t=>{var s;return null==(s=t.ownedGlobalPages)?void 0:s.includes(e)});return s?s.chapterId:t[0].chapterId}case"custom":return s.resolve(e,t)}}class ko{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const s=this._byChapter.get(e);return s?s.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const s=null==(t=this._byChapter.get(e))?void 0:t[0];return s?this._pages.indexOf(s):-1}}function Do(e,t=Lo){const s=function(e,t=Lo){const s=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let r=e;r<=t;r++){const e=s.get(r);e?e.push(n):s.set(r,[n])}}const r=new Map;for(const[n,a]of s)r.set(n,$o(n,a,t));return r}(e,t),r=new Map;for(const o of e.chapters)r.set(o.chapterId,o);const n=Array.from(s.keys()).sort((e,t)=>e-t),a=[];let i=0;for(const o of n){const e=s.get(o),t=r.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(o-n);a.push({globalPageIndex:i++,globalPageNumber:o,chapterId:e,localPageIndex:h})}return new ko(a)}const Uo=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Lo,this.chapterStatus=new Map,this.chapterErrorMessages=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.pendingVisibleUrlRepumps=new Set,this.unloadTimer=null,this.documentManagerUnsubs=[],this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.lastVisibleIndicesKey="",this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Lo,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=So(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=So(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=So(e.documentId);this.findChapter(t)&&this.handleDocumentError(e.documentId,t,e.code,e.message)})),this.setManifestInternal(e.manifest),e.unloadTimeoutMs&&e.unloadTimeoutMs>0){const t=Math.max(5e3,Math.floor(e.unloadTimeoutMs/4));this.unloadTimer=setInterval(()=>this.collectIdleChapters(),t)}}buildCapability(){return{setManifest:(e,t)=>{t&&(this.overlapStrategy=t),this.setManifestInternal(e)},getManifest:()=>this.manifest,getVirtualPageMap:()=>this.virtualPageMap,setVisibleGlobalPages:e=>this.handleVisibleChange(e),visibleRangeNeedsSegmentLoad:e=>this.visibleRangeNeedsSegmentLoad(e),shouldShowChapterLoadError:(e,t)=>this.shouldShowChapterLoadError(e,t),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const s=this.findChapter(e);return s?yo(s,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?wo(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),isSegmentLoadPending:(e,t)=>this.isSegmentLoadPending(e,t),getChapterErrorMessage:e=>this.chapterErrorMessages.get(e),getChapterStatus:e=>this.chapterStatus.get(e)??"idle",getChapter:e=>this.findChapter(e),onChapterStatusChange:this.statusChange$.on,onManifestChange:this.manifestChange$.on}}destroy(){super.destroy();for(const e of this.documentManagerUnsubs)e();this.documentManagerUnsubs=[],this.unloadTimer&&clearInterval(this.unloadTimer),this.unloadTimer=null,this.clearVisibleSegmentBacklog(),this.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const s=function(e){const t=function(e){const t=[],s=e=>{for(const r of e){const{children:e,...n}=r;t.push(n),(null==e?void 0:e.length)&&s(e)}};return s(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const s of e)if(null==(t=s.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${s.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const r=function(e){const t=[],s=new Set;for(const r of e.chapters){s.has(r.chapterId)&&t.push(`Duplicate chapterId: ${r.chapterId}`),s.add(r.chapterId);const[e,n]=r.globalPageRange,[a,i]=r.localPageRange;if(e>n&&t.push(`${r.chapterId}: invalid globalPageRange [${e},${n}]`),a>i&&t.push(`${r.chapterId}: invalid localPageRange [${a},${i}]`),n-e!==i-a&&t.push(`${r.chapterId}: page-count mismatch (global ${n-e+1} vs local ${i-a+1})`),r.ownedGlobalPages)for(const s of r.ownedGlobalPages)(s<e||s>n)&&t.push(`${r.chapterId}: ownedGlobalPages contains ${s} outside range`);t.push(...xo(r))}return t}(s);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(s.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterErrorMessages.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of s.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=s,this.lastVisibleIndicesKey="",this.clearVisibleSegmentBacklog(),this.virtualPageMap=Do(s,this.overlapStrategy),this.manifestChange$.emit({manifest:s,map:this.virtualPageMap}),this.eagerPrefetchFromManifest()}eagerPrefetchFromManifest(){const e=this.config.prefetchChapters??0;if(e<=0||0===this.manifest.chapters.length)return;const t=Date.now(),s=Math.min(e,this.manifest.chapters.length);for(let r=0;r<s;r++){const e=this.manifest.chapters[r];this.chapterLastUsed.set(e.chapterId,t),this.resolveChapterUrls(e).catch(()=>{})}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?wo(t):null}anySegmentOpen(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();return t?t.segments.some(e=>s.isDocumentOpen(e.documentId)):s.isDocumentOpen(e)}isSegmentDocumentOpen(e,t){const s=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!s)return 0===t&&r.isDocumentOpen(e);const n=s.segments[t];return!!n&&r.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var s;const r=this.getSegmentPlanForChapter(e);return r?(null==(s=r.segments[t])?void 0:s.documentId)??null:0===t?e:null}isAnySegmentWorkPending(e){if(this.visibleSegmentBacklog.some(t=>t.chapterId===e))return!0;const t=this.getSegmentPlanForChapter(e);return t?t.segments.some(t=>this.isSegmentLoadPending(e,t.index)):this.isSegmentLoadPending(e,0)}isSegmentLoadPending(e,t){const s=this.resolveSegmentDocumentId(e,t);return!!s&&(!!this.pendingSegmentLoadPromises.has(s)||!(0!==t||!this.pendingChapterLoadPromises.has(e)))}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!t)return void(s.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));if(t.segments.some(e=>s.isDocumentOpen(e.documentId)))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loaded");if(t.segments.some(e=>{const t=this.coreState.core.documents[e.documentId];return"loading"===(null==t?void 0:t.status)})||this.isAnySegmentWorkPending(e))return"error"===this.chapterStatus.get(e)&&this.chapterErrorMessages.delete(e),void this.updateStatus(e,"loading");const r=this.chapterStatus.get(e);"loaded"!==r?"password-required"!==r&&"error"!==r&&this.updateStatus(e,"idle"):this.updateStatus(e,"idle")}visibleRangeNeedsSegmentLoad(e){if(!this.virtualPageMap)return!1;for(const t of e){const e=this.virtualPageMap.atIndex(t);if(!e)continue;const s=this.findChapter(e.chapterId);if(!s)continue;const r=Mo(s,e.localPageIndex);if(!this.isSegmentDocumentOpen(e.chapterId,r))return!0}return!1}shouldShowChapterLoadError(e,t){return 0===t&&("error"===this.chapterStatus.get(e)&&!this.isAnySegmentWorkPending(e))}clearVisibleSegmentBacklog(){this.visibleSegmentBacklog=[],this.activeVisibleSegmentLoads=0,this.pendingVisibleUrlRepumps.clear()}chapterNeedsResolvedUrls(e){var t;const s=e.source;return!Po(s)&&((!s||!("url"in s||"buffer"in s||"load"in s))&&!!(null==(t=this.config.chapterPdfLoader)?void 0:t.loadChapterUrls))}ensureVisibleChapterUrls(e){const{chapterId:t}=e;return!this.chapterNeedsResolvedUrls(e)||(!!this.chapterUrlsCache.has(t)||(this.pendingVisibleUrlRepumps.has(t)||(this.pendingVisibleUrlRepumps.add(t),this.resolveChapterUrls(e).catch(()=>{}).finally(()=>{this.pendingVisibleUrlRepumps.delete(t),this.pumpVisibleSegmentBacklog()})),!1))}segmentStartGlobalIndex(e,t){var s;if(!this.virtualPageMap)return Number.MAX_SAFE_INTEGER;const r=this.findChapter(e);if(!r)return Number.MAX_SAFE_INTEGER;const n=wo(r),a=(null==(s=null==n?void 0:n.segments[t])?void 0:s.localPageStart)??0,i=this.virtualPageMap.toGlobal(e,a);if(i)return i.globalPageIndex;return 1e4*this.manifest.chapters.findIndex(t=>t.chapterId===e)+t}scheduleVisibleSegmentLoads(e){const t=[...e].sort((e,t)=>e.priority-t.priority),s=new Set,r=new Map,n=[];for(const o of t){const e=`${o.chapterId}:${o.segmentIndex}`;s.has(e)||(s.add(e),this.isSegmentDocumentOpen(o.chapterId,o.segmentIndex)||(r.has(o.chapterId)||(r.set(o.chapterId,[]),n.push(o.chapterId)),r.get(o.chapterId).push({chapterId:o.chapterId,segmentIndex:o.segmentIndex})))}const a=[];let i=!0;for(;i;){i=!1;for(const e of n){const t=r.get(e);t&&0!==t.length&&(a.push(t.shift()),i=!0)}}this.visibleSegmentBacklog=a,this.pumpVisibleSegmentBacklog()}pumpVisibleSegmentBacklog(){const e=Math.max(1,this.config.maxConcurrentSegmentLoads??1);let t=0;for(;this.activeVisibleSegmentLoads<e&&this.visibleSegmentBacklog.length>0;){const e=this.visibleSegmentBacklog.shift();if(this.isSegmentDocumentOpen(e.chapterId,e.segmentIndex))continue;if(this.isSegmentLoadPending(e.chapterId,e.segmentIndex))continue;const s=this.findChapter(e.chapterId);if(!s)continue;if(!this.ensureVisibleChapterUrls(s)){if(this.visibleSegmentBacklog.push(e),t++,t>=this.visibleSegmentBacklog.length)break;continue}t=0,this.prepareChapterForSegmentLoad(e.chapterId),this.activeVisibleSegmentLoads++;let r=!1;const n=()=>{r||(r=!0,this.activeVisibleSegmentLoads--,this.pumpVisibleSegmentBacklog())};this.loadSegmentNow(e.chapterId,e.segmentIndex,n).finally(n)}}prepareChapterForSegmentLoad(e){this.chapterLastUsed.set(e,Date.now());const t=this.chapterStatus.get(e);"error"!==t&&"closed"!==t&&"loaded"!==t||("error"===t&&this.chapterErrorMessages.delete(e),this.updateStatus(e,"idle"))}handleVisibleChange(e){if(!this.virtualPageMap||0===e.length)return;const t=e.join(","),s=this.visibleRangeNeedsSegmentLoad(e);if(t===this.lastVisibleIndicesKey&&!s)return;this.lastVisibleIndicesKey=t;const r=Date.now(),n=e[Math.floor(e.length/2)]??e[0],a=new Set,i=new Map,o=(e,t)=>{if(t<0)return;const s=this.findChapter(e);if(!s)return;const r=wo(s);if(r&&t>=r.segments.length)return;const a=`${e}:${t}`,o=this.segmentStartGlobalIndex(e,t),l=Math.abs(o-n),h=i.get(a);(void 0===h||l<h)&&i.set(a,l)};for(const d of e){const e=this.virtualPageMap.atIndex(d);if(!e)continue;a.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const s=Mo(t,e.localPageIndex);o(e.chapterId,s),this.resolveChapterUrls(t).catch(()=>{})}if(0===a.size)return;const l=this.virtualPageMap.atIndex(n);for(const d of a)this.chapterLastUsed.set(d,r);const h=[...i.entries()].map(([e,t])=>{const[s,r]=e.split(":");return{chapterId:s,segmentIndex:Number.parseInt(r,10),priority:t}}).filter(e=>e.chapterId&&Number.isFinite(e.segmentIndex));if(this.scheduleVisibleSegmentLoads(h),l){const e=this.findChapter(l.chapterId);if(e){const t=Mo(e,l.localPageIndex);this.isSegmentDocumentOpen(l.chapterId,t)||(this.prepareChapterForSegmentLoad(l.chapterId),this.loadSegmentNow(l.chapterId,t).finally(()=>{this.pumpVisibleSegmentBacklog()}))}}if(this.config.autoActivateOnLoad??1){const e=this.virtualPageMap.atIndex(n);if(e){const t=yo(this.findChapter(e.chapterId),e.localPageIndex);if(this.documentManager.provides().isDocumentOpen(t.documentId)){this.documentManager.provides().getActiveDocumentId()!==t.documentId&&this.documentManager.provides().setActiveDocument(t.documentId)}}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[s,r]of this.chapterStatus){if("loaded"!==r)continue;t-(this.chapterLastUsed.get(s)??0)>e&&this.closeChapter(s)}}ensureChapterLoaded(e){return this.loadSegmentNow(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const s of t.segments){const t=await this.loadSegmentNow(e,s.index);if("loaded"!==t)return t}return"loaded"})():this.loadSegmentNow(e,0)}ensureSegmentLoaded(e,t){return this.loadSegmentNow(e,t)}loadSegmentNow(e,t,s){this.prepareChapterForSegmentLoad(e);const r=this.findChapter(e);if(!r)return Promise.resolve("error");const n=wo(r);if(!n)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=n.segments.length)return Promise.resolve("error");const a=n.segments[t],i=a.documentId;if(this.documentManager.provides().isDocumentOpen(i))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(i);if(o)return o;const l=this.startLoadSegment(r,a,s).finally(()=>{this.pendingSegmentLoadPromises.delete(i)});return this.pendingSegmentLoadPromises.set(i,l),l}ensureSingleDocumentChapter(e){const t=e.chapterId,s=this.pendingChapterLoadPromises.get(t);if(s)return s;const r=this.chapterStatus.get(t)??"idle";if("loaded"===r)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===r)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,s=this.chapterUrlsCache.get(t);if(s)return s;const r=this.pendingChapterUrlsPromises.get(t);if(r)return r;const n=(async()=>{const s=e.source;if(Po(s)){const e=[...s.urls];return this.chapterUrlsCache.set(t,e),e}const r=this.config.chapterPdfLoader;if(null==r?void 0:r.loadChapterUrls){const s=await r.loadChapterUrls(e);if(!Array.isArray(s)||0===s.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,s),s}throw new Error(`Chapter "${t}" requires chapterPdfLoader.loadChapterUrls, static source.urls, or source.url`)})();this.pendingChapterUrlsPromises.set(t,n);try{return await n}finally{this.pendingChapterUrlsPromises.delete(t)}}async openPayloadFromUrl(e,t,s){const r=s[t];if(!(null==r?void 0:r.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:s.length,urls:s,url:r};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:r}}async resolvePdfPayload(t,s){const r=t.source,n=this.config.chapterPdfLoader,a=Io(t);if(a){const r=Co(vo(t),a);if(s<0||s>=r)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${s} (expected 0..${r-1})`);const n=await this.resolveChapterUrls(t);if(n.length!==r){const[s,i]=t.globalPageRange;this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" loadChapterUrls returned ${n.length} URL(s), expected ${r} (= ceil((${i}-${s}+1) / ${a})). Check globalPageRange [${s},${i}] and segmentPageThreshold.`)}return this.openPayloadFromUrl(t,s,n)}if(0!==s)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(r){if(Po(r)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,s,e)}if("url"in r)return{url:r.url};if("buffer"in r)return{buffer:r.buffer};if("load"in r)return r.load()}if(null==n?void 0:n.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==n?void 0:n.loadPdf)return n.loadPdf(t,s);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,s,r){var n;const a=t.chapterId,i=(null==s?void 0:s.index)??0,o=(null==s?void 0:s.documentId)??a;let l=!1;this.chapterErrorMessages.delete(a),this.anySegmentOpen(a)||this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(n=this.passwordProvider)?void 0:n.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,h=await this.resolvePdfPayload(t,i),d=this.documentManager.provides(),c="url"in h?d.openDocumentUrl({documentId:o,url:h.url,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1}):d.openDocumentBuffer({documentId:o,buffer:h.buffer,name:s?`${t.title} (${s.index+1})`:t.title,password:e??void 0,autoActivate:!1});l||(l=!0,null==r||r());const u=await new Promise((e,t)=>{c.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{u.task.wait(()=>e(),e=>t(e))}),d.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(a),this.waitForTerminalStatus(a)}catch(h){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=h instanceof Error?h.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,h),0!==i||this.isAnySegmentWorkPending(a)||this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const s=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(s(this.chapterStatus.get(e)??"idle"))return;let r=null;r=this.statusChange$.on(t=>{t.chapterId===e&&s(t.status)&&(null==r||r(),r=null)})})}async handleDocumentError(t,s,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==r.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(s),{segmentIndex:r}=So(t);return void(e&&0!==r&&null!==r||this.updateStatus(s,"error"))}if(!this.passwordProvider)return void this.updateStatus(s,"password-required");const i=this.findChapter(s);if(!i)return;const o=(this.passwordAttempts.get(s)??0)+1;this.passwordAttempts.set(s,o);let l=null;try{l=await this.passwordProvider.resolvePassword(i,o-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${s}`,h)}if(!l)return void this.updateStatus(s,"password-required");this.updateStatus(s,"loading");this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})}closeChapter(e){const t=this.findChapter(e),s=this.documentManager.provides(),r=t?wo(t):null,n=e=>{if(s.isDocumentOpen(e)){s.closeDocument(e).wait(()=>{},()=>{})}};if(r)for(const a of r.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.chapterErrorMessages.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,s){const r=this.chapterStatus.get(e);"error"===t&&s?this.chapterErrorMessages.set(e,s):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),r!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&s?{error:{message:s}}:{}}))}};Uo.id="chapter-manager";let Eo=Uo;function Vo(e){const t=e.endPage-e.startPage+1;return{chapterId:e.chapterId,title:e.title,globalPageRange:[e.startPage,e.endPage],localPageRange:[0,t-1],...e.source?{source:e.source}:{},...null!=e.segmentPageThreshold?{segmentPageThreshold:e.segmentPageThreshold}:{},...e.encrypted?{encrypted:e.encrypted}:{}}}function No(e){const t=[],s=e=>{var r;for(const n of e)t.push(Vo(n)),(null==(r=n.children)?void 0:r.length)&&s(n.children)};return s(e),t}function To(e){return e.map(e=>{var t;return{id:e.chapterId,title:e.title,startPage:e.startPage,endPage:e.endPage,children:(null==(t=e.children)?void 0:t.length)?To(e.children):void 0}})}Object.defineProperty(exports,"EmbedPDF",{enumerable:!0,get:()=>t.EmbedPDF}),Object.defineProperty(exports,"useCapability",{enumerable:!0,get:()=>t.useCapability}),Object.defineProperty(exports,"useRegistry",{enumerable:!0,get:()=>t.useRegistry}),Object.defineProperty(exports,"usePdfiumEngine",{enumerable:!0,get:()=>y.usePdfiumEngine}),exports.CHAPTER_ANNOTATIONS_ARCHIVE_VERSION=1,exports.CallbackPasswordProvider=B,exports.ChapterManagerPlugin=Eo,exports.ChapterPdfViewer=_n,exports.ChapterTreePanel=zn,exports.DEFAULT_CHAPTER_TEXT_SELECTION_BACKGROUND="rgba(33, 150, 243)",exports.DEFAULT_CHAPTER_VIEWER_CONFIG={},exports.DEFAULT_CHAPTER_VIEWER_FEATURES=Ss,exports.PdfChapterViewport=$n,exports.applySelectionMarkup=V,exports.buildChapterViewerCatalog=function(e){return{tree:To(e),manifest:{chapters:No(e)}}},exports.buildParagraphBookmarkAnchor=cs,exports.chapterAnnotationsArchiveToJson=go,exports.chapterAnnotationsSnapshotToJson=mo,exports.chapterDescriptorFromTreeNode=Vo,exports.copyTextToClipboard=async function(e){var t;const s=e.trim();if(!s)return!1;try{if("undefined"!=typeof navigator&&(null==(t=navigator.clipboard)?void 0:t.writeText))return await navigator.clipboard.writeText(s),!0}catch{}if("undefined"==typeof document)return!1;try{const e=document.createElement("textarea");e.value=s,e.setAttribute("readonly",""),e.style.position="fixed",e.style.left="-9999px",document.body.appendChild(e),e.select();const t=document.execCommand("copy");return document.body.removeChild(e),t}catch{return!1}},exports.createChapterViewerBundle=xs,exports.createChapterViewerEditor=Cs,exports.createChapterViewerEditorOptions=function(e){const{features:t,...s}=Ms(ys(e));return s},exports.createPdfChapterEditor=Is,exports.defaultOverlapStrategy={kind:"first-wins"},exports.downloadChapterAnnotationsArchive=function(e,t="chapter-annotations.json"){fo(t,go(e))},exports.downloadChapterAnnotationsSnapshot=function(e,t){fo(t??`chapter-annotations-${e.chapterId}.json`,mo(e))},exports.downloadJsonFile=fo,exports.exportAllChapterAnnotations=async function(e,t,s){const r={};for(const n of t.chapters){const t=await uo(e,n.chapterId,s),{chapterId:a,...i}=t;r[n.chapterId]=i}return{version:1,exportedAt:(new Date).toISOString(),chapters:r}},exports.exportChapterAnnotations=uo,exports.flattenChapterTree=No,exports.importChapterAnnotations=po,exports.importChapterAnnotationsArchive=async function(e,t,s){if(1!==t.version)throw new Error(`不支持的归档版本 ${t.version},当前为 1`);for(const[r,n]of Object.entries(t.chapters))await po(e,{chapterId:r,...n},s)},exports.overlapStrategyForSamePageOwner=function(e){return"last"===e?{kind:"last-wins"}:{kind:"first-wins"}},exports.parseChapterAnnotationsArchiveJson=function(e){const t=JSON.parse(e);if(!t||"object"!=typeof t||!t.chapters)throw new Error("无效的章节标注 JSON");return t},exports.parseChapterAnnotationsSnapshotJson=function(e){const t=JSON.parse(e);if(!(null==t?void 0:t.chapterId))throw new Error("无效的章节标注 JSON:缺少 chapterId");return t},exports.toChapterTreeNodes=To;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|