@embedpdf-editor/vue3-chapter-viewer 1.0.4 → 1.0.6

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 CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),t=require("@embedpdf/core/vue"),r=require("@embedpdf/plugin-annotation"),s=require("@embedpdf/models"),n=require("@embedpdf/core"),a=require("@embedpdf/plugin-document-manager"),o=require("@embedpdf/plugin-interaction-manager"),i=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"),f=require("@embedpdf/plugin-commands"),m=require("@embedpdf/plugin-i18n"),v=require("@embedpdf/plugin-ui"),P=require("@embedpdf/plugin-interaction-manager/vue"),I=require("@embedpdf/plugin-rotate/vue"),C=require("@embedpdf/plugin-selection/vue"),b=require("@embedpdf/plugin-annotation/vue"),w=require("@embedpdf/plugin-redaction/vue"),S=require("@embedpdf/plugin-render/vue"),y=require("@embedpdf/engines/vue"),M={position:"relative",height:"100%",width:"100%"},x={userSelect:"none",WebkitUserSelect:"none"};function $(){var e;"undefined"!=typeof window&&(null==(e=window.getSelection())||e.removeAllRanges())}const L="#f1f5f9",D={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:4},strikeout:{offsetY:0}},k={highlight:s.PdfAnnotationSubtype.HIGHLIGHT,underline:s.PdfAnnotationSubtype.UNDERLINE,squiggly:s.PdfAnnotationSubtype.SQUIGGLY,strikeout:s.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 T(e){let t=1/0,r=1/0,s=-1/0,n=-1/0;for(const a of e)t=Math.min(t,a.origin.x),r=Math.min(r,a.origin.y),s=Math.max(s,a.origin.x+a.size.width),n=Math.max(n,a.origin.y+a.size.height);return{origin:{x:t,y:r},size:{width:s-t,height:n-r}}}function E(e,t,n,a,o){const i=n.forDocument(e),l=a.forDocument(e);if(!i||!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={...D[g=t],...null==(f=o)?void 0:f[g]},p=l.getFormattedSelection();var g,f;if(0===p.length)return!1;i.setLocked({type:r.LockModeType.Exclude,categories:["markup","shape"]});for(const r of p){const e=s.uuidV4(),n=u.color??c.color??c.strokeColor,a=u.opacity??c.opacity,o=u.thickness??c.strokeWidth,l=u.offsetY??0,h="underline"===t||"squiggly"===t||"strikeout"===t?U(r.segmentRects,l):r.segmentRects,d="underline"===t||"squiggly"===t||"strikeout"===t?T(h):r.rect;i.createAnnotation(r.pageIndex,{id:e,created:new Date,flags:["print"],type:k[t],..."highlight"===t?{blendMode:s.PdfBlendMode.Multiply}:{},strokeColor:n,opacity:a,...null!=o?{strokeWidth:o}:{},pageIndex:r.pageIndex,rect:d,segmentRects:h})}return l.clear(),!0}const A=new Set([s.PdfAnnotationSubtype.HIGHLIGHT,s.PdfAnnotationSubtype.UNDERLINE,s.PdfAnnotationSubtype.SQUIGGLY,s.PdfAnnotationSubtype.STRIKEOUT]);function F(e,t){const r=e;return!1===e?{...t,enabled:!1}:!0===e||void 0===e?{...t,enabled:t.enabled??!0}:{...t,...r,enabled:!1!==(null==r?void 0:r.enabled)}}function N(e){var t;const r=F(null==e?void 0:e.markup,{enabled:!0}),s=F(null==e?void 0:e.bookmarks,{enabled:!0}),n=F(null==e?void 0:e.notes,{enabled:!0}),a=F(null==e?void 0:e.zoom,{enabled:!0,min:.5,max:3,initial:1}),o=F(void 0===(null==e?void 0:e.selectionToolbar)?!1!==r.enabled||!1!==n.enabled:e.selectionToolbar,{enabled:!0});return{markup:r,bookmarks:s,notes:n,zoom:a,scrollViewport:{background:(null==(t=null==e?void 0:e.scrollViewport)?void 0:t.background)??L},selectionToolbar:o}}function O(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function z(e,t){return`${e}#s${t}`}function G(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return O(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=O(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:z(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}let R=class{constructor(e){this.cb=e}resolvePassword(e,t){return this.cb(e,t)}};const V="chapter-manager",_={id:V,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}};function B(e){const[t,r]=e.localPageRange;return r-t+1}function q(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function H(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return q(t)?t.segmentPageThreshold:null}function W(e,t){return`${e}#s${t}`}function j(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Y(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Z(e){const t=H(e);if(!t)return null;const r=B(e),s=Y(r,t),n=q(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:W(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function K(e,t){const r=Z(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function J(e,t){const r=Z(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function X(e){var t;const r=H(e);if(!r)return[];const s=[],{chapterId:n}=e,a=B(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!q(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=Y(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Q={kind:"first-wins"};function ee(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const re=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.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],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}=j(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=j(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=j(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?K(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Z(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...X(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=Q){const r=function(e,t=Q){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,ee(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new te(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Z(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=J(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=K(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=Z(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(q(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=H(t);if(a){const s=Y(B(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(q(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=j(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?Z(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};re.id="chapter-manager";let se=re;const ne={manifest:_,create:e=>new se(V,e),reducer:e=>e,initialState:{}},ae="chapter-scroll",oe={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 ie(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 r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function de(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ie(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=ie(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:le(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function ce(e){const[t,r]=e.localPageRange;return r-t+1}function ue(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function pe(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ue(t)?t.segmentPageThreshold:null}function ge(e,t){return`${e}#s${t}`}function fe(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function me(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function ve(e){const t=pe(e);if(!t)return null;const r=ce(e),s=me(r,t),n=ue(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:ge(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Pe(e,t){const r=ve(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Ie(e,t){const r=ve(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Ce(e){var t;const r=pe(e);if(!r)return[];const s=[],{chapterId:n}=e,a=ce(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!ue(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=me(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const be={kind:"first-wins"};function we(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let Se=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const ye=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=be,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??be,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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?Pe(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ve(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Ce(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=be){const r=function(e,t=be){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,we(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Se(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ve(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Ie(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=Pe(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=ve(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(ue(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=pe(t);if(a){const s=me(ce(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(ue(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=fe(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?ve(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};ye.id="chapter-manager";let Me=ye;function xe(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.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,xe),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Me.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.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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapterStatus(e);if("error"===s||"password-required"===s)return!0;const n=r.getChapter(e);if(!n)return!0;const a=function(e,t){const r=de(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(n,t);return!r.isSegmentLoaded(e,a)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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:r}=he(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=he(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}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 r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=de(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):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:r}=he(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.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 r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}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,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n),t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(a),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}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 r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};$e.id="chapter-scroll";let Le=$e;const De={manifest:oe,create:e=>new Le(ae,e),reducer:e=>e,initialState:{}},ke="note",Ue={id:ke,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 Te(e){const[t,r]=e.localPageRange;return r-t+1}function Ee(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ae(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ee(t)?t.segmentPageThreshold:null}function Fe(e,t){return`${e}#s${t}`}function Ne(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Oe(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function ze(e){const t=Ae(e);if(!t)return null;const r=Te(e),s=Oe(r,t),n=Ee(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:Fe(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Ge(e,t){const r=ze(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Re(e,t){const r=ze(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Ve(e){var t;const r=Ae(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Te(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!Ee(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=Oe(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const _e={kind:"first-wins"};function Be(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let qe=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-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.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingChapterLoadPromises=new Map,this.pendingSegmentLoadPromises=new Map,this.chapterUrlsCache=new Map,this.pendingChapterUrlsPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],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}=Ne(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Ne(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Ne(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?Ge(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ze(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Ve(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=_e){const r=function(e,t=_e){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Be(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new qe(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ze(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Re(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=Ge(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=ze(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(Ee(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Ae(t);if(a){const s=Oe(Te(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(Ee(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=Ne(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?ze(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};He.id="chapter-manager";let We=He;function je(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ye(e,t){return`${e}#s${t}`}function Ze(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Ke(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 r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=je(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:Ye(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Je(e){const[t,r]=e.localPageRange;return r-t+1}function Xe(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Qe(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Xe(t)?t.segmentPageThreshold:null}function et(e,t){return`${e}#s${t}`}function tt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function rt(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function st(e){const t=Qe(e);if(!t)return null;const r=Je(e),s=rt(r,t),n=Xe(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:et(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function nt(e,t){const r=st(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function at(e,t){const r=st(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function ot(e){var t;const r=Qe(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Je(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!Xe(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=rt(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const it={kind:"first-wins"};function lt(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let ht=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const dt=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=it,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??it,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=tt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=tt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=tt(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?nt(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?st(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...ot(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=it){const r=function(e,t=it){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,lt(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new ht(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?st(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=at(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=nt(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=st(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(Xe(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Qe(t);if(a){const s=rt(Je(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(Xe(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=tt(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?st(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};dt.id="chapter-manager";let ct=dt;function ut(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.height!==n.height)return!1}return!0}const pt=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,ut),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(ct.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.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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapterStatus(e);if("error"===s||"password-required"===s)return!0;const n=r.getChapter(e);if(!n)return!0;const a=function(e,t){const r=Ke(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(n,t);return!r.isSegmentLoaded(e,a)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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:r}=Ze(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=Ze(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}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 r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=Ke(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):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:r}=Ze(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.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 r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}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,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n),t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(a),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}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 r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};pt.id="chapter-scroll";let gt=pt;const ft=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(gt.id),this.chapterManager=this.registry.getPlugin(We.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(r){this.logger.error(e.id,"LoadNotes","Failed to load notes",r)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(r=>r.chapterId===e&&r.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,r;const s=this.notes.get(e);s&&(null==(r=(t=this.config.callbacks).onActivateNote)||r.call(t,e,s),this.noteActivated$.emit({noteId:e,anchor:s}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[r,s]of this.notes.entries())s.chapterId===e&&this.notes.delete(r);for(const r of t)r.chapterId===e&&this.notes.set(r.noteId,r);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:vt(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:r,onCreateNote:s}=this.config.callbacks;return r?(r({draft:t,complete:async e=>{const r={...t,noteId:e};this.registerNote(r)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const r=this.buildDraft(t),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await s(r)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!n)return null;const a={...r,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var r,s;if(this.notes.has(t)){try{await(null==(s=(r=this.config.callbacks).onDeleteNote)?void 0:s.call(r,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,r){var s,n;const a=this.notes.get(t);if(!a)return;const o={...a,content:r};try{await(null==(n=(s=this.config.callbacks).onUpdateNote)?void 0:n.call(s,o))}catch(i){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",i)}this.notes.set(t,o),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const r=this.notes.get(e);if(!r)return;const s=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(r.chapterId);const a=n.resolvePageDocument(r.chapterId,r.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(s.scrollToGlobalPageIndex(r.globalPageIndex),await this.waitForPageInLayout(r.globalPageIndex),s.scrollToGlobalPdfPoint(r.globalPageIndex,r.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(r.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),r=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return r?Promise.resolve(r):new Promise(r=>{const s=setTimeout(()=>{n(),r(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(s),n(),r(a))})})}};ft.id="note";let mt=ft;function vt(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}const Pt={manifest:Ue,create:e=>new mt(ke,e),reducer:e=>e,initialState:{}},It="paragraph-bookmark",Ct={id:It,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}};function bt(e){const[t,r]=e.localPageRange;return r-t+1}function wt(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function St(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return wt(t)?t.segmentPageThreshold:null}function yt(e,t){return`${e}#s${t}`}function Mt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function xt(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function $t(e){const t=St(e);if(!t)return null;const r=bt(e),s=xt(r,t),n=wt(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:yt(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Lt(e,t){const r=$t(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Dt(e,t){const r=$t(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function kt(e){var t;const r=St(e);if(!r)return[];const s=[],{chapterId:n}=e,a=bt(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!wt(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=xt(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Ut={kind:"first-wins"};function Tt(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let Et=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const At=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Ut,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Ut,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Mt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Mt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Mt(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?Lt(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?$t(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...kt(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=Ut){const r=function(e,t=Ut){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Tt(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Et(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?$t(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Dt(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=Lt(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=$t(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(wt(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=St(t);if(a){const s=xt(bt(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(wt(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=Mt(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?$t(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};At.id="chapter-manager";let Ft=At;function Nt(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ot(e,t){return`${e}#s${t}`}function zt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Gt(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Nt(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=Nt(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:Ot(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Rt(e){const[t,r]=e.localPageRange;return r-t+1}function Vt(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function _t(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Vt(t)?t.segmentPageThreshold:null}function Bt(e,t){return`${e}#s${t}`}function qt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Ht(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Wt(e){const t=_t(e);if(!t)return null;const r=Rt(e),s=Ht(r,t),n=Vt(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:Bt(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function jt(e,t){const r=Wt(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Yt(e,t){const r=Wt(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Zt(e){var t;const r=_t(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Rt(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!Vt(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=Ht(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Kt={kind:"first-wins"};function Jt(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let Xt=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const Qt=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Kt,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Kt,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=qt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=qt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=qt(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?jt(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Wt(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Zt(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=Kt){const r=function(e,t=Kt){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Jt(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Xt(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Wt(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Yt(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=jt(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=Wt(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(Vt(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=_t(t);if(a){const s=Ht(Rt(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(Vt(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=qt(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?Wt(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Qt.id="chapter-manager";let er=Qt;function tr(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.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,tr),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(er.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.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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapterStatus(e);if("error"===s||"password-required"===s)return!0;const n=r.getChapter(e);if(!n)return!0;const a=function(e,t){const r=Gt(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(n,t);return!r.isSegmentLoaded(e,a)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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:r}=zt(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=zt(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}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 r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=Gt(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):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:r}=zt(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.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 r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}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,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n),t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(a),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}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 r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};rr.id="chapter-scroll";let sr=rr;function nr(e){if(0===e.length)throw new Error("unionRects: empty rects");let t=1/0,r=1/0,s=-1/0,n=-1/0;for(const a of e)t=Math.min(t,a.origin.x),r=Math.min(r,a.origin.y),s=Math.max(s,a.origin.x+a.size.width),n=Math.max(n,a.origin.y+a.size.height);return{origin:{x:t,y:r},size:{width:s-t,height:n-r}}}function ar(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function or(e,t){const r=e.origin.y,s=e.origin.y+e.size.height,n=t.origin.y,a=t.origin.y+t.size.height,o=Math.max(s,a)-Math.min(r,n);return o<=0?0:Math.max(0,Math.min(s,a)-Math.max(r,n))/o}function ir(e,t){var r,s;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const n=(null==(r=e.rectsPdfCoord)?void 0:r.length)?e.rectsPdfCoord:[e.rectPdfCoord],a=(null==(s=t.rectsPdfCoord)?void 0:s.length)?t.rectsPdfCoord:[t.rectPdfCoord],o=e.markerAnchor??ar(n),i=t.markerAnchor??ar(a);if(Math.hypot(o.x-i.x,o.y-i.y)<=6)return!0;for(const l of n)for(const e of a){if(or(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 lr(e,t,r,s){const n=r.length>0?r:[];if(0===n.length)throw new Error("buildParagraphBookmarkAnchor: no rects");return{chapterId:e,localPageIndex:t,globalPageIndex:null==s?void 0:s.globalPageIndex,globalPageNumber:null==s?void 0:s.globalPageNumber,rectPdfCoord:nr(n),rectsPdfCoord:n,markerAnchor:ar(n)}}const hr=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.change$=n.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(sr.id),this.chapterManager=this.registry.getPlugin(Ft.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){var r;if(this.config=t,null==(r=t.callbacks)?void 0:r.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(s){this.logger.error(e.id,"Load","Failed to load paragraph bookmarks",s)}}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 s of this.entries.values())if(ir(s.anchor,e.anchor))return s;const t=e.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r={id:t,label:e.label,anchor:e.anchor,metadata:e.metadata,createdAt:Date.now()};return this.entries.set(t,r),this.notifyAndPersist(),r}removeBookmark(e){var t,r,s;this.entries.delete(e)&&(this.notifyAndPersist(),null==(s=null==(r=null==(t=this.config)?void 0:t.callbacks)?void 0:r.onRemoveSuccess)||s.call(r,e))}async requestRemoveBookmark(t){var r,s;const n=this.entries.get(t);if(!n)return!1;const a=null==(s=null==(r=this.config)?void 0:r.callbacks)?void 0:s.onRequestRemove;if(a)try{if(!(await a(n)))return!1}catch(o){return this.logger.error(e.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(t),!0}updateBookmark(e,t){const r=this.entries.get(e);r&&(this.entries.set(e,{...r,...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[r,s]of this.entries.entries())s.anchor.chapterId===e&&this.entries.delete(r);for(const r of t)r.anchor.chapterId===e&&this.entries.set(r.id,r);this.notifyAndPersist()}notifyAndPersist(){var t,r;const s=this.list();this.change$.emit(s),(null==(r=null==(t=this.config)?void 0:t.callbacks)?void 0:r.persist)&&Promise.resolve(this.config.callbacks.persist(s)).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 r=this.chapterScroll.provides(),s=this.chapterManager.provides();await s.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,r){e.scrollToGlobalPageIndex(t),await function(e,t,r=2500){const s=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const n=setTimeout(()=>{a(),s(null)},r),a=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(n),a(),s(r))})})}(e,t),e.scrollToGlobalPdfPoint(t,r,{marginTop:80})}(r,n,a)}};hr.id="paragraph-bookmark";let dr=hr;const cr={manifest:Ct,create:e=>new dr(It,e),reducer:e=>e,initialState:{}},ur={"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 pr{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(ur);for(const t of this.specs){const r=e[t.toolbarSlot];if(!r)continue;const s={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??[]};r.items=gr(r.items,s,t.position)}return e}}function gr(e,t,r){return(null==r?void 0:r.after)||(null==r?void 0:r.before)?function(e,t,r){const s=e=>{const n=[];for(const a of e)"group"!==a.type?r.before&&a.id===r.before?n.push(t,a):(n.push(a),r.after&&a.id===r.after&&n.push(t)):n.push({...a,items:s(a.items)});return n};return s(e)}(e,t,r):(s=t,e.map(e=>"group"===e.type?{...e,items:[...e.items,s]}:e));var s}const fr={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function mr(e){var t,s,P,I,C,b;const w=e.toolbar??{},S=w.enabledModes??["view","annotate","shapes","insert","form","redact"],y=S.length>0,{schema:M,operationRegistry:x}=function(e={}){var t,r,s,n,a,o;const i=new Set(e.enabledModes??["view","annotate","shapes","insert","form","redact"]),l=new pr;(null==(t=e.customOperations)?void 0:t.length)&&l.registerAll(e.customOperations);const h=l.buildToolbars(),d={};for(const u of i){if("view"===u)continue;const e=fr[u];h[e]&&(d[e]=h[e])}const c=function(e){if(0===e.size)return null;const t=(e,t,r)=>({type:"command-button",id:`${e}-mode`,commandId:r,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}]}}(i);return c&&(d["chapter-editor-main-toolbar"]=c),(null==(r=e.extend)?void 0:r.toolbars)&&Object.assign(d,e.extend.toolbars),{schema:{id:"chapter-pdf-editor-ui",version:"1.0.0",toolbars:d,menus:(null==(s=e.extend)?void 0:s.menus)??{},sidebars:(null==(n=e.extend)?void 0:n.sidebars)??{},modals:(null==(a=e.extend)?void 0:a.modals)??{},selectionMenus:(null==(o=e.extend)?void 0:o.selectionMenus)??{}},operationRegistry:l}}({...w,enabledModes:S}),$={...y?{"mode:view":{id:"mode:view",label:"View",categories:["mode","mode-view"],action:({registry:e,documentId:t})=>{var s,n,a,o;const i=null==(s=e.getPlugin("ui"))?void 0:s.provides(),l=null==(n=e.getPlugin("interaction-manager"))?void 0:n.provides();i&&l&&(null==(a=l.forDocument(t))||a.activateDefaultMode(),i.forDocument(t).closeToolbarSlot("top","secondary"),null==(o=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||o.provides().forDocument(t).setLocked(e.getPluginConfig(r.ANNOTATION_PLUGIN_ID).locked??{type:r.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 s,n;const a=null==(s=e.getPlugin("ui"))?void 0:s.provides();a&&(a.setActiveToolbar("top","secondary","annotation-toolbar",t),null==(n=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:r.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 s,n;const a=null==(s=e.getPlugin("ui"))?void 0:s.provides();a&&(a.setActiveToolbar("top","secondary","shapes-toolbar",t),null==(n=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:r.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 s,n;const a=null==(s=e.getPlugin("ui"))?void 0:s.provides();a&&(a.setActiveToolbar("top","secondary","insert-toolbar",t),null==(n=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:r.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 s,n;const a=null==(s=e.getPlugin("ui"))?void 0:s.provides();a&&(a.setActiveToolbar("top","secondary","form-toolbar",t),null==(n=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:r.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 s,n;const a=null==(s=e.getPlugin("ui"))?void 0:s.provides();a&&(a.setActiveToolbar("top","secondary","redaction-toolbar",t),null==(n=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:r.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","redaction-toolbar")}}:{},...y?vr(x.list()):{},...e.commands??{}},L=[n.createPluginRegistration(a.DocumentManagerPluginPackage,{initialDocuments:[]}),n.createPluginRegistration(ne,{manifest:e.manifest,overlapStrategy:e.overlapStrategy,passwordProvider:e.passwordProvider,chapterPdfLoader:e.chapterPdfLoader,prefetchChapters:e.prefetchChapters,unloadTimeoutMs:e.unloadTimeoutMs}),n.createPluginRegistration(De,{placeholderPageHeight:e.placeholderPageHeight,placeholderPageWidth:e.placeholderPageWidth}),n.createPluginRegistration(o.InteractionManagerPluginPackage),n.createPluginRegistration(i.RenderPluginPackage),n.createPluginRegistration(l.RotatePluginPackage),n.createPluginRegistration(h.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),n.createPluginRegistration(d.HistoryPluginPackage),n.createPluginRegistration(r.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($).length>0?[n.createPluginRegistration(f.CommandsPluginPackage,{commands:$})]:[],...y?[n.createPluginRegistration(m.I18nPluginPackage),n.createPluginRegistration(v.UIPluginPackage,{schema:M})]:[]];return e.notes&&L.push(n.createPluginRegistration(Pt,{callbacks:e.notes.callbacks,ui:null==(s=null==(t=e.features)?void 0:t.notes)?void 0:s.marker})),e.bookmarks&&L.push(n.createPluginRegistration(cr,{callbacks:e.bookmarks.callbacks,ui:null==(I=null==(P=e.features)?void 0:P.bookmarks)?void 0:I.marker,hover:null==(b=null==(C=e.features)?void 0:C.bookmarks)?void 0:b.hover})),{plugins:L,uiSchema:M,operationRegistry:x}}function vr(e){const t={};for(const r of e)r.handler&&(t[r.commandId]={id:r.commandId,labelKey:r.i18nKey,label:r.label,icon:r.icon,categories:r.categories,action:({documentId:e})=>{var t;null==(t=r.handler)||t.call(r,{documentId:e,chapterId:e})}});return t}const Pr=N();function Ir(e){return mr({...e,toolbar:e.toolbar??{enabledModes:[]},features:N(e.features)})}const Cr={overlapStrategy:{kind:"first-wins"},passwordProvider:new R(async()=>null),prefetchChapters:1,loadDefaultStampLibrary:!1,unloadTimeoutMs:12e4,toolbar:{enabledModes:[]}};function br(e){return"callbacks"in e.notes?{manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,notes:e.notes.callbacks,bookmarks:e.bookmarks.callbacks}:e}function wr(e){return{...Cr,manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,overlapStrategy:e.overlapStrategy??Cr.overlapStrategy,notes:{callbacks:e.notes},bookmarks:{callbacks:e.bookmarks},features:N(e.features)}}function Sr(e){const t=wr(br(e)),{plugins:r}=Ir(t);return{plugins:r,features:t.features,editorOptions:t}}function yr(e,t=.5,r=3){return Math.min(r,Math.max(t,e))}function Mr(e,t){var r;if(t<=0)return 1;let s=0;for(const n of e.pages){const e=(null==(r=null==n?void 0:n.size)?void 0:r.width)??0;e>s&&(s=e)}return s<=0?1:t/s}function xr(e,t){return e<=0?t??0:null==t||t<=0?e:Math.min(t,e)}function $r(e,t,r,s){const n=xr(t,r);if(n<=0)return s;const a=Mr(e,n);return Math.min(s,a)}function Lr(e,t,r){const s=G(t);if(s){for(const t of s.segments){const s=e.getDocument(t.documentId);s&&r(s,t.documentId)}return}const n=e.getDocument(t.chapterId);n&&r(n,t.chapterId)}function Dr(e){return e instanceof HTMLElement?e.clientWidth:0}function kr(e,t,r){return Math.min(r,Math.max(t,e))}const Ur={chapters:[]};function Tr(r){const s=e.ref(null),{provides:o}=t.useCapability(se.id),i=e.computed(()=>{var e;return(null==(e=o.value)?void 0:e.getManifest())??Ur}),l=e.computed(()=>{var e;return null==(e=r.value)?void 0:e.zoom}),{scale:h,setScale:d,zoomEnabled:c,minZoom:u,maxZoom:p}=function(r,s,o){const i=e.isRef(r)?r:e.computed(()=>r),{registry:l}=t.useRegistry(),{provides:h}=t.useCapability(a.DocumentManagerPlugin.id),{provides:d}=t.useCapability(se.id),c=e.ref(m()),u=e.ref(c.value),p=e.ref(0),g=()=>{var e;return null==(e=s.value)?void 0:e.pageWidth},f=()=>{return null!=(e=g())&&e>0;var e},m=()=>{var e;return(null==(e=s.value)?void 0:e.initial)??1},v=e.computed(()=>{var e;return function(e,t,r,s,n){if(!e||r<=0)return n;let a=n;for(const o of t.chapters)Lr(e,o,e=>{a=Math.min(a,$r(e,r,s,n))});return a}(h.value,i.value,p.value,g(),(null==(e=s.value)?void 0:e.max)??3)}),P=e.computed(()=>{var e;return Math.min((null==(e=s.value)?void 0:e.min)??.5,v.value)});let I;function C(e){const t=v.value,r=P.value,s=yr(e,r,t);u.value=s,c.value=s,function(e,t,r,s=.5,a=3){const o=null==e?void 0:e.getStore();if(!o)return;const i=yr(r,s,a);o.dispatchToCore(n.setDefaultScale(i));for(const l of t.chapters){const e=G(l);if(e)for(const t of e.segments)o.getState().core.documents[t.documentId]&&o.dispatchToCore(n.setScale(i,t.documentId));else o.getState().core.documents[l.chapterId]&&o.dispatchToCore(n.setScale(i,l.chapterId))}}(l.value,i.value,s,r,t)}function b(e){if(!h.value||!d.value)return;const t=d.value.resolvePageDocument(e,0),r=h.value.getDocument(t.documentId);if(!r)return;const s=xr(p.value,g());s<=0||C(Mr(r,s))}function w(e){f()?b(e):C(m())}return e.watch(()=>null==o?void 0:o.value,e=>{null==I||I(),I=e?function(e,t){if(!e||"undefined"==typeof ResizeObserver)return()=>{};let r=null;const s=new ResizeObserver(()=>{t(Dr(r))}),n=()=>{const n=e.querySelector("[data-chapter-scroll-viewport]");n!==r?(r&&s.unobserve(r),r=n,r?(s.observe(r),t(Dr(r))):t(0)):t(Dr(r))};n();const a=new MutationObserver(n);a.observe(e,{childList:!0,subtree:!0});const o=requestAnimationFrame(n);return()=>{cancelAnimationFrame(o),a.disconnect(),r&&s.unobserve(r),s.disconnect()}}(e,e=>{p.value=e}):void 0},{immediate:!0}),e.onBeforeUnmount(()=>null==I?void 0:I()),e.watch([l,()=>m(),()=>f()],()=>{l.value&&(f()||C(m()))},{immediate:!0}),e.watch(v,e=>{u.value>e&&C(e)}),e.watch([d,i,()=>f(),()=>m()],()=>{const e=d.value;if(e){for(const t of i.value.chapters)"loaded"===e.getChapterStatus(t.chapterId)&&w(t.chapterId);return e.onChapterStatusChange(e=>{"loaded"===e.status&&w(e.chapterId)})}},{immediate:!0}),e.watch([p,()=>f(),d,i],()=>{if(f()&&!(p.value<=0)&&d.value)for(const e of i.value.chapters)if("loaded"===d.value.getChapterStatus(e.chapterId)){b(e.chapterId);break}}),{scale:c,setScale:C,zoomEnabled:()=>{var e;return!1!==(null==(e=s.value)?void 0:e.enabled)},minZoom:P,maxZoom:v}}(i,l,s);return function(t,r){let s=null;e.watch([t,r],()=>{null==s||s();const e=r.value;s=function(e,t){if(!e||!1===t.enabled)return()=>{};let r=null,s=null,n=0;const a=()=>{const s=e.querySelector("[data-chapter-scroll-viewport]");return!!s&&(null==r||r(),r=function({container:e,getScale:t,setScale:r,minZoom:s=.5,maxZoom:n=3}){let a=0,o=1,i=null,l=1,h=1;const d=e=>{(e.ctrlKey||e.metaKey)&&(e.preventDefault(),null===i?(h=t(),l=1):clearTimeout(i),l*=1-.01*e.deltaY,l=kr(l,.1,10),r(kr(h*l,s,n)),i=setTimeout(()=>{i=null},120))},c=new Map,u=e=>{if(c.set(e.pointerId,{x:e.clientX,y:e.clientY}),2===c.size){const[e,r]=[...c.values()];a=Math.hypot(r.x-e.x,r.y-e.y),o=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,i]=[...c.values()],l=Math.hypot(i.x-t.x,i.y-t.y);r(kr(o*(l/a),s,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),i&&clearTimeout(i)}}({container:s,getScale:t.getScale,setScale:t.setScale,minZoom:t.minZoom,maxZoom:t.maxZoom}),!0)};return a()||(s=new MutationObserver(()=>{a()&&(null==s||s.disconnect(),s=null)}),s.observe(e,{childList:!0,subtree:!0}),n=requestAnimationFrame(()=>a())),()=>{n&&cancelAnimationFrame(n),null==s||s.disconnect(),null==r||r()}}(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==s?void 0:s())}(s,e.computed(()=>({enabled:c(),getScale:()=>h.value,setScale:d,minZoom:u.value,maxZoom:p.value}))),{hostRef:s,scale:h,setScale:d,zoomEnabled:c}}function Er(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ar(e,t){return`${e}#s${t}`}function Fr(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Nr(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Er(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=Er(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:Ar(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Or(e){const[t,r]=e.localPageRange;return r-t+1}function zr(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Gr(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return zr(t)?t.segmentPageThreshold:null}function Rr(e,t){return`${e}#s${t}`}function Vr(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function _r(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Br(e){const t=Gr(e);if(!t)return null;const r=Or(e),s=_r(r,t),n=zr(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:Rr(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function qr(e,t){const r=Br(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Hr(e,t){const r=Br(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Wr(e){var t;const r=Gr(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Or(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!zr(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=_r(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const jr={kind:"first-wins"};function Yr(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}class Zr{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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}}const Kr=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=jr,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??jr,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Vr(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Vr(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Vr(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?qr(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Br(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Wr(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=jr){const r=function(e,t=jr){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Yr(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Zr(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Br(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Hr(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=qr(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=Br(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(zr(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Gr(t);if(a){const s=_r(Or(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(zr(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=Vr(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?Br(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Kr.id="chapter-manager";let Jr=Kr;function Xr(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.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,Xr),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Jr.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.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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapterStatus(e);if("error"===s||"password-required"===s)return!0;const n=r.getChapter(e);if(!n)return!0;const a=function(e,t){const r=Nr(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(n,t);return!r.isSegmentLoaded(e,a)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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:r}=Fr(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=Fr(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}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 r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=Nr(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):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:r}=Fr(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.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 r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}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,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n),t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(a),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}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 r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};Qr.id="chapter-scroll";let es=Qr;const ts=["data-global-page-index","data-chapter-id","data-local-page-index"],rs=(e=>{const t=e.__vccOpts||e;for(const[r,s]of[["__scopeId","data-v-e9ab4da3"]])t[r]=s;return t})(e.defineComponent({__name:"ChapterScroller",props:{class:{},style:{}},setup(r){const{provides:s}=t.useCapability(es.id),n=e.ref(null),a=e.ref(null);let o=null;const i=()=>{null==o||o(),o=null,s.value&&(s.value.registerViewport(n.value),o=s.value.onLayoutChange(e=>{a.value=e}))};return e.onMounted(i),e.onBeforeUnmount(()=>{var e;null==o||o(),null==(e=s.value)||e.registerViewport(null)}),e.watch(s,i),(t,r)=>{var s,o,i;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==(s=a.value)?void 0:s.totalWidth)??0}px`,height:`${(null==(o=a.value)?void 0:o.totalHeight)??0}px`,margin:"0 auto"})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList((null==(i=a.value)?void 0:i.items)??[],s=>(e.openBlock(),e.createElementBlock("div",{key:s.globalPageIndex,"data-global-page-index":s.globalPageIndex,"data-chapter-id":s.chapterId,"data-local-page-index":s.localPageIndex,style:e.normalizeStyle({position:"absolute",top:`${s.offsetTop}px`,left:"50%",transform:"translateX(-50%)",width:`${s.width}px`,height:`${s.height}px`,backgroundColor:s.isPlaceholder?"#f3f4f6":"#fff",boxShadow:"0 1px 4px rgba(0,0,0,0.08)"})},[s.isPlaceholder?e.renderSlot(t.$slots,"placeholder",{key:0,item:s},()=>[r[0]||(r[0]=e.createElementVNode("div",{class:"chapter-scroll-placeholder"},"Loading chapter…",-1))],!0):e.renderSlot(t.$slots,"page",{key:1,item:s},void 0,!0)],12,ts))),128))],4)],6)}}})),ss=e.defineComponent({__name:"ChapterRenderLayer",props:{chapterId:{},localPageIndex:{},pdfDocumentId:{},pdfPageIndex:{},scale:{},dpr:{},class:{}},setup(t){const r=t;return(s,n)=>(e.openBlock(),e.createBlock(e.unref(S.RenderLayer),{"document-id":r.pdfDocumentId??r.chapterId,"page-index":r.pdfPageIndex??r.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 ns(e){const[t,r]=e.localPageRange;return r-t+1}function as(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function os(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return as(t)?t.segmentPageThreshold:null}function is(e,t){return`${e}#s${t}`}function ls(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function hs(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function ds(e){const t=os(e);if(!t)return null;const r=ns(e),s=hs(r,t),n=as(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:is(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function cs(e,t){const r=ds(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function us(e,t){const r=ds(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function ps(e){var t;const r=os(e);if(!r)return[];const s=[],{chapterId:n}=e,a=ns(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!as(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=hs(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const gs={kind:"first-wins"};function fs(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let ms=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const vs=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=gs,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??gs,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=ls(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=ls(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=ls(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?cs(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ds(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...ps(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=gs){const r=function(e,t=gs){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,fs(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new ms(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ds(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=us(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=cs(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=ds(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(as(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=os(t);if(a){const s=hs(ns(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(as(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=ls(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?ds(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};vs.id="chapter-manager";let Ps=vs;function Is(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Cs(e,t){return`${e}#s${t}`}function bs(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function ws(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Is(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=Is(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:Cs(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Ss(e){const[t,r]=e.localPageRange;return r-t+1}function ys(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ms(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ys(t)?t.segmentPageThreshold:null}function xs(e,t){return`${e}#s${t}`}function $s(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Ls(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ds(e){const t=Ms(e);if(!t)return null;const r=Ss(e),s=Ls(r,t),n=ys(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:xs(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function ks(e,t){const r=Ds(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Us(e,t){const r=Ds(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Ts(e){var t;const r=Ms(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Ss(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!ys(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=Ls(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Es={kind:"first-wins"};function As(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}class Fs{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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}}const Ns=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Es,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Es,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=$s(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=$s(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=$s(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?ks(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ds(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Ts(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=Es){const r=function(e,t=Es){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,As(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Fs(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ds(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Us(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=ks(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=Ds(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(ys(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Ms(t);if(a){const s=Ls(Ss(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(ys(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=$s(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?Ds(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Ns.id="chapter-manager";let Os=Ns;function zs(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.height!==n.height)return!1}return!0}const Gs=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,zs),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Os.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.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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapterStatus(e);if("error"===s||"password-required"===s)return!0;const n=r.getChapter(e);if(!n)return!0;const a=function(e,t){const r=ws(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(n,t);return!r.isSegmentLoaded(e,a)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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:r}=bs(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=bs(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}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 r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=ws(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):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:r}=bs(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.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 r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}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,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n),t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(a),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}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 r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};Gs.id="chapter-scroll";let Rs=Gs;const Vs=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(Rs.id),this.chapterManager=this.registry.getPlugin(Ps.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(r){this.logger.error(e.id,"LoadNotes","Failed to load notes",r)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(r=>r.chapterId===e&&r.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,r;const s=this.notes.get(e);s&&(null==(r=(t=this.config.callbacks).onActivateNote)||r.call(t,e,s),this.noteActivated$.emit({noteId:e,anchor:s}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[r,s]of this.notes.entries())s.chapterId===e&&this.notes.delete(r);for(const r of t)r.chapterId===e&&this.notes.set(r.noteId,r);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:Bs(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:r,onCreateNote:s}=this.config.callbacks;return r?(r({draft:t,complete:async e=>{const r={...t,noteId:e};this.registerNote(r)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const r=this.buildDraft(t),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await s(r)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!n)return null;const a={...r,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var r,s;if(this.notes.has(t)){try{await(null==(s=(r=this.config.callbacks).onDeleteNote)?void 0:s.call(r,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,r){var s,n;const a=this.notes.get(t);if(!a)return;const o={...a,content:r};try{await(null==(n=(s=this.config.callbacks).onUpdateNote)?void 0:n.call(s,o))}catch(i){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",i)}this.notes.set(t,o),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const r=this.notes.get(e);if(!r)return;const s=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(r.chapterId);const a=n.resolvePageDocument(r.chapterId,r.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(s.scrollToGlobalPageIndex(r.globalPageIndex),await this.waitForPageInLayout(r.globalPageIndex),s.scrollToGlobalPdfPoint(r.globalPageIndex,r.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(r.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),r=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return r?Promise.resolve(r):new Promise(r=>{const s=setTimeout(()=>{n(),r(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(s),n(),r(a))})})}};Vs.id="note";let _s=Vs;function Bs(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function qs(e){const{markerPdf:t,lineRects:r,sx:s,sy:n,cssPageWidth:a,iconSize:o,gapPx:i=6}=e,l=(null==r?void 0:r.length)?r[r.length-1]:void 0;let h,d;l?(h=(l.origin.x+l.size.width)*s+i,d=l.origin.y*n+(l.size.height*n-o)/2):(h=t.x*s-o/2,d=t.y*n-o-i);const c=Math.max(0,a-o-2);return h>c&&(h=c),d<0&&(d=0),{left:h,top:d}}const Hs={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none",zIndex:25}},Ws=["onMouseenter"],js=["data-note-marker-zone","onMouseenter","onMouseleave"],Ys=["onClick"],Zs=["onClick"],Ks=["onClick"],Js=e.defineComponent({__name:"NoteMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(r){const s=r,{provides:n}=t.useCapability(_s.id),a=e.ref([]),o=e.ref(null),i=e.ref(null);e.watch(n,e=>{if(e)return e.onNotesChange(e=>{a.value=e.filter(e=>e.chapterId===s.chapterId&&e.localPageIndex===s.localPageIndex)})},{immediate:!0});let l=null;e.watch(i,e=>{l&&(document.removeEventListener("mousedown",l),l=null),e&&(l=t=>{var r;const s=t.target;(null==(r=s.closest)?void 0:r.call(s,`[data-note-marker-zone="${e}"]`))||(i.value=null,o.value=null)},document.addEventListener("mousedown",l))}),e.onBeforeUnmount(()=>{l&&document.removeEventListener("mousedown",l)});const h=e.computed(()=>{var e;return(null==(e=s.ui)?void 0:e.iconSize)??16}),d=e.computed(()=>{var e;return(null==(e=s.ui)?void 0:e.highlightColor)??"rgba(245, 158, 11, 0.08)"});function c(e){const t=s.cssPageWidth/s.pdfPageWidth,r=s.cssPageHeight/s.pdfPageHeight,n=h.value,{left:a,top:o}=qs({markerPdf:e.endAnchor,lineRects:e.rectsPdfCoord,sx:t,sy:r,cssPageWidth:s.cssPageWidth,iconSize:n}),l=function(e,t,r){let s=1/0,n=1/0,a=-1/0,o=-1/0;for(const i of e)s=Math.min(s,i.origin.x*t),n=Math.min(n,i.origin.y*r),a=Math.max(a,(i.origin.x+i.size.width)*t),o=Math.max(o,(i.origin.y+i.size.height)*r);return{left:s,top:n,width:a-s,height:o-n}}(e.rectsPdfCoord,t,r),d=i.value===e.noteId?72:0,c=Math.max(0,Math.min(l.left,a)-8),u=Math.max(0,Math.min(l.top,o)-8);return{zoneLeft:c,zoneTop:u,zoneW:Math.min(s.cssPageWidth,Math.max(l.left+l.width,a+n)+8)-c,zoneH:Math.max(l.top+l.height,o+n+6+d)+8-u,iconLeft:a,iconTop:o,sx:t,sy:r}}return(t,s)=>e.unref(n)&&a.value.length&&r.pdfPageWidth&&r.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",Hs,[(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,(r,s)=>(e.openBlock(),e.createElementBlock("div",{key:`${t.noteId}-bg-${s}`,style:e.normalizeStyle({position:"absolute",left:r.origin.x*c(t).sx+"px",top:r.origin.y*c(t).sy+"px",width:r.size.width*c(t).sx+"px",height:r.size.height*c(t).sy+"px",background:d.value,borderRadius:"2px",pointerEvents:"auto"}),onMouseenter:e=>o.value=t.noteId},null,44,Ws))),128)),o.value===t.noteId||i.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=>o.value=t.noteId,onMouseleave:e=>i.value!==t.noteId&&(o.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:s[0]||(s[0]=e.withModifiers(()=>{},["stop"])),onClick:e.withModifiers(e=>i.value=i.value===t.noteId?null:t.noteId,["stop"])}," 💬 ",44,Ys),i.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:s[1]||(s[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 r=t,void(null==(s=n.value)||s.requestEditNote(r.noteId,r));var r,s}}," 编辑 ",8,Zs),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 r,s;return s=t.noteId,null==(r=n.value)||r.requestDeleteNote(s),void(i.value=null)}}," 删除 ",8,Ks)],36)):e.createCommentVNode("",!0)],44,js)):e.createCommentVNode("",!0)],64))),128))])):e.createCommentVNode("",!0)}}),Xs={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none"}},Qs=["title","onClick"],en=["onClick"],tn=e.defineComponent({__name:"BookmarkMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(r){const s=r,{provides:n}=t.useCapability(dr.id),a=e.ref([]),o=e.ref(null),i=e.ref(null);function l(){const e=n.value;e&&(a.value=e.listBookmarks().filter(e=>e.anchor.chapterId===s.chapterId&&e.anchor.localPageIndex===s.localPageIndex))}e.watch(n,e=>{if(e)return l(),e.onBookmarksChange(l)},{immediate:!0});let h=null;e.watch(o,e=>{h&&(document.removeEventListener("mousedown",h),h=null),e&&(h=e=>{var t;(null==(t=i.value)?void 0:t.contains(e.target))||(o.value=null)},document.addEventListener("mousedown",h))}),e.onBeforeUnmount(()=>{h&&document.removeEventListener("mousedown",h)});const d=e.computed(()=>{var e;return(null==(e=s.ui)?void 0:e.iconSize)??16});function c(e){const{left:t,top:r}=function(e){var t;const r=s.cssPageWidth/s.pdfPageWidth,n=s.cssPageHeight/s.pdfPageHeight,a=(null==(t=e.anchor.rectsPdfCoord)?void 0:t.length)?e.anchor.rectsPdfCoord:[e.anchor.rectPdfCoord];return qs({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:r,sy:n,cssPageWidth:s.cssPageWidth,iconSize:d.value})}(e);return{position:"absolute",left:`${Math.max(0,t-6)}px`,top:`${Math.max(0,r-6)}px`,width:`${d.value+12}px`,height:`${d.value+12}px`,pointerEvents:"auto",zIndex:20}}return(t,s)=>e.unref(n)&&a.value.length&&r.pdfPageWidth&&r.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",Xs,[(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:s[1]||(s[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=>o.value=o.value===t.id?null:t.id,["stop"])}," 🔖 ",12,Qs),o.value===t.id?(e.openBlock(),e.createElementBlock("div",{key:0,ref_for:!0,ref_key:"deleteMenuRef",ref:i,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:s[0]||(s[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)&&(o.value=null)}(t.id)}," 删除书签 ",8,en)],512)):e.createCommentVNode("",!0)],36))),128))])):e.createCommentVNode("",!0)}});function rn(e){return e.pdfDocumentId??e.chapterId}function sn(e){return e.pdfPageIndex??e.localPageIndex}function nn(e,t){e.wait(t,()=>{})}const an={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)"},on={padding:"6px 12px",fontSize:"12px",fontWeight:"500",border:"none",borderRadius:"6px",background:"transparent",color:"#dc2626",cursor:"pointer"};const ln=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(r){const s=r,n=e.computed(()=>rn(s.item)),o=e.computed(()=>sn(s.item));!function(r){const{provides:s}=t.useCapability(a.DocumentManagerPlugin.id);e.watch([s,r],([e,t])=>{e&&t&&e.isDocumentOpen(t)&&e.setActiveDocument(t)},{immediate:!0})}(n);const{provides:i}=t.useCapability(a.DocumentManagerPlugin.id),{provides:l}=t.useCapability(h.SelectionPlugin.id),d=e.computed(()=>{var e,t;return null==(t=null==(e=i.value)?void 0:e.getDocument(n.value))?void 0:t.pages[o.value]});function c(t,r){var n,a,o,i;const h=s.createNote.value;if(h&&!1!==(null==(a=null==(n=s.features)?void 0:n.notes)?void 0:a.enabled)&&!1!==(null==(i=null==(o=s.features)?void 0:o.selectionToolbar)?void 0:i.enabled))return s=>{var n;const a={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==(n=s.placement)?void 0:n.suggestTop)?-40:s.rect.size.height+8};return e.h("div",s.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(sn(t),r);nn(l.value.getSelectedText(r),r=>{var s,n,a;h((s=t,n=e,a=r.join("\n"),{chapterId:s.chapterId,localPageIndex:s.localPageIndex,globalPageIndex:s.globalPageIndex,globalPageNumber:s.globalPageNumber,rectsPdfCoord:n,selectedText:a}))})}},"添加附注"))])}}const u=e.computed(()=>{const e=s.buildSelectionMenu,t={item:s.item,defaultMenu:c(s.item,n.value),createNote:s.createNote.value};if(e){const r=e(t);if(r)return r}return t.defaultMenu}),p=function(t,r){var s,n;const{provides:a}=b.useAnnotationCapability(),o=null==(s=null==r?void 0:r.markup)?void 0:s.annotationMenu,i=!1!==(null==(n=null==r?void 0:r.markup)?void 0:n.enabled),l=!1!==(null==o?void 0:o.enabled);return e.computed(()=>{const r="string"==typeof t?t:t.value;if(i&&l&&a.value)return t=>{const{context:s,rect:n,placement:i,menuWrapperProps:l,selected:h}=t;if(!h||"annotation"!==s.type)return e.h("span",l);if(s.structurallyLocked)return e.h("span",l);if(d=s.annotation.object.type,!A.has(d))return e.h("span",l);var d;const c=a.value.forDocument(r),{pageIndex:u,id:p}=s.annotation.object,g=()=>{null==c||c.deleteAnnotation(u,p)},f={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==i?void 0:i.suggestTop)?void 0:`${n.size.height+8}px`,bottom:(null==i?void 0:i.suggestTop)?`${n.size.height+8}px`:void 0},m=(null==o?void 0:o.renderMenu)?o.renderMenu({pageIndex:u,annotationId:p,onDelete:g}):e.h("button",{type:"button",style:on,onClick:g},"删除");return e.h("div",l,[e.h("div",{style:f},[e.h("div",{style:an,role:"toolbar","aria-label":"划线标注"},[m])])])}})}(n,s.features),g=e.computed(()=>function(e,t){if(e||t)return r=>{if(e){const t=e(r);if(null!=t)return t}return(null==t?void 0:t(r))??null}}(s.annotationSelectionMenu,p.value)),f=e.computed(()=>{var e;return null==(e=s.renderPageOverlay)?void 0:e.call(s,s.item)}),m=e.computed(()=>{var e;return function(e){const t=null==e?void 0:e.selectionBackground;if(t)return{background:t}}(null==(e=s.features)?void 0:e.selectionToolbar)});return(t,s)=>r.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":o.value,style:{backgroundColor:"#fff"}},{default:e.withCtx(()=>[e.createVNode(e.unref(P.PagePointerProvider),{"document-id":n.value,"page-index":o.value,style:e.normalizeStyle(e.unref(x)),onPointerdown:e.unref($)},{default:e.withCtx(()=>[e.createVNode(e.unref(ss),{"chapter-id":r.item.chapterId,"local-page-index":r.item.localPageIndex,"pdf-document-id":n.value,"pdf-page-index":o.value},null,8,["chapter-id","local-page-index","pdf-document-id","pdf-page-index"]),e.createVNode(e.unref(C.SelectionLayer),{"document-id":n.value,"page-index":o.value,"text-style":m.value,"selection-menu":u.value},null,8,["document-id","page-index","text-style","selection-menu"]),r.showRedactionLayer?(e.openBlock(),e.createBlock(e.unref(w.RedactionLayer),{key:0,"document-id":n.value,"page-index":o.value,"selection-menu":r.redactionSelectionMenu},null,8,["document-id","page-index","selection-menu"])):e.createCommentVNode("",!0),e.createVNode(e.unref(b.AnnotationLayer),{"document-id":n.value,"page-index":o.value,"selection-menu":g.value},null,8,["document-id","page-index","selection-menu"]),r.showBookmarkMarkers&&d.value?(e.openBlock(),e.createBlock(tn,{key:1,"chapter-id":r.item.chapterId,"local-page-index":r.item.localPageIndex,"pdf-page-width":d.value.size.width,"pdf-page-height":d.value.size.height,"css-page-width":r.item.width,"css-page-height":r.item.height,ui:r.bookmarkMarkerUi},null,8,["chapter-id","local-page-index","pdf-page-width","pdf-page-height","css-page-width","css-page-height","ui"])):e.createCommentVNode("",!0),f.value?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(f.value),{key:2})):e.createCommentVNode("",!0),r.showNoteMarkers&&d.value?(e.openBlock(),e.createBlock(Js,{key:3,"chapter-id":r.item.chapterId,"local-page-index":r.item.localPageIndex,"pdf-page-width":d.value.size.width,"pdf-page-height":d.value.size.height,"css-page-width":r.item.width,"css-page-height":r.item.height,ui:r.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"]))}}),hn=e.defineComponent({__name:"HoverBookmarkLayer",props:{item:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},hoverUi:{}},setup(r){const s=r,n=e.computed(()=>rn(s.item)),{provides:a}=t.useCapability(h.SelectionPlugin.id),{provides:o}=t.useCapability(dr.id),i=e.ref(null),l=e.ref(null),d=e.ref(null),c=e.ref(null),u=e.computed(()=>{var e;return(null==(e=s.hoverUi)?void 0:e.iconSize)??16}),p=e.computed(()=>c.value??d.value);let g=null,f=0;function m(){const e=a.value;if(!e)return;const t=e.forDocument(n.value).getState().geometry[s.item.localPageIndex];t&&(l.value=t)}e.watch([a,n,()=>s.item.localPageIndex],([e])=>{if(null==g||g(),g=null,cancelAnimationFrame(f),l.value=null,!e)return;const t=e.forDocument(n.value);g=t.onSelectionChange(m);let r=!1;const a=()=>{if(!r){try{if(m(),t.getState().geometry[s.item.localPageIndex])return}catch{}f=requestAnimationFrame(a)}};return a(),()=>{r=!0,cancelAnimationFrame(f),null==g||g(),g=null}},{immediate:!0});let v=null;e.watch([l,()=>s.pdfPageWidth,c,a],()=>{v&&(document.removeEventListener("mousemove",v),v=null),l.value&&s.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 r=i.value;if(!r)return;const o=r.getBoundingClientRect();if(e.clientX<o.left||e.clientX>o.right||e.clientY<o.top||e.clientY>o.bottom)return void(d.value=null);const u=function(e,t){const r=h.glyphAt(e,t);if(r<0)return null;const s=h.expandToLineBoundary(e,r);if(!s)return null;const n=h.rectsWithinSlice(e,s.from,s.to);return 0===n.length?null:{lineRects:n,charFrom:s.from,charTo:s.to}}(l.value,{x:(e.clientX-o.left)/(s.cssPageWidth/s.pdfPageWidth),y:(e.clientY-o.top)/(s.cssPageHeight/s.pdfPageHeight)});d.value=(null==u?void 0:u.lineRects)??null},document.addEventListener("mousemove",v))},{immediate:!0}),e.onBeforeUnmount(()=>{v&&document.removeEventListener("mousemove",v),cancelAnimationFrame(f),null==g||g()});const P=e.computed(()=>{const e=p.value;return(null==e?void 0:e.length)?lr(s.item.chapterId,s.item.localPageIndex,e,{globalPageIndex:s.item.globalPageIndex,globalPageNumber:s.item.globalPageNumber}):null}),I=e.computed(()=>{const e=P.value,t=o.value;return!(!e||!t)&&t.listBookmarks().some(t=>ir(t.anchor,e))});function C(){const e=o.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 b=e.computed(()=>{const e=p.value,t=null==e?void 0:e[e.length-1];if(!t||!s.pdfPageWidth)return null;const r=s.cssPageWidth/s.pdfPageWidth,n=s.cssPageHeight/s.pdfPageHeight,a=u.value;return{iconLeft:Math.min((t.origin.x+t.size.width)*r+6,Math.max(0,s.cssPageWidth-a-2)),iconTop:t.origin.y*n+(t.size.height*n-a)/2,zoneLeft:Math.max(0,(t.origin.x+t.size.width)*r-4),zoneTop:Math.max(0,t.origin.y*n-4),size:a}});return(t,s)=>{var n;return e.unref(o)&&r.pdfPageWidth&&r.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",{key:0,ref_key:"rootRef",ref:i,style:{position:"absolute",inset:"0",zIndex:14,pointerEvents:"none"}},[b.value&&p.value&&!I.value?(e.openBlock(),e.createElementBlock("div",{key:0,style:e.normalizeStyle({position:"absolute",left:`${b.value.zoneLeft}px`,top:`${b.value.zoneTop}px`,width:`${b.value.size+20}px`,height:`${((null==(n=p.value[p.value.length-1])?void 0:n.size.height)??0)*(r.cssPageHeight/r.pdfPageHeight)+b.value.size+12}px`,pointerEvents:"auto"}),onMouseenter:s[0]||(s[0]=e=>c.value=p.value),onMouseleave:s[1]||(s[1]=e=>c.value=null)},[e.createElementVNode("button",{type:"button",title:"添加书签",style:e.normalizeStyle({position:"absolute",left:b.value.iconLeft-b.value.zoneLeft+"px",top:b.value.iconTop-b.value.zoneTop+"px",width:`${b.value.size}px`,height:`${b.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(C,["stop"])}," 🔖 ",4)],36)):e.createCommentVNode("",!0)],512)):e.createCommentVNode("",!0)}}}),dn={key:0,width:"20",height:"20",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},cn={key:1,width:"24",height:"24",viewBox:"0 0 28 28",fill:"none","aria-hidden":""},un={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"},gn={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"},fn={key:3,d:"M5 14h18",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},mn={key:2,width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},vn=e.defineComponent({__name:"SelectionToolbarIcons",props:{kind:{}},setup:t=>(r,s)=>"copy"===t.kind?(e.openBlock(),e.createElementBlock("svg",dn,[...s[0]||(s[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",cn,["highlight"===t.kind?(e.openBlock(),e.createElementBlock("rect",un)):e.createCommentVNode("",!0),s[1]||(s[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",gn)):"strikeout"===t.kind?(e.openBlock(),e.createElementBlock("path",fn)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("svg",mn,[...s[2]||(s[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)])]))}),Pn=["title","aria-label","onMouseenter","onClick"],In=["title","onMouseenter","onClick"],Cn={style:{"font-size":"11px","font-weight":"600"}},bn=e.defineComponent({__name:"SelectionToolbarCard",props:{placementAbove:{type:Boolean},anchorHeight:{},hiddenBuiltinActions:{},extraActions:{},renderCopyIcon:{type:Function}},emits:["action"],setup(t,{emit:r}){const s=t,n=r,a=[{id:"highlight",label:"高亮背景"},{id:"underline",label:"下划线"},{id:"squiggly",label:"波浪线"},{id:"strikeout",label:"删除线"}],o=e.computed(()=>new Set(s.hiddenBuiltinActions??[])),i=e.computed(()=>!o.value.has("copy")),l=e.computed(()=>a.filter(e=>!o.value.has(e.id))),h=e.computed(()=>!o.value.has("note")),d=e.computed(()=>[...s.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:s.placementAbove?void 0:`${s.anchorHeight+10}px`,bottom:s.placementAbove?`${s.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 f={width:"1px",height:"20px",margin:"0 4px",background:"rgba(15, 23, 42, 0.1)",flexShrink:0};return(r,s)=>(e.openBlock(),e.createElementBlock("div",{role:"toolbar","aria-label":"选区工具",style:e.normalizeStyle(p.value)},[i.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createElementVNode("button",{type:"button",title:"复制","aria-label":"复制",style:e.normalizeStyle(g("copy")),onMouseenter:s[0]||(s[0]=e=>u.value="copy"),onMouseleave:s[1]||(s[1]=e=>u.value=null),onClick:s[2]||(s[2]=e=>n("action","copy"))},[t.renderCopyIcon?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(t.renderCopyIcon),{key:0})):(e.openBlock(),e.createBlock(vn,{key:1,kind:"copy"}))],36),c.value?(e.openBlock(),e.createElementBlock("span",{key:0,style:f,"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:s[3]||(s[3]=e=>u.value=null),onClick:e=>n("action",t.id)},[e.createVNode(vn,{kind:t.id},null,8,["kind"])],44,Pn))),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:s[4]||(s[4]=e=>u.value=null),onClick:e=>n("action",t.id)},[e.createElementVNode("span",Cn,e.toDisplayString(t.label.slice(0,2)),1)],44,In))),128)),h.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[c.value||i.value?(e.openBlock(),e.createElementBlock("span",{key:0,style:f,"aria-hidden":""})):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",title:"添加笔记","aria-label":"添加笔记",style:e.normalizeStyle(g("note",!0)),onMouseenter:s[5]||(s[5]=e=>u.value="note"),onMouseleave:s[6]||(s[6]=e=>u.value=null),onClick:s[7]||(s[7]=e=>n("action","note"))},[e.createVNode(vn,{kind:"note"})],36)],64)):e.createCommentVNode("",!0)],4))}}),wn={highlight:"highlight",underline:"underline",squiggly:"squiggly",strikeout:"strikeout"},Sn=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(s){const n=s,o=e.computed(()=>n.features),{hostRef:i}=Tr(o),l=e.computed(()=>{var e,t;return{background:(null==(t=null==(e=n.features)?void 0:e.scrollViewport)?void 0:t.background)??L}}),d=function(){const{registry:r}=t.useRegistry();return e.computed(()=>{var e,t,s;const n=null==(s=null==(t=null==(e=r.value)?void 0:e.getPlugin(mt.id))?void 0:t.provides)?void 0:s.call(t);return n?e=>n.createNoteFromSelection(e):null})}(),c=function(){const{registry:r}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=r.value)?void 0:e.getPlugin(mt.id))})}(),u=function(){const{registry:r}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=r.value)?void 0:e.getPlugin(dr.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)}),f=e.computed(()=>{var e,t;return u.value&&!1!==(null==(t=null==(e=n.features)?void 0:e.bookmarks)?void 0:t.enabled)}),m=function(s,n){const a=e.computed(()=>{var e;return null==(e=s())?void 0:e.selectionToolbar}),o=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=s())?void 0:e.markup)?void 0:t.enabled)}),i=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=s())?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(r.AnnotationPlugin.id),{provides:u}=t.useCapability(mt.id);return e.computed(()=>{var t,r,h;if(!1!==(null==(t=a.value)?void 0:t.enabled)&&(o.value||i.value||l.value||(null==(h=null==(r=a.value)?void 0:r.extraActions)?void 0:h.length)))return t=>{const r=rn(t.item),h=sn(t.item);return p=>{var g,f,m,v;return e.h("div",p.menuWrapperProps,e.h(bn,{placementAbove:!!(null==(g=p.placement)?void 0:g.suggestTop),anchorHeight:p.rect.size.height,hiddenBuiltinActions:null==(f=a.value)?void 0:f.hiddenBuiltinActions,extraActions:null==(m=a.value)?void 0:m.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||!i.value)return;const e=d.value.getHighlightRectsForPage(h,r);return void nn(d.value.getSelectedText(r),r=>{var s;null==(s=u.value)||s.requestCreateFromSelection({chapterId:t.item.chapterId,localPageIndex:t.item.localPageIndex,globalPageIndex:t.item.globalPageIndex,globalPageNumber:t.item.globalPageNumber,rectsPdfCoord:e,selectedText:r.join("\n")})})}null==(a=null==n?void 0:n.onExtraAction)||a.call(n,e,t)}else{if(!d.value||!c.value||!o.value)return;E(r,wn[e],c.value,d.value,null==(g=null==(p=s())?void 0:p.markup)?void 0:g.styles)}else{if(!d.value||!l.value)return;nn(d.value.getSelectedText(r),e=>{!async function(e){var t;const r=e.trim();if(!r)return!1;try{if("undefined"!=typeof navigator&&(null==(t=navigator.clipboard)?void 0:t.writeText))return await navigator.clipboard.writeText(r),!0}catch{}if("undefined"==typeof document)return!1;try{const e=document.createElement("textarea");e.value=r,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||m.value)return e=>{const t=m.value?m.value(e):e.defaultMenu;return n.buildSelectionMenu?n.buildSelectionMenu({...e,defaultMenu:t}):t}}),{provides:P}=t.useCapability(a.DocumentManagerPlugin.id);function I(t){var r;const s=[];if(f.value){const r=function(t){var r,s,a,o;const i=rn(t),l=sn(t),h=null==(s=null==(r=P.value)?void 0:r.getDocument(i))?void 0:s.pages[l];return t.isPlaceholder||!h?null:e.h(hn,{item:t,pdfPageWidth:h.size.width,pdfPageHeight:h.size.height,cssPageWidth:t.width,cssPageHeight:t.height,hoverUi:null==(o=null==(a=n.features)?void 0:a.bookmarks)?void 0:o.hover})}(t);r&&s.push(r)}const a=null==(r=n.renderPageOverlay)?void 0:r.call(n,t);if(a&&s.push(a),s.length)return e.h("div",s)}return(t,r)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"hostRef",ref:i,class:e.normalizeClass(s.className),style:e.normalizeStyle(s.className?void 0:e.unref(M))},[e.createVNode(e.unref(rs),{class:e.normalizeClass(s.className),style:e.normalizeStyle(l.value)},{page:e.withCtx(({item:t})=>{var r,n,a,o;return[e.createVNode(ln,{item:t,features:s.features,"show-note-markers":p.value,"show-bookmark-markers":g.value,"show-redaction-layer":s.showRedactionLayer,"note-marker-ui":null==(n=null==(r=s.features)?void 0:r.notes)?void 0:n.marker,"bookmark-marker-ui":null==(o=null==(a=s.features)?void 0:a.bookmarks)?void 0:o.marker,"build-selection-menu":v.value,"create-note":e.unref(d),"annotation-selection-menu":s.annotationSelectionMenu,"redaction-selection-menu":s.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))}}),yn={key:0,style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,width:"100%"}},Mn=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{},onExtraSelectionAction:{type:Function}},setup(r){const s=r,n=e.computed(()=>function(e){if(e.options)return Sr(e.options);if(!e.editorOptions)throw new Error("ChapterPdfViewer: 请传入 `options`(推荐),或同时传入 `editorOptions` 与 `features`");const t=N(e.features),{plugins:r}=Ir({...e.editorOptions,features:t});return{plugins:r,features:t,editorOptions:{...e.editorOptions,features:t}}}({engine:s.engine,options:s.options,editorOptions:s.editorOptions,features:s.features}));return(s,a)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(r.className),style:e.normalizeStyle(r.className?void 0:e.unref(M))},[e.createVNode(e.unref(t.EmbedPDF),{engine:r.engine,plugins:n.value.plugins},{default:e.withCtx(({pluginsReady:t})=>[t?(e.openBlock(),e.createElementBlock("div",yn,[e.renderSlot(s.$slots,"prepend"),e.createVNode(Sn,{class:e.normalizeClass(r.viewportClassName),style:{flex:1,minHeight:0},features:n.value.features,"on-extra-selection-action":r.onExtraSelectionAction},null,8,["class","features","on-extra-selection-action"]),e.renderSlot(s.$slots,"default")])):e.createCommentVNode("",!0)]),_:3},8,["engine","plugins"])],6))}}),xn={class:"chapter-tree-row"},$n=["aria-expanded"],Ln={key:1,class:"chapter-tree-toggle-spacer","aria-hidden":""},Dn={class:"chapter-tree-label"},kn={class:"chapter-tree-meta"},Un={key:0},Tn=(e,t)=>{const r=e.__vccOpts||e;for(const[s,n]of t)r[s]=n;return r},En=Tn(e.defineComponent({__name:"ChapterTreeItem",props:{node:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup(t){const r={idle:"未加载",loading:"加载中",loaded:"已加载",closed:"已卸载",error:"失败","password-required":"需密码"},s=t,n=e.computed(()=>s.node.children??[]),a=e.computed(()=>n.value.length>0),o=e.ref(s.depth<1),i=e.computed(()=>s.activeChapterId===s.node.id),l=e.computed(()=>s.chapterStatus[s.node.id]??"idle"),h=e.computed(()=>!a.value);return(s,d)=>(e.openBlock(),e.createElementBlock("li",null,[e.createElementVNode("div",xn,[a.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"chapter-tree-toggle","aria-expanded":o.value,onClick:d[0]||(d[0]=e=>o.value=!o.value)},e.toDisplayString(o.value?"▼":"▶"),9,$n)):(e.openBlock(),e.createElementBlock("span",Ln)),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["chapter-tree-btn",{"chapter-tree-btn-active":i.value}]),onClick:d[1]||(d[1]=e=>s.$emit("select",t.node.id))},[e.createElementVNode("div",Dn,e.toDisplayString(t.node.title),1),e.createElementVNode("div",kn,[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",Un,e.toDisplayString(r[l.value]),1)):e.createCommentVNode("",!0)])],2)]),a.value&&o.value?(e.openBlock(),e.createBlock(An,{key:0,nodes:n.value,depth:t.depth+1,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:d[2]||(d[2]=e=>s.$emit("select",e))},null,8,["nodes","depth","active-chapter-id","chapter-status"])):e.createCommentVNode("",!0)]))}}),[["__scopeId","data-v-315bbf7a"]]),An=Tn(e.defineComponent({__name:"ChapterTreeList",props:{nodes:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup:t=>(r,s)=>(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(En,{key:n.id,node:n,depth:t.depth,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:s[0]||(s[0]=e=>r.$emit("select",e))},null,8,["node","depth","active-chapter-id","chapter-status"]))),128))],4))}),[["__scopeId","data-v-eb742e4f"]]),Fn={class:"chapter-tree"},Nn={class:"chapter-tree-nav","aria-label":"章节目录"},On=Tn(e.defineComponent({__name:"ChapterTreePanel",props:{tree:{},activeChapterId:{}},emits:["active-chapter-change"],setup(r,{emit:s}){const n=r,a=s,{provides:o}=t.useCapability(Le.id),{provides:i}=t.useCapability(se.id),l=e.ref({});function h(){if(!i.value)return;const e={},t=r=>{var s;for(const n of r)e[n.id]=i.value.getChapterStatus(n.id),(null==(s=n.children)?void 0:s.length)&&t(n.children)};t(n.tree),l.value=e}e.watch([i,()=>n.tree],h,{immediate:!0});let d=null;function c(e){var t;a("active-chapter-change",e),null==(t=o.value)||t.scrollToChapter(e)}return e.watch(i,e=>{null==d||d(),d=e?e.onChapterStatusChange(h):null},{immediate:!0}),e.onBeforeUnmount(()=>null==d?void 0:d()),(t,s)=>(e.openBlock(),e.createElementBlock("aside",Fn,[s[0]||(s[0]=e.createElementVNode("h2",{class:"chapter-tree-title"},"章节目录",-1)),e.createElementVNode("nav",Nn,[e.createVNode(An,{nodes:r.tree,depth:0,"active-chapter-id":r.activeChapterId,"chapter-status":l.value,onSelect:c},null,8,["nodes","active-chapter-id","chapter-status"])])]))}}),[["__scopeId","data-v-d7a0838d"]]),zn=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{}},setup:t=>(t,r)=>(e.openBlock(),e.createBlock(e.unref(Mn),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 Gn(e){const[t,r]=e.localPageRange;return r-t+1}function Rn(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Vn(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Rn(t)?t.segmentPageThreshold:null}function _n(e,t){return`${e}#s${t}`}function Bn(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function qn(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Hn(e){const t=Vn(e);if(!t)return null;const r=Gn(e),s=qn(r,t),n=Rn(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:_n(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Wn(e,t){const r=Hn(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function jn(e,t){const r=Hn(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Yn(e){var t;const r=Vn(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Gn(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!Rn(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=qn(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Zn={kind:"first-wins"};function Kn(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let Jn=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const Xn=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Zn,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Zn,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Bn(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Bn(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Bn(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?Wn(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Hn(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Yn(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=Zn){const r=function(e,t=Zn){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Kn(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Jn(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Hn(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=jn(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=Wn(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=Hn(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(Rn(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Vn(t);if(a){const s=qn(Gn(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(Rn(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=Bn(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?Hn(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Xn.id="chapter-manager";let Qn=Xn;function ea(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ta(e,t){return`${e}#s${t}`}function ra(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function sa(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ea(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=ea(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:ta(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function na(e){const[t,r]=e.localPageRange;return r-t+1}function aa(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function oa(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return aa(t)?t.segmentPageThreshold:null}function ia(e,t){return`${e}#s${t}`}function la(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function ha(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function da(e){const t=oa(e);if(!t)return null;const r=na(e),s=ha(r,t),n=aa(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:ia(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function ca(e,t){const r=da(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function ua(e,t){const r=da(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function pa(e){var t;const r=oa(e);if(!r)return[];const s=[],{chapterId:n}=e,a=na(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!aa(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=ha(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const ga={kind:"first-wins"};function fa(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}class ma{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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}}const va=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ga,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ga,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=la(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=la(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=la(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?ca(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?da(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...pa(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=ga){const r=function(e,t=ga){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,fa(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new ma(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?da(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=ua(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=ca(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=da(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(aa(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=oa(t);if(a){const s=ha(na(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(aa(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=la(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?da(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};va.id="chapter-manager";let Pa=va;function Ia(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.height!==n.height)return!1}return!0}function Ca(e){const[t,r]=e.localPageRange;return r-t+1}function ba(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function wa(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ba(t)?t.segmentPageThreshold:null}function Sa(e,t){return`${e}#s${t}`}function ya(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Ma(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function xa(e){const t=wa(e);if(!t)return null;const r=Ca(e),s=Ma(r,t),n=ba(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:Sa(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function $a(e,t){const r=xa(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function La(e,t){const r=xa(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Da(e){var t;const r=wa(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Ca(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!ba(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=Ma(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}(class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,Ia),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Pa.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.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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapterStatus(e);if("error"===s||"password-required"===s)return!0;const n=r.getChapter(e);if(!n)return!0;const a=function(e,t){const r=sa(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(n,t);return!r.isSegmentLoaded(e,a)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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:r}=ra(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=ra(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}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 r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=sa(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):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:r}=ra(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.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 r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}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,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n),t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(a),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}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 r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}}).id="chapter-scroll";const ka={kind:"first-wins"};function Ua(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let Ta=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const Ea=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ka,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ka,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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?$a(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?xa(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Da(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=ka){const r=function(e,t=ka){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Ua(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Ta(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?xa(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=La(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=$a(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=xa(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(ba(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=wa(t);if(a){const s=Ma(Ca(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(ba(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=ya(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?xa(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Ea.id="chapter-manager";let Aa=Ea;function Fa(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Na(e,t){return`${e}#s${t}`}function Oa(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function za(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Fa(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=Fa(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:Na(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Ga(e){const[t,r]=e.localPageRange;return r-t+1}function Ra(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Va(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ra(t)?t.segmentPageThreshold:null}function _a(e,t){return`${e}#s${t}`}function Ba(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function qa(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ha(e){const t=Va(e);if(!t)return null;const r=Ga(e),s=qa(r,t),n=Ra(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:_a(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Wa(e,t){const r=Ha(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function ja(e,t){const r=Ha(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Ya(e){var t;const r=Va(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Ga(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!Ra(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=qa(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Za={kind:"first-wins"};function Ka(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let Ja=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const Xa=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Za,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Za,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Ba(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Ba(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Ba(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?Wa(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ha(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Ya(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=Za){const r=function(e,t=Za){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Ka(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Ja(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ha(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=ja(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=Wa(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=Ha(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(Ra(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Va(t);if(a){const s=qa(Ga(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(Ra(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=Ba(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?Ha(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Xa.id="chapter-manager";let Qa=Xa;function eo(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.height!==n.height)return!1}return!0}const to=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,eo),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Qa.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.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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapterStatus(e);if("error"===s||"password-required"===s)return!0;const n=r.getChapter(e);if(!n)return!0;const a=function(e,t){const r=za(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(n,t);return!r.isSegmentLoaded(e,a)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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:r}=Oa(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=Oa(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}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 r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=za(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):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:r}=Oa(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.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 r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}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,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n),t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(a),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}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 r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};to.id="chapter-scroll";let ro=to;const so=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(ro.id),this.chapterManager=this.registry.getPlugin(Aa.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(r){this.logger.error(e.id,"LoadNotes","Failed to load notes",r)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(r=>r.chapterId===e&&r.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,r;const s=this.notes.get(e);s&&(null==(r=(t=this.config.callbacks).onActivateNote)||r.call(t,e,s),this.noteActivated$.emit({noteId:e,anchor:s}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[r,s]of this.notes.entries())s.chapterId===e&&this.notes.delete(r);for(const r of t)r.chapterId===e&&this.notes.set(r.noteId,r);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:ao(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:r,onCreateNote:s}=this.config.callbacks;return r?(r({draft:t,complete:async e=>{const r={...t,noteId:e};this.registerNote(r)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const r=this.buildDraft(t),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await s(r)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!n)return null;const a={...r,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var r,s;if(this.notes.has(t)){try{await(null==(s=(r=this.config.callbacks).onDeleteNote)?void 0:s.call(r,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,r){var s,n;const a=this.notes.get(t);if(!a)return;const o={...a,content:r};try{await(null==(n=(s=this.config.callbacks).onUpdateNote)?void 0:n.call(s,o))}catch(i){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",i)}this.notes.set(t,o),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const r=this.notes.get(e);if(!r)return;const s=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(r.chapterId);const a=n.resolvePageDocument(r.chapterId,r.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(s.scrollToGlobalPageIndex(r.globalPageIndex),await this.waitForPageInLayout(r.globalPageIndex),s.scrollToGlobalPdfPoint(r.globalPageIndex,r.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(r.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),r=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return r?Promise.resolve(r):new Promise(r=>{const s=setTimeout(()=>{n(),r(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(s),n(),r(a))})})}};so.id="note";let no=so;function ao(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function oo(e){const[t,r]=e.localPageRange;return r-t+1}function io(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function lo(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return io(t)?t.segmentPageThreshold:null}function ho(e,t){return`${e}#s${t}`}function co(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function uo(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function po(e){const t=lo(e);if(!t)return null;const r=oo(e),s=uo(r,t),n=io(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:ho(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function go(e,t){const r=po(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function fo(e,t){const r=po(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function mo(e){var t;const r=lo(e);if(!r)return[];const s=[],{chapterId:n}=e,a=oo(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!io(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=uo(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const vo={kind:"first-wins"};function Po(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let Io=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const Co=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=vo,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??vo,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=co(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=co(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=co(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?go(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?po(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...mo(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=vo){const r=function(e,t=vo){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Po(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Io(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?po(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=fo(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=go(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=po(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(io(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=lo(t);if(a){const s=uo(oo(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(io(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=co(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?po(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Co.id="chapter-manager";let bo=Co;function wo(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function So(e,t){return`${e}#s${t}`}function yo(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Mo(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return wo(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=wo(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:So(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function xo(e){const[t,r]=e.localPageRange;return r-t+1}function $o(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Lo(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return $o(t)?t.segmentPageThreshold:null}function Do(e,t){return`${e}#s${t}`}function ko(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Uo(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function To(e){const t=Lo(e);if(!t)return null;const r=xo(e),s=Uo(r,t),n=$o(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:Do(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Eo(e,t){const r=To(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Ao(e,t){const r=To(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Fo(e){var t;const r=Lo(e);if(!r)return[];const s=[],{chapterId:n}=e,a=xo(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!$o(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=Uo(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const No={kind:"first-wins"};function Oo(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}class zo{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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}}const Go=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=No,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??No,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=ko(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=ko(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=ko(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?Eo(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?To(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Fo(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=No){const r=function(e,t=No){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Oo(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new zo(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?To(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Ao(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=Eo(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=To(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if($o(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Lo(t);if(a){const s=Uo(xo(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if($o(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=ko(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?To(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Go.id="chapter-manager";let Ro=Go;function Vo(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.height!==n.height)return!1}return!0}const _o=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,Vo),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Ro.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.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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapterStatus(e);if("error"===s||"password-required"===s)return!0;const n=r.getChapter(e);if(!n)return!0;const a=function(e,t){const r=Mo(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(n,t);return!r.isSegmentLoaded(e,a)}refreshLayout(){this.layoutChange$.emit(this.computeLayout())}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:r}=yo(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=yo(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}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 r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=Mo(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):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:r}=yo(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.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 r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}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,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n),t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(a),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}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 r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};_o.id="chapter-scroll";let Bo=_o;function qo(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Ho(e,t){const r=e.origin.y,s=e.origin.y+e.size.height,n=t.origin.y,a=t.origin.y+t.size.height,o=Math.max(s,a)-Math.min(r,n);return o<=0?0:Math.max(0,Math.min(s,a)-Math.max(r,n))/o}function Wo(e,t){var r,s;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const n=(null==(r=e.rectsPdfCoord)?void 0:r.length)?e.rectsPdfCoord:[e.rectPdfCoord],a=(null==(s=t.rectsPdfCoord)?void 0:s.length)?t.rectsPdfCoord:[t.rectPdfCoord],o=e.markerAnchor??qo(n),i=t.markerAnchor??qo(a);if(Math.hypot(o.x-i.x,o.y-i.y)<=6)return!0;for(const l of n)for(const e of a){if(Ho(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 jo=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.change$=n.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(Bo.id),this.chapterManager=this.registry.getPlugin(bo.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){var r;if(this.config=t,null==(r=t.callbacks)?void 0:r.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(s){this.logger.error(e.id,"Load","Failed to load paragraph bookmarks",s)}}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 s of this.entries.values())if(Wo(s.anchor,e.anchor))return s;const t=e.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r={id:t,label:e.label,anchor:e.anchor,metadata:e.metadata,createdAt:Date.now()};return this.entries.set(t,r),this.notifyAndPersist(),r}removeBookmark(e){var t,r,s;this.entries.delete(e)&&(this.notifyAndPersist(),null==(s=null==(r=null==(t=this.config)?void 0:t.callbacks)?void 0:r.onRemoveSuccess)||s.call(r,e))}async requestRemoveBookmark(t){var r,s;const n=this.entries.get(t);if(!n)return!1;const a=null==(s=null==(r=this.config)?void 0:r.callbacks)?void 0:s.onRequestRemove;if(a)try{if(!(await a(n)))return!1}catch(o){return this.logger.error(e.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(t),!0}updateBookmark(e,t){const r=this.entries.get(e);r&&(this.entries.set(e,{...r,...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[r,s]of this.entries.entries())s.anchor.chapterId===e&&this.entries.delete(r);for(const r of t)r.anchor.chapterId===e&&this.entries.set(r.id,r);this.notifyAndPersist()}notifyAndPersist(){var t,r;const s=this.list();this.change$.emit(s),(null==(r=null==(t=this.config)?void 0:t.callbacks)?void 0:r.persist)&&Promise.resolve(this.config.callbacks.persist(s)).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 r=this.chapterScroll.provides(),s=this.chapterManager.provides();await s.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,r){e.scrollToGlobalPageIndex(t),await function(e,t,r=2500){const s=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const n=setTimeout(()=>{a(),s(null)},r),a=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(n),a(),s(r))})})}(e,t),e.scrollToGlobalPdfPoint(t,r,{marginTop:80})}(r,n,a)}};jo.id="paragraph-bookmark";let Yo=jo;function Zo(e,t){const r=e;return!1===e?{...t,enabled:!1}:!0===e||void 0===e?{...t,enabled:t.enabled??!0}:{...t,...r,enabled:!1!==(null==r?void 0:r.enabled)}}function Ko(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Jo(e,t){return`${e}#s${t}`}function Xo(e,t){const r=function(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ko(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=Ko(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:Jo(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}s.PdfAnnotationSubtype.HIGHLIGHT,s.PdfAnnotationSubtype.UNDERLINE,s.PdfAnnotationSubtype.SQUIGGLY,s.PdfAnnotationSubtype.STRIKEOUT,s.PdfAnnotationSubtype.HIGHLIGHT,s.PdfAnnotationSubtype.UNDERLINE,s.PdfAnnotationSubtype.SQUIGGLY,s.PdfAnnotationSubtype.STRIKEOUT,function(){const e=Zo(void 0,{enabled:!0}),t=Zo(void 0,{enabled:!0}),r=Zo(void 0,{enabled:!0}),s=Zo(void 0,{enabled:!0,min:.5,max:3,initial:1}),n=Zo(!1!==e.enabled||!1!==r.enabled,{enabled:!0});null==void 0||(void 0).background}();function Qo(e){const t=new Uint8Array(e);let r="";for(let s=0;s<t.length;s++)r+=String.fromCharCode(t[s]);return btoa(r)}function ei(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 ti(e){return new Promise((t,r)=>{e.wait(e=>t(e),e=>r(e))})}function ri(e){var t,s,n,a;return{annotation:null==(t=e.getPlugin(r.AnnotationPlugin.id))?void 0:t.provides(),note:null==(s=e.getPlugin(no.id))?void 0:s.provides(),bookmark:null==(n=e.getPlugin(Yo.id))?void 0:n.provides(),chapterManager:null==(a=e.getPlugin(Qn.id))?void 0:a.provides()}}async function si(e,t,r){if(!r||!e)return;const s=e.getSegmentPlan(t)?await e.ensureAllSegmentsLoaded(t):await e.ensureChapterLoaded(t);if("loaded"!==s)throw new Error(`章节 ${t} 未加载成功(${s}),无法导入/导出划线`)}async function ni(e,t,r){const s=ei(r),{annotation:n,note:a,bookmark:o,chapterManager:i}=ri(e),l={chapterId:t};if(s.bookmarks){if(!o)throw new Error("paragraph-bookmark 插件未注册");l.bookmarks=o.listBookmarksForChapter(t)}if(s.notes){if(!a)throw new Error("note 插件未注册");l.notes=a.listNotesForChapter(t)}if(s.markup){if(!n)throw new Error("annotation 插件未注册");await si(i,t,!1!==(null==r?void 0:r.ensureChapterLoaded));const e=await async function(e,t,r){const s=t.getSegmentPlan(r);if(!s)return ti(e.forDocument(r).exportAnnotations());const n=[];for(const a of s.segments){if(!t.isSegmentLoaded(r,a.index))continue;const s=await ti(e.forDocument(a.documentId).exportAnnotations());for(const e of s){const t=e.annotation.pageIndex;n.push({...e,annotation:{...e.annotation,pageIndex:t+a.localPageStart}})}}return n}(n,i,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:Qo(t.data),mimeType:t.mimeType}}})}(e)}return l}async function ai(e,t,r){const s=ei(r),n=(null==r?void 0:r.mode)??"replace",{annotation:a,note:o,bookmark:i,chapterManager:l}=ri(e),h=t.chapterId;if(s.bookmarks&&t.bookmarks){if(!i)throw new Error("paragraph-bookmark 插件未注册");if("replace"===n)i.replaceBookmarksForChapter(h,t.bookmarks);else for(const e of t.bookmarks)i.addBookmark(e)}if(s.notes&&t.notes){if(!o)throw new Error("note 插件未注册");if("replace"===n)o.replaceNotesForChapter(h,t.notes);else for(const e of t.notes)o.registerNote(e)}if(s.markup&&t.markup){if(!a)throw new Error("annotation 插件未注册");await si(l,h,!1!==(null==r?void 0:r.ensureChapterLoaded)),function(e,t,r,s,n){const a=t.getSegmentPlan(r);if(!a){const t=e.forDocument(r);return"replace"===n&&t.deleteAllAnnotations(),void t.importAnnotations(s)}const o=t.getChapter(r);if(!o)return;const i=new Map;for(const l of s){const e=l.annotation.pageIndex,t=Xo(o,e),r=a.segments[t];if(!r)continue;const s=i.get(t)??[];s.push({...l,annotation:{...l.annotation,pageIndex:e-r.localPageStart}}),i.set(t,s)}for(const l of a.segments){const t=e.forDocument(l.documentId),r=i.get(l.index)??[];"replace"===n&&t.deleteAllAnnotations(),r.length>0&&t.importAnnotations(r)}}(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 r=function(e){const t=atob(e),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r.buffer}(e.ctx.dataBase64);return{annotation:e.annotation,ctx:{data:r,...e.ctx.mimeType?{mimeType:e.ctx.mimeType}:{}}}})}(t.markup),n)}(null==r?void 0:r.persistNotes)&&o&&await r.persistNotes(o.listAllNotes()),(null==r?void 0:r.persistBookmarks)&&i&&await r.persistBookmarks(i.listBookmarks())}function oi(e){return JSON.stringify(e,null,2)}function ii(e){return JSON.stringify(e,null,2)}function li(e,t){const r=new Blob([t],{type:"application/json;charset=utf-8"}),s=URL.createObjectURL(r),n=document.createElement("a");n.href=s,n.download=e,n.click(),URL.revokeObjectURL(s)}s.PdfAnnotationSubtype.HIGHLIGHT,s.PdfAnnotationSubtype.UNDERLINE,s.PdfAnnotationSubtype.SQUIGGLY,s.PdfAnnotationSubtype.STRIKEOUT,s.PdfAnnotationSubtype.HIGHLIGHT,s.PdfAnnotationSubtype.UNDERLINE,s.PdfAnnotationSubtype.SQUIGGLY,s.PdfAnnotationSubtype.STRIKEOUT;function hi(e){const[t,r]=e.localPageRange;return r-t+1}function di(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ci(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return di(t)?t.segmentPageThreshold:null}function ui(e,t){return`${e}#s${t}`}function pi(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function gi(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function fi(e){const t=ci(e);if(!t)return null;const r=hi(e),s=gi(r,t),n=di(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:ui(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function mi(e,t){const r=fi(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function vi(e,t){const r=fi(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Pi(e){var t;const r=ci(e);if(!r)return[];const s=[],{chapterId:n}=e,a=hi(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!di(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=gi(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Ii={kind:"first-wins"};function Ci(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}class bi{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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}}function wi(e,t=Ii){const r=function(e,t=Ii){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Ci(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new bi(a)}const Si=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Ii,this.chapterStatus=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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Ii,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=pi(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=pi(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=pi(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?mi(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?fi(t):null},isSegmentLoaded:(e,t)=>this.isSegmentDocumentOpen(e,t),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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Pi(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.chapters.map(e=>e.chapterId));for(const e of n)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=wi(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?fi(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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)}))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=vi(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=mi(this.findChapter(r.chapterId),r.localPageIndex);if(this.documentManager.provides().isDocumentOpen(e.documentId)){this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus){if("loaded"!==s)continue;t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=fi(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(di(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=ci(t);if(a){const s=gi(hi(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(di(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;0===a&&this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=pi(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}if(!l)return void this.updateStatus(r,"password-required");this.updateStatus(r,"loading");this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?fi(t):null,n=e=>{if(r.isDocumentOpen(e)){r.closeDocument(e).wait(()=>{},()=>{})}};if(s)for(const a of s.segments)n(a.documentId);else n(e);this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e),this.updateStatus(e,"closed")}updateStatus(e,t,r){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Si.id="chapter-manager";let yi=Si;function Mi(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 xi(e){const t=[],r=e=>{var s;for(const n of e)t.push(Mi(n)),(null==(s=n.children)?void 0:s.length)&&r(n.children)};return r(e),t}function $i(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)?$i(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=R,exports.ChapterManagerPlugin=yi,exports.ChapterPdfViewer=zn,exports.ChapterTreePanel=On,exports.DEFAULT_CHAPTER_TEXT_SELECTION_BACKGROUND="rgba(33, 150, 243)",exports.DEFAULT_CHAPTER_VIEWER_CONFIG={},exports.DEFAULT_CHAPTER_VIEWER_FEATURES=Pr,exports.PdfChapterViewport=Sn,exports.applySelectionMarkup=E,exports.buildChapterViewerCatalog=function(e){return{tree:$i(e),manifest:{chapters:xi(e)}}},exports.buildParagraphBookmarkAnchor=lr,exports.chapterAnnotationsArchiveToJson=oi,exports.chapterAnnotationsSnapshotToJson=ii,exports.chapterDescriptorFromTreeNode=Mi,exports.copyTextToClipboard=async function(e){var t;const r=e.trim();if(!r)return!1;try{if("undefined"!=typeof navigator&&(null==(t=navigator.clipboard)?void 0:t.writeText))return await navigator.clipboard.writeText(r),!0}catch{}if("undefined"==typeof document)return!1;try{const e=document.createElement("textarea");e.value=r,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=Sr,exports.createChapterViewerEditor=Ir,exports.createChapterViewerEditorOptions=function(e){const{features:t,...r}=wr(br(e));return r},exports.createPdfChapterEditor=mr,exports.defaultOverlapStrategy={kind:"first-wins"},exports.downloadChapterAnnotationsArchive=function(e,t="chapter-annotations.json"){li(t,oi(e))},exports.downloadChapterAnnotationsSnapshot=function(e,t){li(t??`chapter-annotations-${e.chapterId}.json`,ii(e))},exports.downloadJsonFile=li,exports.exportAllChapterAnnotations=async function(e,t,r){const s={};for(const n of t.chapters){const t=await ni(e,n.chapterId,r),{chapterId:a,...o}=t;s[n.chapterId]=o}return{version:1,exportedAt:(new Date).toISOString(),chapters:s}},exports.exportChapterAnnotations=ni,exports.flattenChapterTree=xi,exports.importChapterAnnotations=ai,exports.importChapterAnnotationsArchive=async function(e,t,r){if(1!==t.version)throw new Error(`不支持的归档版本 ${t.version},当前为 1`);for(const[s,n]of Object.entries(t.chapters))await ai(e,{chapterId:s,...n},r)},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=$i;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),t=require("@embedpdf/core/vue"),r=require("@embedpdf/plugin-annotation"),s=require("@embedpdf/models"),n=require("@embedpdf/core"),a=require("@embedpdf/plugin-document-manager"),o=require("@embedpdf/plugin-interaction-manager"),i=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"),C=require("@embedpdf/plugin-selection/vue"),b=require("@embedpdf/plugin-annotation/vue"),S=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",D={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:4},strikeout:{offsetY:0}},k={highlight:s.PdfAnnotationSubtype.HIGHLIGHT,underline:s.PdfAnnotationSubtype.UNDERLINE,squiggly:s.PdfAnnotationSubtype.SQUIGGLY,strikeout:s.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,r=1/0,s=-1/0,n=-1/0;for(const a of e)t=Math.min(t,a.origin.x),r=Math.min(r,a.origin.y),s=Math.max(s,a.origin.x+a.size.width),n=Math.max(n,a.origin.y+a.size.height);return{origin:{x:t,y:r},size:{width:s-t,height:n-r}}}function T(e,t,n,a,o){const i=n.forDocument(e),l=a.forDocument(e);if(!i||!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={...D[g=t],...null==(m=o)?void 0:m[g]},p=l.getFormattedSelection();var g,m;if(0===p.length)return!1;i.setLocked({type:r.LockModeType.Exclude,categories:["markup","shape"]});for(const r of p){const e=s.uuidV4(),n=u.color??c.color??c.strokeColor,a=u.opacity??c.opacity,o=u.thickness??c.strokeWidth,l=u.offsetY??0,h="underline"===t||"squiggly"===t||"strikeout"===t?U(r.segmentRects,l):r.segmentRects,d="underline"===t||"squiggly"===t||"strikeout"===t?E(h):r.rect;i.createAnnotation(r.pageIndex,{id:e,created:new Date,flags:["print"],type:k[t],..."highlight"===t?{blendMode:s.PdfBlendMode.Multiply}:{},strokeColor:n,opacity:a,...null!=o?{strokeWidth:o}:{},pageIndex:r.pageIndex,rect:d,segmentRects:h})}return l.clear(),!0}const F=new Set([s.PdfAnnotationSubtype.HIGHLIGHT,s.PdfAnnotationSubtype.UNDERLINE,s.PdfAnnotationSubtype.SQUIGGLY,s.PdfAnnotationSubtype.STRIKEOUT]);function A(e,t){const r=e;return!1===e?{...t,enabled:!1}:!0===e||void 0===e?{...t,enabled:t.enabled??!0}:{...t,...r,enabled:!1!==(null==r?void 0:r.enabled)}}function N(e){var t;const r=A(null==e?void 0:e.markup,{enabled:!0}),s=A(null==e?void 0:e.bookmarks,{enabled:!0}),n=A(null==e?void 0:e.notes,{enabled:!0}),a=A(null==e?void 0:e.zoom,{enabled:!0,min:.5,max:3,initial:1}),o=A(void 0===(null==e?void 0:e.selectionToolbar)?!1!==r.enabled||!1!==n.enabled:e.selectionToolbar,{enabled:!0});return{markup:r,bookmarks:s,notes:n,zoom:a,scrollViewport:{background:(null==(t=null==e?void 0:e.scrollViewport)?void 0:t.background)??$},selectionToolbar:o}}function O(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function z(e,t){return`${e}#s${t}`}function G(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return O(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=O(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:z(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}let V=class{constructor(e){this.cb=e}resolvePassword(e,t){return this.cb(e,t)}};const R="chapter-manager",B={id:R,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}};function _(e){const[t,r]=e.localPageRange;return r-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 j(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Y(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Z(e){const t=W(e);if(!t)return null;const r=_(e),s=Y(r,t),n=q(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:H(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function K(e,t){const r=Z(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function J(e,t){const r=Z(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function X(e){var t;const r=W(e);if(!r)return[];const s=[],{chapterId:n}=e,a=_(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!q(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=Y(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Q={kind:"first-wins"};function ee(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const re=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.unloadTimer=null,this.documentManagerUnsubs=[],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}=j(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=j(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=j(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?K(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Z(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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...X(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.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 r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=Q){const r=function(e,t=Q){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,ee(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new te(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Z(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var r;const s=this.getSegmentPlanForChapter(e);return s?(null==(r=s.segments[t])?void 0:r.documentId)??null:0===t?e:null}isSegmentLoadPending(e,t){const r=this.resolveSegmentDocumentId(e,t);if(!r)return!1;if(this.pendingSegmentLoadPromises.has(r))return!0;if(0===t&&this.pendingChapterLoadPromises.has(e))return!0;const s=this.coreState.core.documents[r];return"loading"===(null==s?void 0:s.status)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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.isSegmentLoadPending(e,0))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=J(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=K(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=Z(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(q(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=W(t);if(a){const s=Y(_(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(q(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;this.chapterErrorMessages.delete(n),this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=j(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?Z(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.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,r){const s=this.chapterStatus.get(e);"error"===t&&r?this.chapterErrorMessages.set(e,r):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),s!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};re.id="chapter-manager";let se=re;const ne={manifest:B,create:e=>new se(R,e),reducer:e=>e,initialState:{}},ae="chapter-scroll",oe={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 ie(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 r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function de(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ie(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=ie(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:le(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function ce(e){const[t,r]=e.localPageRange;return r-t+1}function ue(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function pe(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ue(t)?t.segmentPageThreshold:null}function ge(e,t){return`${e}#s${t}`}function me(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function fe(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function ve(e){const t=pe(e);if(!t)return null;const r=ce(e),s=fe(r,t),n=ue(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:ge(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Pe(e,t){const r=ve(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Ie(e,t){const r=ve(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Ce(e){var t;const r=pe(e);if(!r)return[];const s=[],{chapterId:n}=e,a=ce(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!ue(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=fe(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const be={kind:"first-wins"};function Se(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const ye=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=be,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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??be,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=me(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=me(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=me(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?Pe(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ve(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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Ce(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.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 r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=be){const r=function(e,t=be){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Se(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new we(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ve(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var r;const s=this.getSegmentPlanForChapter(e);return s?(null==(r=s.segments[t])?void 0:r.documentId)??null:0===t?e:null}isSegmentLoadPending(e,t){const r=this.resolveSegmentDocumentId(e,t);if(!r)return!1;if(this.pendingSegmentLoadPromises.has(r))return!0;if(0===t&&this.pendingChapterLoadPromises.has(e))return!0;const s=this.coreState.core.documents[r];return"loading"===(null==s?void 0:s.status)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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.isSegmentLoadPending(e,0))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Ie(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=Pe(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=ve(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(ue(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=pe(t);if(a){const s=fe(ce(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(ue(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;this.chapterErrorMessages.delete(n),this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=me(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?ve(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.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,r){const s=this.chapterStatus.get(e);"error"===t&&r?this.chapterErrorMessages.set(e,r):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),s!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};ye.id="chapter-manager";let Me=ye;function xe(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.height!==n.height)return!1}return!0}const Le=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,xe),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Me.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.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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapter(e);if(!s)return!0;const n=function(e,t){const r=de(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(s,t);return!r.isSegmentLoaded(e,n)}refreshLayout(){this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);0!==e.length&&this.chapterManager.provides().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:r}=he(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=he(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}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 r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=de(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):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:r}=he(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.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 r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const r=this.config.bufferSize,s=Math.max(0,e[0]-r),n=Math.min(t-1,e[e.length-1]+r),a=[];for(let o=s;o<=n;o++)a.push(o);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,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}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 r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};Le.id="chapter-scroll";let $e=Le;const De={manifest:oe,create:e=>new $e(ae,e),reducer:e=>e,initialState:{}},ke="note",Ue={id:ke,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 Ee(e){const[t,r]=e.localPageRange;return r-t+1}function Te(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Fe(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Te(t)?t.segmentPageThreshold:null}function Ae(e,t){return`${e}#s${t}`}function Ne(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Oe(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function ze(e){const t=Fe(e);if(!t)return null;const r=Ee(e),s=Oe(r,t),n=Te(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:Ae(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Ge(e,t){const r=ze(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Ve(e,t){const r=ze(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Re(e){var t;const r=Fe(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Ee(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!Te(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=Oe(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Be={kind:"first-wins"};function _e(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let qe=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const We=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Be,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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Be,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Ne(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Ne(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Ne(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?Ge(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ze(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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Re(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.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 r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=Be){const r=function(e,t=Be){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,_e(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new qe(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ze(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var r;const s=this.getSegmentPlanForChapter(e);return s?(null==(r=s.segments[t])?void 0:r.documentId)??null:0===t?e:null}isSegmentLoadPending(e,t){const r=this.resolveSegmentDocumentId(e,t);if(!r)return!1;if(this.pendingSegmentLoadPromises.has(r))return!0;if(0===t&&this.pendingChapterLoadPromises.has(e))return!0;const s=this.coreState.core.documents[r];return"loading"===(null==s?void 0:s.status)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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.isSegmentLoadPending(e,0))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Ve(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=Ge(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=ze(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(Te(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Fe(t);if(a){const s=Oe(Ee(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(Te(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;this.chapterErrorMessages.delete(n),this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=Ne(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?ze(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.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,r){const s=this.chapterStatus.get(e);"error"===t&&r?this.chapterErrorMessages.set(e,r):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),s!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};We.id="chapter-manager";let He=We;function je(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ye(e,t){return`${e}#s${t}`}function Ze(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Ke(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 r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=je(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:Ye(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Je(e){const[t,r]=e.localPageRange;return r-t+1}function Xe(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Qe(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Xe(t)?t.segmentPageThreshold:null}function et(e,t){return`${e}#s${t}`}function tt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function rt(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function st(e){const t=Qe(e);if(!t)return null;const r=Je(e),s=rt(r,t),n=Xe(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:et(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function nt(e,t){const r=st(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function at(e,t){const r=st(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function ot(e){var t;const r=Qe(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Je(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!Xe(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=rt(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const it={kind:"first-wins"};function lt(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let ht=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const dt=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=it,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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??it,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=tt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=tt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=tt(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?nt(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?st(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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...ot(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.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 r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=it){const r=function(e,t=it){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,lt(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new ht(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?st(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var r;const s=this.getSegmentPlanForChapter(e);return s?(null==(r=s.segments[t])?void 0:r.documentId)??null:0===t?e:null}isSegmentLoadPending(e,t){const r=this.resolveSegmentDocumentId(e,t);if(!r)return!1;if(this.pendingSegmentLoadPromises.has(r))return!0;if(0===t&&this.pendingChapterLoadPromises.has(e))return!0;const s=this.coreState.core.documents[r];return"loading"===(null==s?void 0:s.status)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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.isSegmentLoadPending(e,0))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=at(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=nt(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=st(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(Xe(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Qe(t);if(a){const s=rt(Je(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(Xe(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;this.chapterErrorMessages.delete(n),this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=tt(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?st(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.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,r){const s=this.chapterStatus.get(e);"error"===t&&r?this.chapterErrorMessages.set(e,r):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),s!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};dt.id="chapter-manager";let ct=dt;function ut(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.height!==n.height)return!1}return!0}const pt=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,ut),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(ct.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.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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapter(e);if(!s)return!0;const n=function(e,t){const r=Ke(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(s,t);return!r.isSegmentLoaded(e,n)}refreshLayout(){this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);0!==e.length&&this.chapterManager.provides().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:r}=Ze(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=Ze(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}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 r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=Ke(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):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:r}=Ze(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.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 r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const r=this.config.bufferSize,s=Math.max(0,e[0]-r),n=Math.min(t-1,e[e.length-1]+r),a=[];for(let o=s;o<=n;o++)a.push(o);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,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}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 r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};pt.id="chapter-scroll";let gt=pt;const mt=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(gt.id),this.chapterManager=this.registry.getPlugin(He.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(r){this.logger.error(e.id,"LoadNotes","Failed to load notes",r)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(r=>r.chapterId===e&&r.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,r;const s=this.notes.get(e);s&&(null==(r=(t=this.config.callbacks).onActivateNote)||r.call(t,e,s),this.noteActivated$.emit({noteId:e,anchor:s}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[r,s]of this.notes.entries())s.chapterId===e&&this.notes.delete(r);for(const r of t)r.chapterId===e&&this.notes.set(r.noteId,r);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:vt(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:r,onCreateNote:s}=this.config.callbacks;return r?(r({draft:t,complete:async e=>{const r={...t,noteId:e};this.registerNote(r)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const r=this.buildDraft(t),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await s(r)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!n)return null;const a={...r,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var r,s;if(this.notes.has(t)){try{await(null==(s=(r=this.config.callbacks).onDeleteNote)?void 0:s.call(r,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,r){var s,n;const a=this.notes.get(t);if(!a)return;const o={...a,content:r};try{await(null==(n=(s=this.config.callbacks).onUpdateNote)?void 0:n.call(s,o))}catch(i){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",i)}this.notes.set(t,o),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const r=this.notes.get(e);if(!r)return;const s=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(r.chapterId);const a=n.resolvePageDocument(r.chapterId,r.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(s.scrollToGlobalPageIndex(r.globalPageIndex),await this.waitForPageInLayout(r.globalPageIndex),s.scrollToGlobalPdfPoint(r.globalPageIndex,r.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(r.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),r=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return r?Promise.resolve(r):new Promise(r=>{const s=setTimeout(()=>{n(),r(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(s),n(),r(a))})})}};mt.id="note";let ft=mt;function vt(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}const Pt={manifest:Ue,create:e=>new ft(ke,e),reducer:e=>e,initialState:{}},It="paragraph-bookmark",Ct={id:It,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}};function bt(e){const[t,r]=e.localPageRange;return r-t+1}function St(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 St(t)?t.segmentPageThreshold:null}function yt(e,t){return`${e}#s${t}`}function Mt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function xt(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Lt(e){const t=wt(e);if(!t)return null;const r=bt(e),s=xt(r,t),n=St(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:yt(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function $t(e,t){const r=Lt(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Dt(e,t){const r=Lt(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function kt(e){var t;const r=wt(e);if(!r)return[];const s=[],{chapterId:n}=e,a=bt(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!St(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=xt(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Ut={kind:"first-wins"};function Et(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const Ft=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Ut,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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Ut,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Mt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Mt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Mt(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?$t(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Lt(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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...kt(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.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 r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=Ut){const r=function(e,t=Ut){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Et(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Tt(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Lt(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var r;const s=this.getSegmentPlanForChapter(e);return s?(null==(r=s.segments[t])?void 0:r.documentId)??null:0===t?e:null}isSegmentLoadPending(e,t){const r=this.resolveSegmentDocumentId(e,t);if(!r)return!1;if(this.pendingSegmentLoadPromises.has(r))return!0;if(0===t&&this.pendingChapterLoadPromises.has(e))return!0;const s=this.coreState.core.documents[r];return"loading"===(null==s?void 0:s.status)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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.isSegmentLoadPending(e,0))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Dt(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=$t(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=Lt(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(St(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=wt(t);if(a){const s=xt(bt(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(St(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;this.chapterErrorMessages.delete(n),this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=Mt(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?Lt(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.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,r){const s=this.chapterStatus.get(e);"error"===t&&r?this.chapterErrorMessages.set(e,r):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),s!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Ft.id="chapter-manager";let At=Ft;function Nt(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ot(e,t){return`${e}#s${t}`}function zt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Gt(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Nt(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=Nt(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:Ot(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Vt(e){const[t,r]=e.localPageRange;return r-t+1}function Rt(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Bt(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Rt(t)?t.segmentPageThreshold:null}function _t(e,t){return`${e}#s${t}`}function qt(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Wt(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ht(e){const t=Bt(e);if(!t)return null;const r=Vt(e),s=Wt(r,t),n=Rt(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:_t(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function jt(e,t){const r=Ht(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Yt(e,t){const r=Ht(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Zt(e){var t;const r=Bt(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Vt(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!Rt(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=Wt(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Kt={kind:"first-wins"};function Jt(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let Xt=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const Qt=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Kt,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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Kt,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=qt(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=qt(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=qt(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?jt(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ht(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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Zt(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.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 r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=Kt){const r=function(e,t=Kt){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Jt(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Xt(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ht(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var r;const s=this.getSegmentPlanForChapter(e);return s?(null==(r=s.segments[t])?void 0:r.documentId)??null:0===t?e:null}isSegmentLoadPending(e,t){const r=this.resolveSegmentDocumentId(e,t);if(!r)return!1;if(this.pendingSegmentLoadPromises.has(r))return!0;if(0===t&&this.pendingChapterLoadPromises.has(e))return!0;const s=this.coreState.core.documents[r];return"loading"===(null==s?void 0:s.status)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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.isSegmentLoadPending(e,0))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Yt(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=jt(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=Ht(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(Rt(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Bt(t);if(a){const s=Wt(Vt(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(Rt(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;this.chapterErrorMessages.delete(n),this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=qt(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?Ht(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.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,r){const s=this.chapterStatus.get(e);"error"===t&&r?this.chapterErrorMessages.set(e,r):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),s!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Qt.id="chapter-manager";let er=Qt;function tr(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.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,tr),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(er.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.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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapter(e);if(!s)return!0;const n=function(e,t){const r=Gt(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(s,t);return!r.isSegmentLoaded(e,n)}refreshLayout(){this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);0!==e.length&&this.chapterManager.provides().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:r}=zt(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=zt(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}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 r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=Gt(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):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:r}=zt(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.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 r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const r=this.config.bufferSize,s=Math.max(0,e[0]-r),n=Math.min(t-1,e[e.length-1]+r),a=[];for(let o=s;o<=n;o++)a.push(o);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,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}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 r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};rr.id="chapter-scroll";let sr=rr;function nr(e){if(0===e.length)throw new Error("unionRects: empty rects");let t=1/0,r=1/0,s=-1/0,n=-1/0;for(const a of e)t=Math.min(t,a.origin.x),r=Math.min(r,a.origin.y),s=Math.max(s,a.origin.x+a.size.width),n=Math.max(n,a.origin.y+a.size.height);return{origin:{x:t,y:r},size:{width:s-t,height:n-r}}}function ar(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function or(e,t){const r=e.origin.y,s=e.origin.y+e.size.height,n=t.origin.y,a=t.origin.y+t.size.height,o=Math.max(s,a)-Math.min(r,n);return o<=0?0:Math.max(0,Math.min(s,a)-Math.max(r,n))/o}function ir(e,t){var r,s;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const n=(null==(r=e.rectsPdfCoord)?void 0:r.length)?e.rectsPdfCoord:[e.rectPdfCoord],a=(null==(s=t.rectsPdfCoord)?void 0:s.length)?t.rectsPdfCoord:[t.rectPdfCoord],o=e.markerAnchor??ar(n),i=t.markerAnchor??ar(a);if(Math.hypot(o.x-i.x,o.y-i.y)<=6)return!0;for(const l of n)for(const e of a){if(or(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 lr(e,t,r,s){const n=r.length>0?r:[];if(0===n.length)throw new Error("buildParagraphBookmarkAnchor: no rects");return{chapterId:e,localPageIndex:t,globalPageIndex:null==s?void 0:s.globalPageIndex,globalPageNumber:null==s?void 0:s.globalPageNumber,rectPdfCoord:nr(n),rectsPdfCoord:n,markerAnchor:ar(n)}}const hr=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.change$=n.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(sr.id),this.chapterManager=this.registry.getPlugin(At.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){var r;if(this.config=t,null==(r=t.callbacks)?void 0:r.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(s){this.logger.error(e.id,"Load","Failed to load paragraph bookmarks",s)}}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 s of this.entries.values())if(ir(s.anchor,e.anchor))return s;const t=e.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r={id:t,label:e.label,anchor:e.anchor,metadata:e.metadata,createdAt:Date.now()};return this.entries.set(t,r),this.notifyAndPersist(),r}removeBookmark(e){var t,r,s;this.entries.delete(e)&&(this.notifyAndPersist(),null==(s=null==(r=null==(t=this.config)?void 0:t.callbacks)?void 0:r.onRemoveSuccess)||s.call(r,e))}async requestRemoveBookmark(t){var r,s;const n=this.entries.get(t);if(!n)return!1;const a=null==(s=null==(r=this.config)?void 0:r.callbacks)?void 0:s.onRequestRemove;if(a)try{if(!(await a(n)))return!1}catch(o){return this.logger.error(e.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(t),!0}updateBookmark(e,t){const r=this.entries.get(e);r&&(this.entries.set(e,{...r,...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[r,s]of this.entries.entries())s.anchor.chapterId===e&&this.entries.delete(r);for(const r of t)r.anchor.chapterId===e&&this.entries.set(r.id,r);this.notifyAndPersist()}notifyAndPersist(){var t,r;const s=this.list();this.change$.emit(s),(null==(r=null==(t=this.config)?void 0:t.callbacks)?void 0:r.persist)&&Promise.resolve(this.config.callbacks.persist(s)).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 r=this.chapterScroll.provides(),s=this.chapterManager.provides();await s.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,r){e.scrollToGlobalPageIndex(t),await function(e,t,r=2500){const s=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const n=setTimeout(()=>{a(),s(null)},r),a=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(n),a(),s(r))})})}(e,t),e.scrollToGlobalPdfPoint(t,r,{marginTop:80})}(r,n,a)}};hr.id="paragraph-bookmark";let dr=hr;const cr={manifest:Ct,create:e=>new dr(It,e),reducer:e=>e,initialState:{}},ur={"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 pr{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(ur);for(const t of this.specs){const r=e[t.toolbarSlot];if(!r)continue;const s={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??[]};r.items=gr(r.items,s,t.position)}return e}}function gr(e,t,r){return(null==r?void 0:r.after)||(null==r?void 0:r.before)?function(e,t,r){const s=e=>{const n=[];for(const a of e)"group"!==a.type?r.before&&a.id===r.before?n.push(t,a):(n.push(a),r.after&&a.id===r.after&&n.push(t)):n.push({...a,items:s(a.items)});return n};return s(e)}(e,t,r):(s=t,e.map(e=>"group"===e.type?{...e,items:[...e.items,s]}:e));var s}const mr={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function fr(e){var t,s,P,I,C,b;const S=e.toolbar??{},w=S.enabledModes??["view","annotate","shapes","insert","form","redact"],y=w.length>0,{schema:M,operationRegistry:x}=function(e={}){var t,r,s,n,a,o;const i=new Set(e.enabledModes??["view","annotate","shapes","insert","form","redact"]),l=new pr;(null==(t=e.customOperations)?void 0:t.length)&&l.registerAll(e.customOperations);const h=l.buildToolbars(),d={};for(const u of i){if("view"===u)continue;const e=mr[u];h[e]&&(d[e]=h[e])}const c=function(e){if(0===e.size)return null;const t=(e,t,r)=>({type:"command-button",id:`${e}-mode`,commandId:r,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}]}}(i);return c&&(d["chapter-editor-main-toolbar"]=c),(null==(r=e.extend)?void 0:r.toolbars)&&Object.assign(d,e.extend.toolbars),{schema:{id:"chapter-pdf-editor-ui",version:"1.0.0",toolbars:d,menus:(null==(s=e.extend)?void 0:s.menus)??{},sidebars:(null==(n=e.extend)?void 0:n.sidebars)??{},modals:(null==(a=e.extend)?void 0:a.modals)??{},selectionMenus:(null==(o=e.extend)?void 0:o.selectionMenus)??{}},operationRegistry:l}}({...S,enabledModes:w}),L={...y?{"mode:view":{id:"mode:view",label:"View",categories:["mode","mode-view"],action:({registry:e,documentId:t})=>{var s,n,a,o;const i=null==(s=e.getPlugin("ui"))?void 0:s.provides(),l=null==(n=e.getPlugin("interaction-manager"))?void 0:n.provides();i&&l&&(null==(a=l.forDocument(t))||a.activateDefaultMode(),i.forDocument(t).closeToolbarSlot("top","secondary"),null==(o=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||o.provides().forDocument(t).setLocked(e.getPluginConfig(r.ANNOTATION_PLUGIN_ID).locked??{type:r.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 s,n;const a=null==(s=e.getPlugin("ui"))?void 0:s.provides();a&&(a.setActiveToolbar("top","secondary","annotation-toolbar",t),null==(n=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:r.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 s,n;const a=null==(s=e.getPlugin("ui"))?void 0:s.provides();a&&(a.setActiveToolbar("top","secondary","shapes-toolbar",t),null==(n=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:r.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 s,n;const a=null==(s=e.getPlugin("ui"))?void 0:s.provides();a&&(a.setActiveToolbar("top","secondary","insert-toolbar",t),null==(n=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:r.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 s,n;const a=null==(s=e.getPlugin("ui"))?void 0:s.provides();a&&(a.setActiveToolbar("top","secondary","form-toolbar",t),null==(n=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:r.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 s,n;const a=null==(s=e.getPlugin("ui"))?void 0:s.provides();a&&(a.setActiveToolbar("top","secondary","redaction-toolbar",t),null==(n=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||n.provides().forDocument(t).setLocked({type:r.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","redaction-toolbar")}}:{},...y?vr(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,unloadTimeoutMs:e.unloadTimeoutMs}),n.createPluginRegistration(De,{placeholderPageHeight:e.placeholderPageHeight,placeholderPageWidth:e.placeholderPageWidth}),n.createPluginRegistration(o.InteractionManagerPluginPackage),n.createPluginRegistration(i.RenderPluginPackage),n.createPluginRegistration(l.RotatePluginPackage),n.createPluginRegistration(h.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),n.createPluginRegistration(d.HistoryPluginPackage),n.createPluginRegistration(r.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(Pt,{callbacks:e.notes.callbacks,ui:null==(s=null==(t=e.features)?void 0:t.notes)?void 0:s.marker})),e.bookmarks&&$.push(n.createPluginRegistration(cr,{callbacks:e.bookmarks.callbacks,ui:null==(I=null==(P=e.features)?void 0:P.bookmarks)?void 0:I.marker,hover:null==(b=null==(C=e.features)?void 0:C.bookmarks)?void 0:b.hover})),{plugins:$,uiSchema:M,operationRegistry:x}}function vr(e){const t={};for(const r of e)r.handler&&(t[r.commandId]={id:r.commandId,labelKey:r.i18nKey,label:r.label,icon:r.icon,categories:r.categories,action:({documentId:e})=>{var t;null==(t=r.handler)||t.call(r,{documentId:e,chapterId:e})}});return t}const Pr=N();function Ir(e){return fr({...e,toolbar:e.toolbar??{enabledModes:[]},features:N(e.features)})}const Cr={overlapStrategy:{kind:"first-wins"},passwordProvider:new V(async()=>null),prefetchChapters:1,loadDefaultStampLibrary:!1,unloadTimeoutMs:12e4,toolbar:{enabledModes:[]}};function br(e){return"callbacks"in e.notes?{manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,notes:e.notes.callbacks,bookmarks:e.bookmarks.callbacks}:e}function Sr(e){return{...Cr,manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,overlapStrategy:e.overlapStrategy??Cr.overlapStrategy,notes:{callbacks:e.notes},bookmarks:{callbacks:e.bookmarks},features:N(e.features)}}function wr(e){const t=Sr(br(e)),{plugins:r}=Ir(t);return{plugins:r,features:t.features,editorOptions:t}}function yr(e,t=.5,r=3){return Math.min(r,Math.max(t,e))}function Mr(e,t){var r;if(t<=0)return 1;let s=0;for(const n of e.pages){const e=(null==(r=null==n?void 0:n.size)?void 0:r.width)??0;e>s&&(s=e)}return s<=0?1:t/s}function xr(e,t){return e<=0?t??0:null==t||t<=0?e:Math.min(t,e)}function Lr(e,t,r,s){const n=xr(t,r);if(n<=0)return s;const a=Mr(e,n);return Math.min(s,a)}function $r(e,t,r){const s=G(t);if(s){for(const t of s.segments){const s=e.getDocument(t.documentId);s&&r(s,t.documentId)}return}const n=e.getDocument(t.chapterId);n&&r(n,t.chapterId)}function Dr(e){return e instanceof HTMLElement?e.clientWidth:0}function kr(e,t,r){return Math.min(r,Math.max(t,e))}const Ur={chapters:[]};function Er(r){const s=e.ref(null),{provides:o}=t.useCapability(se.id),i=e.computed(()=>{var e;return(null==(e=o.value)?void 0:e.getManifest())??Ur}),l=e.computed(()=>{var e;return null==(e=r.value)?void 0:e.zoom}),{scale:h,setScale:d,zoomEnabled:c,minZoom:u,maxZoom:p}=function(r,s,o){const i=e.isRef(r)?r:e.computed(()=>r),{registry:l}=t.useRegistry(),{provides:h}=t.useCapability(a.DocumentManagerPlugin.id),{provides:d}=t.useCapability(se.id),c=e.ref(v()),u=e.ref(c.value),p=e.ref(0),g=e.ref(!1),m=()=>{var e;return null==(e=s.value)?void 0:e.pageWidth},f=()=>{return null!=(e=m())&&e>0;var e},v=()=>{var e;return(null==(e=s.value)?void 0:e.initial)??1},P=e.computed(()=>{var e;return function(e,t,r,s,n){if(!e||r<=0)return n;let a=n;for(const o of t.chapters)$r(e,o,e=>{a=Math.min(a,Lr(e,r,s,n))});return a}(h.value,i.value,p.value,m(),(null==(e=s.value)?void 0:e.max)??3)}),I=e.computed(()=>{var e;return Math.min((null==(e=s.value)?void 0:e.min)??.5,P.value)});let C;function b(e){const t=P.value,r=I.value,s=yr(e,r,t);u.value=s,c.value=s,function(e,t,r,s=.5,a=3){const o=null==e?void 0:e.getStore();if(!o)return;const i=yr(r,s,a);o.dispatchToCore(n.setDefaultScale(i));for(const l of t.chapters){const e=G(l);if(e)for(const t of e.segments)o.getState().core.documents[t.documentId]&&o.dispatchToCore(n.setScale(i,t.documentId));else o.getState().core.documents[l.chapterId]&&o.dispatchToCore(n.setScale(i,l.chapterId))}}(l.value,i.value,s,r,t)}function S(e){if(!h.value||!d.value)return;const t=d.value.resolvePageDocument(e,0),r=h.value.getDocument(t.documentId);if(!r)return;const s=xr(p.value,m());s<=0||b(Mr(r,s))}function w(e){if(!g.value)return f()?S(e):b(v()),void(g.value=!0);b(u.value)}return e.watch(()=>null==o?void 0:o.value,e=>{null==C||C(),C=e?function(e,t){if(!e||"undefined"==typeof ResizeObserver)return()=>{};let r=null;const s=new ResizeObserver(()=>{t(Dr(r))}),n=()=>{const n=e.querySelector("[data-chapter-scroll-viewport]");n!==r?(r&&s.unobserve(r),r=n,r?(s.observe(r),t(Dr(r))):t(0)):t(Dr(r))};n();const a=new MutationObserver(n);a.observe(e,{childList:!0,subtree:!0});const o=requestAnimationFrame(n);return()=>{cancelAnimationFrame(o),a.disconnect(),r&&s.unobserve(r),s.disconnect()}}(e,e=>{p.value=e}):void 0},{immediate:!0}),e.onBeforeUnmount(()=>null==C?void 0:C()),e.watch([l,()=>v(),()=>f()],()=>{l.value&&(f()||b(v()))},{immediate:!0}),e.watch(P,e=>{u.value>e&&b(e)}),e.watch([d,i,()=>f(),()=>v()],()=>{const e=d.value;if(e){for(const t of i.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,r)=>{e&&r(e.onDocumentOpened(()=>{g.value&&b(u.value)}))}),e.watch([p,()=>f(),d,i],()=>{if(f()&&!(p.value<=0)&&d.value&&!g.value)for(const e of i.value.chapters)if("loaded"===d.value.getChapterStatus(e.chapterId)){S(e.chapterId),g.value=!0;break}}),{scale:c,setScale:b,zoomEnabled:()=>{var e;return!1!==(null==(e=s.value)?void 0:e.enabled)},minZoom:I,maxZoom:P}}(i,l,s);return function(t,r){let s=null;e.watch([t,r],()=>{null==s||s();const e=r.value;s=function(e,t){if(!e||!1===t.enabled)return()=>{};let r=null,s=null,n=0;const a=()=>{const s=e.querySelector("[data-chapter-scroll-viewport]");return!!s&&(null==r||r(),r=function({container:e,getScale:t,setScale:r,minZoom:s=.5,maxZoom:n=3}){let a=0,o=1,i=null,l=1,h=1;const d=e=>{(e.ctrlKey||e.metaKey)&&(e.preventDefault(),null===i?(h=t(),l=1):clearTimeout(i),l*=1-.01*e.deltaY,l=kr(l,.1,10),r(kr(h*l,s,n)),i=setTimeout(()=>{i=null},120))},c=new Map,u=e=>{if(c.set(e.pointerId,{x:e.clientX,y:e.clientY}),2===c.size){const[e,r]=[...c.values()];a=Math.hypot(r.x-e.x,r.y-e.y),o=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,i]=[...c.values()],l=Math.hypot(i.x-t.x,i.y-t.y);r(kr(o*(l/a),s,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),i&&clearTimeout(i)}}({container:s,getScale:t.getScale,setScale:t.setScale,minZoom:t.minZoom,maxZoom:t.maxZoom}),!0)};return a()||(s=new MutationObserver(()=>{a()&&(null==s||s.disconnect(),s=null)}),s.observe(e,{childList:!0,subtree:!0}),n=requestAnimationFrame(()=>a())),()=>{n&&cancelAnimationFrame(n),null==s||s.disconnect(),null==r||r()}}(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==s?void 0:s())}(s,e.computed(()=>({enabled:c(),getScale:()=>h.value,setScale:d,minZoom:u.value,maxZoom:p.value}))),{hostRef:s,scale:h,setScale:d,zoomEnabled:c}}function Tr(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Fr(e,t){return`${e}#s${t}`}function Ar(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Nr(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Tr(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=Tr(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:Fr(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Or(e){const[t,r]=e.localPageRange;return r-t+1}function zr(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Gr(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return zr(t)?t.segmentPageThreshold:null}function Vr(e,t){return`${e}#s${t}`}function Rr(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Br(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function _r(e){const t=Gr(e);if(!t)return null;const r=Or(e),s=Br(r,t),n=zr(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:Vr(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function qr(e,t){const r=_r(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Wr(e,t){const r=_r(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Hr(e){var t;const r=Gr(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Or(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!zr(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=Br(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const jr={kind:"first-wins"};function Yr(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}class Zr{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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}}const Kr=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=jr,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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??jr,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Rr(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Rr(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Rr(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?qr(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?_r(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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Hr(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.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 r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=jr){const r=function(e,t=jr){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Yr(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Zr(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?_r(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var r;const s=this.getSegmentPlanForChapter(e);return s?(null==(r=s.segments[t])?void 0:r.documentId)??null:0===t?e:null}isSegmentLoadPending(e,t){const r=this.resolveSegmentDocumentId(e,t);if(!r)return!1;if(this.pendingSegmentLoadPromises.has(r))return!0;if(0===t&&this.pendingChapterLoadPromises.has(e))return!0;const s=this.coreState.core.documents[r];return"loading"===(null==s?void 0:s.status)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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.isSegmentLoadPending(e,0))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Wr(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=qr(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=_r(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(zr(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Gr(t);if(a){const s=Br(Or(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(zr(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;this.chapterErrorMessages.delete(n),this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=Rr(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?_r(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.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,r){const s=this.chapterStatus.get(e);"error"===t&&r?this.chapterErrorMessages.set(e,r):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),s!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Kr.id="chapter-manager";let Jr=Kr;function Xr(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.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,Xr),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Jr.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.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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapter(e);if(!s)return!0;const n=function(e,t){const r=Nr(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(s,t);return!r.isSegmentLoaded(e,n)}refreshLayout(){this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);0!==e.length&&this.chapterManager.provides().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:r}=Ar(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=Ar(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}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 r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=Nr(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):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:r}=Ar(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.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 r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const r=this.config.bufferSize,s=Math.max(0,e[0]-r),n=Math.min(t-1,e[e.length-1]+r),a=[];for(let o=s;o<=n;o++)a.push(o);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,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}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 r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};Qr.id="chapter-scroll";let es=Qr;const ts=["data-global-page-index","data-chapter-id","data-local-page-index"],rs=(e=>{const t=e.__vccOpts||e;for(const[r,s]of[["__scopeId","data-v-e9ab4da3"]])t[r]=s;return t})(e.defineComponent({__name:"ChapterScroller",props:{class:{},style:{}},setup(r){const{provides:s}=t.useCapability(es.id),n=e.ref(null),a=e.ref(null);let o=null;const i=()=>{null==o||o(),o=null,s.value&&(s.value.registerViewport(n.value),o=s.value.onLayoutChange(e=>{a.value=e}))};return e.onMounted(i),e.onBeforeUnmount(()=>{var e;null==o||o(),null==(e=s.value)||e.registerViewport(null)}),e.watch(s,i),(t,r)=>{var s,o,i;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==(s=a.value)?void 0:s.totalWidth)??0}px`,height:`${(null==(o=a.value)?void 0:o.totalHeight)??0}px`,margin:"0 auto"})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList((null==(i=a.value)?void 0:i.items)??[],s=>(e.openBlock(),e.createElementBlock("div",{key:s.globalPageIndex,"data-global-page-index":s.globalPageIndex,"data-chapter-id":s.chapterId,"data-local-page-index":s.localPageIndex,style:e.normalizeStyle({position:"absolute",top:`${s.offsetTop}px`,left:"50%",transform:"translateX(-50%)",width:`${s.width}px`,height:`${s.height}px`,backgroundColor:s.isPlaceholder?"#f3f4f6":"#fff",boxShadow:"0 1px 4px rgba(0,0,0,0.08)"})},[s.isPlaceholder?e.renderSlot(t.$slots,"placeholder",{key:0,item:s},()=>[r[0]||(r[0]=e.createElementVNode("div",{class:"chapter-scroll-placeholder"},"Loading chapter…",-1))],!0):e.renderSlot(t.$slots,"page",{key:1,item:s},void 0,!0)],12,ts))),128))],4)],6)}}})),ss=e.defineComponent({__name:"ChapterRenderLayer",props:{chapterId:{},localPageIndex:{},pdfDocumentId:{},pdfPageIndex:{},scale:{},dpr:{},class:{}},setup(t){const r=t;return(s,n)=>(e.openBlock(),e.createBlock(e.unref(w.RenderLayer),{"document-id":r.pdfDocumentId??r.chapterId,"page-index":r.pdfPageIndex??r.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 ns(e){const[t,r]=e.localPageRange;return r-t+1}function as(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function os(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return as(t)?t.segmentPageThreshold:null}function is(e,t){return`${e}#s${t}`}function ls(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function hs(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function ds(e){const t=os(e);if(!t)return null;const r=ns(e),s=hs(r,t),n=as(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:is(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function cs(e,t){const r=ds(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function us(e,t){const r=ds(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function ps(e){var t;const r=os(e);if(!r)return[];const s=[],{chapterId:n}=e,a=ns(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!as(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=hs(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const gs={kind:"first-wins"};function ms(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let fs=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const vs=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=gs,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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??gs,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=ls(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=ls(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=ls(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?cs(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?ds(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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...ps(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.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 r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=gs){const r=function(e,t=gs){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,ms(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new fs(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?ds(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var r;const s=this.getSegmentPlanForChapter(e);return s?(null==(r=s.segments[t])?void 0:r.documentId)??null:0===t?e:null}isSegmentLoadPending(e,t){const r=this.resolveSegmentDocumentId(e,t);if(!r)return!1;if(this.pendingSegmentLoadPromises.has(r))return!0;if(0===t&&this.pendingChapterLoadPromises.has(e))return!0;const s=this.coreState.core.documents[r];return"loading"===(null==s?void 0:s.status)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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.isSegmentLoadPending(e,0))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=us(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=cs(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=ds(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(as(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=os(t);if(a){const s=hs(ns(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(as(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;this.chapterErrorMessages.delete(n),this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=ls(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?ds(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.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,r){const s=this.chapterStatus.get(e);"error"===t&&r?this.chapterErrorMessages.set(e,r):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),s!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};vs.id="chapter-manager";let Ps=vs;function Is(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Cs(e,t){return`${e}#s${t}`}function bs(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Ss(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Is(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=Is(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:Cs(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function ws(e){const[t,r]=e.localPageRange;return r-t+1}function ys(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ms(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ys(t)?t.segmentPageThreshold:null}function xs(e,t){return`${e}#s${t}`}function Ls(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function $s(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Ds(e){const t=Ms(e);if(!t)return null;const r=ws(e),s=$s(r,t),n=ys(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:xs(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function ks(e,t){const r=Ds(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Us(e,t){const r=Ds(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Es(e){var t;const r=Ms(e);if(!r)return[];const s=[],{chapterId:n}=e,a=ws(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!ys(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=$s(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Ts={kind:"first-wins"};function Fs(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}class As{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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}}const Ns=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Ts,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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Ts,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=Ls(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Ls(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Ls(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?ks(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Ds(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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Es(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.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 r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=Ts){const r=function(e,t=Ts){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Fs(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new As(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Ds(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var r;const s=this.getSegmentPlanForChapter(e);return s?(null==(r=s.segments[t])?void 0:r.documentId)??null:0===t?e:null}isSegmentLoadPending(e,t){const r=this.resolveSegmentDocumentId(e,t);if(!r)return!1;if(this.pendingSegmentLoadPromises.has(r))return!0;if(0===t&&this.pendingChapterLoadPromises.has(e))return!0;const s=this.coreState.core.documents[r];return"loading"===(null==s?void 0:s.status)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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.isSegmentLoadPending(e,0))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Us(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=ks(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=Ds(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(ys(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Ms(t);if(a){const s=$s(ws(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(ys(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;this.chapterErrorMessages.delete(n),this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=Ls(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?Ds(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.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,r){const s=this.chapterStatus.get(e);"error"===t&&r?this.chapterErrorMessages.set(e,r):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),s!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Ns.id="chapter-manager";let Os=Ns;function zs(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.height!==n.height)return!1}return!0}const Gs=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,zs),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Os.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.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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapter(e);if(!s)return!0;const n=function(e,t){const r=Ss(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(s,t);return!r.isSegmentLoaded(e,n)}refreshLayout(){this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);0!==e.length&&this.chapterManager.provides().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:r}=bs(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=bs(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}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 r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=Ss(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):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:r}=bs(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.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 r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const r=this.config.bufferSize,s=Math.max(0,e[0]-r),n=Math.min(t-1,e[e.length-1]+r),a=[];for(let o=s;o<=n;o++)a.push(o);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,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}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 r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};Gs.id="chapter-scroll";let Vs=Gs;const Rs=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(Vs.id),this.chapterManager=this.registry.getPlugin(Ps.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(r){this.logger.error(e.id,"LoadNotes","Failed to load notes",r)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(r=>r.chapterId===e&&r.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,r;const s=this.notes.get(e);s&&(null==(r=(t=this.config.callbacks).onActivateNote)||r.call(t,e,s),this.noteActivated$.emit({noteId:e,anchor:s}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[r,s]of this.notes.entries())s.chapterId===e&&this.notes.delete(r);for(const r of t)r.chapterId===e&&this.notes.set(r.noteId,r);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:_s(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:r,onCreateNote:s}=this.config.callbacks;return r?(r({draft:t,complete:async e=>{const r={...t,noteId:e};this.registerNote(r)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const r=this.buildDraft(t),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await s(r)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!n)return null;const a={...r,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var r,s;if(this.notes.has(t)){try{await(null==(s=(r=this.config.callbacks).onDeleteNote)?void 0:s.call(r,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,r){var s,n;const a=this.notes.get(t);if(!a)return;const o={...a,content:r};try{await(null==(n=(s=this.config.callbacks).onUpdateNote)?void 0:n.call(s,o))}catch(i){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",i)}this.notes.set(t,o),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const r=this.notes.get(e);if(!r)return;const s=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(r.chapterId);const a=n.resolvePageDocument(r.chapterId,r.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(s.scrollToGlobalPageIndex(r.globalPageIndex),await this.waitForPageInLayout(r.globalPageIndex),s.scrollToGlobalPdfPoint(r.globalPageIndex,r.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(r.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),r=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return r?Promise.resolve(r):new Promise(r=>{const s=setTimeout(()=>{n(),r(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(s),n(),r(a))})})}};Rs.id="note";let Bs=Rs;function _s(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function qs(e){const{markerPdf:t,lineRects:r,sx:s,sy:n,cssPageWidth:a,iconSize:o,gapPx:i=6}=e,l=(null==r?void 0:r.length)?r[r.length-1]:void 0;let h,d;l?(h=(l.origin.x+l.size.width)*s+i,d=l.origin.y*n+(l.size.height*n-o)/2):(h=t.x*s-o/2,d=t.y*n-o-i);const c=Math.max(0,a-o-2);return h>c&&(h=c),d<0&&(d=0),{left:h,top:d}}const Ws={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none",zIndex:25}},Hs=["onMouseenter"],js=["data-note-marker-zone","onMouseenter","onMouseleave"],Ys=["onClick"],Zs=["onClick"],Ks=["onClick"],Js=e.defineComponent({__name:"NoteMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(r){const s=r,{provides:n}=t.useCapability(Bs.id),a=e.ref([]),o=e.ref(null),i=e.ref(null);e.watch(n,e=>{if(e)return e.onNotesChange(e=>{a.value=e.filter(e=>e.chapterId===s.chapterId&&e.localPageIndex===s.localPageIndex)})},{immediate:!0});let l=null;e.watch(i,e=>{l&&(document.removeEventListener("mousedown",l),l=null),e&&(l=t=>{var r;const s=t.target;(null==(r=s.closest)?void 0:r.call(s,`[data-note-marker-zone="${e}"]`))||(i.value=null,o.value=null)},document.addEventListener("mousedown",l))}),e.onBeforeUnmount(()=>{l&&document.removeEventListener("mousedown",l)});const h=e.computed(()=>{var e;return(null==(e=s.ui)?void 0:e.iconSize)??16}),d=e.computed(()=>{var e;return(null==(e=s.ui)?void 0:e.highlightColor)??"rgba(245, 158, 11, 0.08)"});function c(e){const t=s.cssPageWidth/s.pdfPageWidth,r=s.cssPageHeight/s.pdfPageHeight,n=h.value,{left:a,top:o}=qs({markerPdf:e.endAnchor,lineRects:e.rectsPdfCoord,sx:t,sy:r,cssPageWidth:s.cssPageWidth,iconSize:n}),l=function(e,t,r){let s=1/0,n=1/0,a=-1/0,o=-1/0;for(const i of e)s=Math.min(s,i.origin.x*t),n=Math.min(n,i.origin.y*r),a=Math.max(a,(i.origin.x+i.size.width)*t),o=Math.max(o,(i.origin.y+i.size.height)*r);return{left:s,top:n,width:a-s,height:o-n}}(e.rectsPdfCoord,t,r),d=i.value===e.noteId?72:0,c=Math.max(0,Math.min(l.left,a)-8),u=Math.max(0,Math.min(l.top,o)-8);return{zoneLeft:c,zoneTop:u,zoneW:Math.min(s.cssPageWidth,Math.max(l.left+l.width,a+n)+8)-c,zoneH:Math.max(l.top+l.height,o+n+6+d)+8-u,iconLeft:a,iconTop:o,sx:t,sy:r}}return(t,s)=>e.unref(n)&&a.value.length&&r.pdfPageWidth&&r.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",Ws,[(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,(r,s)=>(e.openBlock(),e.createElementBlock("div",{key:`${t.noteId}-bg-${s}`,style:e.normalizeStyle({position:"absolute",left:r.origin.x*c(t).sx+"px",top:r.origin.y*c(t).sy+"px",width:r.size.width*c(t).sx+"px",height:r.size.height*c(t).sy+"px",background:d.value,borderRadius:"2px",pointerEvents:"auto"}),onMouseenter:e=>o.value=t.noteId},null,44,Hs))),128)),o.value===t.noteId||i.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=>o.value=t.noteId,onMouseleave:e=>i.value!==t.noteId&&(o.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:s[0]||(s[0]=e.withModifiers(()=>{},["stop"])),onClick:e.withModifiers(e=>i.value=i.value===t.noteId?null:t.noteId,["stop"])}," 💬 ",44,Ys),i.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:s[1]||(s[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 r=t,void(null==(s=n.value)||s.requestEditNote(r.noteId,r));var r,s}}," 编辑 ",8,Zs),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 r,s;return s=t.noteId,null==(r=n.value)||r.requestDeleteNote(s),void(i.value=null)}}," 删除 ",8,Ks)],36)):e.createCommentVNode("",!0)],44,js)):e.createCommentVNode("",!0)],64))),128))])):e.createCommentVNode("",!0)}}),Xs={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none"}},Qs=["title","onClick"],en=["onClick"],tn=e.defineComponent({__name:"BookmarkMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(r){const s=r,{provides:n}=t.useCapability(dr.id),a=e.ref([]),o=e.ref(null),i=e.ref(null);function l(){const e=n.value;e&&(a.value=e.listBookmarks().filter(e=>e.anchor.chapterId===s.chapterId&&e.anchor.localPageIndex===s.localPageIndex))}e.watch(n,e=>{if(e)return l(),e.onBookmarksChange(l)},{immediate:!0});let h=null;e.watch(o,e=>{h&&(document.removeEventListener("mousedown",h),h=null),e&&(h=e=>{var t;(null==(t=i.value)?void 0:t.contains(e.target))||(o.value=null)},document.addEventListener("mousedown",h))}),e.onBeforeUnmount(()=>{h&&document.removeEventListener("mousedown",h)});const d=e.computed(()=>{var e;return(null==(e=s.ui)?void 0:e.iconSize)??16});function c(e){const{left:t,top:r}=function(e){var t;const r=s.cssPageWidth/s.pdfPageWidth,n=s.cssPageHeight/s.pdfPageHeight,a=(null==(t=e.anchor.rectsPdfCoord)?void 0:t.length)?e.anchor.rectsPdfCoord:[e.anchor.rectPdfCoord];return qs({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:r,sy:n,cssPageWidth:s.cssPageWidth,iconSize:d.value})}(e);return{position:"absolute",left:`${Math.max(0,t-6)}px`,top:`${Math.max(0,r-6)}px`,width:`${d.value+12}px`,height:`${d.value+12}px`,pointerEvents:"auto",zIndex:20}}return(t,s)=>e.unref(n)&&a.value.length&&r.pdfPageWidth&&r.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",Xs,[(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:s[1]||(s[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=>o.value=o.value===t.id?null:t.id,["stop"])}," 🔖 ",12,Qs),o.value===t.id?(e.openBlock(),e.createElementBlock("div",{key:0,ref_for:!0,ref_key:"deleteMenuRef",ref:i,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:s[0]||(s[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)&&(o.value=null)}(t.id)}," 删除书签 ",8,en)],512)):e.createCommentVNode("",!0)],36))),128))])):e.createCommentVNode("",!0)}});function rn(e){return e.pdfDocumentId??e.chapterId}function sn(e){return e.pdfPageIndex??e.localPageIndex}function nn(e,t){e.wait(t,()=>{})}const an={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)"},on={padding:"6px 12px",fontSize:"12px",fontWeight:"500",border:"none",borderRadius:"6px",background:"transparent",color:"#dc2626",cursor:"pointer"};const ln=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(r){const s=r,n=e.computed(()=>rn(s.item)),o=e.computed(()=>sn(s.item));!function(r){const{provides:s}=t.useCapability(a.DocumentManagerPlugin.id);e.watch([s,r],([e,t])=>{e&&t&&e.isDocumentOpen(t)&&e.setActiveDocument(t)},{immediate:!0})}(n);const{provides:i}=t.useCapability(a.DocumentManagerPlugin.id),{provides:l}=t.useCapability(h.SelectionPlugin.id),d=e.computed(()=>{var e,t;return null==(t=null==(e=i.value)?void 0:e.getDocument(n.value))?void 0:t.pages[o.value]});function c(t,r){var n,a,o,i;const h=s.createNote.value;if(h&&!1!==(null==(a=null==(n=s.features)?void 0:n.notes)?void 0:a.enabled)&&!1!==(null==(i=null==(o=s.features)?void 0:o.selectionToolbar)?void 0:i.enabled))return s=>{var n;const a={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==(n=s.placement)?void 0:n.suggestTop)?-40:s.rect.size.height+8};return e.h("div",s.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(sn(t),r);nn(l.value.getSelectedText(r),r=>{var s,n,a;h((s=t,n=e,a=r.join("\n"),{chapterId:s.chapterId,localPageIndex:s.localPageIndex,globalPageIndex:s.globalPageIndex,globalPageNumber:s.globalPageNumber,rectsPdfCoord:n,selectedText:a}))})}},"添加附注"))])}}const u=e.computed(()=>{const e=s.buildSelectionMenu,t={item:s.item,defaultMenu:c(s.item,n.value),createNote:s.createNote.value};if(e){const r=e(t);if(r)return r}return t.defaultMenu}),p=function(t,r){var s,n;const{provides:a}=b.useAnnotationCapability(),o=null==(s=null==r?void 0:r.markup)?void 0:s.annotationMenu,i=!1!==(null==(n=null==r?void 0:r.markup)?void 0:n.enabled),l=!1!==(null==o?void 0:o.enabled);return e.computed(()=>{const r="string"==typeof t?t:t.value;if(i&&l&&a.value)return t=>{const{context:s,rect:n,placement:i,menuWrapperProps:l,selected:h}=t;if(!h||"annotation"!==s.type)return e.h("span",l);if(s.structurallyLocked)return e.h("span",l);if(d=s.annotation.object.type,!F.has(d))return e.h("span",l);var d;const c=a.value.forDocument(r),{pageIndex:u,id:p}=s.annotation.object,g=()=>{null==c||c.deleteAnnotation(u,p)},m={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==i?void 0:i.suggestTop)?void 0:`${n.size.height+8}px`,bottom:(null==i?void 0:i.suggestTop)?`${n.size.height+8}px`:void 0},f=(null==o?void 0:o.renderMenu)?o.renderMenu({pageIndex:u,annotationId:p,onDelete:g}):e.h("button",{type:"button",style:on,onClick:g},"删除");return e.h("div",l,[e.h("div",{style:m},[e.h("div",{style:an,role:"toolbar","aria-label":"划线标注"},[f])])])}})}(n,s.features),g=e.computed(()=>function(e,t){if(e||t)return r=>{if(e){const t=e(r);if(null!=t)return t}return(null==t?void 0:t(r))??null}}(s.annotationSelectionMenu,p.value)),m=e.computed(()=>{var e;return null==(e=s.renderPageOverlay)?void 0:e.call(s,s.item)}),f=e.computed(()=>{var e;return function(e){const t=null==e?void 0:e.selectionBackground;if(t)return{background:t}}(null==(e=s.features)?void 0:e.selectionToolbar)});return(t,s)=>r.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":o.value,style:{backgroundColor:"#fff"}},{default:e.withCtx(()=>[e.createVNode(e.unref(P.PagePointerProvider),{"document-id":n.value,"page-index":o.value,style:e.normalizeStyle(e.unref(x)),onPointerdown:e.unref(L)},{default:e.withCtx(()=>[e.createVNode(e.unref(ss),{"chapter-id":r.item.chapterId,"local-page-index":r.item.localPageIndex,"pdf-document-id":n.value,"pdf-page-index":o.value},null,8,["chapter-id","local-page-index","pdf-document-id","pdf-page-index"]),e.createVNode(e.unref(C.SelectionLayer),{"document-id":n.value,"page-index":o.value,"text-style":f.value,"selection-menu":u.value},null,8,["document-id","page-index","text-style","selection-menu"]),r.showRedactionLayer?(e.openBlock(),e.createBlock(e.unref(S.RedactionLayer),{key:0,"document-id":n.value,"page-index":o.value,"selection-menu":r.redactionSelectionMenu},null,8,["document-id","page-index","selection-menu"])):e.createCommentVNode("",!0),e.createVNode(e.unref(b.AnnotationLayer),{"document-id":n.value,"page-index":o.value,"selection-menu":g.value},null,8,["document-id","page-index","selection-menu"]),r.showBookmarkMarkers&&d.value?(e.openBlock(),e.createBlock(tn,{key:1,"chapter-id":r.item.chapterId,"local-page-index":r.item.localPageIndex,"pdf-page-width":d.value.size.width,"pdf-page-height":d.value.size.height,"css-page-width":r.item.width,"css-page-height":r.item.height,ui:r.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),r.showNoteMarkers&&d.value?(e.openBlock(),e.createBlock(Js,{key:3,"chapter-id":r.item.chapterId,"local-page-index":r.item.localPageIndex,"pdf-page-width":d.value.size.width,"pdf-page-height":d.value.size.height,"css-page-width":r.item.width,"css-page-height":r.item.height,ui:r.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"]))}}),hn=e.defineComponent({__name:"HoverBookmarkLayer",props:{item:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},hoverUi:{}},setup(r){const s=r,n=e.computed(()=>rn(s.item)),{provides:a}=t.useCapability(h.SelectionPlugin.id),{provides:o}=t.useCapability(dr.id),i=e.ref(null),l=e.ref(null),d=e.ref(null),c=e.ref(null),u=e.computed(()=>{var e;return(null==(e=s.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[s.item.localPageIndex];t&&(l.value=t)}e.watch([a,n,()=>s.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 r=!1;const a=()=>{if(!r){try{if(f(),t.getState().geometry[s.item.localPageIndex])return}catch{}m=requestAnimationFrame(a)}};return a(),()=>{r=!0,cancelAnimationFrame(m),null==g||g(),g=null}},{immediate:!0});let v=null;e.watch([l,()=>s.pdfPageWidth,c,a],()=>{v&&(document.removeEventListener("mousemove",v),v=null),l.value&&s.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 r=i.value;if(!r)return;const o=r.getBoundingClientRect();if(e.clientX<o.left||e.clientX>o.right||e.clientY<o.top||e.clientY>o.bottom)return void(d.value=null);const u=function(e,t){const r=h.glyphAt(e,t);if(r<0)return null;const s=h.expandToLineBoundary(e,r);if(!s)return null;const n=h.rectsWithinSlice(e,s.from,s.to);return 0===n.length?null:{lineRects:n,charFrom:s.from,charTo:s.to}}(l.value,{x:(e.clientX-o.left)/(s.cssPageWidth/s.pdfPageWidth),y:(e.clientY-o.top)/(s.cssPageHeight/s.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)?lr(s.item.chapterId,s.item.localPageIndex,e,{globalPageIndex:s.item.globalPageIndex,globalPageNumber:s.item.globalPageNumber}):null}),I=e.computed(()=>{const e=P.value,t=o.value;return!(!e||!t)&&t.listBookmarks().some(t=>ir(t.anchor,e))});function C(){const e=o.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 b=e.computed(()=>{const e=p.value,t=null==e?void 0:e[e.length-1];if(!t||!s.pdfPageWidth)return null;const r=s.cssPageWidth/s.pdfPageWidth,n=s.cssPageHeight/s.pdfPageHeight,a=u.value;return{iconLeft:Math.min((t.origin.x+t.size.width)*r+6,Math.max(0,s.cssPageWidth-a-2)),iconTop:t.origin.y*n+(t.size.height*n-a)/2,zoneLeft:Math.max(0,(t.origin.x+t.size.width)*r-4),zoneTop:Math.max(0,t.origin.y*n-4),size:a}});return(t,s)=>{var n;return e.unref(o)&&r.pdfPageWidth&&r.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",{key:0,ref_key:"rootRef",ref:i,style:{position:"absolute",inset:"0",zIndex:14,pointerEvents:"none"}},[b.value&&p.value&&!I.value?(e.openBlock(),e.createElementBlock("div",{key:0,style:e.normalizeStyle({position:"absolute",left:`${b.value.zoneLeft}px`,top:`${b.value.zoneTop}px`,width:`${b.value.size+20}px`,height:`${((null==(n=p.value[p.value.length-1])?void 0:n.size.height)??0)*(r.cssPageHeight/r.pdfPageHeight)+b.value.size+12}px`,pointerEvents:"auto"}),onMouseenter:s[0]||(s[0]=e=>c.value=p.value),onMouseleave:s[1]||(s[1]=e=>c.value=null)},[e.createElementVNode("button",{type:"button",title:"添加书签",style:e.normalizeStyle({position:"absolute",left:b.value.iconLeft-b.value.zoneLeft+"px",top:b.value.iconTop-b.value.zoneTop+"px",width:`${b.value.size}px`,height:`${b.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(C,["stop"])}," 🔖 ",4)],36)):e.createCommentVNode("",!0)],512)):e.createCommentVNode("",!0)}}}),dn={key:0,width:"20",height:"20",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},cn={key:1,width:"24",height:"24",viewBox:"0 0 28 28",fill:"none","aria-hidden":""},un={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"},gn={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"},mn={key:3,d:"M5 14h18",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},fn={key:2,width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},vn=e.defineComponent({__name:"SelectionToolbarIcons",props:{kind:{}},setup:t=>(r,s)=>"copy"===t.kind?(e.openBlock(),e.createElementBlock("svg",dn,[...s[0]||(s[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",cn,["highlight"===t.kind?(e.openBlock(),e.createElementBlock("rect",un)):e.createCommentVNode("",!0),s[1]||(s[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",gn)):"strikeout"===t.kind?(e.openBlock(),e.createElementBlock("path",mn)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("svg",fn,[...s[2]||(s[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)])]))}),Pn=["title","aria-label","onMouseenter","onClick"],In=["title","onMouseenter","onClick"],Cn={style:{"font-size":"11px","font-weight":"600"}},bn=e.defineComponent({__name:"SelectionToolbarCard",props:{placementAbove:{type:Boolean},anchorHeight:{},hiddenBuiltinActions:{},extraActions:{},renderCopyIcon:{type:Function}},emits:["action"],setup(t,{emit:r}){const s=t,n=r,a=[{id:"highlight",label:"高亮背景"},{id:"underline",label:"下划线"},{id:"squiggly",label:"波浪线"},{id:"strikeout",label:"删除线"}],o=e.computed(()=>new Set(s.hiddenBuiltinActions??[])),i=e.computed(()=>!o.value.has("copy")),l=e.computed(()=>a.filter(e=>!o.value.has(e.id))),h=e.computed(()=>!o.value.has("note")),d=e.computed(()=>[...s.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:s.placementAbove?void 0:`${s.anchorHeight+10}px`,bottom:s.placementAbove?`${s.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(r,s)=>(e.openBlock(),e.createElementBlock("div",{role:"toolbar","aria-label":"选区工具",style:e.normalizeStyle(p.value)},[i.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createElementVNode("button",{type:"button",title:"复制","aria-label":"复制",style:e.normalizeStyle(g("copy")),onMouseenter:s[0]||(s[0]=e=>u.value="copy"),onMouseleave:s[1]||(s[1]=e=>u.value=null),onClick:s[2]||(s[2]=e=>n("action","copy"))},[t.renderCopyIcon?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(t.renderCopyIcon),{key:0})):(e.openBlock(),e.createBlock(vn,{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:s[3]||(s[3]=e=>u.value=null),onClick:e=>n("action",t.id)},[e.createVNode(vn,{kind:t.id},null,8,["kind"])],44,Pn))),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:s[4]||(s[4]=e=>u.value=null),onClick:e=>n("action",t.id)},[e.createElementVNode("span",Cn,e.toDisplayString(t.label.slice(0,2)),1)],44,In))),128)),h.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[c.value||i.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:s[5]||(s[5]=e=>u.value="note"),onMouseleave:s[6]||(s[6]=e=>u.value=null),onClick:s[7]||(s[7]=e=>n("action","note"))},[e.createVNode(vn,{kind:"note"})],36)],64)):e.createCommentVNode("",!0)],4))}}),Sn={highlight:"highlight",underline:"underline",squiggly:"squiggly",strikeout:"strikeout"},wn=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(s){const n=s,o=e.computed(()=>n.features),{hostRef:i}=Er(o),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:r}=t.useRegistry();return e.computed(()=>{var e,t,s;const n=null==(s=null==(t=null==(e=r.value)?void 0:e.getPlugin(ft.id))?void 0:t.provides)?void 0:s.call(t);return n?e=>n.createNoteFromSelection(e):null})}(),c=function(){const{registry:r}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=r.value)?void 0:e.getPlugin(ft.id))})}(),u=function(){const{registry:r}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=r.value)?void 0:e.getPlugin(dr.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(s,n){const a=e.computed(()=>{var e;return null==(e=s())?void 0:e.selectionToolbar}),o=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=s())?void 0:e.markup)?void 0:t.enabled)}),i=e.computed(()=>{var e,t;return!1!==(null==(t=null==(e=s())?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(r.AnnotationPlugin.id),{provides:u}=t.useCapability(ft.id);return e.computed(()=>{var t,r,h;if(!1!==(null==(t=a.value)?void 0:t.enabled)&&(o.value||i.value||l.value||(null==(h=null==(r=a.value)?void 0:r.extraActions)?void 0:h.length)))return t=>{const r=rn(t.item),h=sn(t.item);return p=>{var g,m,f,v;return e.h("div",p.menuWrapperProps,e.h(bn,{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||!i.value)return;const e=d.value.getHighlightRectsForPage(h,r);return void nn(d.value.getSelectedText(r),r=>{var s;null==(s=u.value)||s.requestCreateFromSelection({chapterId:t.item.chapterId,localPageIndex:t.item.localPageIndex,globalPageIndex:t.item.globalPageIndex,globalPageNumber:t.item.globalPageNumber,rectsPdfCoord:e,selectedText:r.join("\n")})})}null==(a=null==n?void 0:n.onExtraAction)||a.call(n,e,t)}else{if(!d.value||!c.value||!o.value)return;T(r,Sn[e],c.value,d.value,null==(g=null==(p=s())?void 0:p.markup)?void 0:g.styles)}else{if(!d.value||!l.value)return;nn(d.value.getSelectedText(r),e=>{!async function(e){var t;const r=e.trim();if(!r)return!1;try{if("undefined"!=typeof navigator&&(null==(t=navigator.clipboard)?void 0:t.writeText))return await navigator.clipboard.writeText(r),!0}catch{}if("undefined"==typeof document)return!1;try{const e=document.createElement("textarea");e.value=r,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 r;const s=[];if(m.value){const r=function(t){var r,s,a,o;const i=rn(t),l=sn(t),h=null==(s=null==(r=P.value)?void 0:r.getDocument(i))?void 0:s.pages[l];return t.isPlaceholder||!h?null:e.h(hn,{item:t,pdfPageWidth:h.size.width,pdfPageHeight:h.size.height,cssPageWidth:t.width,cssPageHeight:t.height,hoverUi:null==(o=null==(a=n.features)?void 0:a.bookmarks)?void 0:o.hover})}(t);r&&s.push(r)}const a=null==(r=n.renderPageOverlay)?void 0:r.call(n,t);if(a&&s.push(a),s.length)return e.h("div",s)}return(t,r)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"hostRef",ref:i,class:e.normalizeClass(s.className),style:e.normalizeStyle(s.className?void 0:e.unref(M))},[e.createVNode(e.unref(rs),{class:e.normalizeClass(s.className),style:e.normalizeStyle(l.value)},{page:e.withCtx(({item:t})=>{var r,n,a,o;return[e.createVNode(ln,{item:t,features:s.features,"show-note-markers":p.value,"show-bookmark-markers":g.value,"show-redaction-layer":s.showRedactionLayer,"note-marker-ui":null==(n=null==(r=s.features)?void 0:r.notes)?void 0:n.marker,"bookmark-marker-ui":null==(o=null==(a=s.features)?void 0:a.bookmarks)?void 0:o.marker,"build-selection-menu":v.value,"create-note":e.unref(d),"annotation-selection-menu":s.annotationSelectionMenu,"redaction-selection-menu":s.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))}}),yn={key:0,style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,width:"100%"}},Mn=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{},onExtraSelectionAction:{type:Function}},setup(r){const s=r,n=e.computed(()=>function(e){if(e.options)return wr(e.options);if(!e.editorOptions)throw new Error("ChapterPdfViewer: 请传入 `options`(推荐),或同时传入 `editorOptions` 与 `features`");const t=N(e.features),{plugins:r}=Ir({...e.editorOptions,features:t});return{plugins:r,features:t,editorOptions:{...e.editorOptions,features:t}}}({engine:s.engine,options:s.options,editorOptions:s.editorOptions,features:s.features}));return(s,a)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(r.className),style:e.normalizeStyle(r.className?void 0:e.unref(M))},[e.createVNode(e.unref(t.EmbedPDF),{engine:r.engine,plugins:n.value.plugins},{default:e.withCtx(({pluginsReady:t})=>[t?(e.openBlock(),e.createElementBlock("div",yn,[e.renderSlot(s.$slots,"prepend"),e.createVNode(wn,{class:e.normalizeClass(r.viewportClassName),style:{flex:1,minHeight:0},features:n.value.features,"on-extra-selection-action":r.onExtraSelectionAction},null,8,["class","features","on-extra-selection-action"]),e.renderSlot(s.$slots,"default")])):e.createCommentVNode("",!0)]),_:3},8,["engine","plugins"])],6))}}),xn={class:"chapter-tree-row"},Ln=["aria-expanded"],$n={key:1,class:"chapter-tree-toggle-spacer","aria-hidden":""},Dn={class:"chapter-tree-label"},kn={class:"chapter-tree-meta"},Un={key:0},En=(e,t)=>{const r=e.__vccOpts||e;for(const[s,n]of t)r[s]=n;return r},Tn=En(e.defineComponent({__name:"ChapterTreeItem",props:{node:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup(t){const r={idle:"未加载",loading:"加载中",loaded:"已加载",closed:"已卸载",error:"失败","password-required":"需密码"},s=t,n=e.computed(()=>s.node.children??[]),a=e.computed(()=>n.value.length>0),o=e.ref(s.depth<1),i=e.computed(()=>s.activeChapterId===s.node.id),l=e.computed(()=>s.chapterStatus[s.node.id]??"idle"),h=e.computed(()=>!a.value);return(s,d)=>(e.openBlock(),e.createElementBlock("li",null,[e.createElementVNode("div",xn,[a.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"chapter-tree-toggle","aria-expanded":o.value,onClick:d[0]||(d[0]=e=>o.value=!o.value)},e.toDisplayString(o.value?"▼":"▶"),9,Ln)):(e.openBlock(),e.createElementBlock("span",$n)),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["chapter-tree-btn",{"chapter-tree-btn-active":i.value}]),onClick:d[1]||(d[1]=e=>s.$emit("select",t.node.id))},[e.createElementVNode("div",Dn,e.toDisplayString(t.node.title),1),e.createElementVNode("div",kn,[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",Un,e.toDisplayString(r[l.value]),1)):e.createCommentVNode("",!0)])],2)]),a.value&&o.value?(e.openBlock(),e.createBlock(Fn,{key:0,nodes:n.value,depth:t.depth+1,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:d[2]||(d[2]=e=>s.$emit("select",e))},null,8,["nodes","depth","active-chapter-id","chapter-status"])):e.createCommentVNode("",!0)]))}}),[["__scopeId","data-v-315bbf7a"]]),Fn=En(e.defineComponent({__name:"ChapterTreeList",props:{nodes:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup:t=>(r,s)=>(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(Tn,{key:n.id,node:n,depth:t.depth,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:s[0]||(s[0]=e=>r.$emit("select",e))},null,8,["node","depth","active-chapter-id","chapter-status"]))),128))],4))}),[["__scopeId","data-v-eb742e4f"]]),An={class:"chapter-tree"},Nn={class:"chapter-tree-nav","aria-label":"章节目录"},On=En(e.defineComponent({__name:"ChapterTreePanel",props:{tree:{},activeChapterId:{}},emits:["active-chapter-change"],setup(r,{emit:s}){const n=r,a=s,{provides:o}=t.useCapability($e.id),{provides:i}=t.useCapability(se.id),l=e.ref({});function h(){if(!i.value)return;const e={},t=r=>{var s;for(const n of r)e[n.id]=i.value.getChapterStatus(n.id),(null==(s=n.children)?void 0:s.length)&&t(n.children)};t(n.tree),l.value=e}e.watch([i,()=>n.tree],h,{immediate:!0});let d=null;function c(e){var t;a("active-chapter-change",e),null==(t=o.value)||t.scrollToChapter(e)}return e.watch(i,e=>{null==d||d(),d=e?e.onChapterStatusChange(h):null},{immediate:!0}),e.onBeforeUnmount(()=>null==d?void 0:d()),(t,s)=>(e.openBlock(),e.createElementBlock("aside",An,[s[0]||(s[0]=e.createElementVNode("h2",{class:"chapter-tree-title"},"章节目录",-1)),e.createElementVNode("nav",Nn,[e.createVNode(Fn,{nodes:r.tree,depth:0,"active-chapter-id":r.activeChapterId,"chapter-status":l.value,onSelect:c},null,8,["nodes","active-chapter-id","chapter-status"])])]))}}),[["__scopeId","data-v-d7a0838d"]]),zn=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{}},setup:t=>(t,r)=>(e.openBlock(),e.createBlock(e.unref(Mn),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 Gn(e){const[t,r]=e.localPageRange;return r-t+1}function Vn(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Rn(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Vn(t)?t.segmentPageThreshold:null}function Bn(e,t){return`${e}#s${t}`}function _n(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function qn(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Wn(e){const t=Rn(e);if(!t)return null;const r=Gn(e),s=qn(r,t),n=Vn(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:Bn(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Hn(e,t){const r=Wn(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function jn(e,t){const r=Wn(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Yn(e){var t;const r=Rn(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Gn(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!Vn(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=qn(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Zn={kind:"first-wins"};function Kn(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let Jn=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const Xn=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Zn,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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Zn,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=_n(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=_n(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=_n(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?Hn(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Wn(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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Yn(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.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 r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=Zn){const r=function(e,t=Zn){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Kn(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Jn(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Wn(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var r;const s=this.getSegmentPlanForChapter(e);return s?(null==(r=s.segments[t])?void 0:r.documentId)??null:0===t?e:null}isSegmentLoadPending(e,t){const r=this.resolveSegmentDocumentId(e,t);if(!r)return!1;if(this.pendingSegmentLoadPromises.has(r))return!0;if(0===t&&this.pendingChapterLoadPromises.has(e))return!0;const s=this.coreState.core.documents[r];return"loading"===(null==s?void 0:s.status)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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.isSegmentLoadPending(e,0))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=jn(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=Hn(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=Wn(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(Vn(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Rn(t);if(a){const s=qn(Gn(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(Vn(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;this.chapterErrorMessages.delete(n),this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=_n(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?Wn(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.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,r){const s=this.chapterStatus.get(e);"error"===t&&r?this.chapterErrorMessages.set(e,r):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),s!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Xn.id="chapter-manager";let Qn=Xn;function ea(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ta(e,t){return`${e}#s${t}`}function ra(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function sa(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ea(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=ea(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:ta(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function na(e){const[t,r]=e.localPageRange;return r-t+1}function aa(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function oa(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return aa(t)?t.segmentPageThreshold:null}function ia(e,t){return`${e}#s${t}`}function la(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function ha(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function da(e){const t=oa(e);if(!t)return null;const r=na(e),s=ha(r,t),n=aa(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:ia(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function ca(e,t){const r=da(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function ua(e,t){const r=da(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function pa(e){var t;const r=oa(e);if(!r)return[];const s=[],{chapterId:n}=e,a=na(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!aa(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=ha(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const ga={kind:"first-wins"};function ma(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}class fa{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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}}const va=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ga,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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ga,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=la(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=la(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=la(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?ca(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?da(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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...pa(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.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 r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=ga){const r=function(e,t=ga){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,ma(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new fa(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?da(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var r;const s=this.getSegmentPlanForChapter(e);return s?(null==(r=s.segments[t])?void 0:r.documentId)??null:0===t?e:null}isSegmentLoadPending(e,t){const r=this.resolveSegmentDocumentId(e,t);if(!r)return!1;if(this.pendingSegmentLoadPromises.has(r))return!0;if(0===t&&this.pendingChapterLoadPromises.has(e))return!0;const s=this.coreState.core.documents[r];return"loading"===(null==s?void 0:s.status)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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.isSegmentLoadPending(e,0))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=ua(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=ca(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=da(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(aa(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=oa(t);if(a){const s=ha(na(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(aa(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;this.chapterErrorMessages.delete(n),this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=la(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?da(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.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,r){const s=this.chapterStatus.get(e);"error"===t&&r?this.chapterErrorMessages.set(e,r):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),s!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};va.id="chapter-manager";let Pa=va;function Ia(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.height!==n.height)return!1}return!0}function Ca(e){const[t,r]=e.localPageRange;return r-t+1}function ba(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Sa(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return ba(t)?t.segmentPageThreshold:null}function wa(e,t){return`${e}#s${t}`}function ya(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Ma(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function xa(e){const t=Sa(e);if(!t)return null;const r=Ca(e),s=Ma(r,t),n=ba(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:wa(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function La(e,t){const r=xa(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function $a(e,t){const r=xa(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Da(e){var t;const r=Sa(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Ca(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!ba(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=Ma(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}(class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,Ia),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Pa.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.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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapter(e);if(!s)return!0;const n=function(e,t){const r=sa(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(s,t);return!r.isSegmentLoaded(e,n)}refreshLayout(){this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);0!==e.length&&this.chapterManager.provides().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:r}=ra(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=ra(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}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 r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=sa(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):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:r}=ra(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.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 r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const r=this.config.bufferSize,s=Math.max(0,e[0]-r),n=Math.min(t-1,e[e.length-1]+r),a=[];for(let o=s;o<=n;o++)a.push(o);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,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}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 r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}}).id="chapter-scroll";const ka={kind:"first-wins"};function Ua(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let Ea=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const Ta=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=ka,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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ka,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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?La(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?xa(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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Da(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.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 r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=ka){const r=function(e,t=ka){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Ua(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Ea(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?xa(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var r;const s=this.getSegmentPlanForChapter(e);return s?(null==(r=s.segments[t])?void 0:r.documentId)??null:0===t?e:null}isSegmentLoadPending(e,t){const r=this.resolveSegmentDocumentId(e,t);if(!r)return!1;if(this.pendingSegmentLoadPromises.has(r))return!0;if(0===t&&this.pendingChapterLoadPromises.has(e))return!0;const s=this.coreState.core.documents[r];return"loading"===(null==s?void 0:s.status)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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.isSegmentLoadPending(e,0))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=$a(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=La(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=xa(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(ba(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Sa(t);if(a){const s=Ma(Ca(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(ba(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;this.chapterErrorMessages.delete(n),this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=ya(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?xa(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.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,r){const s=this.chapterStatus.get(e);"error"===t&&r?this.chapterErrorMessages.set(e,r):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),s!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Ta.id="chapter-manager";let Fa=Ta;function Aa(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Na(e,t){return`${e}#s${t}`}function Oa(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function za(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 r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=Aa(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:Na(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Ga(e){const[t,r]=e.localPageRange;return r-t+1}function Va(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ra(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Va(t)?t.segmentPageThreshold:null}function Ba(e,t){return`${e}#s${t}`}function _a(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function qa(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Wa(e){const t=Ra(e);if(!t)return null;const r=Ga(e),s=qa(r,t),n=Va(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:Ba(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function Ha(e,t){const r=Wa(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function ja(e,t){const r=Wa(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Ya(e){var t;const r=Ra(e);if(!r)return[];const s=[],{chapterId:n}=e,a=Ga(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!Va(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=qa(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Za={kind:"first-wins"};function Ka(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let Ja=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const Xa=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Za,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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Za,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=_a(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=_a(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=_a(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?Ha(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Wa(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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Ya(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.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 r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=Za){const r=function(e,t=Za){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Ka(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Ja(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Wa(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var r;const s=this.getSegmentPlanForChapter(e);return s?(null==(r=s.segments[t])?void 0:r.documentId)??null:0===t?e:null}isSegmentLoadPending(e,t){const r=this.resolveSegmentDocumentId(e,t);if(!r)return!1;if(this.pendingSegmentLoadPromises.has(r))return!0;if(0===t&&this.pendingChapterLoadPromises.has(e))return!0;const s=this.coreState.core.documents[r];return"loading"===(null==s?void 0:s.status)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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.isSegmentLoadPending(e,0))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=ja(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=Ha(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=Wa(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(Va(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=Ra(t);if(a){const s=qa(Ga(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(Va(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;this.chapterErrorMessages.delete(n),this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=_a(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?Wa(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.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,r){const s=this.chapterStatus.get(e);"error"===t&&r?this.chapterErrorMessages.set(e,r):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),s!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Xa.id="chapter-manager";let Qa=Xa;function eo(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.height!==n.height)return!1}return!0}const to=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,eo),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Qa.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.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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapter(e);if(!s)return!0;const n=function(e,t){const r=za(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(s,t);return!r.isSegmentLoaded(e,n)}refreshLayout(){this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);0!==e.length&&this.chapterManager.provides().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:r}=Oa(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=Oa(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}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 r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=za(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):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:r}=Oa(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.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 r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const r=this.config.bufferSize,s=Math.max(0,e[0]-r),n=Math.min(t-1,e[e.length-1]+r),a=[];for(let o=s;o<=n;o++)a.push(o);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,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}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 r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};to.id="chapter-scroll";let ro=to;const so=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(ro.id),this.chapterManager=this.registry.getPlugin(Fa.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(r){this.logger.error(e.id,"LoadNotes","Failed to load notes",r)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(r=>r.chapterId===e&&r.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,r;const s=this.notes.get(e);s&&(null==(r=(t=this.config.callbacks).onActivateNote)||r.call(t,e,s),this.noteActivated$.emit({noteId:e,anchor:s}))}listAll(){return Array.from(this.notes.values())}listNotesForChapter(e){return this.listAll().filter(t=>t.chapterId===e)}replaceNotesForChapter(e,t){for(const[r,s]of this.notes.entries())s.chapterId===e&&this.notes.delete(r);for(const r of t)r.chapterId===e&&this.notes.set(r.noteId,r);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:ao(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:r,onCreateNote:s}=this.config.callbacks;return r?(r({draft:t,complete:async e=>{const r={...t,noteId:e};this.registerNote(r)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const r=this.buildDraft(t),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let n=null;try{n=await s(r)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!n)return null;const a={...r,noteId:n.noteId};return this.registerNote(a),a}async deleteNote(t){var r,s;if(this.notes.has(t)){try{await(null==(s=(r=this.config.callbacks).onDeleteNote)?void 0:s.call(r,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,r){var s,n;const a=this.notes.get(t);if(!a)return;const o={...a,content:r};try{await(null==(n=(s=this.config.callbacks).onUpdateNote)?void 0:n.call(s,o))}catch(i){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",i)}this.notes.set(t,o),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const r=this.notes.get(e);if(!r)return;const s=this.chapterScroll.provides(),n=this.chapterManager.provides();await n.ensureAllSegmentsLoaded(r.chapterId);const a=n.resolvePageDocument(r.chapterId,r.localPageIndex);(null==(t=this.documentManager.provides().getDocument(a.documentId))?void 0:t.pages[a.pageIndex])?(s.scrollToGlobalPageIndex(r.globalPageIndex),await this.waitForPageInLayout(r.globalPageIndex),s.scrollToGlobalPdfPoint(r.globalPageIndex,r.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(r.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),r=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return r?Promise.resolve(r):new Promise(r=>{const s=setTimeout(()=>{n(),r(null)},2500),n=t.onLayoutChange(t=>{const a=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);a&&(clearTimeout(s),n(),r(a))})})}};so.id="note";let no=so;function ao(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function oo(e){const[t,r]=e.localPageRange;return r-t+1}function io(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function lo(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return io(t)?t.segmentPageThreshold:null}function ho(e,t){return`${e}#s${t}`}function co(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function uo(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function po(e){const t=lo(e);if(!t)return null;const r=oo(e),s=uo(r,t),n=io(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:ho(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function go(e,t){const r=po(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function mo(e,t){const r=po(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function fo(e){var t;const r=lo(e);if(!r)return[];const s=[],{chapterId:n}=e,a=oo(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!io(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=uo(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const vo={kind:"first-wins"};function Po(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}let Io=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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}};const Co=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=vo,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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??vo,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=co(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=co(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=co(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?go(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?po(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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...fo(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.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 r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=vo){const r=function(e,t=vo){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Po(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Io(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?po(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var r;const s=this.getSegmentPlanForChapter(e);return s?(null==(r=s.segments[t])?void 0:r.documentId)??null:0===t?e:null}isSegmentLoadPending(e,t){const r=this.resolveSegmentDocumentId(e,t);if(!r)return!1;if(this.pendingSegmentLoadPromises.has(r))return!0;if(0===t&&this.pendingChapterLoadPromises.has(e))return!0;const s=this.coreState.core.documents[r];return"loading"===(null==s?void 0:s.status)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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.isSegmentLoadPending(e,0))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=mo(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=go(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=po(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(io(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=lo(t);if(a){const s=uo(oo(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(io(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;this.chapterErrorMessages.delete(n),this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=co(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?po(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.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,r){const s=this.chapterStatus.get(e);"error"===t&&r?this.chapterErrorMessages.set(e,r):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),s!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Co.id="chapter-manager";let bo=Co;function So(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function wo(e,t){return`${e}#s${t}`}function yo(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Mo(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return So(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=So(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:wo(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function xo(e){const[t,r]=e.localPageRange;return r-t+1}function Lo(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function $o(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Lo(t)?t.segmentPageThreshold:null}function Do(e,t){return`${e}#s${t}`}function ko(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function Uo(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Eo(e){const t=$o(e);if(!t)return null;const r=xo(e),s=Uo(r,t),n=Lo(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:Do(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function To(e,t){const r=Eo(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function Fo(e,t){const r=Eo(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Ao(e){var t;const r=$o(e);if(!r)return[];const s=[],{chapterId:n}=e,a=xo(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!Lo(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=Uo(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const No={kind:"first-wins"};function Oo(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}class zo{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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}}const Go=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=No,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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??No,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=ko(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=ko(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=ko(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?To(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Eo(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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Ao(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.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 r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=function(e,t=No){const r=function(e,t=No){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Oo(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new zo(a)}(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?Eo(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var r;const s=this.getSegmentPlanForChapter(e);return s?(null==(r=s.segments[t])?void 0:r.documentId)??null:0===t?e:null}isSegmentLoadPending(e,t){const r=this.resolveSegmentDocumentId(e,t);if(!r)return!1;if(this.pendingSegmentLoadPromises.has(r))return!0;if(0===t&&this.pendingChapterLoadPromises.has(e))return!0;const s=this.coreState.core.documents[r];return"loading"===(null==s?void 0:s.status)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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.isSegmentLoadPending(e,0))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=Fo(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=To(this.findChapter(r.chapterId),r.localPageIndex);this.documentManager.provides().isDocumentOpen(e.documentId)&&this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=Eo(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(Lo(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=$o(t);if(a){const s=Uo(xo(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(Lo(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;this.chapterErrorMessages.delete(n),this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=ko(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}l?(this.updateStatus(r,"loading"),this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})):this.updateStatus(r,"password-required")}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?Eo(t):null,n=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const a of s.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,r){const s=this.chapterStatus.get(e);"error"===t&&r?this.chapterErrorMessages.set(e,r):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),s!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};Go.id="chapter-manager";let Vo=Go;function Ro(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 r=0;r<e.items.length;r++){const s=e.items[r],n=t.items[r];if(s.globalPageIndex!==n.globalPageIndex||s.isPlaceholder!==n.isPlaceholder||s.chapterId!==n.chapterId||s.localPageIndex!==n.localPageIndex||s.pdfDocumentId!==n.pdfDocumentId||s.pdfPageIndex!==n.pdfPageIndex||s.offsetTop!==n.offsetTop||s.width!==n.width||s.height!==n.height)return!1}return!0}const Bo=class extends n.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=n.createBehaviorEmitter(void 0,Ro),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.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Vo.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.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()})),this.syncReadyChapterSizes()}isChapterDocumentReady(e){return this.chapterManager.provides().isSegmentLoaded(e,0)}isChapterPagePlaceholder(e,t){const r=this.chapterManager.provides(),s=r.getChapter(e);if(!s)return!0;const n=function(e,t){const r=Mo(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}(s,t);return!r.isSegmentLoaded(e,n)}refreshLayout(){this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}pushVisibleLoads(){if(!this.virtualPageMap||0===this.currentVisible.length)return;const e=this.expandIndicesWithBuffer(this.currentVisible,this.virtualPageMap.totalPages);0!==e.length&&this.chapterManager.provides().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:r}=yo(e);if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0))return;const s=this.documentManager.provides();s.getActiveDocumentId()||s.setActiveDocument(e),this.harvestChapterSizes(r),this.refreshLayout()}onDocumentClosed(e){var t;const{chapterId:r}=yo(e);0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(r).length)??0)&&(this.dropChapterSizes(r),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,r)=>this.scrollToGlobalPdfPoint(e,t,r),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.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,r=0;for(let s=0;s<e;s++){const{width:e,height:n}=this.getPageSize(s);this.offsets[s]=t,t+=n+this.config.pageGap,e>r&&(r=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=r,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let r=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const n=this.pageSizes.get(t.globalPageIndex);n&&n.width===s.width&&n.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),r=!0)}if(r){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const r=(this.offsets[e]??0)-t;0!==r&&(this.viewportEl.scrollTop+=r)}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 r=this.chapterManager.provides(),s=r.getChapter(e),n=this.virtualPageMap.pagesOfChapter(e);if(!s||0===n.length)return;const a=Mo(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var n;const a=o.getDocument(e);if(!(null==(n=null==a?void 0:a.pages)?void 0:n.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=a.pages[r+o];(null==e?void 0:e.size)&&i.push({localPageIndex:t+o,width:e.size.width*l,height:e.size.height*l})}return i.length>0};if(a)for(const h of a.segments){if(!r.isSegmentLoaded(e,h.index))continue;const t=h.localPageEnd-h.localPageStart+1;l(h.documentId,h.localPageStart,0,t)}else r.isSegmentLoaded(e,0)&&l(e,0,0,n.length);0!==i.length?this.applyChapterPageSizes(e,i):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:r}=yo(e);this.chapterManager.provides().getChapter(r)&&this.harvestChapterSizes(r)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const r of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(r.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 r=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",r,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",r),s.disconnect()}},this.syncReadyChapterSizes(),this.recomputeVisible(),0===e.clientHeight&&requestAnimationFrame(()=>{requestAnimationFrame(()=>this.recomputeVisible())})}expandIndicesWithBuffer(e,t){if(0===e.length||t<=0)return[];const r=this.config.bufferSize,s=Math.max(0,e[0]-r),n=Math.min(t-1,e[e.length-1]+r),a=[];for(let o=s;o<=n;o++)a.push(o);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,r=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let n=s;for(;n<e;){const e=this.getPageSize(n);if(e.height<=0)break;const t=this.offsets[n];if(e.height,t>=r)break;n++}const a=[];let o=s,i=-1;for(let l=s;l<n;l++){a.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,n=Math.max(0,Math.min(s,r)-Math.max(e,t));n>i&&(i=n,o=l)}this.currentVisible=a,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:a,currentGlobalPageIndex:o}),this.pushVisibleLoads(),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const n=t+r>>1;this.offsets[n]<=e?(s=n,t=n+1):r=n-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),r=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(r>=0?r:0)+e),n=[];if(this.virtualPageMap&&this.offsets.length>0)for(let a=t;a<=s;a++){const e=this.virtualPageMap.atIndex(a);if(!e)continue;const t=this.getPageSize(a),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);n.push({globalPageIndex:a,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,pdfDocumentId:null==r?void 0:r.documentId,pdfPageIndex:null==r?void 0:r.pageIndex,width:t.width,height:t.height,offsetTop:this.offsets[a]??0,isPlaceholder:s})}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 r=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:r,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,r){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const n=(null==r?void 0:r.marginTop)??80,a=this.virtualPageMap.atIndex(e);if(!a)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(a.chapterId,a.localPageIndex),l=i?null==(s=this.documentManager.provides().getDocument(i.documentId))?void 0:s.pages[i.pageIndex]:void 0;if(!o||!l)return void this.scrollToIndex(e,r);const h=o.height/l.size.height,d=(this.offsets[e]??0)+t*h-n;this.viewportEl.scrollTo({top:Math.max(0,d),behavior:(null==r?void 0:r.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.firstIndexOfChapter(e);r<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(r,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const r=this.virtualPageMap.byGlobalNumber(e);r&&this.scrollToIndex(r.globalPageIndex,t)}};Bo.id="chapter-scroll";let _o=Bo;function qo(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Wo(e,t){const r=e.origin.y,s=e.origin.y+e.size.height,n=t.origin.y,a=t.origin.y+t.size.height,o=Math.max(s,a)-Math.min(r,n);return o<=0?0:Math.max(0,Math.min(s,a)-Math.max(r,n))/o}function Ho(e,t){var r,s;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const n=(null==(r=e.rectsPdfCoord)?void 0:r.length)?e.rectsPdfCoord:[e.rectPdfCoord],a=(null==(s=t.rectsPdfCoord)?void 0:s.length)?t.rectsPdfCoord:[t.rectPdfCoord],o=e.markerAnchor??qo(n),i=t.markerAnchor??qo(a);if(Math.hypot(o.x-i.x,o.y-i.y)<=6)return!0;for(const l of n)for(const e of a){if(Wo(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 jo=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.change$=n.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(_o.id),this.chapterManager=this.registry.getPlugin(bo.id),this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(t){var r;if(this.config=t,null==(r=t.callbacks)?void 0:r.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(s){this.logger.error(e.id,"Load","Failed to load paragraph bookmarks",s)}}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 s of this.entries.values())if(Ho(s.anchor,e.anchor))return s;const t=e.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r={id:t,label:e.label,anchor:e.anchor,metadata:e.metadata,createdAt:Date.now()};return this.entries.set(t,r),this.notifyAndPersist(),r}removeBookmark(e){var t,r,s;this.entries.delete(e)&&(this.notifyAndPersist(),null==(s=null==(r=null==(t=this.config)?void 0:t.callbacks)?void 0:r.onRemoveSuccess)||s.call(r,e))}async requestRemoveBookmark(t){var r,s;const n=this.entries.get(t);if(!n)return!1;const a=null==(s=null==(r=this.config)?void 0:r.callbacks)?void 0:s.onRequestRemove;if(a)try{if(!(await a(n)))return!1}catch(o){return this.logger.error(e.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(t),!0}updateBookmark(e,t){const r=this.entries.get(e);r&&(this.entries.set(e,{...r,...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[r,s]of this.entries.entries())s.anchor.chapterId===e&&this.entries.delete(r);for(const r of t)r.anchor.chapterId===e&&this.entries.set(r.id,r);this.notifyAndPersist()}notifyAndPersist(){var t,r;const s=this.list();this.change$.emit(s),(null==(r=null==(t=this.config)?void 0:t.callbacks)?void 0:r.persist)&&Promise.resolve(this.config.callbacks.persist(s)).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 r=this.chapterScroll.provides(),s=this.chapterManager.provides();await s.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,r){e.scrollToGlobalPageIndex(t),await function(e,t,r=2500){const s=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const n=setTimeout(()=>{a(),s(null)},r),a=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(n),a(),s(r))})})}(e,t),e.scrollToGlobalPdfPoint(t,r,{marginTop:80})}(r,n,a)}};jo.id="paragraph-bookmark";let Yo=jo;function Zo(e,t){const r=e;return!1===e?{...t,enabled:!1}:!0===e||void 0===e?{...t,enabled:t.enabled??!0}:{...t,...r,enabled:!1!==(null==r?void 0:r.enabled)}}function Ko(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Jo(e,t){return`${e}#s${t}`}function Xo(e,t){const r=function(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Ko(t)?t.segmentPageThreshold:null}(e);if(!t)return null;const r=function(e){const[t,r]=e.localPageRange;return r-t+1}(e),s=(i=t,(o=r)<=0||i<=0?0:Math.ceil(o/i)),n=Ko(e.source)?e.source.urls:void 0,a=[];var o,i;for(let l=0;l<s;l++){const s=l*t,o=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:l,url:(null==n?void 0:n[l])??"",localPageStart:s,localPageEnd:o,documentId:Jo(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}s.PdfAnnotationSubtype.HIGHLIGHT,s.PdfAnnotationSubtype.UNDERLINE,s.PdfAnnotationSubtype.SQUIGGLY,s.PdfAnnotationSubtype.STRIKEOUT,s.PdfAnnotationSubtype.HIGHLIGHT,s.PdfAnnotationSubtype.UNDERLINE,s.PdfAnnotationSubtype.SQUIGGLY,s.PdfAnnotationSubtype.STRIKEOUT,function(){const e=Zo(void 0,{enabled:!0}),t=Zo(void 0,{enabled:!0}),r=Zo(void 0,{enabled:!0}),s=Zo(void 0,{enabled:!0,min:.5,max:3,initial:1}),n=Zo(!1!==e.enabled||!1!==r.enabled,{enabled:!0});null==void 0||(void 0).background}();function Qo(e){const t=new Uint8Array(e);let r="";for(let s=0;s<t.length;s++)r+=String.fromCharCode(t[s]);return btoa(r)}function ei(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 ti(e){return new Promise((t,r)=>{e.wait(e=>t(e),e=>r(e))})}function ri(e){var t,s,n,a;return{annotation:null==(t=e.getPlugin(r.AnnotationPlugin.id))?void 0:t.provides(),note:null==(s=e.getPlugin(no.id))?void 0:s.provides(),bookmark:null==(n=e.getPlugin(Yo.id))?void 0:n.provides(),chapterManager:null==(a=e.getPlugin(Qn.id))?void 0:a.provides()}}async function si(e,t,r){if(!r||!e)return;const s=e.getSegmentPlan(t)?await e.ensureAllSegmentsLoaded(t):await e.ensureChapterLoaded(t);if("loaded"!==s)throw new Error(`章节 ${t} 未加载成功(${s}),无法导入/导出划线`)}async function ni(e,t,r){const s=ei(r),{annotation:n,note:a,bookmark:o,chapterManager:i}=ri(e),l={chapterId:t};if(s.bookmarks){if(!o)throw new Error("paragraph-bookmark 插件未注册");l.bookmarks=o.listBookmarksForChapter(t)}if(s.notes){if(!a)throw new Error("note 插件未注册");l.notes=a.listNotesForChapter(t)}if(s.markup){if(!n)throw new Error("annotation 插件未注册");await si(i,t,!1!==(null==r?void 0:r.ensureChapterLoaded));const e=await async function(e,t,r){const s=t.getSegmentPlan(r);if(!s)return ti(e.forDocument(r).exportAnnotations());const n=[];for(const a of s.segments){if(!t.isSegmentLoaded(r,a.index))continue;const s=await ti(e.forDocument(a.documentId).exportAnnotations());for(const e of s){const t=e.annotation.pageIndex;n.push({...e,annotation:{...e.annotation,pageIndex:t+a.localPageStart}})}}return n}(n,i,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:Qo(t.data),mimeType:t.mimeType}}})}(e)}return l}async function ai(e,t,r){const s=ei(r),n=(null==r?void 0:r.mode)??"replace",{annotation:a,note:o,bookmark:i,chapterManager:l}=ri(e),h=t.chapterId;if(s.bookmarks&&t.bookmarks){if(!i)throw new Error("paragraph-bookmark 插件未注册");if("replace"===n)i.replaceBookmarksForChapter(h,t.bookmarks);else for(const e of t.bookmarks)i.addBookmark(e)}if(s.notes&&t.notes){if(!o)throw new Error("note 插件未注册");if("replace"===n)o.replaceNotesForChapter(h,t.notes);else for(const e of t.notes)o.registerNote(e)}if(s.markup&&t.markup){if(!a)throw new Error("annotation 插件未注册");await si(l,h,!1!==(null==r?void 0:r.ensureChapterLoaded)),function(e,t,r,s,n){const a=t.getSegmentPlan(r);if(!a){const t=e.forDocument(r);return"replace"===n&&t.deleteAllAnnotations(),void t.importAnnotations(s)}const o=t.getChapter(r);if(!o)return;const i=new Map;for(const l of s){const e=l.annotation.pageIndex,t=Xo(o,e),r=a.segments[t];if(!r)continue;const s=i.get(t)??[];s.push({...l,annotation:{...l.annotation,pageIndex:e-r.localPageStart}}),i.set(t,s)}for(const l of a.segments){const t=e.forDocument(l.documentId),r=i.get(l.index)??[];"replace"===n&&t.deleteAllAnnotations(),r.length>0&&t.importAnnotations(r)}}(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 r=function(e){const t=atob(e),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r.buffer}(e.ctx.dataBase64);return{annotation:e.annotation,ctx:{data:r,...e.ctx.mimeType?{mimeType:e.ctx.mimeType}:{}}}})}(t.markup),n)}(null==r?void 0:r.persistNotes)&&o&&await r.persistNotes(o.listAllNotes()),(null==r?void 0:r.persistBookmarks)&&i&&await r.persistBookmarks(i.listBookmarks())}function oi(e){return JSON.stringify(e,null,2)}function ii(e){return JSON.stringify(e,null,2)}function li(e,t){const r=new Blob([t],{type:"application/json;charset=utf-8"}),s=URL.createObjectURL(r),n=document.createElement("a");n.href=s,n.download=e,n.click(),URL.revokeObjectURL(s)}s.PdfAnnotationSubtype.HIGHLIGHT,s.PdfAnnotationSubtype.UNDERLINE,s.PdfAnnotationSubtype.SQUIGGLY,s.PdfAnnotationSubtype.STRIKEOUT,s.PdfAnnotationSubtype.HIGHLIGHT,s.PdfAnnotationSubtype.UNDERLINE,s.PdfAnnotationSubtype.SQUIGGLY,s.PdfAnnotationSubtype.STRIKEOUT;function hi(e){const[t,r]=e.localPageRange;return r-t+1}function di(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function ci(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return di(t)?t.segmentPageThreshold:null}function ui(e,t){return`${e}#s${t}`}function pi(e){const t=e.lastIndexOf("#s");if(-1===t)return{chapterId:e,segmentIndex:null};const r=e.slice(0,t),s=Number.parseInt(e.slice(t+2),10);return!Number.isFinite(s)||s<0?{chapterId:e,segmentIndex:null}:{chapterId:r,segmentIndex:s}}function gi(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function mi(e){const t=ci(e);if(!t)return null;const r=hi(e),s=gi(r,t),n=di(e.source)?e.source.urls:void 0,a=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;a.push({index:o,url:(null==n?void 0:n[o])??"",localPageStart:s,localPageEnd:i,documentId:ui(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:a}}function fi(e,t){const r=mi(e);if(!r)return{documentId:e.chapterId,pageIndex:t};const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);if(!s){const s=r.segments[r.segments.length-1];return s?{documentId:s.documentId,pageIndex:t-s.localPageStart}:{documentId:e.chapterId,pageIndex:t}}return{documentId:s.documentId,pageIndex:t-s.localPageStart}}function vi(e,t){const r=mi(e);if(!r)return 0;const s=r.segments.find(e=>t>=e.localPageStart&&t<=e.localPageEnd);return(null==s?void 0:s.index)??Math.floor(t/r.threshold)}function Pi(e){var t;const r=ci(e);if(!r)return[];const s=[],{chapterId:n}=e,a=hi(e);r<=0&&s.push(`${n}: segmentPageThreshold must be > 0`);const o=e.source;if(!di(o))return s;0===o.urls.length&&s.push(`${n}: source.urls must not be empty`);const i=gi(a,r);o.urls.length!==i&&s.push(`${n}: source.urls.length (${o.urls.length}) must equal ceil(pageCount/threshold) (${i})`);for(let l=0;l<o.urls.length;l++)(null==(t=o.urls[l])?void 0:t.trim())||s.push(`${n}: source.urls[${l}] is empty`);return s}const Ii={kind:"first-wins"};function Ci(e,t,r){if(1===t.length)return t[0].chapterId;switch(r.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const r=t.find(t=>{var r;return null==(r=t.ownedGlobalPages)?void 0:r.includes(e)});return r?r.chapterId:t[0].chapterId}case"custom":return r.resolve(e,t)}}class bi{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 r=this._byChapter.get(e);return r?r.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const r=null==(t=this._byChapter.get(e))?void 0:t[0];return r?this._pages.indexOf(r):-1}}function Si(e,t=Ii){const r=function(e,t=Ii){const r=new Map;for(const n of e.chapters){const[e,t]=n.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(n):r.set(s,[n])}}const s=new Map;for(const[n,a]of r)s.set(n,Ci(n,a,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const n=Array.from(r.keys()).sort((e,t)=>e-t),a=[];let o=0;for(const i of n){const e=r.get(i),t=s.get(e);if(!t)continue;const[n]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-n);a.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new bi(a)}const wi=class e extends n.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=n.createBehaviorEmitter(),this.manifestChange$=n.createEmitter(),this.overlapStrategy=Ii,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.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(a.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Ii,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=pi(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=pi(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=pi(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),ensureChapterLoaded:e=>this.ensureChapterLoaded(e),ensureSegmentLoaded:(e,t)=>this.ensureSegmentLoaded(e,t),ensureAllSegmentsLoaded:e=>this.ensureAllSegmentsLoaded(e),resolvePageDocument:(e,t)=>{const r=this.findChapter(e);return r?fi(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?mi(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.statusChange$.clear(),this.manifestChange$.clear()}setManifestInternal(t){const r=function(e){const t=function(e){const t=[],r=e=>{for(const s of e){const{children:e,...n}=s;t.push(n),(null==e?void 0:e.length)&&r(e)}};return r(e),t}(e.chapters);return t.length===e.chapters.length?e:{...e,chapters:t}}(t);(function(e){var t;for(const r of e)if(null==(t=r.children)?void 0:t.length)return!0;return!1})(t.chapters)&&this.logger.warn(e.id,"ManifestFlatten",`manifest.chapters 含嵌套 children,已自动展开为 ${r.chapters.length} 条(顶层 ${t.chapters.length} 条)。侧栏树请单独传入,勿依赖 children 渲染 PDF。`);const s=function(e){const t=[],r=new Set;for(const s of e.chapters){r.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),r.add(s.chapterId);const[e,n]=s.globalPageRange,[a,o]=s.localPageRange;if(e>n&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${n}]`),a>o&&t.push(`${s.chapterId}: invalid localPageRange [${a},${o}]`),n-e!==o-a&&t.push(`${s.chapterId}: page-count mismatch (global ${n-e+1} vs local ${o-a+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>n)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Pi(s))}return t}(r);s.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${s.join("; ")}`);const n=new Set(this.chapterStatus.keys()),a=new Set(r.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 r.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=r,this.virtualPageMap=Si(r,this.overlapStrategy),this.manifestChange$.emit({manifest:r,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(),r=Math.min(e,this.manifest.chapters.length);for(let s=0;s<r;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const r=this.chapterStatus.get(e)??"idle";"idle"!==r&&"closed"!==r&&"error"!==r||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}getSegmentPlanForChapter(e){const t=this.findChapter(e);return t?mi(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const n=r.segments[t];return!!n&&s.isDocumentOpen(n.documentId)}resolveSegmentDocumentId(e,t){var r;const s=this.getSegmentPlanForChapter(e);return s?(null==(r=s.segments[t])?void 0:r.documentId)??null:0===t?e:null}isSegmentLoadPending(e,t){const r=this.resolveSegmentDocumentId(e,t);if(!r)return!1;if(this.pendingSegmentLoadPromises.has(r))return!0;if(0===t&&this.pendingChapterLoadPromises.has(e))return!0;const s=this.coreState.core.documents[r];return"loading"===(null==s?void 0:s.status)}syncChapterStatusFromDocuments(e){const t=this.getSegmentPlanForChapter(e),r=this.documentManager.provides();if(!t)return void(r.isDocumentOpen(e)?this.updateStatus(e,"loaded"):"loaded"===this.chapterStatus.get(e)&&this.updateStatus(e,"closed"));const s=t.segments[0];if(s&&r.isDocumentOpen(s.documentId))return 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.isSegmentLoadPending(e,0))return void this.updateStatus(e,"loading");const n=this.chapterStatus.get(e);"loaded"!==n&&"password-required"!==n&&"error"!==n&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,n=new Set;for(const i of e){const e=this.virtualPageMap.atIndex(i);if(!e)continue;s.add(e.chapterId);const t=this.findChapter(e.chapterId);if(!t)continue;const r=vi(t,e.localPageIndex);n.add(`${e.chapterId}:${r}`),n.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const a=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=a.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<a.length&&o.add(t)}for(const i of o){const e=a[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of n){const[e,r]=i.split(":"),s=Number.parseInt(r,10);e&&Number.isFinite(s)&&(this.chapterLastUsed.set(e,t),this.ensureSegmentLoaded(e,s))}if(this.config.autoActivateOnLoad??1){const t=e[0],r=null!=t?this.virtualPageMap.atIndex(t):null;if(r){const e=fi(this.findChapter(r.chapterId),r.localPageIndex);if(this.documentManager.provides().isDocumentOpen(e.documentId)){this.documentManager.provides().getActiveDocumentId()!==e.documentId&&this.documentManager.provides().setActiveDocument(e.documentId)}}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[r,s]of this.chapterStatus){if("loaded"!==s)continue;t-(this.chapterLastUsed.get(r)??0)>e&&this.closeChapter(r)}}ensureChapterLoaded(e){return this.ensureSegmentLoaded(e,0)}ensureAllSegmentsLoaded(e){const t=this.getSegmentPlanForChapter(e);return t?(async()=>{for(const r of t.segments){const t=await this.ensureSegmentLoaded(e,r.index);if("loaded"!==t)return t}return"loaded"})():this.ensureChapterLoaded(e)}ensureSegmentLoaded(e,t){const r=this.findChapter(e);if(!r)return Promise.resolve("error");const s=mi(r);if(!s)return 0!==t?Promise.resolve(this.isSegmentDocumentOpen(e,0)?"loaded":"error"):this.ensureSingleDocumentChapter(r);if(t<0||t>=s.segments.length)return Promise.resolve("error");const n=s.segments[t],a=n.documentId;if(this.documentManager.provides().isDocumentOpen(a))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(a);if(o)return o;const i=this.startLoadSegment(r,n).finally(()=>{this.pendingSegmentLoadPromises.delete(a)});return this.pendingSegmentLoadPromises.set(a,i),i}ensureSingleDocumentChapter(e){const t=e.chapterId,r=this.pendingChapterLoadPromises.get(t);if(r)return r;const s=this.chapterStatus.get(t)??"idle";if("loaded"===s)return this.chapterLastUsed.set(t,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(t);const n=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,n),n}async resolveChapterUrls(e){const{chapterId:t}=e,r=this.chapterUrlsCache.get(t);if(r)return r;const s=this.pendingChapterUrlsPromises.get(t);if(s)return s;const n=(async()=>{const r=e.source;if(di(r)){const e=[...r.urls];return this.chapterUrlsCache.set(t,e),e}const s=this.config.chapterPdfLoader;if(null==s?void 0:s.loadChapterUrls){const r=await s.loadChapterUrls(e);if(!Array.isArray(r)||0===r.length)throw new Error(`Chapter "${t}" loadChapterUrls returned no URLs`);return this.chapterUrlsCache.set(t,r),r}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,r){const s=r[t];if(!(null==s?void 0:s.trim()))throw new Error(`Chapter "${e.chapterId}" missing URL for segment ${t}`);const n=this.config.chapterPdfLoader,a={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==n?void 0:n.openPdf)?n.openPdf(a):{url:s}}async resolvePdfPayload(t,r){const s=t.source,n=this.config.chapterPdfLoader,a=ci(t);if(a){const s=gi(hi(t),a);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const n=await this.resolveChapterUrls(t);return n.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${n.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,n)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(di(s)){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,r,e)}if("url"in s)return{url:s.url};if("buffer"in s)return{buffer:s.buffer};if("load"in s)return s.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,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const n=t.chapterId,a=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??n;this.chapterErrorMessages.delete(n),this.updateStatus(n,"loading"),this.chapterLastUsed.set(n,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(n):null,i=await this.resolvePdfPayload(t,a),l=this.documentManager.provides(),h="url"in i?l.openDocumentUrl({documentId:o,url:i.url,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}):l.openDocumentBuffer({documentId:o,buffer:i.buffer,name:r?`${t.title} (${r.index+1})`:t.title,password:e??void 0,autoActivate:!1}),d=await new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{d.task.wait(()=>e(),e=>t(e))}),l.isDocumentOpen(o)&&this.syncChapterStatusFromDocuments(n),this.waitForTerminalStatus(n)}catch(i){const t=this.chapterStatus.get(n);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${n}"`;this.logger.error(e.id,"LoadChapter",t,i),0===a&&this.updateStatus(n,"error",t)}return this.chapterStatus.get(n)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const r=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(r(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&r(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,r,n,a){if(this.pendingSegmentLoadPromises.has(t))return;if(n!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=pi(t);return void(e&&0!==s&&null!==s||this.updateStatus(r,"error"))}if(!this.passwordProvider)return void this.updateStatus(r,"password-required");const o=this.findChapter(r);if(!o)return;const i=(this.passwordAttempts.get(r)??0)+1;this.passwordAttempts.set(r,i);let l=null;try{l=await this.passwordProvider.resolvePassword(o,i-1)}catch(h){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${r}`,h)}if(!l)return void this.updateStatus(r,"password-required");this.updateStatus(r,"loading");this.documentManager.provides().retryDocument(t,{password:l}).wait(()=>{},()=>{})}closeChapter(e){const t=this.findChapter(e),r=this.documentManager.provides(),s=t?mi(t):null,n=e=>{if(r.isDocumentOpen(e)){r.closeDocument(e).wait(()=>{},()=>{})}};if(s)for(const a of s.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,r){const s=this.chapterStatus.get(e);"error"===t&&r?this.chapterErrorMessages.set(e,r):"loading"!==t&&"loaded"!==t||this.chapterErrorMessages.delete(e),s!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&r?{error:{message:r}}:{}}))}};wi.id="chapter-manager";let yi=wi;function Mi(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 xi(e){const t=[],r=e=>{var s;for(const n of e)t.push(Mi(n)),(null==(s=n.children)?void 0:s.length)&&r(n.children)};return r(e),t}function Li(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)?Li(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=V,exports.ChapterManagerPlugin=yi,exports.ChapterPdfViewer=zn,exports.ChapterTreePanel=On,exports.DEFAULT_CHAPTER_TEXT_SELECTION_BACKGROUND="rgba(33, 150, 243)",exports.DEFAULT_CHAPTER_VIEWER_CONFIG={},exports.DEFAULT_CHAPTER_VIEWER_FEATURES=Pr,exports.PdfChapterViewport=wn,exports.applySelectionMarkup=T,exports.buildChapterViewerCatalog=function(e){return{tree:Li(e),manifest:{chapters:xi(e)}}},exports.buildParagraphBookmarkAnchor=lr,exports.chapterAnnotationsArchiveToJson=oi,exports.chapterAnnotationsSnapshotToJson=ii,exports.chapterDescriptorFromTreeNode=Mi,exports.copyTextToClipboard=async function(e){var t;const r=e.trim();if(!r)return!1;try{if("undefined"!=typeof navigator&&(null==(t=navigator.clipboard)?void 0:t.writeText))return await navigator.clipboard.writeText(r),!0}catch{}if("undefined"==typeof document)return!1;try{const e=document.createElement("textarea");e.value=r,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=wr,exports.createChapterViewerEditor=Ir,exports.createChapterViewerEditorOptions=function(e){const{features:t,...r}=Sr(br(e));return r},exports.createPdfChapterEditor=fr,exports.defaultOverlapStrategy={kind:"first-wins"},exports.downloadChapterAnnotationsArchive=function(e,t="chapter-annotations.json"){li(t,oi(e))},exports.downloadChapterAnnotationsSnapshot=function(e,t){li(t??`chapter-annotations-${e.chapterId}.json`,ii(e))},exports.downloadJsonFile=li,exports.exportAllChapterAnnotations=async function(e,t,r){const s={};for(const n of t.chapters){const t=await ni(e,n.chapterId,r),{chapterId:a,...o}=t;s[n.chapterId]=o}return{version:1,exportedAt:(new Date).toISOString(),chapters:s}},exports.exportChapterAnnotations=ni,exports.flattenChapterTree=xi,exports.importChapterAnnotations=ai,exports.importChapterAnnotationsArchive=async function(e,t,r){if(1!==t.version)throw new Error(`不支持的归档版本 ${t.version},当前为 1`);for(const[s,n]of Object.entries(t.chapters))await ai(e,{chapterId:s,...n},r)},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=Li;
2
2
  //# sourceMappingURL=index.cjs.map