@embedpdf-editor/vue3-chapter-viewer 1.0.0 → 1.0.3

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"),a=require("@embedpdf/plugin-annotation"),s=require("@embedpdf/models"),r=require("@embedpdf/core"),i=require("@embedpdf/plugin-document-manager"),o=require("@embedpdf/plugin-interaction-manager"),n=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"),b=require("@embedpdf/plugin-interaction-manager/vue"),P=require("@embedpdf/plugin-rotate/vue"),w=require("@embedpdf/plugin-selection/vue"),C=require("@embedpdf/plugin-annotation/vue"),y=require("@embedpdf/plugin-redaction/vue"),I=require("@embedpdf/plugin-render/vue"),M=require("@embedpdf/engines/vue"),S={position:"relative",height:"100%",width:"100%"},x={userSelect:"none",WebkitUserSelect:"none"};function k(){var e;"undefined"!=typeof window&&(null==(e=window.getSelection())||e.removeAllRanges())}const L="#f1f5f9",$={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:4},strikeout:{offsetY:0}},T={highlight:s.PdfAnnotationSubtype.HIGHLIGHT,underline:s.PdfAnnotationSubtype.UNDERLINE,squiggly:s.PdfAnnotationSubtype.SQUIGGLY,strikeout:s.PdfAnnotationSubtype.STRIKEOUT};function D(e,t){return 0===t?e:e.map(e=>({origin:{x:e.origin.x,y:e.origin.y+t},size:{...e.size}}))}function z(e){let t=1/0,a=1/0,s=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.origin.x),a=Math.min(a,i.origin.y),s=Math.max(s,i.origin.x+i.size.width),r=Math.max(r,i.origin.y+i.size.height);return{origin:{x:t,y:a},size:{width:s-t,height:r-a}}}function N(e,t,r,i,o){const n=r.forDocument(e),l=i.forDocument(e);if(!n||!l)return!1;const h="highlight"===t?"highlight":"underline"===t?"underline":"squiggly"===t?"squiggly":"strikeout",d=r.getTool(h);if(!d)return!1;const c=d.defaults,u={...$[g=t],...null==(f=o)?void 0:f[g]},p=l.getFormattedSelection();var g,f;if(0===p.length)return!1;n.setLocked({type:a.LockModeType.Exclude,categories:["markup","shape"]});for(const a of p){const e=s.uuidV4(),r=u.color??c.color??c.strokeColor,i=u.opacity??c.opacity,o=u.thickness??c.strokeWidth,l=u.offsetY??0,h="underline"===t||"squiggly"===t||"strikeout"===t?D(a.segmentRects,l):a.segmentRects,d="underline"===t||"squiggly"===t||"strikeout"===t?z(h):a.rect;n.createAnnotation(a.pageIndex,{id:e,created:new Date,flags:["print"],type:T[t],..."highlight"===t?{blendMode:s.PdfBlendMode.Multiply}:{},strokeColor:r,opacity:i,...null!=o?{strokeWidth:o}:{},pageIndex:a.pageIndex,rect:d,segmentRects:h})}return l.clear(),!0}const O=new Set([s.PdfAnnotationSubtype.HIGHLIGHT,s.PdfAnnotationSubtype.UNDERLINE,s.PdfAnnotationSubtype.SQUIGGLY,s.PdfAnnotationSubtype.STRIKEOUT]);function E(e,t){const a=e;return!1===e?{...t,enabled:!1}:!0===e||void 0===e?{...t,enabled:t.enabled??!0}:{...t,...a,enabled:!1!==(null==a?void 0:a.enabled)}}function A(e){var t;const a=E(null==e?void 0:e.markup,{enabled:!0}),s=E(null==e?void 0:e.bookmarks,{enabled:!0}),r=E(null==e?void 0:e.notes,{enabled:!0}),i=E(null==e?void 0:e.zoom,{enabled:!0,min:.5,max:3,initial:1}),o=E(void 0===(null==e?void 0:e.selectionToolbar)?!1!==a.enabled||!1!==r.enabled:e.selectionToolbar,{enabled:!0});return{markup:a,bookmarks:s,notes:r,zoom:i,scrollViewport:{background:(null==(t=null==e?void 0:e.scrollViewport)?void 0:t.background)??L},selectionToolbar:o}}class G{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}},R={kind:"first-wins"};function B(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let F=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 a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const U=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=R,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??R,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,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),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 a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=R){const a=function(e,t=R){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,B(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new F(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};U.id="chapter-manager";let q=U;const H={manifest:_,create:e=>new q(V,e),reducer:e=>e,initialState:{}},W="chapter-scroll",j={id:W,name:"Chapter Scroll Plugin",version:"0.1.0",provides:["chapter-scroll"],requires:["chapter-manager"],optional:[],defaultConfig:{placeholderPageHeight:1200,placeholderPageWidth:900,bufferSize:2,pageGap:20}},Z={kind:"first-wins"};function Y(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let J=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 a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const K=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Z,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Z,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,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),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 a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Z){const a=function(e,t=Z){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,Y(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new J(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};K.id="chapter-manager";let X=K;function Q(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 a=0;a<e.items.length;a++){const s=e.items[a],r=t.items[a];if(s.globalPageIndex!==r.globalPageIndex||s.isPlaceholder!==r.isPlaceholder||s.chapterId!==r.chapterId||s.localPageIndex!==r.localPageIndex||s.offsetTop!==r.offsetTop||s.width!==r.width||s.height!==r.height)return!1}return!0}const ee=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,Q),this.visibleChange$=r.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(X.id),this.documentManager=this.registry.getPlugin(i.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){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}isChapterPagePlaceholder(e){const t=this.chapterManager.provides().getChapterStatus(e);return"error"===t||"password-required"===t||"loaded"!==t}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;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),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,a)=>this.scrollToGlobalPdfPoint(e,t,a),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,a=0;for(let s=0;s<e;s++){const{width:e,height:r}=this.getPageSize(s);this.offsets[s]=t,t+=r+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===s.width&&r.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),r=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===r.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const i=this.getChapterDocumentScale(e),o=[];for(const n of r){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&o.push({localPageIndex:n.localPageIndex,width:e.size.width*i,height:e.size.height*i})}0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.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 a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),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,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let r=s;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=a)break;r++}const i=[];let o=s,n=-1;for(let l=s;l<r;l++){i.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,r=Math.max(0,Math.min(s,a)-Math.max(e,t));r>n&&(n=r,o=l)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(i),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const r=t+a>>1;this.offsets[r]<=e?(s=r,t=r+1):a=r-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let i=t;i<=s;i++){const e=this.virtualPageMap.atIndex(i);if(!e)continue;const t=this.getPageSize(i),a=this.isChapterPagePlaceholder(e.chapterId);r.push({globalPageIndex:i,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[i],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==a?void 0:a.marginTop)??80,i=this.virtualPageMap.atIndex(e);if(!i)return void this.scrollToIndex(e,a);const o=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(i.chapterId))?void 0:s.pages[i.localPageIndex];if(!o||!n)return void this.scrollToIndex(e,a);const l=o.height/n.size.height,h=(this.offsets[e]??0)+t*l-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}};ee.id="chapter-scroll";let te=ee;const ae={manifest:j,create:e=>new te(W,e),reducer:e=>e,initialState:{}},se="note",re={id:se,name:"Note Plugin",version:"0.1.0",provides:["note"],requires:["selection","chapter-scroll","chapter-manager"],optional:[],defaultConfig:{callbacks:{onCreateNote:async()=>null,onActivateNote:()=>{}},markerSize:18}},ie={kind:"first-wins"};function oe(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let ne=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 a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const le=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=ie,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ie,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,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),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 a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=ie){const a=function(e,t=ie){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,oe(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new ne(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};le.id="chapter-manager";let he=le;const de={kind:"first-wins"};function ce(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let ue=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 a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const pe=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=de,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??de,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,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),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 a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=de){const a=function(e,t=de){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,ce(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new ue(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};pe.id="chapter-manager";let ge=pe;function fe(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 a=0;a<e.items.length;a++){const s=e.items[a],r=t.items[a];if(s.globalPageIndex!==r.globalPageIndex||s.isPlaceholder!==r.isPlaceholder||s.chapterId!==r.chapterId||s.localPageIndex!==r.localPageIndex||s.offsetTop!==r.offsetTop||s.width!==r.width||s.height!==r.height)return!1}return!0}const me=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,fe),this.visibleChange$=r.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(ge.id),this.documentManager=this.registry.getPlugin(i.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){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}isChapterPagePlaceholder(e){const t=this.chapterManager.provides().getChapterStatus(e);return"error"===t||"password-required"===t||"loaded"!==t}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;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),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,a)=>this.scrollToGlobalPdfPoint(e,t,a),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,a=0;for(let s=0;s<e;s++){const{width:e,height:r}=this.getPageSize(s);this.offsets[s]=t,t+=r+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===s.width&&r.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),r=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===r.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const i=this.getChapterDocumentScale(e),o=[];for(const n of r){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&o.push({localPageIndex:n.localPageIndex,width:e.size.width*i,height:e.size.height*i})}0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.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 a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),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,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let r=s;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=a)break;r++}const i=[];let o=s,n=-1;for(let l=s;l<r;l++){i.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,r=Math.max(0,Math.min(s,a)-Math.max(e,t));r>n&&(n=r,o=l)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(i),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const r=t+a>>1;this.offsets[r]<=e?(s=r,t=r+1):a=r-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let i=t;i<=s;i++){const e=this.virtualPageMap.atIndex(i);if(!e)continue;const t=this.getPageSize(i),a=this.isChapterPagePlaceholder(e.chapterId);r.push({globalPageIndex:i,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[i],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==a?void 0:a.marginTop)??80,i=this.virtualPageMap.atIndex(e);if(!i)return void this.scrollToIndex(e,a);const o=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(i.chapterId))?void 0:s.pages[i.localPageIndex];if(!o||!n)return void this.scrollToIndex(e,a);const l=o.height/n.size.height,h=(this.offsets[e]??0)+t*l-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}};me.id="chapter-scroll";let ve=me;const be=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=r.createBehaviorEmitter([]),this.noteActivated$=r.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(ve.id),this.chapterManager=this.registry.getPlugin(he.id),this.documentManager=this.registry.getPlugin(i.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(a){this.logger.error(e.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(a=>a.chapterId===e&&a.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,a;const s=this.notes.get(e);s&&(null==(a=(t=this.config.callbacks).onActivateNote)||a.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[a,s]of this.notes.entries())s.chapterId===e&&this.notes.delete(a);for(const a of t)a.chapterId===e&&this.notes.set(a.noteId,a);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:we(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:t,complete:async e=>{const a={...t,noteId:e};this.registerNote(a)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const a=this.buildDraft(t),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let r=null;try{r=await s(a)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!r)return null;const i={...a,noteId:r.noteId};return this.registerNote(i),i}async deleteNote(t){var a,s;if(this.notes.has(t)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,t))}catch(r){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",r)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,a){var s,r;const i=this.notes.get(t);if(!i)return;const o={...i,content:a};try{await(null==(r=(s=this.config.callbacks).onUpdateNote)?void 0:r.call(s,o))}catch(n){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",n)}this.notes.set(t,o),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const a=this.notes.get(e);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(t=this.documentManager.provides().getDocument(a.chapterId))?void 0:t.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),a=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{r(),a(null)},2500),r=t.onLayoutChange(t=>{const i=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);i&&(clearTimeout(s),r(),a(i))})})}};be.id="note";let Pe=be;function we(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}const Ce={manifest:re,create:e=>new Pe(se,e),reducer:e=>e,initialState:{}},ye="paragraph-bookmark",Ie={id:ye,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}},Me={kind:"first-wins"};function Se(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let xe=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 a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const ke=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Me,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Me,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,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),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 a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Me){const a=function(e,t=Me){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,Se(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new xe(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};ke.id="chapter-manager";let Le=ke;const $e={kind:"first-wins"};function Te(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let De=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 a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const ze=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=$e,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.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=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,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),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 a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=$e){const a=function(e,t=$e){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,Te(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new De(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};ze.id="chapter-manager";let Ne=ze;function Oe(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 a=0;a<e.items.length;a++){const s=e.items[a],r=t.items[a];if(s.globalPageIndex!==r.globalPageIndex||s.isPlaceholder!==r.isPlaceholder||s.chapterId!==r.chapterId||s.localPageIndex!==r.localPageIndex||s.offsetTop!==r.offsetTop||s.width!==r.width||s.height!==r.height)return!1}return!0}const Ee=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,Oe),this.visibleChange$=r.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Ne.id),this.documentManager=this.registry.getPlugin(i.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){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}isChapterPagePlaceholder(e){const t=this.chapterManager.provides().getChapterStatus(e);return"error"===t||"password-required"===t||"loaded"!==t}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;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),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,a)=>this.scrollToGlobalPdfPoint(e,t,a),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,a=0;for(let s=0;s<e;s++){const{width:e,height:r}=this.getPageSize(s);this.offsets[s]=t,t+=r+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===s.width&&r.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),r=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===r.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const i=this.getChapterDocumentScale(e),o=[];for(const n of r){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&o.push({localPageIndex:n.localPageIndex,width:e.size.width*i,height:e.size.height*i})}0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.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 a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),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,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let r=s;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=a)break;r++}const i=[];let o=s,n=-1;for(let l=s;l<r;l++){i.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,r=Math.max(0,Math.min(s,a)-Math.max(e,t));r>n&&(n=r,o=l)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(i),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const r=t+a>>1;this.offsets[r]<=e?(s=r,t=r+1):a=r-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let i=t;i<=s;i++){const e=this.virtualPageMap.atIndex(i);if(!e)continue;const t=this.getPageSize(i),a=this.isChapterPagePlaceholder(e.chapterId);r.push({globalPageIndex:i,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[i],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==a?void 0:a.marginTop)??80,i=this.virtualPageMap.atIndex(e);if(!i)return void this.scrollToIndex(e,a);const o=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(i.chapterId))?void 0:s.pages[i.localPageIndex];if(!o||!n)return void this.scrollToIndex(e,a);const l=o.height/n.size.height,h=(this.offsets[e]??0)+t*l-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}};Ee.id="chapter-scroll";let Ae=Ee;function Ge(e){if(0===e.length)throw new Error("unionRects: empty rects");let t=1/0,a=1/0,s=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.origin.x),a=Math.min(a,i.origin.y),s=Math.max(s,i.origin.x+i.size.width),r=Math.max(r,i.origin.y+i.size.height);return{origin:{x:t,y:a},size:{width:s-t,height:r-a}}}function Ve(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function _e(e,t){const a=e.origin.y,s=e.origin.y+e.size.height,r=t.origin.y,i=t.origin.y+t.size.height,o=Math.max(s,i)-Math.min(a,r);return o<=0?0:Math.max(0,Math.min(s,i)-Math.max(a,r))/o}function Re(e,t){var a,s;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const r=(null==(a=e.rectsPdfCoord)?void 0:a.length)?e.rectsPdfCoord:[e.rectPdfCoord],i=(null==(s=t.rectsPdfCoord)?void 0:s.length)?t.rectsPdfCoord:[t.rectPdfCoord],o=e.markerAnchor??Ve(r),n=t.markerAnchor??Ve(i);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const l of r)for(const e of i){if(_e(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 Be(e,t,a,s){const r=a.length>0?a:[];if(0===r.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:Ge(r),rectsPdfCoord:r,markerAnchor:Ve(r)}}const Fe=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.change$=r.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(Ae.id),this.chapterManager=this.registry.getPlugin(Le.id),this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(t){var a;if(this.config=t,null==(a=t.callbacks)?void 0:a.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(Re(s.anchor,e.anchor))return s;const t=e.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:t,label:e.label,anchor:e.anchor,metadata:e.metadata,createdAt:Date.now()};return this.entries.set(t,a),this.notifyAndPersist(),a}removeBookmark(e){var t,a,s;this.entries.delete(e)&&(this.notifyAndPersist(),null==(s=null==(a=null==(t=this.config)?void 0:t.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,e))}async requestRemoveBookmark(t){var a,s;const r=this.entries.get(t);if(!r)return!1;const i=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(i)try{if(!(await i(r)))return!1}catch(o){return this.logger.error(e.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(t),!0}updateBookmark(e,t){const a=this.entries.get(e);a&&(this.entries.set(e,{...a,...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[a,s]of this.entries.entries())s.anchor.chapterId===e&&this.entries.delete(a);for(const a of t)a.anchor.chapterId===e&&this.entries.set(a.id,a);this.notifyAndPersist()}notifyAndPersist(){var t,a;const s=this.list();this.change$.emit(s),(null==(a=null==(t=this.config)?void 0:t.callbacks)?void 0:a.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 a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(t.anchor.chapterId);let s=t.anchor.globalPageIndex;if(void 0===s){const e=this.chapterManager.provides().getVirtualPageMap().toGlobal(t.anchor.chapterId,t.anchor.localPageIndex);if(!e)return;s=e.globalPageIndex}const r=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,a){e.scrollToGlobalPageIndex(t),await function(e,t,a=2500){const s=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const r=setTimeout(()=>{i(),s(null)},a),i=e.onLayoutChange(e=>{const a=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);a&&(clearTimeout(r),i(),s(a))})})}(e,t),e.scrollToGlobalPdfPoint(t,a,{marginTop:80})}(a,s,r)}};Fe.id="paragraph-bookmark";let Ue=Fe;const qe={manifest:Ie,create:e=>new Ue(ye,e),reducer:e=>e,initialState:{}},He={"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 We{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(He);for(const t of this.specs){const a=e[t.toolbarSlot];if(!a)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??[]};a.items=je(a.items,s,t.position)}return e}}function je(e,t,a){return(null==a?void 0:a.after)||(null==a?void 0:a.before)?function(e,t,a){const s=e=>{const r=[];for(const i of e)"group"!==i.type?a.before&&i.id===a.before?r.push(t,i):(r.push(i),a.after&&i.id===a.after&&r.push(t)):r.push({...i,items:s(i.items)});return r};return s(e)}(e,t,a):(s=t,e.map(e=>"group"===e.type?{...e,items:[...e.items,s]}:e));var s}const Ze={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function Ye(e){var t,s,b,P,w,C;const y=e.toolbar??{},I=y.enabledModes??["view","annotate","shapes","insert","form","redact"],M=I.length>0,{schema:S,operationRegistry:x}=function(e={}){var t,a,s,r,i,o;const n=new Set(e.enabledModes??["view","annotate","shapes","insert","form","redact"]),l=new We;(null==(t=e.customOperations)?void 0:t.length)&&l.registerAll(e.customOperations);const h=l.buildToolbars(),d={};for(const u of n){if("view"===u)continue;const e=Ze[u];h[e]&&(d[e]=h[e])}const c=function(e){if(0===e.size)return null;const t=(e,t,a)=>({type:"command-button",id:`${e}-mode`,commandId:a,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}]}}(n);return c&&(d["chapter-editor-main-toolbar"]=c),(null==(a=e.extend)?void 0:a.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==(r=e.extend)?void 0:r.sidebars)??{},modals:(null==(i=e.extend)?void 0:i.modals)??{},selectionMenus:(null==(o=e.extend)?void 0:o.selectionMenus)??{}},operationRegistry:l}}({...y,enabledModes:I}),k={...M?{"mode:view":{id:"mode:view",label:"View",categories:["mode","mode-view"],action:({registry:e,documentId:t})=>{var s,r,i,o;const n=null==(s=e.getPlugin("ui"))?void 0:s.provides(),l=null==(r=e.getPlugin("interaction-manager"))?void 0:r.provides();n&&l&&(null==(i=l.forDocument(t))||i.activateDefaultMode(),n.forDocument(t).closeToolbarSlot("top","secondary"),null==(o=e.getPlugin(a.ANNOTATION_PLUGIN_ID))||o.provides().forDocument(t).setLocked(e.getPluginConfig(a.ANNOTATION_PLUGIN_ID).locked??{type:a.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,r;const i=null==(s=e.getPlugin("ui"))?void 0:s.provides();i&&(i.setActiveToolbar("top","secondary","annotation-toolbar",t),null==(r=e.getPlugin(a.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(t).setLocked({type:a.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,r;const i=null==(s=e.getPlugin("ui"))?void 0:s.provides();i&&(i.setActiveToolbar("top","secondary","shapes-toolbar",t),null==(r=e.getPlugin(a.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(t).setLocked({type:a.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,r;const i=null==(s=e.getPlugin("ui"))?void 0:s.provides();i&&(i.setActiveToolbar("top","secondary","insert-toolbar",t),null==(r=e.getPlugin(a.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(t).setLocked({type:a.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,r;const i=null==(s=e.getPlugin("ui"))?void 0:s.provides();i&&(i.setActiveToolbar("top","secondary","form-toolbar",t),null==(r=e.getPlugin(a.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(t).setLocked({type:a.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,r;const i=null==(s=e.getPlugin("ui"))?void 0:s.provides();i&&(i.setActiveToolbar("top","secondary","redaction-toolbar",t),null==(r=e.getPlugin(a.ANNOTATION_PLUGIN_ID))||r.provides().forDocument(t).setLocked({type:a.LockModeType.Include,categories:["form"]}))},active:({state:e,documentId:t})=>v.isToolbarOpen(e.plugins,t,"top","secondary","redaction-toolbar")}}:{},...M?Je(x.list()):{},...e.commands??{}},L=[r.createPluginRegistration(i.DocumentManagerPluginPackage,{initialDocuments:[]}),r.createPluginRegistration(H,{manifest:e.manifest,overlapStrategy:e.overlapStrategy,passwordProvider:e.passwordProvider,chapterPdfLoader:e.chapterPdfLoader,prefetchChapters:e.prefetchChapters,unloadTimeoutMs:e.unloadTimeoutMs}),r.createPluginRegistration(ae,{placeholderPageHeight:e.placeholderPageHeight,placeholderPageWidth:e.placeholderPageWidth}),r.createPluginRegistration(o.InteractionManagerPluginPackage),r.createPluginRegistration(n.RenderPluginPackage),r.createPluginRegistration(l.RotatePluginPackage),r.createPluginRegistration(h.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),r.createPluginRegistration(d.HistoryPluginPackage),r.createPluginRegistration(a.AnnotationPluginPackage),r.createPluginRegistration(c.RedactionPluginPackage),r.createPluginRegistration(u.FormPluginPackage),r.createPluginRegistration(p.StampPluginPackage,!1===e.loadDefaultStampLibrary?{manifests:[]}:void 0),r.createPluginRegistration(g.SignaturePluginPackage),...Object.keys(k).length>0?[r.createPluginRegistration(f.CommandsPluginPackage,{commands:k})]:[],...M?[r.createPluginRegistration(m.I18nPluginPackage),r.createPluginRegistration(v.UIPluginPackage,{schema:S})]:[]];return e.notes&&L.push(r.createPluginRegistration(Ce,{callbacks:e.notes.callbacks,ui:null==(s=null==(t=e.features)?void 0:t.notes)?void 0:s.marker})),e.bookmarks&&L.push(r.createPluginRegistration(qe,{callbacks:e.bookmarks.callbacks,ui:null==(P=null==(b=e.features)?void 0:b.bookmarks)?void 0:P.marker,hover:null==(C=null==(w=e.features)?void 0:w.bookmarks)?void 0:C.hover})),{plugins:L,uiSchema:S,operationRegistry:x}}function Je(e){const t={};for(const a of e)a.handler&&(t[a.commandId]={id:a.commandId,labelKey:a.i18nKey,label:a.label,icon:a.icon,categories:a.categories,action:({documentId:e})=>{var t;null==(t=a.handler)||t.call(a,{documentId:e,chapterId:e})}});return t}const Ke=A();function Xe(e){return Ye({...e,toolbar:e.toolbar??{enabledModes:[]},features:A(e.features)})}const Qe={overlapStrategy:{kind:"first-wins"},passwordProvider:new G(async()=>null),prefetchChapters:1,loadDefaultStampLibrary:!1,unloadTimeoutMs:12e4,toolbar:{enabledModes:[]}};function et(e){return"callbacks"in e.notes?{manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,notes:e.notes.callbacks,bookmarks:e.bookmarks.callbacks}:e}function tt(e){return{...Qe,manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,overlapStrategy:e.overlapStrategy??Qe.overlapStrategy,notes:{callbacks:e.notes},bookmarks:{callbacks:e.bookmarks},features:A(e.features)}}function at(e){const t=tt(et(e)),{plugins:a}=Xe(t);return{plugins:a,features:t.features,editorOptions:t}}function st(e,t=.5,a=3){return Math.min(a,Math.max(t,e))}function rt(e,t){var a;if(t<=0)return 1;let s=0;for(const r of e.pages){const e=(null==(a=null==r?void 0:r.size)?void 0:a.width)??0;e>s&&(s=e)}return s<=0?1:t/s}function it(e,t){return e<=0?t??0:null==t||t<=0?e:Math.min(t,e)}function ot(e,t,a,s){const r=it(t,a);if(r<=0)return s;const i=rt(e,r);return Math.min(s,i)}function nt(e){return e instanceof HTMLElement?e.clientWidth:0}function lt(e,t,a){return Math.min(a,Math.max(t,e))}const ht={chapters:[]};function dt(a){const s=e.ref(null),{provides:o}=t.useCapability(q.id),n=e.computed(()=>{var e;return(null==(e=o.value)?void 0:e.getManifest())??ht}),l=e.computed(()=>{var e;return null==(e=a.value)?void 0:e.zoom}),{scale:h,setScale:d,zoomEnabled:c,minZoom:u,maxZoom:p}=function(a,s,o){const n=e.isRef(a)?a:e.computed(()=>a),{registry:l}=t.useRegistry(),{provides:h}=t.useCapability(i.DocumentManagerPlugin.id),{provides:d}=t.useCapability(q.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,a,s,r){if(!e||a<=0)return r;let i=r;for(const o of t.chapters){const t=e.getDocument(o.chapterId);t&&(i=Math.min(i,ot(t,a,s,r)))}return i}(h.value,n.value,p.value,g(),(null==(e=s.value)?void 0:e.max)??3)}),b=e.computed(()=>{var e;return Math.min((null==(e=s.value)?void 0:e.min)??.5,v.value)});let P;function w(e){const t=v.value,a=b.value,s=st(e,a,t);u.value=s,c.value=s,function(e,t,a,s=.5,i=3){const o=null==e?void 0:e.getStore();if(!o)return;const n=st(a,s,i);o.dispatchToCore(r.setDefaultScale(n));for(const l of t.chapters)o.getState().core.documents[l.chapterId]&&o.dispatchToCore(r.setScale(n,l.chapterId))}(l.value,n.value,s,a,t)}function C(e){if(!h.value)return;const t=h.value.getDocument(e);if(!t)return;const a=it(p.value,g());a<=0||w(rt(t,a))}function y(e){f()?C(e):w(m())}return e.watch(()=>null==o?void 0:o.value,e=>{null==P||P(),P=e?function(e,t){if(!e||"undefined"==typeof ResizeObserver)return()=>{};let a=null;const s=new ResizeObserver(()=>{t(nt(a))}),r=()=>{const r=e.querySelector("[data-chapter-scroll-viewport]");r!==a?(a&&s.unobserve(a),a=r,a?(s.observe(a),t(nt(a))):t(0)):t(nt(a))};r();const i=new MutationObserver(r);i.observe(e,{childList:!0,subtree:!0});const o=requestAnimationFrame(r);return()=>{cancelAnimationFrame(o),i.disconnect(),a&&s.unobserve(a),s.disconnect()}}(e,e=>{p.value=e}):void 0},{immediate:!0}),e.onBeforeUnmount(()=>null==P?void 0:P()),e.watch([l,()=>m(),()=>f()],()=>{l.value&&(f()||w(m()))},{immediate:!0}),e.watch(v,e=>{u.value>e&&w(e)}),e.watch([d,n,()=>f(),()=>m()],()=>{const e=d.value;if(e){for(const t of n.value.chapters)"loaded"===e.getChapterStatus(t.chapterId)&&y(t.chapterId);return e.onChapterStatusChange(e=>{"loaded"===e.status&&y(e.chapterId)})}},{immediate:!0}),e.watch([p,()=>f(),d,n],()=>{if(f()&&!(p.value<=0)&&d.value)for(const e of n.value.chapters)if("loaded"===d.value.getChapterStatus(e.chapterId)){C(e.chapterId);break}}),{scale:c,setScale:w,zoomEnabled:()=>{var e;return!1!==(null==(e=s.value)?void 0:e.enabled)},minZoom:b,maxZoom:v}}(n,l,s);return function(t,a){let s=null;e.watch([t,a],()=>{null==s||s();const e=a.value;s=function(e,t){if(!e||!1===t.enabled)return()=>{};let a=null,s=null,r=0;const i=()=>{const s=e.querySelector("[data-chapter-scroll-viewport]");return!!s&&(null==a||a(),a=function({container:e,getScale:t,setScale:a,minZoom:s=.5,maxZoom:r=3}){let i=0,o=1,n=null,l=1,h=1;const d=e=>{(e.ctrlKey||e.metaKey)&&(e.preventDefault(),null===n?(h=t(),l=1):clearTimeout(n),l*=1-.01*e.deltaY,l=lt(l,.1,10),a(lt(h*l,s,r)),n=setTimeout(()=>{n=null},120))},c=new Map,u=e=>{if(c.set(e.pointerId,{x:e.clientX,y:e.clientY}),2===c.size){const[e,a]=[...c.values()];i=Math.hypot(a.x-e.x,a.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&&i>0)){e.preventDefault();const[t,n]=[...c.values()],l=Math.hypot(n.x-t.x,n.y-t.y);a(lt(o*(l/i),s,r))}},g=e=>{c.delete(e.pointerId),c.size<2&&(i=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),n&&clearTimeout(n)}}({container:s,getScale:t.getScale,setScale:t.setScale,minZoom:t.minZoom,maxZoom:t.maxZoom}),!0)};return i()||(s=new MutationObserver(()=>{i()&&(null==s||s.disconnect(),s=null)}),s.observe(e,{childList:!0,subtree:!0}),r=requestAnimationFrame(()=>i())),()=>{r&&cancelAnimationFrame(r),null==s||s.disconnect(),null==a||a()}}(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}}const ct={kind:"first-wins"};function ut(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}class pt{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 a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}}const gt=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=ct,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ct,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,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),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 a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=ct){const a=function(e,t=ct){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,ut(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new pt(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};gt.id="chapter-manager";let ft=gt;function mt(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 a=0;a<e.items.length;a++){const s=e.items[a],r=t.items[a];if(s.globalPageIndex!==r.globalPageIndex||s.isPlaceholder!==r.isPlaceholder||s.chapterId!==r.chapterId||s.localPageIndex!==r.localPageIndex||s.offsetTop!==r.offsetTop||s.width!==r.width||s.height!==r.height)return!1}return!0}const vt=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,mt),this.visibleChange$=r.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(ft.id),this.documentManager=this.registry.getPlugin(i.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){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}isChapterPagePlaceholder(e){const t=this.chapterManager.provides().getChapterStatus(e);return"error"===t||"password-required"===t||"loaded"!==t}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;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),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,a)=>this.scrollToGlobalPdfPoint(e,t,a),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,a=0;for(let s=0;s<e;s++){const{width:e,height:r}=this.getPageSize(s);this.offsets[s]=t,t+=r+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===s.width&&r.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),r=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===r.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const i=this.getChapterDocumentScale(e),o=[];for(const n of r){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&o.push({localPageIndex:n.localPageIndex,width:e.size.width*i,height:e.size.height*i})}0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.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 a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),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,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let r=s;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=a)break;r++}const i=[];let o=s,n=-1;for(let l=s;l<r;l++){i.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,r=Math.max(0,Math.min(s,a)-Math.max(e,t));r>n&&(n=r,o=l)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(i),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const r=t+a>>1;this.offsets[r]<=e?(s=r,t=r+1):a=r-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let i=t;i<=s;i++){const e=this.virtualPageMap.atIndex(i);if(!e)continue;const t=this.getPageSize(i),a=this.isChapterPagePlaceholder(e.chapterId);r.push({globalPageIndex:i,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[i],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==a?void 0:a.marginTop)??80,i=this.virtualPageMap.atIndex(e);if(!i)return void this.scrollToIndex(e,a);const o=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(i.chapterId))?void 0:s.pages[i.localPageIndex];if(!o||!n)return void this.scrollToIndex(e,a);const l=o.height/n.size.height,h=(this.offsets[e]??0)+t*l-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}};vt.id="chapter-scroll";let bt=vt;const Pt=["data-global-page-index","data-chapter-id","data-local-page-index"],wt=(e=>{const t=e.__vccOpts||e;for(const[a,s]of[["__scopeId","data-v-e9ab4da3"]])t[a]=s;return t})(e.defineComponent({__name:"ChapterScroller",props:{class:{},style:{}},setup(a){const{provides:s}=t.useCapability(bt.id),r=e.ref(null),i=e.ref(null);let o=null;const n=()=>{null==o||o(),o=null,s.value&&(s.value.registerViewport(r.value),o=s.value.onLayoutChange(e=>{i.value=e}))};return e.onMounted(n),e.onBeforeUnmount(()=>{var e;null==o||o(),null==(e=s.value)||e.registerViewport(null)}),e.watch(s,n),(t,a)=>{var s,o,n;return e.openBlock(),e.createElementBlock("div",{ref_key:"containerRef",ref:r,"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=i.value)?void 0:s.totalWidth)??0}px`,height:`${(null==(o=i.value)?void 0:o.totalHeight)??0}px`,margin:"0 auto"})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList((null==(n=i.value)?void 0:n.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},()=>[a[0]||(a[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,Pt))),128))],4)],6)}}})),Ct=e.defineComponent({__name:"ChapterRenderLayer",props:{chapterId:{},localPageIndex:{},scale:{},dpr:{},class:{}},setup:t=>(a,s)=>(e.openBlock(),e.createBlock(e.unref(I.RenderLayer),{"document-id":t.chapterId,"page-index":t.localPageIndex,scale:t.scale,dpr:t.dpr,class:e.normalizeClass(t.class),style:{pointerEvents:"none"}},null,8,["document-id","page-index","scale","dpr","class"]))}),yt={kind:"first-wins"};function It(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let Mt=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 a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const St=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=yt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??yt,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,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),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 a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=yt){const a=function(e,t=yt){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,It(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new Mt(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};St.id="chapter-manager";let xt=St;const kt={kind:"first-wins"};function Lt(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}class $t{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 a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}}const Tt=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=kt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.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=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,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),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 a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=kt){const a=function(e,t=kt){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,Lt(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new $t(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};Tt.id="chapter-manager";let Dt=Tt;function zt(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 a=0;a<e.items.length;a++){const s=e.items[a],r=t.items[a];if(s.globalPageIndex!==r.globalPageIndex||s.isPlaceholder!==r.isPlaceholder||s.chapterId!==r.chapterId||s.localPageIndex!==r.localPageIndex||s.offsetTop!==r.offsetTop||s.width!==r.width||s.height!==r.height)return!1}return!0}const Nt=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,zt),this.visibleChange$=r.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Dt.id),this.documentManager=this.registry.getPlugin(i.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){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}isChapterPagePlaceholder(e){const t=this.chapterManager.provides().getChapterStatus(e);return"error"===t||"password-required"===t||"loaded"!==t}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;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),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,a)=>this.scrollToGlobalPdfPoint(e,t,a),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,a=0;for(let s=0;s<e;s++){const{width:e,height:r}=this.getPageSize(s);this.offsets[s]=t,t+=r+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===s.width&&r.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),r=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===r.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const i=this.getChapterDocumentScale(e),o=[];for(const n of r){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&o.push({localPageIndex:n.localPageIndex,width:e.size.width*i,height:e.size.height*i})}0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.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 a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),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,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let r=s;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=a)break;r++}const i=[];let o=s,n=-1;for(let l=s;l<r;l++){i.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,r=Math.max(0,Math.min(s,a)-Math.max(e,t));r>n&&(n=r,o=l)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(i),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const r=t+a>>1;this.offsets[r]<=e?(s=r,t=r+1):a=r-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let i=t;i<=s;i++){const e=this.virtualPageMap.atIndex(i);if(!e)continue;const t=this.getPageSize(i),a=this.isChapterPagePlaceholder(e.chapterId);r.push({globalPageIndex:i,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[i],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==a?void 0:a.marginTop)??80,i=this.virtualPageMap.atIndex(e);if(!i)return void this.scrollToIndex(e,a);const o=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(i.chapterId))?void 0:s.pages[i.localPageIndex];if(!o||!n)return void this.scrollToIndex(e,a);const l=o.height/n.size.height,h=(this.offsets[e]??0)+t*l-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}};Nt.id="chapter-scroll";let Ot=Nt;const Et=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=r.createBehaviorEmitter([]),this.noteActivated$=r.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(Ot.id),this.chapterManager=this.registry.getPlugin(xt.id),this.documentManager=this.registry.getPlugin(i.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(a){this.logger.error(e.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(a=>a.chapterId===e&&a.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,a;const s=this.notes.get(e);s&&(null==(a=(t=this.config.callbacks).onActivateNote)||a.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[a,s]of this.notes.entries())s.chapterId===e&&this.notes.delete(a);for(const a of t)a.chapterId===e&&this.notes.set(a.noteId,a);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:Gt(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:t,complete:async e=>{const a={...t,noteId:e};this.registerNote(a)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const a=this.buildDraft(t),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let r=null;try{r=await s(a)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!r)return null;const i={...a,noteId:r.noteId};return this.registerNote(i),i}async deleteNote(t){var a,s;if(this.notes.has(t)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,t))}catch(r){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",r)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,a){var s,r;const i=this.notes.get(t);if(!i)return;const o={...i,content:a};try{await(null==(r=(s=this.config.callbacks).onUpdateNote)?void 0:r.call(s,o))}catch(n){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",n)}this.notes.set(t,o),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const a=this.notes.get(e);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(t=this.documentManager.provides().getDocument(a.chapterId))?void 0:t.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),a=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{r(),a(null)},2500),r=t.onLayoutChange(t=>{const i=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);i&&(clearTimeout(s),r(),a(i))})})}};Et.id="note";let At=Et;function Gt(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Vt(e){const{markerPdf:t,lineRects:a,sx:s,sy:r,cssPageWidth:i,iconSize:o,gapPx:n=6}=e,l=(null==a?void 0:a.length)?a[a.length-1]:void 0;let h,d;l?(h=(l.origin.x+l.size.width)*s+n,d=l.origin.y*r+(l.size.height*r-o)/2):(h=t.x*s-o/2,d=t.y*r-o-n);const c=Math.max(0,i-o-2);return h>c&&(h=c),d<0&&(d=0),{left:h,top:d}}const _t={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none",zIndex:25}},Rt=["onMouseenter"],Bt=["data-note-marker-zone","onMouseenter","onMouseleave"],Ft=["onClick"],Ut=["onClick"],qt=["onClick"],Ht=e.defineComponent({__name:"NoteMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(a){const s=a,{provides:r}=t.useCapability(At.id),i=e.ref([]),o=e.ref(null),n=e.ref(null);e.watch(r,e=>{if(e)return e.onNotesChange(e=>{i.value=e.filter(e=>e.chapterId===s.chapterId&&e.localPageIndex===s.localPageIndex)})},{immediate:!0});let l=null;e.watch(n,e=>{l&&(document.removeEventListener("mousedown",l),l=null),e&&(l=t=>{var a;const s=t.target;(null==(a=s.closest)?void 0:a.call(s,`[data-note-marker-zone="${e}"]`))||(n.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,a=s.cssPageHeight/s.pdfPageHeight,r=h.value,{left:i,top:o}=Vt({markerPdf:e.endAnchor,lineRects:e.rectsPdfCoord,sx:t,sy:a,cssPageWidth:s.cssPageWidth,iconSize:r}),l=function(e,t,a){let s=1/0,r=1/0,i=-1/0,o=-1/0;for(const n of e)s=Math.min(s,n.origin.x*t),r=Math.min(r,n.origin.y*a),i=Math.max(i,(n.origin.x+n.size.width)*t),o=Math.max(o,(n.origin.y+n.size.height)*a);return{left:s,top:r,width:i-s,height:o-r}}(e.rectsPdfCoord,t,a),d=n.value===e.noteId?72:0,c=Math.max(0,Math.min(l.left,i)-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,i+r)+8)-c,zoneH:Math.max(l.top+l.height,o+r+6+d)+8-u,iconLeft:i,iconTop:o,sx:t,sy:a}}return(t,s)=>e.unref(r)&&i.value.length&&a.pdfPageWidth&&a.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",_t,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i.value,t=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:t.noteId},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.rectsPdfCoord,(a,s)=>(e.openBlock(),e.createElementBlock("div",{key:`${t.noteId}-bg-${s}`,style:e.normalizeStyle({position:"absolute",left:a.origin.x*c(t).sx+"px",top:a.origin.y*c(t).sy+"px",width:a.size.width*c(t).sx+"px",height:a.size.height*c(t).sy+"px",background:d.value,borderRadius:"2px",pointerEvents:"auto"}),onMouseenter:e=>o.value=t.noteId},null,44,Rt))),128)),o.value===t.noteId||n.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=>n.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=>n.value=n.value===t.noteId?null:t.noteId,["stop"])}," 💬 ",44,Ft),n.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 a=t,void(null==(s=r.value)||s.requestEditNote(a.noteId,a));var a,s}}," 编辑 ",8,Ut),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 a,s;return s=t.noteId,null==(a=r.value)||a.requestDeleteNote(s),void(n.value=null)}}," 删除 ",8,qt)],36)):e.createCommentVNode("",!0)],44,Bt)):e.createCommentVNode("",!0)],64))),128))])):e.createCommentVNode("",!0)}}),Wt={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none"}},jt=["title","onClick"],Zt=["onClick"],Yt=e.defineComponent({__name:"BookmarkMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(a){const s=a,{provides:r}=t.useCapability(Ue.id),i=e.ref([]),o=e.ref(null),n=e.ref(null);function l(){const e=r.value;e&&(i.value=e.listBookmarks().filter(e=>e.anchor.chapterId===s.chapterId&&e.anchor.localPageIndex===s.localPageIndex))}e.watch(r,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=n.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:a}=function(e){var t;const a=s.cssPageWidth/s.pdfPageWidth,r=s.cssPageHeight/s.pdfPageHeight,i=(null==(t=e.anchor.rectsPdfCoord)?void 0:t.length)?e.anchor.rectsPdfCoord:[e.anchor.rectPdfCoord];return Vt({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:i,sx:a,sy:r,cssPageWidth:s.cssPageWidth,iconSize:d.value})}(e);return{position:"absolute",left:`${Math.max(0,t-6)}px`,top:`${Math.max(0,a-6)}px`,width:`${d.value+12}px`,height:`${d.value+12}px`,pointerEvents:"auto",zIndex:20}}return(t,s)=>e.unref(r)&&i.value.length&&a.pdfPageWidth&&a.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",Wt,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i.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,jt),o.value===t.id?(e.openBlock(),e.createElementBlock("div",{key:0,ref_for:!0,ref_key:"deleteMenuRef",ref:n,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=r.value;t&&await t.requestRemoveBookmark(e)&&(o.value=null)}(t.id)}," 删除书签 ",8,Zt)],512)):e.createCommentVNode("",!0)],36))),128))])):e.createCommentVNode("",!0)}});function Jt(e){return e.chapterId}function Kt(e,t){e.wait(t,()=>{})}const Xt={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)"},Qt={padding:"6px 12px",fontSize:"12px",fontWeight:"500",border:"none",borderRadius:"6px",background:"transparent",color:"#dc2626",cursor:"pointer"};const ea=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(a){const s=a,r=e.computed(()=>Jt(s.item));!function(a){const{provides:s}=t.useCapability(i.DocumentManagerPlugin.id);e.watch([s,a],([e,t])=>{e&&t&&e.isDocumentOpen(t)&&e.setActiveDocument(t)},{immediate:!0})}(r);const{provides:o}=t.useCapability(i.DocumentManagerPlugin.id),{provides:n}=t.useCapability(h.SelectionPlugin.id),l=e.computed(()=>{var e,t;return null==(t=null==(e=o.value)?void 0:e.getDocument(r.value))?void 0:t.pages[s.item.localPageIndex]});function d(t,a){var r,i,o,l;const h=s.createNote.value;if(h&&!1!==(null==(i=null==(r=s.features)?void 0:r.notes)?void 0:i.enabled)&&!1!==(null==(l=null==(o=s.features)?void 0:o.selectionToolbar)?void 0:l.enabled))return s=>{var r;const i={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==(r=s.placement)?void 0:r.suggestTop)?-40:s.rect.size.height+8};return e.h("div",s.menuWrapperProps,[e.h("div",{style:i},e.h("button",{type:"button",style:{padding:"6px 10px",fontSize:"12px",border:"1px solid #e2e8f0",borderRadius:"6px",background:"#fff",cursor:"pointer"},onClick:()=>{if(!n.value)return;const e=n.value.getHighlightRectsForPage(t.localPageIndex,a);Kt(n.value.getSelectedText(a),a=>{var s,r,i;h((s=t,r=e,i=a.join("\n"),{chapterId:s.chapterId,localPageIndex:s.localPageIndex,globalPageIndex:s.globalPageIndex,globalPageNumber:s.globalPageNumber,rectsPdfCoord:r,selectedText:i}))})}},"添加附注"))])}}const c=e.computed(()=>{const e=s.buildSelectionMenu,t={item:s.item,defaultMenu:d(s.item,r.value),createNote:s.createNote.value};if(e){const a=e(t);if(a)return a}return t.defaultMenu}),u=function(t,a){var s,r;const{provides:i}=C.useAnnotationCapability(),o=null==(s=null==a?void 0:a.markup)?void 0:s.annotationMenu,n=!1!==(null==(r=null==a?void 0:a.markup)?void 0:r.enabled),l=!1!==(null==o?void 0:o.enabled);return e.computed(()=>{const a="string"==typeof t?t:t.value;if(n&&l&&i.value)return t=>{const{context:s,rect:r,placement:n,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,!O.has(d))return e.h("span",l);var d;const c=i.value.forDocument(a),{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==n?void 0:n.suggestTop)?void 0:`${r.size.height+8}px`,bottom:(null==n?void 0:n.suggestTop)?`${r.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:Qt,onClick:g},"删除");return e.h("div",l,[e.h("div",{style:f},[e.h("div",{style:Xt,role:"toolbar","aria-label":"划线标注"},[m])])])}})}(r,s.features),p=e.computed(()=>function(e,t){if(e||t)return a=>{if(e){const t=e(a);if(null!=t)return t}return(null==t?void 0:t(a))??null}}(s.annotationSelectionMenu,u.value)),g=e.computed(()=>{var e;return null==(e=s.renderPageOverlay)?void 0:e.call(s,s.item)});return(t,s)=>a.item.isPlaceholder?e.createCommentVNode("",!0):(e.openBlock(),e.createBlock(e.unref(b.GlobalPointerProvider),{key:0,"document-id":r.value},{default:e.withCtx(()=>[e.createVNode(e.unref(P.Rotate),{"document-id":r.value,"page-index":a.item.localPageIndex,style:{backgroundColor:"#fff"}},{default:e.withCtx(()=>[e.createVNode(e.unref(b.PagePointerProvider),{"document-id":r.value,"page-index":a.item.localPageIndex,style:e.normalizeStyle(e.unref(x)),onPointerdown:e.unref(k)},{default:e.withCtx(()=>[e.createVNode(e.unref(Ct),{"chapter-id":r.value,"local-page-index":a.item.localPageIndex},null,8,["chapter-id","local-page-index"]),e.createVNode(e.unref(w.SelectionLayer),{"document-id":r.value,"page-index":a.item.localPageIndex,"selection-menu":c.value},null,8,["document-id","page-index","selection-menu"]),a.showRedactionLayer?(e.openBlock(),e.createBlock(e.unref(y.RedactionLayer),{key:0,"document-id":r.value,"page-index":a.item.localPageIndex,"selection-menu":a.redactionSelectionMenu},null,8,["document-id","page-index","selection-menu"])):e.createCommentVNode("",!0),e.createVNode(e.unref(C.AnnotationLayer),{"document-id":r.value,"page-index":a.item.localPageIndex,"selection-menu":p.value},null,8,["document-id","page-index","selection-menu"]),a.showBookmarkMarkers&&l.value?(e.openBlock(),e.createBlock(Yt,{key:1,"chapter-id":r.value,"local-page-index":a.item.localPageIndex,"pdf-page-width":l.value.size.width,"pdf-page-height":l.value.size.height,"css-page-width":a.item.width,"css-page-height":a.item.height,ui:a.bookmarkMarkerUi},null,8,["chapter-id","local-page-index","pdf-page-width","pdf-page-height","css-page-width","css-page-height","ui"])):e.createCommentVNode("",!0),g.value?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(g.value),{key:2})):e.createCommentVNode("",!0),a.showNoteMarkers&&l.value?(e.openBlock(),e.createBlock(Ht,{key:3,"chapter-id":r.value,"local-page-index":a.item.localPageIndex,"pdf-page-width":l.value.size.width,"pdf-page-height":l.value.size.height,"css-page-width":a.item.width,"css-page-height":a.item.height,ui:a.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"]))}}),ta=e.defineComponent({__name:"HoverBookmarkLayer",props:{item:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},hoverUi:{}},setup(a){const s=a,r=e.computed(()=>Jt(s.item)),{provides:i}=t.useCapability(h.SelectionPlugin.id),{provides:o}=t.useCapability(Ue.id),n=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=i.value;if(!e)return;const t=e.forDocument(r.value).getState().geometry[s.item.localPageIndex];t&&(l.value=t)}e.watch([i,r,()=>s.item.localPageIndex],([e])=>{if(null==g||g(),g=null,cancelAnimationFrame(f),l.value=null,!e)return;const t=e.forDocument(r.value);g=t.onSelectionChange(m);let a=!1;const i=()=>{if(!a){try{if(m(),t.getState().geometry[s.item.localPageIndex])return}catch{}f=requestAnimationFrame(i)}};return i(),()=>{a=!0,cancelAnimationFrame(f),null==g||g(),g=null}},{immediate:!0});let v=null;e.watch([l,()=>s.pdfPageWidth,c,i],()=>{v&&(document.removeEventListener("mousemove",v),v=null),l.value&&s.pdfPageWidth&&(v=e=>{if(c.value)return;const t=i.value;if(t)try{if(t.forDocument(r.value).getState().selecting)return void(d.value=null)}catch{}const a=n.value;if(!a)return;const o=a.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 a=h.glyphAt(e,t);if(a<0)return null;const s=h.expandToLineBoundary(e,a);if(!s)return null;const r=h.rectsWithinSlice(e,s.from,s.to);return 0===r.length?null:{lineRects:r,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 b=e.computed(()=>{const e=p.value;return(null==e?void 0:e.length)?Be(s.item.chapterId,s.item.localPageIndex,e,{globalPageIndex:s.item.globalPageIndex,globalPageNumber:s.item.globalPageNumber}):null}),P=e.computed(()=>{const e=b.value,t=o.value;return!(!e||!t)&&t.listBookmarks().some(t=>Re(t.anchor,e))});function w(){const e=o.value,t=b.value;e&&t&&!P.value&&(e.addBookmark({label:`书签 ${(new Date).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"})}`,anchor:t}),d.value=null,c.value=null)}const C=e.computed(()=>{const e=p.value,t=null==e?void 0:e[e.length-1];if(!t||!s.pdfPageWidth)return null;const a=s.cssPageWidth/s.pdfPageWidth,r=s.cssPageHeight/s.pdfPageHeight,i=u.value;return{iconLeft:Math.min((t.origin.x+t.size.width)*a+6,Math.max(0,s.cssPageWidth-i-2)),iconTop:t.origin.y*r+(t.size.height*r-i)/2,zoneLeft:Math.max(0,(t.origin.x+t.size.width)*a-4),zoneTop:Math.max(0,t.origin.y*r-4),size:i}});return(t,s)=>{var r;return e.unref(o)&&a.pdfPageWidth&&a.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",{key:0,ref_key:"rootRef",ref:n,style:{position:"absolute",inset:"0",zIndex:14,pointerEvents:"none"}},[C.value&&p.value&&!P.value?(e.openBlock(),e.createElementBlock("div",{key:0,style:e.normalizeStyle({position:"absolute",left:`${C.value.zoneLeft}px`,top:`${C.value.zoneTop}px`,width:`${C.value.size+20}px`,height:`${((null==(r=p.value[p.value.length-1])?void 0:r.size.height)??0)*(a.cssPageHeight/a.pdfPageHeight)+C.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:C.value.iconLeft-C.value.zoneLeft+"px",top:C.value.iconTop-C.value.zoneTop+"px",width:`${C.value.size}px`,height:`${C.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(w,["stop"])}," 🔖 ",4)],36)):e.createCommentVNode("",!0)],512)):e.createCommentVNode("",!0)}}}),aa={key:0,width:"20",height:"20",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},sa={key:1,width:"24",height:"24",viewBox:"0 0 28 28",fill:"none","aria-hidden":""},ra={key:0,x:"5",y:"4",width:"18",height:"20",rx:"3",fill:"#fde047"},ia={key:1,d:"M6 22h16",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},oa={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"},na={key:3,d:"M5 14h18",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},la={key:2,width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},ha=e.defineComponent({__name:"SelectionToolbarIcons",props:{kind:{}},setup:t=>(a,s)=>"copy"===t.kind?(e.openBlock(),e.createElementBlock("svg",aa,[...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",sa,["highlight"===t.kind?(e.openBlock(),e.createElementBlock("rect",ra)):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",ia)):"squiggly"===t.kind?(e.openBlock(),e.createElementBlock("path",oa)):"strikeout"===t.kind?(e.openBlock(),e.createElementBlock("path",na)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("svg",la,[...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)])]))}),da=["title","aria-label","onMouseenter","onClick"],ca=["title","onMouseenter","onClick"],ua={style:{"font-size":"11px","font-weight":"600"}},pa=e.defineComponent({__name:"SelectionToolbarCard",props:{placementAbove:{type:Boolean},anchorHeight:{},hiddenBuiltinActions:{},extraActions:{},renderCopyIcon:{type:Function}},emits:["action"],setup(t,{emit:a}){const s=t,r=a,i=[{id:"highlight",label:"高亮背景"},{id:"underline",label:"下划线"},{id:"squiggly",label:"波浪线"},{id:"strikeout",label:"删除线"}],o=e.computed(()=>new Set(s.hiddenBuiltinActions??[])),n=e.computed(()=>!o.value.has("copy")),l=e.computed(()=>i.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(a,s)=>(e.openBlock(),e.createElementBlock("div",{role:"toolbar","aria-label":"选区工具",style:e.normalizeStyle(p.value)},[n.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=>r("action","copy"))},[t.renderCopyIcon?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(t.renderCopyIcon),{key:0})):(e.openBlock(),e.createBlock(ha,{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=>r("action",t.id)},[e.createVNode(ha,{kind:t.id},null,8,["kind"])],44,da))),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=>r("action",t.id)},[e.createElementVNode("span",ua,e.toDisplayString(t.label.slice(0,2)),1)],44,ca))),128)),h.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[c.value||n.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=>r("action","note"))},[e.createVNode(ha,{kind:"note"})],36)],64)):e.createCommentVNode("",!0)],4))}}),ga={highlight:"highlight",underline:"underline",squiggly:"squiggly",strikeout:"strikeout"};const fa=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 r=s,o=e.computed(()=>r.features),{hostRef:n}=dt(o),l=e.computed(()=>{var e,t;return{background:(null==(t=null==(e=r.features)?void 0:e.scrollViewport)?void 0:t.background)??L}}),d=function(){const{registry:a}=t.useRegistry();return e.computed(()=>{var e,t,s;const r=null==(s=null==(t=null==(e=a.value)?void 0:e.getPlugin(Pe.id))?void 0:t.provides)?void 0:s.call(t);return r?e=>r.createNoteFromSelection(e):null})}(),c=function(){const{registry:a}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=a.value)?void 0:e.getPlugin(Pe.id))})}(),u=function(){const{registry:a}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=a.value)?void 0:e.getPlugin(Ue.id))})}(),p=e.computed(()=>{var e,t;return r.showNoteMarkers&&c.value&&!1!==(null==(t=null==(e=r.features)?void 0:e.notes)?void 0:t.enabled)}),g=e.computed(()=>{var e,t;return r.showBookmarkMarkers&&u.value&&!1!==(null==(t=null==(e=r.features)?void 0:e.bookmarks)?void 0:t.enabled)}),f=e.computed(()=>{var e,t;return u.value&&!1!==(null==(t=null==(e=r.features)?void 0:e.bookmarks)?void 0:t.enabled)}),m=function(s,r){const i=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)}),n=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=i.value)?void 0:e.hiddenBuiltinActions)?void 0:t.includes("copy"))}),{provides:d}=t.useCapability(h.SelectionPlugin.id),{provides:c}=t.useCapability(a.AnnotationPlugin.id),{provides:u}=t.useCapability(Pe.id);return e.computed(()=>{var t,a,h;if(!1!==(null==(t=i.value)?void 0:t.enabled)&&(o.value||n.value||l.value||(null==(h=null==(a=i.value)?void 0:a.extraActions)?void 0:h.length)))return t=>{const a=Jt(t.item);return h=>{var p,g,f,m;return e.h("div",h.menuWrapperProps,e.h(pa,{placementAbove:!!(null==(p=h.placement)?void 0:p.suggestTop),anchorHeight:h.rect.size.height,hiddenBuiltinActions:null==(g=i.value)?void 0:g.hiddenBuiltinActions,extraActions:null==(f=i.value)?void 0:f.extraActions,renderCopyIcon:null==(m=i.value)?void 0:m.renderCopyIcon,onAction:e=>{var i,h,p;if("copy"!==e)if("highlight"!==e&&"underline"!==e&&"squiggly"!==e&&"strikeout"!==e){if("note"===e){if(!d.value||!u.value||!n.value)return;const e=d.value.getHighlightRectsForPage(t.item.localPageIndex,a);return void Kt(d.value.getSelectedText(a),a=>{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:a.join("\n")})})}null==(i=null==r?void 0:r.onExtraAction)||i.call(r,e,t)}else{if(!d.value||!c.value||!o.value)return;N(a,ga[e],c.value,d.value,null==(p=null==(h=s())?void 0:h.markup)?void 0:p.styles)}else{if(!d.value||!l.value)return;Kt(d.value.getSelectedText(a),e=>{!async function(e){var t;const a=e.trim();if(!a)return!1;try{if("undefined"!=typeof navigator&&(null==(t=navigator.clipboard)?void 0:t.writeText))return await navigator.clipboard.writeText(a),!0}catch{}if("undefined"==typeof document)return!1;try{const e=document.createElement("textarea");e.value=a,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"))})}}}))}}})}(()=>r.features,{onExtraAction:r.onExtraSelectionAction}),v=e.computed(()=>{if(r.buildSelectionMenu||m.value)return e=>{const t=m.value?m.value(e):e.defaultMenu;return r.buildSelectionMenu?r.buildSelectionMenu({...e,defaultMenu:t}):t}}),{provides:b}=t.useCapability(i.DocumentManagerPlugin.id);function P(t){var a;const s=[];if(f.value){const a=function(t){var a,s,i,o;const n=Jt(t),l=null==(s=null==(a=b.value)?void 0:a.getDocument(n))?void 0:s.pages[t.localPageIndex];return t.isPlaceholder||!l?null:e.h(ta,{item:t,pdfPageWidth:l.size.width,pdfPageHeight:l.size.height,cssPageWidth:t.width,cssPageHeight:t.height,hoverUi:null==(o=null==(i=r.features)?void 0:i.bookmarks)?void 0:o.hover})}(t);a&&s.push(a)}const i=null==(a=r.renderPageOverlay)?void 0:a.call(r,t);if(i&&s.push(i),s.length)return e.h("div",s)}return(t,a)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"hostRef",ref:n,class:e.normalizeClass(s.className),style:e.normalizeStyle(s.className?void 0:e.unref(S))},[e.createVNode(e.unref(wt),{class:e.normalizeClass(s.className),style:e.normalizeStyle(l.value)},{page:e.withCtx(({item:t})=>{var a,r,i,o;return[e.createVNode(ea,{item:t,features:s.features,"show-note-markers":p.value,"show-bookmark-markers":g.value,"show-redaction-layer":s.showRedactionLayer,"note-marker-ui":null==(r=null==(a=s.features)?void 0:a.notes)?void 0:r.marker,"bookmark-marker-ui":null==(o=null==(i=s.features)?void 0:i.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":P},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))}}),ma={key:0,style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,width:"100%"}},va=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{},onExtraSelectionAction:{type:Function}},setup(a){const s=a,r=e.computed(()=>function(e){if(e.options)return at(e.options);if(!e.editorOptions)throw new Error("ChapterPdfViewer: 请传入 `options`(推荐),或同时传入 `editorOptions` 与 `features`");const t=A(e.features),{plugins:a}=Xe({...e.editorOptions,features:t});return{plugins:a,features:t,editorOptions:{...e.editorOptions,features:t}}}({engine:s.engine,options:s.options,editorOptions:s.editorOptions,features:s.features}));return(s,i)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(a.className),style:e.normalizeStyle(a.className?void 0:e.unref(S))},[e.createVNode(e.unref(t.EmbedPDF),{engine:a.engine,plugins:r.value.plugins},{default:e.withCtx(({pluginsReady:t})=>[t?(e.openBlock(),e.createElementBlock("div",ma,[e.renderSlot(s.$slots,"prepend"),e.createVNode(fa,{class:e.normalizeClass(a.viewportClassName),style:{flex:1,minHeight:0},features:r.value.features,"on-extra-selection-action":a.onExtraSelectionAction},null,8,["class","features","on-extra-selection-action"]),e.renderSlot(s.$slots,"default")])):e.createCommentVNode("",!0)]),_:3},8,["engine","plugins"])],6))}}),ba={class:"chapter-tree-row"},Pa=["aria-expanded"],wa={key:1,class:"chapter-tree-toggle-spacer","aria-hidden":""},Ca={class:"chapter-tree-label"},ya={class:"chapter-tree-meta"},Ia={key:0},Ma=(e,t)=>{const a=e.__vccOpts||e;for(const[s,r]of t)a[s]=r;return a},Sa=Ma(e.defineComponent({__name:"ChapterTreeItem",props:{node:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup(t){const a={idle:"未加载",loading:"加载中",loaded:"已加载",closed:"已卸载",error:"失败","password-required":"需密码"},s=t,r=e.computed(()=>s.node.children??[]),i=e.computed(()=>r.value.length>0),o=e.ref(s.depth<1),n=e.computed(()=>s.activeChapterId===s.node.id),l=e.computed(()=>s.chapterStatus[s.node.id]??"idle"),h=e.computed(()=>!i.value);return(s,d)=>(e.openBlock(),e.createElementBlock("li",null,[e.createElementVNode("div",ba,[i.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,Pa)):(e.openBlock(),e.createElementBlock("span",wa)),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["chapter-tree-btn",{"chapter-tree-btn-active":n.value}]),onClick:d[1]||(d[1]=e=>s.$emit("select",t.node.id))},[e.createElementVNode("div",Ca,e.toDisplayString(t.node.title),1),e.createElementVNode("div",ya,[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",Ia,e.toDisplayString(a[l.value]),1)):e.createCommentVNode("",!0)])],2)]),i.value&&o.value?(e.openBlock(),e.createBlock(xa,{key:0,nodes:r.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"]]),xa=Ma(e.defineComponent({__name:"ChapterTreeList",props:{nodes:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup:t=>(a,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,r=>(e.openBlock(),e.createBlock(Sa,{key:r.id,node:r,depth:t.depth,"active-chapter-id":t.activeChapterId,"chapter-status":t.chapterStatus,onSelect:s[0]||(s[0]=e=>a.$emit("select",e))},null,8,["node","depth","active-chapter-id","chapter-status"]))),128))],4))}),[["__scopeId","data-v-eb742e4f"]]),ka={class:"chapter-tree"},La={class:"chapter-tree-nav","aria-label":"章节目录"},$a=Ma(e.defineComponent({__name:"ChapterTreePanel",props:{tree:{},activeChapterId:{}},emits:["active-chapter-change"],setup(a,{emit:s}){const r=a,i=s,{provides:o}=t.useCapability(te.id),{provides:n}=t.useCapability(q.id),l=e.ref({});function h(){if(!n.value)return;const e={},t=a=>{var s;for(const r of a)e[r.id]=n.value.getChapterStatus(r.id),(null==(s=r.children)?void 0:s.length)&&t(r.children)};t(r.tree),l.value=e}e.watch([n,()=>r.tree],h,{immediate:!0});let d=null;function c(e){var t;i("active-chapter-change",e),null==(t=o.value)||t.scrollToChapter(e)}return e.watch(n,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",ka,[s[0]||(s[0]=e.createElementVNode("h2",{class:"chapter-tree-title"},"章节目录",-1)),e.createElementVNode("nav",La,[e.createVNode(xa,{nodes:a.tree,depth:0,"active-chapter-id":a.activeChapterId,"chapter-status":l.value,onSelect:c},null,8,["nodes","active-chapter-id","chapter-status"])])]))}}),[["__scopeId","data-v-d7a0838d"]]),Ta=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{}},setup:t=>(t,a)=>(e.openBlock(),e.createBlock(e.unref(va),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))});const Da={kind:"first-wins"};function za(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}class Na{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 a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}}function Oa(e,t=Da){const a=function(e,t=Da){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,za(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new Na(i)}const Ea=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Da,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Da,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,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),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 a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=Oa(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));if(e&&this.documentManager.provides().isDocumentOpen(e)){this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus){if("loaded"!==s)continue;t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}if(!n)return void this.updateStatus(t,"password-required");this.updateStatus(t,"loading");this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})}closeChapter(e){const t=this.documentManager.provides();if(t.isDocumentOpen(e)){t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed"))}else this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};Ea.id="chapter-manager";let Aa=Ea;const Ga={kind:"first-wins"};function Va(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let _a=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 a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const Ra=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Ga,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.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=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,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),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 a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Ga){const a=function(e,t=Ga){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,Va(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new _a(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};Ra.id="chapter-manager";let Ba=Ra;const Fa={kind:"first-wins"};function Ua(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}class qa{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 a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}}const Ha=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Fa,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Fa,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,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),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 a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Fa){const a=function(e,t=Fa){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,Ua(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new qa(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};Ha.id="chapter-manager";let Wa=Ha;function ja(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 a=0;a<e.items.length;a++){const s=e.items[a],r=t.items[a];if(s.globalPageIndex!==r.globalPageIndex||s.isPlaceholder!==r.isPlaceholder||s.chapterId!==r.chapterId||s.localPageIndex!==r.localPageIndex||s.offsetTop!==r.offsetTop||s.width!==r.width||s.height!==r.height)return!1}return!0}(class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,ja),this.visibleChange$=r.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(Wa.id),this.documentManager=this.registry.getPlugin(i.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){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}isChapterPagePlaceholder(e){const t=this.chapterManager.provides().getChapterStatus(e);return"error"===t||"password-required"===t||"loaded"!==t}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;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),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,a)=>this.scrollToGlobalPdfPoint(e,t,a),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,a=0;for(let s=0;s<e;s++){const{width:e,height:r}=this.getPageSize(s);this.offsets[s]=t,t+=r+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===s.width&&r.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),r=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===r.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const i=this.getChapterDocumentScale(e),o=[];for(const n of r){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&o.push({localPageIndex:n.localPageIndex,width:e.size.width*i,height:e.size.height*i})}0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.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 a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),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,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let r=s;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=a)break;r++}const i=[];let o=s,n=-1;for(let l=s;l<r;l++){i.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,r=Math.max(0,Math.min(s,a)-Math.max(e,t));r>n&&(n=r,o=l)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(i),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const r=t+a>>1;this.offsets[r]<=e?(s=r,t=r+1):a=r-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let i=t;i<=s;i++){const e=this.virtualPageMap.atIndex(i);if(!e)continue;const t=this.getPageSize(i),a=this.isChapterPagePlaceholder(e.chapterId);r.push({globalPageIndex:i,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[i],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==a?void 0:a.marginTop)??80,i=this.virtualPageMap.atIndex(e);if(!i)return void this.scrollToIndex(e,a);const o=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(i.chapterId))?void 0:s.pages[i.localPageIndex];if(!o||!n)return void this.scrollToIndex(e,a);const l=o.height/n.size.height,h=(this.offsets[e]??0)+t*l-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}}).id="chapter-scroll";const Za={kind:"first-wins"};function Ya(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.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 a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const Ka=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Za,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.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=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,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),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 a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Za){const a=function(e,t=Za){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,Ya(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new Ja(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};Ka.id="chapter-manager";let Xa=Ka;const Qa={kind:"first-wins"};function es(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let ts=class{constructor(e){this._pages=e,this._byChapter=new Map,this._byGlobalNumber=new Map;for(const t of e){this._byGlobalNumber.set(t.globalPageNumber,t);let e=this._byChapter.get(t.chapterId);e||(e=[],this._byChapter.set(t.chapterId,e)),e.push(t)}}get totalPages(){return this._pages.length}list(){return this._pages}atIndex(e){return this._pages[e]??null}byGlobalNumber(e){return this._byGlobalNumber.get(e)??null}toGlobal(e,t){const a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const as=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Qa,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Qa,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,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),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 a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Qa){const a=function(e,t=Qa){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,es(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new ts(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};as.id="chapter-manager";let ss=as;function rs(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 a=0;a<e.items.length;a++){const s=e.items[a],r=t.items[a];if(s.globalPageIndex!==r.globalPageIndex||s.isPlaceholder!==r.isPlaceholder||s.chapterId!==r.chapterId||s.localPageIndex!==r.localPageIndex||s.offsetTop!==r.offsetTop||s.width!==r.width||s.height!==r.height)return!1}return!0}const is=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,rs),this.visibleChange$=r.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(ss.id),this.documentManager=this.registry.getPlugin(i.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){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}isChapterPagePlaceholder(e){const t=this.chapterManager.provides().getChapterStatus(e);return"error"===t||"password-required"===t||"loaded"!==t}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;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),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,a)=>this.scrollToGlobalPdfPoint(e,t,a),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,a=0;for(let s=0;s<e;s++){const{width:e,height:r}=this.getPageSize(s);this.offsets[s]=t,t+=r+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===s.width&&r.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),r=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===r.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const i=this.getChapterDocumentScale(e),o=[];for(const n of r){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&o.push({localPageIndex:n.localPageIndex,width:e.size.width*i,height:e.size.height*i})}0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.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 a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),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,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let r=s;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=a)break;r++}const i=[];let o=s,n=-1;for(let l=s;l<r;l++){i.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,r=Math.max(0,Math.min(s,a)-Math.max(e,t));r>n&&(n=r,o=l)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(i),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const r=t+a>>1;this.offsets[r]<=e?(s=r,t=r+1):a=r-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let i=t;i<=s;i++){const e=this.virtualPageMap.atIndex(i);if(!e)continue;const t=this.getPageSize(i),a=this.isChapterPagePlaceholder(e.chapterId);r.push({globalPageIndex:i,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[i],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==a?void 0:a.marginTop)??80,i=this.virtualPageMap.atIndex(e);if(!i)return void this.scrollToIndex(e,a);const o=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(i.chapterId))?void 0:s.pages[i.localPageIndex];if(!o||!n)return void this.scrollToIndex(e,a);const l=o.height/n.size.height,h=(this.offsets[e]??0)+t*l-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}};is.id="chapter-scroll";let os=is;const ns=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=r.createBehaviorEmitter([]),this.noteActivated$=r.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(os.id),this.chapterManager=this.registry.getPlugin(Xa.id),this.documentManager=this.registry.getPlugin(i.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(a){this.logger.error(e.id,"LoadNotes","Failed to load notes",a)}}buildCapability(){return{createNoteFromSelection:e=>this.createNoteFromSelection(e),requestCreateFromSelection:e=>this.requestCreateFromSelection(e),registerNote:e=>this.registerNote(e),listNotesForPage:(e,t)=>this.listAll().filter(a=>a.chapterId===e&&a.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,a;const s=this.notes.get(e);s&&(null==(a=(t=this.config.callbacks).onActivateNote)||a.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[a,s]of this.notes.entries())s.chapterId===e&&this.notes.delete(a);for(const a of t)a.chapterId===e&&this.notes.set(a.noteId,a);this.notesChange$.emit(this.listAll())}buildDraft(e){return{chapterId:e.chapterId,localPageIndex:e.localPageIndex,globalPageNumber:e.globalPageNumber,globalPageIndex:e.globalPageIndex,rectsPdfCoord:e.rectsPdfCoord,endAnchor:hs(e.rectsPdfCoord),selectedText:e.selectedText,content:e.content}}async requestCreateFromSelection(e){if(0===e.rectsPdfCoord.length)return null;const t=this.buildDraft(e),{onRequestCreateNote:a,onCreateNote:s}=this.config.callbacks;return a?(a({draft:t,complete:async e=>{const a={...t,noteId:e};this.registerNote(a)}}),null):this.createNoteFromSelection(e)}async createNoteFromSelection(t){if(0===t.rectsPdfCoord.length)return null;const a=this.buildDraft(t),s=this.config.callbacks.onCreateNote;if(!s)return this.logger.error(e.id,"CreateNote","Missing onCreateNote / onRequestCreateNote"),null;let r=null;try{r=await s(a)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!r)return null;const i={...a,noteId:r.noteId};return this.registerNote(i),i}async deleteNote(t){var a,s;if(this.notes.has(t)){try{await(null==(s=(a=this.config.callbacks).onDeleteNote)?void 0:s.call(a,t))}catch(r){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",r)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,a){var s,r;const i=this.notes.get(t);if(!i)return;const o={...i,content:a};try{await(null==(r=(s=this.config.callbacks).onUpdateNote)?void 0:r.call(s,o))}catch(n){return void this.logger.error(e.id,"OnUpdateNote","Callback failed",n)}this.notes.set(t,o),this.notesChange$.emit(this.listAll())}async scrollToNote(e){var t;const a=this.notes.get(e);if(!a)return;const s=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(a.chapterId),(null==(t=this.documentManager.provides().getDocument(a.chapterId))?void 0:t.pages[a.localPageIndex])?(s.scrollToGlobalPageIndex(a.globalPageIndex),await this.waitForPageInLayout(a.globalPageIndex),s.scrollToGlobalPdfPoint(a.globalPageIndex,a.endAnchor.y,{marginTop:80})):s.scrollToGlobalPageIndex(a.globalPageIndex)}waitForPageInLayout(e){const t=this.chapterScroll.provides(),a=t.getLayout().items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);return a?Promise.resolve(a):new Promise(a=>{const s=setTimeout(()=>{r(),a(null)},2500),r=t.onLayoutChange(t=>{const i=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);i&&(clearTimeout(s),r(),a(i))})})}};ns.id="note";let ls=ns;function hs(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}const ds={kind:"first-wins"};function cs(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}let us=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 a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}};const ps=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=ds,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??ds,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,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),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 a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=ds){const a=function(e,t=ds){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,cs(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new us(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};ps.id="chapter-manager";let gs=ps;const fs={kind:"first-wins"};function ms(e,t,a){if(1===t.length)return t[0].chapterId;switch(a.kind){case"first-wins":return t[0].chapterId;case"last-wins":return t[t.length-1].chapterId;case"explicit":{const a=t.find(t=>{var a;return null==(a=t.ownedGlobalPages)?void 0:a.includes(e)});return a?a.chapterId:t[0].chapterId}case"custom":return a.resolve(e,t)}}class vs{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 a=this._byChapter.get(e);return a?a.find(e=>e.localPageIndex===t)??null:null}pagesOfChapter(e){return this._byChapter.get(e)??[]}firstIndexOfChapter(e){var t;const a=null==(t=this._byChapter.get(e))?void 0:t[0];return a?this._pages.indexOf(a):-1}}const bs=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=fs,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??fs,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{this.isOwnedChapter(e.id)&&(this.passwordAttempts.delete(e.id),this.updateStatus(e.id,"loaded"))}),this.documentManager.provides().onDocumentClosed(e=>{this.isOwnedChapter(e)&&this.updateStatus(e,"closed")}),this.documentManager.provides().onDocumentError(e=>{this.isOwnedChapter(e.documentId)&&this.handleDocumentError(e.documentId,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),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 a=function(e){const t=[],a=new Set;for(const s of e.chapters){a.has(s.chapterId)&&t.push(`Duplicate chapterId: ${s.chapterId}`),a.add(s.chapterId);const[e,r]=s.globalPageRange,[i,o]=s.localPageRange;if(e>r&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${r}]`),i>o&&t.push(`${s.chapterId}: invalid localPageRange [${i},${o}]`),r-e!==o-i&&t.push(`${s.chapterId}: page-count mismatch (global ${r-e+1} vs local ${o-i+1})`),s.ownedGlobalPages)for(const a of s.ownedGlobalPages)(a<e||a>r)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${a} outside range`)}return t}(t);a.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${a.join("; ")}`);const s=new Set(this.chapterStatus.keys()),r=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)r.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=fs){const a=function(e,t=fs){const a=new Map;for(const r of e.chapters){const[e,t]=r.globalPageRange;for(let s=e;s<=t;s++){const e=a.get(s);e?e.push(r):a.set(s,[r])}}const s=new Map;for(const[r,i]of a)s.set(r,ms(r,i,t));return s}(e,t),s=new Map;for(const n of e.chapters)s.set(n.chapterId,n);const r=Array.from(a.keys()).sort((e,t)=>e-t),i=[];let o=0;for(const n of r){const e=a.get(n),t=s.get(e);if(!t)continue;const[r]=t.globalPageRange,[l]=t.localPageRange,h=l+(n-r);i.push({globalPageIndex:o++,globalPageNumber:n,chapterId:e,localPageIndex:h})}return new vs(i)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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(),a=Math.min(e,this.manifest.chapters.length);for(let s=0;s<a;s++){const e=this.manifest.chapters[s].chapterId;this.chapterLastUsed.set(e,t);const a=this.chapterStatus.get(e)??"idle";"idle"!==a&&"closed"!==a&&"error"!==a||this.ensureChapterLoaded(e)}}findChapter(e){return this.manifest.chapters.find(t=>t.chapterId===e)??null}isOwnedChapter(e){return!!this.findChapter(e)}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),a=this.config.prefetchChapters??1,s=new Set;for(const n of e){const e=this.virtualPageMap.atIndex(n);e&&s.add(e.chapterId)}if(0===s.size)return;const r=this.manifest.chapters.map(e=>e.chapterId),i=new Set;for(const n of s){const e=r.indexOf(n);if(-1!==e)for(let t=e-a;t<=e+a;t++)t>=0&&t<r.length&&i.add(t)}const o=new Set;for(const n of i)o.add(r[n]);for(const n of o){this.chapterLastUsed.set(n,t);const e=this.chapterStatus.get(n)??"idle";"idle"!==e&&"closed"!==e&&"error"!==e||this.ensureChapterLoaded(n)}if(this.config.autoActivateOnLoad??1){const e=r.find(e=>s.has(e));e&&this.documentManager.provides().isDocumentOpen(e)&&this.documentManager.provides().getActiveDocumentId()!==e&&this.documentManager.provides().setActiveDocument(e)}}collectIdleChapters(){const e=this.config.unloadTimeoutMs??6e4;if(e<=0)return;const t=Date.now();for(const[a,s]of this.chapterStatus)"loaded"===s&&t-(this.chapterLastUsed.get(a)??0)>e&&this.closeChapter(a)}ensureChapterLoaded(e){const t=this.pendingLoadPromises.get(e);if(t)return t;const a=this.findChapter(e);if(!a)return Promise.resolve("error");const s=this.chapterStatus.get(e)??"idle";if("loaded"===s)return this.chapterLastUsed.set(e,Date.now()),Promise.resolve("loaded");if("loading"===s)return this.waitForTerminalStatus(e);const r=this.startLoad(a).finally(()=>{this.pendingLoadPromises.delete(e)});return this.pendingLoadPromises.set(e,r),r}async resolvePdfPayload(e){const t=e.source;if(t){if("url"in t)return{url:t.url};if("buffer"in t)return{buffer:t.buffer};if("load"in t)return t.load()}const a=this.config.chapterPdfLoader;if(a)return a.loadPdf(e);throw new Error(`Chapter "${e.chapterId}" has no PDF source; set descriptor.source or chapterPdfLoader`)}async startLoad(t){var a;const s=t.chapterId;this.updateStatus(s,"loading"),this.chapterLastUsed.set(s,Date.now());try{const e=t.encrypted&&(null==(a=this.passwordProvider)?void 0:a.getCachedPassword)?this.passwordProvider.getCachedPassword(s):null,r=await this.resolvePdfPayload(t),i=this.documentManager.provides(),o="url"in r?i.openDocumentUrl({documentId:s,url:r.url,name:t.title,password:e??void 0,autoActivate:!1}):i.openDocumentBuffer({documentId:s,buffer:r.buffer,name:t.title,password:e??void 0,autoActivate:!1}),n=await new Promise((e,t)=>{o.wait(t=>e(t),e=>t(e))});return await new Promise((e,t)=>{n.task.wait(()=>e(),e=>t(e))}),i.isDocumentOpen(s)&&this.updateStatus(s,"loaded"),this.waitForTerminalStatus(s)}catch(r){const t=this.chapterStatus.get(s);if("loaded"!==t&&"password-required"!==t){const t=r instanceof Error?r.message:`Failed to load chapter "${s}"`;this.logger.error(e.id,"LoadChapter",t,r),this.updateStatus(s,"error",t)}return this.chapterStatus.get(s)??"error"}}waitForTerminalStatus(e){return new Promise(t=>{const a=e=>("loaded"===e||"error"===e||"password-required"===e||"closed"===e)&&(t(e),!0);if(a(this.chapterStatus.get(e)??"idle"))return;let s=null;s=this.statusChange$.on(t=>{t.chapterId===e&&a(t.status)&&(null==s||s(),s=null)})})}async handleDocumentError(t,a,r){if(a!==s.PdfErrorCode.Password)return void this.updateStatus(t,"error");if(!this.passwordProvider)return void this.updateStatus(t,"password-required");const i=this.findChapter(t);if(!i)return;const o=(this.passwordAttempts.get(t)??0)+1;this.passwordAttempts.set(t,o);let n=null;try{n=await this.passwordProvider.resolvePassword(i,o-1)}catch(l){this.logger.error(e.id,"PasswordProvider",`Provider rejected for ${t}`,l)}n?(this.updateStatus(t,"loading"),this.documentManager.provides().retryDocument(t,{password:n}).wait(()=>{},()=>{})):this.updateStatus(t,"password-required")}closeChapter(e){const t=this.documentManager.provides();t.isDocumentOpen(e)?t.closeDocument(e).wait(()=>this.updateStatus(e,"closed"),()=>this.updateStatus(e,"closed")):this.updateStatus(e,"closed")}updateStatus(e,t,a){this.chapterStatus.get(e)!==t&&(this.chapterStatus.set(e,t),this.statusChange$.emit({chapterId:e,status:t,..."error"===t&&a?{error:{message:a}}:{}}))}};bs.id="chapter-manager";let Ps=bs;function ws(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 a=0;a<e.items.length;a++){const s=e.items[a],r=t.items[a];if(s.globalPageIndex!==r.globalPageIndex||s.isPlaceholder!==r.isPlaceholder||s.chapterId!==r.chapterId||s.localPageIndex!==r.localPageIndex||s.offsetTop!==r.offsetTop||s.width!==r.width||s.height!==r.height)return!1}return!0}const Cs=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,ws),this.visibleChange$=r.createBehaviorEmitter(),this.virtualPageMap=null,this.pageSizes=new Map,this.offsets=[],this.totalHeight=0,this.totalWidth=0,this.viewportEl=null,this.viewportObservers=null,this.currentVisible=[],this.currentGlobalPageIndex=0,this.chapterManagerUnsubs=[],this.chapterManager=this.registry.getPlugin(Ps.id),this.documentManager=this.registry.getPlugin(i.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){const t=this.coreState.core.documents[e];return!(!t||"loaded"!==t.status||!t.document)&&t.document.pages.length>0}isChapterPagePlaceholder(e){const t=this.chapterManager.provides().getChapterStatus(e);return"error"===t||"password-required"===t||"loaded"!==t}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;if(0===((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0))return;const a=this.documentManager.provides();a.getActiveDocumentId()||a.setActiveDocument(e),this.harvestChapterSizes(e),this.refreshLayout()}onDocumentClosed(e){var t;0!==((null==(t=this.virtualPageMap)?void 0:t.pagesOfChapter(e).length)??0)&&(this.dropChapterSizes(e),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,a)=>this.scrollToGlobalPdfPoint(e,t,a),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,a=0;for(let s=0;s<e;s++){const{width:e,height:r}=this.getPageSize(s);this.offsets[s]=t,t+=r+this.config.pageGap,e>a&&(a=e)}this.totalHeight=e>0?t-this.config.pageGap:0,this.totalWidth=a,this.layoutChange$.emit(this.computeLayout())}applyChapterPageSizes(e,t){if(!this.virtualPageMap)return;let a=!1;for(const s of t){const t=this.virtualPageMap.toGlobal(e,s.localPageIndex);if(!t)continue;const r=this.pageSizes.get(t.globalPageIndex);r&&r.width===s.width&&r.height===s.height||(this.pageSizes.set(t.globalPageIndex,{width:s.width,height:s.height}),a=!0)}if(a){const e=this.currentGlobalPageIndex,t=this.offsets[e]??0;if(this.rebuildOffsets(),this.viewportEl){const a=(this.offsets[e]??0)-t;0!==a&&(this.viewportEl.scrollTop+=a)}this.recomputeVisible()}}getChapterDocumentScale(e){var t;return(null==(t=this.coreState.core.documents[e])?void 0:t.scale)??1}harvestChapterSizes(e,t=0){var a;if(!this.virtualPageMap)return;const s=this.documentManager.provides().getDocument(e),r=this.virtualPageMap.pagesOfChapter(e);if(!(null==(a=null==s?void 0:s.pages)?void 0:a.length)||0===r.length)return void(t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1)));const i=this.getChapterDocumentScale(e),o=[];for(const n of r){const e=s.pages[n.localPageIndex];(null==e?void 0:e.size)&&o.push({localPageIndex:n.localPageIndex,width:e.size.width*i,height:e.size.height*i})}0!==o.length?this.applyChapterPageSizes(e,o):t<60&&requestAnimationFrame(()=>this.harvestChapterSizes(e,t+1))}onScaleChanged(e){const t=this.coreState.core.documents[e];t&&"loaded"===t.status&&this.chapterManager.provides().getChapter(e)&&this.harvestChapterSizes(e)}dropChapterSizes(e){if(!this.virtualPageMap)return;let t=!1;for(const a of this.virtualPageMap.pagesOfChapter(e))this.pageSizes.delete(a.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 a=()=>this.recomputeVisible(),s=new ResizeObserver(()=>this.recomputeVisible());e.addEventListener("scroll",a,{passive:!0}),s.observe(e),this.viewportObservers={unbind:()=>{e.removeEventListener("scroll",a),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,a=t+this.viewportEl.clientHeight,s=this.findFirstVisibleIndex(t);let r=s;for(;r<e;){const e=this.getPageSize(r),t=this.offsets[r];if(e.height,t>=a)break;r++}const i=[];let o=s,n=-1;for(let l=s;l<r;l++){i.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,r=Math.max(0,Math.min(s,a)-Math.max(e,t));r>n&&(n=r,o=l)}this.currentVisible=i,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:i,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(i),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,a=this.offsets.length-1,s=0;for(;t<=a;){const r=t+a>>1;this.offsets[r]<=e?(s=r,t=r+1):a=r-1}return s}computeLayout(){const e=this.config.bufferSize,t=Math.max(0,(this.currentVisible[0]??0)-e),a=this.currentVisible[this.currentVisible.length-1]??-1,s=Math.min(this.offsets.length-1,(a>=0?a:0)+e),r=[];if(this.virtualPageMap&&this.offsets.length>0)for(let i=t;i<=s;i++){const e=this.virtualPageMap.atIndex(i);if(!e)continue;const t=this.getPageSize(i),a=this.isChapterPagePlaceholder(e.chapterId);r.push({globalPageIndex:i,globalPageNumber:e.globalPageNumber,chapterId:e.chapterId,localPageIndex:e.localPageIndex,width:t.width,height:t.height,offsetTop:this.offsets[i],isPlaceholder:a})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:r,pageGap:this.config.pageGap}}scrollToIndex(e,t){if(!this.viewportEl||e<0||e>=this.offsets.length)return;const a=(this.offsets[e]??0)-((null==t?void 0:t.topOffset)??0);this.viewportEl.scrollTo({top:a,behavior:(null==t?void 0:t.behavior)??"auto"})}scrollToGlobalPdfPoint(e,t,a){var s;if(!this.viewportEl||e<0||e>=this.offsets.length||!this.virtualPageMap)return;const r=(null==a?void 0:a.marginTop)??80,i=this.virtualPageMap.atIndex(e);if(!i)return void this.scrollToIndex(e,a);const o=this.pageSizes.get(e),n=null==(s=this.documentManager.provides().getDocument(i.chapterId))?void 0:s.pages[i.localPageIndex];if(!o||!n)return void this.scrollToIndex(e,a);const l=o.height/n.size.height,h=(this.offsets[e]??0)+t*l-r;this.viewportEl.scrollTo({top:Math.max(0,h),behavior:(null==a?void 0:a.behavior)??"auto"})}scrollToChapter(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.firstIndexOfChapter(e);a<0||(this.chapterManager.provides().ensureChapterLoaded(e),this.scrollToIndex(a,t))}scrollToGlobalNumber(e,t){if(!this.virtualPageMap)return;const a=this.virtualPageMap.byGlobalNumber(e);a&&this.scrollToIndex(a.globalPageIndex,t)}};Cs.id="chapter-scroll";let ys=Cs;function Is(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Ms(e,t){const a=e.origin.y,s=e.origin.y+e.size.height,r=t.origin.y,i=t.origin.y+t.size.height,o=Math.max(s,i)-Math.min(a,r);return o<=0?0:Math.max(0,Math.min(s,i)-Math.max(a,r))/o}function Ss(e,t){var a,s;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const r=(null==(a=e.rectsPdfCoord)?void 0:a.length)?e.rectsPdfCoord:[e.rectPdfCoord],i=(null==(s=t.rectsPdfCoord)?void 0:s.length)?t.rectsPdfCoord:[t.rectPdfCoord],o=e.markerAnchor??Is(r),n=t.markerAnchor??Is(i);if(Math.hypot(o.x-n.x,o.y-n.y)<=6)return!0;for(const l of r)for(const e of i){if(Ms(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 xs=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.change$=r.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(ys.id),this.chapterManager=this.registry.getPlugin(gs.id),this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(t){var a;if(this.config=t,null==(a=t.callbacks)?void 0:a.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(Ss(s.anchor,e.anchor))return s;const t=e.id??`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,a={id:t,label:e.label,anchor:e.anchor,metadata:e.metadata,createdAt:Date.now()};return this.entries.set(t,a),this.notifyAndPersist(),a}removeBookmark(e){var t,a,s;this.entries.delete(e)&&(this.notifyAndPersist(),null==(s=null==(a=null==(t=this.config)?void 0:t.callbacks)?void 0:a.onRemoveSuccess)||s.call(a,e))}async requestRemoveBookmark(t){var a,s;const r=this.entries.get(t);if(!r)return!1;const i=null==(s=null==(a=this.config)?void 0:a.callbacks)?void 0:s.onRequestRemove;if(i)try{if(!(await i(r)))return!1}catch(o){return this.logger.error(e.id,"RequestRemove","callback failed",o),!1}return this.removeBookmark(t),!0}updateBookmark(e,t){const a=this.entries.get(e);a&&(this.entries.set(e,{...a,...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[a,s]of this.entries.entries())s.anchor.chapterId===e&&this.entries.delete(a);for(const a of t)a.anchor.chapterId===e&&this.entries.set(a.id,a);this.notifyAndPersist()}notifyAndPersist(){var t,a;const s=this.list();this.change$.emit(s),(null==(a=null==(t=this.config)?void 0:t.callbacks)?void 0:a.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 a=this.chapterScroll.provides();await this.chapterManager.provides().ensureChapterLoaded(t.anchor.chapterId);let s=t.anchor.globalPageIndex;if(void 0===s){const e=this.chapterManager.provides().getVirtualPageMap().toGlobal(t.anchor.chapterId,t.anchor.localPageIndex);if(!e)return;s=e.globalPageIndex}const r=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,a){e.scrollToGlobalPageIndex(t),await function(e,t,a=2500){const s=e.getLayout().items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);return s?Promise.resolve(s):new Promise(s=>{const r=setTimeout(()=>{i(),s(null)},a),i=e.onLayoutChange(e=>{const a=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);a&&(clearTimeout(r),i(),s(a))})})}(e,t),e.scrollToGlobalPdfPoint(t,a,{marginTop:80})}(a,s,r)}};xs.id="paragraph-bookmark";let ks=xs;function Ls(e,t){const a=e;return!1===e?{...t,enabled:!1}:!0===e||void 0===e?{...t,enabled:t.enabled??!0}:{...t,...a,enabled:!1!==(null==a?void 0:a.enabled)}}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=Ls(void 0,{enabled:!0}),t=Ls(void 0,{enabled:!0}),a=Ls(void 0,{enabled:!0}),s=Ls(void 0,{enabled:!0,min:.5,max:3,initial:1}),r=Ls(!1!==e.enabled||!1!==a.enabled,{enabled:!0});null==void 0||(void 0).background}();function $s(e){const t=new Uint8Array(e);let a="";for(let s=0;s<t.length;s++)a+=String.fromCharCode(t[s]);return btoa(a)}function Ts(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 Ds(e){var t,s,r,i;return{annotation:null==(t=e.getPlugin(a.AnnotationPlugin.id))?void 0:t.provides(),note:null==(s=e.getPlugin(ls.id))?void 0:s.provides(),bookmark:null==(r=e.getPlugin(ks.id))?void 0:r.provides(),chapterManager:null==(i=e.getPlugin(Ba.id))?void 0:i.provides()}}async function zs(e,t,a){if(!a||!e)return;const s=await e.ensureChapterLoaded(t);if("loaded"!==s)throw new Error(`章节 ${t} 未加载成功(${s}),无法导入/导出划线`)}async function Ns(e,t,a){const s=Ts(a),{annotation:r,note:i,bookmark:o,chapterManager:n}=Ds(e),l={chapterId:t};if(s.bookmarks){if(!o)throw new Error("paragraph-bookmark 插件未注册");l.bookmarks=o.listBookmarksForChapter(t)}if(s.notes){if(!i)throw new Error("note 插件未注册");l.notes=i.listNotesForChapter(t)}if(s.markup){if(!r)throw new Error("annotation 插件未注册");await zs(n,t,!1!==(null==a?void 0:a.ensureChapterLoaded));const e=await(h=r.forDocument(t).exportAnnotations(),new Promise((e,t)=>{h.wait(t=>e(t),e=>t(e))}));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:$s(t.data),mimeType:t.mimeType}}})}(e)}var h;return l}async function Os(e,t,a){const s=Ts(a),r=(null==a?void 0:a.mode)??"replace",{annotation:i,note:o,bookmark:n,chapterManager:l}=Ds(e),h=t.chapterId;if(s.bookmarks&&t.bookmarks){if(!n)throw new Error("paragraph-bookmark 插件未注册");if("replace"===r)n.replaceBookmarksForChapter(h,t.bookmarks);else for(const e of t.bookmarks)n.addBookmark(e)}if(s.notes&&t.notes){if(!o)throw new Error("note 插件未注册");if("replace"===r)o.replaceNotesForChapter(h,t.notes);else for(const e of t.notes)o.registerNote(e)}if(s.markup&&t.markup){if(!i)throw new Error("annotation 插件未注册");await zs(l,h,!1!==(null==a?void 0:a.ensureChapterLoaded));const e=i.forDocument(h),s=function(e){return e.map(e=>{var t;if(!(null==(t=e.ctx)?void 0:t.dataBase64))return{annotation:e.annotation};const a=function(e){const t=atob(e),a=new Uint8Array(t.length);for(let s=0;s<t.length;s++)a[s]=t.charCodeAt(s);return a.buffer}(e.ctx.dataBase64);return{annotation:e.annotation,ctx:{data:a,...e.ctx.mimeType?{mimeType:e.ctx.mimeType}:{}}}})}(t.markup);"replace"===r&&e.deleteAllAnnotations(),e.importAnnotations(s)}(null==a?void 0:a.persistNotes)&&o&&await a.persistNotes(o.listAllNotes()),(null==a?void 0:a.persistBookmarks)&&n&&await a.persistBookmarks(n.listBookmarks())}function Es(e){return JSON.stringify(e,null,2)}function As(e){return JSON.stringify(e,null,2)}function Gs(e,t){const a=new Blob([t],{type:"application/json;charset=utf-8"}),s=URL.createObjectURL(a),r=document.createElement("a");r.href=s,r.download=e,r.click(),URL.revokeObjectURL(s)}function Vs(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}:{},...e.encrypted?{encrypted:e.encrypted}:{}}}function _s(e){const t=[],a=e=>{var s;for(const r of e)t.push(Vs(r)),(null==(s=r.children)?void 0:s.length)&&a(r.children)};return a(e),t}function Rs(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)?Rs(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:()=>M.usePdfiumEngine}),exports.CHAPTER_ANNOTATIONS_ARCHIVE_VERSION=1,exports.CallbackPasswordProvider=G,exports.ChapterManagerPlugin=Aa,exports.ChapterPdfViewer=Ta,exports.ChapterTreePanel=$a,exports.DEFAULT_CHAPTER_VIEWER_CONFIG={},exports.DEFAULT_CHAPTER_VIEWER_FEATURES=Ke,exports.PdfChapterViewport=fa,exports.applySelectionMarkup=N,exports.buildChapterViewerCatalog=function(e){return{tree:Rs(e),manifest:{chapters:_s(e)}}},exports.buildParagraphBookmarkAnchor=Be,exports.chapterAnnotationsArchiveToJson=Es,exports.chapterAnnotationsSnapshotToJson=As,exports.chapterDescriptorFromTreeNode=Vs,exports.createChapterViewerBundle=at,exports.createChapterViewerEditor=Xe,exports.createChapterViewerEditorOptions=function(e){const{features:t,...a}=tt(et(e));return a},exports.createPdfChapterEditor=Ye,exports.defaultOverlapStrategy={kind:"first-wins"},exports.downloadChapterAnnotationsArchive=function(e,t="chapter-annotations.json"){Gs(t,Es(e))},exports.downloadChapterAnnotationsSnapshot=function(e,t){Gs(t??`chapter-annotations-${e.chapterId}.json`,As(e))},exports.downloadJsonFile=Gs,exports.exportAllChapterAnnotations=async function(e,t,a){const s={};for(const r of t.chapters){const t=await Ns(e,r.chapterId,a),{chapterId:i,...o}=t;s[r.chapterId]=o}return{version:1,exportedAt:(new Date).toISOString(),chapters:s}},exports.exportChapterAnnotations=Ns,exports.flattenChapterTree=_s,exports.importChapterAnnotations=Os,exports.importChapterAnnotationsArchive=async function(e,t,a){if(1!==t.version)throw new Error(`不支持的归档版本 ${t.version},当前为 1`);for(const[s,r]of Object.entries(t.chapters))await Os(e,{chapterId:s,...r},a)},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=Rs;
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"),a=require("@embedpdf/core"),n=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"),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,a=-1/0;for(const n of e)t=Math.min(t,n.origin.x),r=Math.min(r,n.origin.y),s=Math.max(s,n.origin.x+n.size.width),a=Math.max(a,n.origin.y+n.size.height);return{origin:{x:t,y:r},size:{width:s-t,height:a-r}}}function E(e,t,a,n,o){const i=a.forDocument(e),l=n.forDocument(e);if(!i||!l)return!1;const h="highlight"===t?"highlight":"underline"===t?"underline":"squiggly"===t?"squiggly":"strikeout",d=a.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(),a=u.color??c.color??c.strokeColor,n=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:a,opacity:n,...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 O(e){var t;const r=F(null==e?void 0:e.markup,{enabled:!0}),s=F(null==e?void 0:e.bookmarks,{enabled:!0}),a=F(null==e?void 0:e.notes,{enabled:!0}),n=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!==a.enabled:e.selectionToolbar,{enabled:!0});return{markup:r,bookmarks:s,notes:a,zoom:n,scrollViewport:{background:(null==(t=null==e?void 0:e.scrollViewport)?void 0:t.background)??L},selectionToolbar:o}}function N(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 N(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)),a=N(e.source)?e.source.urls:void 0,n=[];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;n.push({index:l,url:(null==a?void 0:a[l])??"",localPageStart:s,localPageEnd:o,documentId:z(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}let V=class{constructor(e){this.cb=e}resolvePassword(e,t){return this.cb(e,t)}};const R="chapter-manager",_={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 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 Z(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function Y(e){const t=H(e);if(!t)return null;const r=B(e),s=Z(r,t),a=q(e.source)?e.source.urls:void 0,n=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;n.push({index:o,url:(null==a?void 0:a[o])??"",localPageStart:s,localPageEnd:i,documentId:W(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}function J(e,t){const r=Y(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 K(e,t){const r=Y(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:a}=e,n=B(e);r<=0&&s.push(`${a}: segmentPageThreshold must be > 0`);const o=e.source;if(!q(o))return s;0===o.urls.length&&s.push(`${a}: source.urls must not be empty`);const i=Z(n,r);o.urls.length!==i&&s.push(`${a}: 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(`${a}: 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 a.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=a.createBehaviorEmitter(),this.manifestChange$=a.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(n.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?J(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?Y(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=[],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,a]=s.globalPageRange,[n,o]=s.localPageRange;if(e>a&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${a}]`),n>o&&t.push(`${s.chapterId}: invalid localPageRange [${n},${o}]`),a-e!==o-n&&t.push(`${s.chapterId}: page-count mismatch (global ${a-e+1} vs local ${o-n+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>a)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...X(s))}return t}(t);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const s=new Set(this.chapterStatus.keys()),a=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Q){const r=function(e,t=Q){const r=new Map;for(const a of e.chapters){const[e,t]=a.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(a):r.set(s,[a])}}const s=new Map;for(const[a,n]of r)s.set(a,ee(a,n,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const a=Array.from(r.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of a){const e=r.get(i),t=s.get(e);if(!t)continue;const[a]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-a);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new te(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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?Y(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const a=r.segments[t];return!!a&&s.isDocumentOpen(a.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 a=this.chapterStatus.get(e);"loaded"!==a&&"password-required"!==a&&"error"!==a&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,a=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=K(t,e.localPageIndex);a.add(`${e.chapterId}:${r}`),a.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=n.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of a){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=J(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=Y(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 a=s.segments[t],n=a.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(r,a).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,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 a=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,a),a}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 a=(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,a);try{return await a}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 a=this.config.chapterPdfLoader,n={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==a?void 0:a.openPdf)?a.openPdf(n):{url:s}}async resolvePdfPayload(t,r){const s=t.source,a=this.config.chapterPdfLoader,n=H(t);if(n){const s=Z(B(t),n);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const a=await this.resolveChapterUrls(t);return a.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${a.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,a)}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==a?void 0:a.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==a?void 0:a.loadPdf)return a.loadPdf(t,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const a=t.chapterId,n=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??a;0===n&&this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,i=await this.resolvePdfPayload(t,n),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(a),this.waitForTerminalStatus(a)}catch(i){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"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,a,n){if(a!==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?Y(t):null,a=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const n of s.segments)a(n.documentId);else a(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 ae={manifest:_,create:e=>new se(R,e),reducer:e=>e,initialState:{}},ne="chapter-scroll",oe={id:ne,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)),a=ie(e.source)?e.source.urls:void 0,n=[];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;n.push({index:l,url:(null==a?void 0:a[l])??"",localPageStart:s,localPageEnd:o,documentId:le(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}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),a=ue(e.source)?e.source.urls:void 0,n=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;n.push({index:o,url:(null==a?void 0:a[o])??"",localPageStart:s,localPageEnd:i,documentId:ge(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}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:a}=e,n=ce(e);r<=0&&s.push(`${a}: segmentPageThreshold must be > 0`);const o=e.source;if(!ue(o))return s;0===o.urls.length&&s.push(`${a}: source.urls must not be empty`);const i=fe(n,r);o.urls.length!==i&&s.push(`${a}: 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(`${a}: 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 a.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=a.createBehaviorEmitter(),this.manifestChange$=a.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(n.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),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=[],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,a]=s.globalPageRange,[n,o]=s.localPageRange;if(e>a&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${a}]`),n>o&&t.push(`${s.chapterId}: invalid localPageRange [${n},${o}]`),a-e!==o-n&&t.push(`${s.chapterId}: page-count mismatch (global ${a-e+1} vs local ${o-n+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>a)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Ce(s))}return t}(t);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const s=new Set(this.chapterStatus.keys()),a=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=be){const r=function(e,t=be){const r=new Map;for(const a of e.chapters){const[e,t]=a.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(a):r.set(s,[a])}}const s=new Map;for(const[a,n]of r)s.set(a,we(a,n,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const a=Array.from(r.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of a){const e=r.get(i),t=s.get(e);if(!t)continue;const[a]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-a);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Se(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=r.segments[t];return!!a&&s.isDocumentOpen(a.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 a=this.chapterStatus.get(e);"loaded"!==a&&"password-required"!==a&&"error"!==a&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,a=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);a.add(`${e.chapterId}:${r}`),a.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=n.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of a){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 a=s.segments[t],n=a.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(r,a).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,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 a=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,a),a}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 a=(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,a);try{return await a}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 a=this.config.chapterPdfLoader,n={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==a?void 0:a.openPdf)?a.openPdf(n):{url:s}}async resolvePdfPayload(t,r){const s=t.source,a=this.config.chapterPdfLoader,n=pe(t);if(n){const s=fe(ce(t),n);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const a=await this.resolveChapterUrls(t);return a.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${a.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,a)}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==a?void 0:a.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==a?void 0:a.loadPdf)return a.loadPdf(t,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const a=t.chapterId,n=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??a;0===n&&this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,i=await this.resolvePdfPayload(t,n),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(a),this.waitForTerminalStatus(a)}catch(i){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"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,a,n){if(a!==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,a=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const n of s.segments)a(n.documentId);else a(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],a=t.items[r];if(s.globalPageIndex!==a.globalPageIndex||s.isPlaceholder!==a.isPlaceholder||s.chapterId!==a.chapterId||s.localPageIndex!==a.localPageIndex||s.pdfDocumentId!==a.pdfDocumentId||s.pdfPageIndex!==a.pdfPageIndex||s.offsetTop!==a.offsetTop||s.width!==a.width||s.height!==a.height)return!1}return!0}const $e=class extends a.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=a.createBehaviorEmitter(void 0,xe),this.visibleChange$=a.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(n.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 a=r.getChapter(e);if(!a)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)}(a,t);return!r.isSegmentLoaded(e,n)}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:a}=this.getPageSize(s);this.offsets[s]=t,t+=a+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 a=this.pageSizes.get(t.globalPageIndex);a&&a.width===s.width&&a.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),a=this.virtualPageMap.pagesOfChapter(e);if(!s||0===a.length)return;const n=de(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var a;const n=o.getDocument(e);if(!(null==(a=null==n?void 0:n.pages)?void 0:a.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=n.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(n)for(const h of n.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,a.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 a=s;for(;a<e;){const e=this.getPageSize(a),t=this.offsets[a];if(e.height,t>=r)break;a++}const n=[];let o=s,i=-1;for(let l=s;l<a;l++){n.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,a=Math.max(0,Math.min(s,r)-Math.max(e,t));a>i&&(i=a,o=l)}this.currentVisible=n,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:n,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(n),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const a=t+r>>1;this.offsets[a]<=e?(s=a,t=a+1):r=a-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),a=[];if(this.virtualPageMap&&this.offsets.length>0)for(let n=t;n<=s;n++){const e=this.virtualPageMap.atIndex(n);if(!e)continue;const t=this.getPageSize(n),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);a.push({globalPageIndex:n,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[n]??0,isPlaceholder:s})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:a,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 a=(null==r?void 0:r.marginTop)??80,n=this.virtualPageMap.atIndex(e);if(!n)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(n.chapterId,n.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-a;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(ne,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 Oe(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 Ne(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=Ne(r,t),a=Ee(e.source)?e.source.urls:void 0,n=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;n.push({index:o,url:(null==a?void 0:a[o])??"",localPageStart:s,localPageEnd:i,documentId:Fe(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}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=Ae(e);if(!r)return[];const s=[],{chapterId:a}=e,n=Te(e);r<=0&&s.push(`${a}: segmentPageThreshold must be > 0`);const o=e.source;if(!Ee(o))return s;0===o.urls.length&&s.push(`${a}: source.urls must not be empty`);const i=Ne(n,r);o.urls.length!==i&&s.push(`${a}: 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(`${a}: 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 a.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=a.createBehaviorEmitter(),this.manifestChange$=a.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(n.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}=Oe(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=Oe(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=Oe(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=[],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,a]=s.globalPageRange,[n,o]=s.localPageRange;if(e>a&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${a}]`),n>o&&t.push(`${s.chapterId}: invalid localPageRange [${n},${o}]`),a-e!==o-n&&t.push(`${s.chapterId}: page-count mismatch (global ${a-e+1} vs local ${o-n+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>a)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Re(s))}return t}(t);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const s=new Set(this.chapterStatus.keys()),a=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=_e){const r=function(e,t=_e){const r=new Map;for(const a of e.chapters){const[e,t]=a.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(a):r.set(s,[a])}}const s=new Map;for(const[a,n]of r)s.set(a,Be(a,n,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const a=Array.from(r.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of a){const e=r.get(i),t=s.get(e);if(!t)continue;const[a]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-a);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new qe(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=r.segments[t];return!!a&&s.isDocumentOpen(a.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 a=this.chapterStatus.get(e);"loaded"!==a&&"password-required"!==a&&"error"!==a&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,a=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);a.add(`${e.chapterId}:${r}`),a.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=n.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of a){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 a=s.segments[t],n=a.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(r,a).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,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 a=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,a),a}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 a=(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,a);try{return await a}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 a=this.config.chapterPdfLoader,n={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==a?void 0:a.openPdf)?a.openPdf(n):{url:s}}async resolvePdfPayload(t,r){const s=t.source,a=this.config.chapterPdfLoader,n=Ae(t);if(n){const s=Ne(Te(t),n);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const a=await this.resolveChapterUrls(t);return a.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${a.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,a)}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==a?void 0:a.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==a?void 0:a.loadPdf)return a.loadPdf(t,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const a=t.chapterId,n=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??a;0===n&&this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,i=await this.resolvePdfPayload(t,n),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(a),this.waitForTerminalStatus(a)}catch(i){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"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,a,n){if(a!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=Oe(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,a=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const n of s.segments)a(n.documentId);else a(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 Ze(e,t){return`${e}#s${t}`}function Ye(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 Je(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)),a=je(e.source)?e.source.urls:void 0,n=[];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;n.push({index:l,url:(null==a?void 0:a[l])??"",localPageStart:s,localPageEnd:o,documentId:Ze(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}function Ke(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=Ke(e),s=rt(r,t),a=Xe(e.source)?e.source.urls:void 0,n=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;n.push({index:o,url:(null==a?void 0:a[o])??"",localPageStart:s,localPageEnd:i,documentId:et(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}function at(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 nt(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:a}=e,n=Ke(e);r<=0&&s.push(`${a}: segmentPageThreshold must be > 0`);const o=e.source;if(!Xe(o))return s;0===o.urls.length&&s.push(`${a}: source.urls must not be empty`);const i=rt(n,r);o.urls.length!==i&&s.push(`${a}: 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(`${a}: 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 a.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=a.createBehaviorEmitter(),this.manifestChange$=a.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(n.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?at(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=[],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,a]=s.globalPageRange,[n,o]=s.localPageRange;if(e>a&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${a}]`),n>o&&t.push(`${s.chapterId}: invalid localPageRange [${n},${o}]`),a-e!==o-n&&t.push(`${s.chapterId}: page-count mismatch (global ${a-e+1} vs local ${o-n+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>a)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...ot(s))}return t}(t);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const s=new Set(this.chapterStatus.keys()),a=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=it){const r=function(e,t=it){const r=new Map;for(const a of e.chapters){const[e,t]=a.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(a):r.set(s,[a])}}const s=new Map;for(const[a,n]of r)s.set(a,lt(a,n,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const a=Array.from(r.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of a){const e=r.get(i),t=s.get(e);if(!t)continue;const[a]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-a);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new ht(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=r.segments[t];return!!a&&s.isDocumentOpen(a.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 a=this.chapterStatus.get(e);"loaded"!==a&&"password-required"!==a&&"error"!==a&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,a=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=nt(t,e.localPageIndex);a.add(`${e.chapterId}:${r}`),a.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=n.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of a){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=at(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 a=s.segments[t],n=a.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(r,a).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,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 a=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,a),a}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 a=(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,a);try{return await a}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 a=this.config.chapterPdfLoader,n={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==a?void 0:a.openPdf)?a.openPdf(n):{url:s}}async resolvePdfPayload(t,r){const s=t.source,a=this.config.chapterPdfLoader,n=Qe(t);if(n){const s=rt(Ke(t),n);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const a=await this.resolveChapterUrls(t);return a.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${a.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,a)}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==a?void 0:a.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==a?void 0:a.loadPdf)return a.loadPdf(t,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const a=t.chapterId,n=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??a;0===n&&this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,i=await this.resolvePdfPayload(t,n),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(a),this.waitForTerminalStatus(a)}catch(i){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"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,a,n){if(a!==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,a=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const n of s.segments)a(n.documentId);else a(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],a=t.items[r];if(s.globalPageIndex!==a.globalPageIndex||s.isPlaceholder!==a.isPlaceholder||s.chapterId!==a.chapterId||s.localPageIndex!==a.localPageIndex||s.pdfDocumentId!==a.pdfDocumentId||s.pdfPageIndex!==a.pdfPageIndex||s.offsetTop!==a.offsetTop||s.width!==a.width||s.height!==a.height)return!1}return!0}const pt=class extends a.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=a.createBehaviorEmitter(void 0,ut),this.visibleChange$=a.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(n.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 a=r.getChapter(e);if(!a)return!0;const n=function(e,t){const r=Je(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)}(a,t);return!r.isSegmentLoaded(e,n)}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}=Ye(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}=Ye(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:a}=this.getPageSize(s);this.offsets[s]=t,t+=a+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 a=this.pageSizes.get(t.globalPageIndex);a&&a.width===s.width&&a.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),a=this.virtualPageMap.pagesOfChapter(e);if(!s||0===a.length)return;const n=Je(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var a;const n=o.getDocument(e);if(!(null==(a=null==n?void 0:n.pages)?void 0:a.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=n.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(n)for(const h of n.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,a.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}=Ye(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 a=s;for(;a<e;){const e=this.getPageSize(a),t=this.offsets[a];if(e.height,t>=r)break;a++}const n=[];let o=s,i=-1;for(let l=s;l<a;l++){n.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,a=Math.max(0,Math.min(s,r)-Math.max(e,t));a>i&&(i=a,o=l)}this.currentVisible=n,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:n,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(n),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const a=t+r>>1;this.offsets[a]<=e?(s=a,t=a+1):r=a-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),a=[];if(this.virtualPageMap&&this.offsets.length>0)for(let n=t;n<=s;n++){const e=this.virtualPageMap.atIndex(n);if(!e)continue;const t=this.getPageSize(n),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);a.push({globalPageIndex:n,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[n]??0,isPlaceholder:s})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:a,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 a=(null==r?void 0:r.marginTop)??80,n=this.virtualPageMap.atIndex(e);if(!n)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(n.chapterId,n.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-a;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 a.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=a.createBehaviorEmitter([]),this.noteActivated$=a.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(gt.id),this.chapterManager=this.registry.getPlugin(We.id),this.documentManager=this.registry.getPlugin(n.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 a=null;try{a=await s(r)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!a)return null;const n={...r,noteId:a.noteId};return this.registerNote(n),n}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(a){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",a)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,r){var s,a;const n=this.notes.get(t);if(!n)return;const o={...n,content:r};try{await(null==(a=(s=this.config.callbacks).onUpdateNote)?void 0:a.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(),a=this.chapterManager.provides();await a.ensureAllSegmentsLoaded(r.chapterId);const n=a.resolvePageDocument(r.chapterId,r.localPageIndex);(null==(t=this.documentManager.provides().getDocument(n.documentId))?void 0:t.pages[n.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(()=>{a(),r(null)},2500),a=t.onLayoutChange(t=>{const n=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);n&&(clearTimeout(s),a(),r(n))})})}};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 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),a=wt(e.source)?e.source.urls:void 0,n=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;n.push({index:o,url:(null==a?void 0:a[o])??"",localPageStart:s,localPageEnd:i,documentId:yt(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}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:a}=e,n=bt(e);r<=0&&s.push(`${a}: segmentPageThreshold must be > 0`);const o=e.source;if(!wt(o))return s;0===o.urls.length&&s.push(`${a}: source.urls must not be empty`);const i=xt(n,r);o.urls.length!==i&&s.push(`${a}: 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(`${a}: 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 a.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=a.createBehaviorEmitter(),this.manifestChange$=a.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(n.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=[],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,a]=s.globalPageRange,[n,o]=s.localPageRange;if(e>a&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${a}]`),n>o&&t.push(`${s.chapterId}: invalid localPageRange [${n},${o}]`),a-e!==o-n&&t.push(`${s.chapterId}: page-count mismatch (global ${a-e+1} vs local ${o-n+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>a)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...kt(s))}return t}(t);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const s=new Set(this.chapterStatus.keys()),a=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Ut){const r=function(e,t=Ut){const r=new Map;for(const a of e.chapters){const[e,t]=a.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(a):r.set(s,[a])}}const s=new Map;for(const[a,n]of r)s.set(a,Tt(a,n,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const a=Array.from(r.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of a){const e=r.get(i),t=s.get(e);if(!t)continue;const[a]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-a);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Et(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=r.segments[t];return!!a&&s.isDocumentOpen(a.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 a=this.chapterStatus.get(e);"loaded"!==a&&"password-required"!==a&&"error"!==a&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,a=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);a.add(`${e.chapterId}:${r}`),a.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=n.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of a){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 a=s.segments[t],n=a.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(r,a).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,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 a=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,a),a}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 a=(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,a);try{return await a}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 a=this.config.chapterPdfLoader,n={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==a?void 0:a.openPdf)?a.openPdf(n):{url:s}}async resolvePdfPayload(t,r){const s=t.source,a=this.config.chapterPdfLoader,n=St(t);if(n){const s=xt(bt(t),n);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const a=await this.resolveChapterUrls(t);return a.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${a.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,a)}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==a?void 0:a.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==a?void 0:a.loadPdf)return a.loadPdf(t,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const a=t.chapterId,n=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??a;0===n&&this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,i=await this.resolvePdfPayload(t,n),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(a),this.waitForTerminalStatus(a)}catch(i){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"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,a,n){if(a!==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,a=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const n of s.segments)a(n.documentId);else a(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 Ot(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Nt(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 Ot(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)),a=Ot(e.source)?e.source.urls:void 0,n=[];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;n.push({index:l,url:(null==a?void 0:a[l])??"",localPageStart:s,localPageEnd:o,documentId:Nt(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}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 _t(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Rt(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=Vt(e),s=Ht(r,t),a=Rt(e.source)?e.source.urls:void 0,n=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;n.push({index:o,url:(null==a?void 0:a[o])??"",localPageStart:s,localPageEnd:i,documentId:Bt(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}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 Zt(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 Yt(e){var t;const r=_t(e);if(!r)return[];const s=[],{chapterId:a}=e,n=Vt(e);r<=0&&s.push(`${a}: segmentPageThreshold must be > 0`);const o=e.source;if(!Rt(o))return s;0===o.urls.length&&s.push(`${a}: source.urls must not be empty`);const i=Ht(n,r);o.urls.length!==i&&s.push(`${a}: 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(`${a}: source.urls[${l}] is empty`);return s}const Jt={kind:"first-wins"};function Kt(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 a.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=a.createBehaviorEmitter(),this.manifestChange$=a.createEmitter(),this.overlapStrategy=Jt,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(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Jt,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=[],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,a]=s.globalPageRange,[n,o]=s.localPageRange;if(e>a&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${a}]`),n>o&&t.push(`${s.chapterId}: invalid localPageRange [${n},${o}]`),a-e!==o-n&&t.push(`${s.chapterId}: page-count mismatch (global ${a-e+1} vs local ${o-n+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>a)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Yt(s))}return t}(t);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const s=new Set(this.chapterStatus.keys()),a=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Jt){const r=function(e,t=Jt){const r=new Map;for(const a of e.chapters){const[e,t]=a.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(a):r.set(s,[a])}}const s=new Map;for(const[a,n]of r)s.set(a,Kt(a,n,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const a=Array.from(r.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of a){const e=r.get(i),t=s.get(e);if(!t)continue;const[a]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-a);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Xt(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=r.segments[t];return!!a&&s.isDocumentOpen(a.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 a=this.chapterStatus.get(e);"loaded"!==a&&"password-required"!==a&&"error"!==a&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,a=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=Zt(t,e.localPageIndex);a.add(`${e.chapterId}:${r}`),a.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=n.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of a){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 a=s.segments[t],n=a.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(r,a).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,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 a=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,a),a}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 a=(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,a);try{return await a}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 a=this.config.chapterPdfLoader,n={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==a?void 0:a.openPdf)?a.openPdf(n):{url:s}}async resolvePdfPayload(t,r){const s=t.source,a=this.config.chapterPdfLoader,n=_t(t);if(n){const s=Ht(Vt(t),n);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const a=await this.resolveChapterUrls(t);return a.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${a.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,a)}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==a?void 0:a.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==a?void 0:a.loadPdf)return a.loadPdf(t,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const a=t.chapterId,n=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??a;0===n&&this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,i=await this.resolvePdfPayload(t,n),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(a),this.waitForTerminalStatus(a)}catch(i){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"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,a,n){if(a!==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,a=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const n of s.segments)a(n.documentId);else a(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],a=t.items[r];if(s.globalPageIndex!==a.globalPageIndex||s.isPlaceholder!==a.isPlaceholder||s.chapterId!==a.chapterId||s.localPageIndex!==a.localPageIndex||s.pdfDocumentId!==a.pdfDocumentId||s.pdfPageIndex!==a.pdfPageIndex||s.offsetTop!==a.offsetTop||s.width!==a.width||s.height!==a.height)return!1}return!0}const rr=class extends a.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=a.createBehaviorEmitter(void 0,tr),this.visibleChange$=a.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(n.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 a=r.getChapter(e);if(!a)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)}(a,t);return!r.isSegmentLoaded(e,n)}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:a}=this.getPageSize(s);this.offsets[s]=t,t+=a+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 a=this.pageSizes.get(t.globalPageIndex);a&&a.width===s.width&&a.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),a=this.virtualPageMap.pagesOfChapter(e);if(!s||0===a.length)return;const n=Gt(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var a;const n=o.getDocument(e);if(!(null==(a=null==n?void 0:n.pages)?void 0:a.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=n.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(n)for(const h of n.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,a.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 a=s;for(;a<e;){const e=this.getPageSize(a),t=this.offsets[a];if(e.height,t>=r)break;a++}const n=[];let o=s,i=-1;for(let l=s;l<a;l++){n.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,a=Math.max(0,Math.min(s,r)-Math.max(e,t));a>i&&(i=a,o=l)}this.currentVisible=n,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:n,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(n),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const a=t+r>>1;this.offsets[a]<=e?(s=a,t=a+1):r=a-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),a=[];if(this.virtualPageMap&&this.offsets.length>0)for(let n=t;n<=s;n++){const e=this.virtualPageMap.atIndex(n);if(!e)continue;const t=this.getPageSize(n),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);a.push({globalPageIndex:n,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[n]??0,isPlaceholder:s})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:a,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 a=(null==r?void 0:r.marginTop)??80,n=this.virtualPageMap.atIndex(e);if(!n)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(n.chapterId,n.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-a;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 ar(e){if(0===e.length)throw new Error("unionRects: empty rects");let t=1/0,r=1/0,s=-1/0,a=-1/0;for(const n of e)t=Math.min(t,n.origin.x),r=Math.min(r,n.origin.y),s=Math.max(s,n.origin.x+n.size.width),a=Math.max(a,n.origin.y+n.size.height);return{origin:{x:t,y:r},size:{width:s-t,height:a-r}}}function nr(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,a=t.origin.y,n=t.origin.y+t.size.height,o=Math.max(s,n)-Math.min(r,a);return o<=0?0:Math.max(0,Math.min(s,n)-Math.max(r,a))/o}function ir(e,t){var r,s;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const a=(null==(r=e.rectsPdfCoord)?void 0:r.length)?e.rectsPdfCoord:[e.rectPdfCoord],n=(null==(s=t.rectsPdfCoord)?void 0:s.length)?t.rectsPdfCoord:[t.rectPdfCoord],o=e.markerAnchor??nr(a),i=t.markerAnchor??nr(n);if(Math.hypot(o.x-i.x,o.y-i.y)<=6)return!0;for(const l of a)for(const e of n){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 a=r.length>0?r:[];if(0===a.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:ar(a),rectsPdfCoord:a,markerAnchor:nr(a)}}const hr=class e extends a.BasePlugin{constructor(e,t){super(e,t),this.change$=a.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(sr.id),this.chapterManager=this.registry.getPlugin(Ft.id),this.documentManager=this.registry.getPlugin(n.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 a=this.entries.get(t);if(!a)return!1;const n=null==(s=null==(r=this.config)?void 0:r.callbacks)?void 0:s.onRequestRemove;if(n)try{if(!(await n(a)))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 a=t.anchor.globalPageIndex;if(void 0===a){const e=this.chapterManager.provides().getVirtualPageMap().toGlobal(t.anchor.chapterId,t.anchor.localPageIndex);if(!e)return;a=e.globalPageIndex}const n=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 a=setTimeout(()=>{n(),s(null)},r),n=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(a),n(),s(r))})})}(e,t),e.scrollToGlobalPdfPoint(t,r,{marginTop:80})}(r,a,n)}};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 a=[];for(const n of e)"group"!==n.type?r.before&&n.id===r.before?a.push(t,n):(a.push(n),r.after&&n.id===r.after&&a.push(t)):a.push({...n,items:s(n.items)});return a};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 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,a,n,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==(a=e.extend)?void 0:a.sidebars)??{},modals:(null==(n=e.extend)?void 0:n.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,a,n,o;const i=null==(s=e.getPlugin("ui"))?void 0:s.provides(),l=null==(a=e.getPlugin("interaction-manager"))?void 0:a.provides();i&&l&&(null==(n=l.forDocument(t))||n.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,a;const n=null==(s=e.getPlugin("ui"))?void 0:s.provides();n&&(n.setActiveToolbar("top","secondary","annotation-toolbar",t),null==(a=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||a.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,a;const n=null==(s=e.getPlugin("ui"))?void 0:s.provides();n&&(n.setActiveToolbar("top","secondary","shapes-toolbar",t),null==(a=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||a.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,a;const n=null==(s=e.getPlugin("ui"))?void 0:s.provides();n&&(n.setActiveToolbar("top","secondary","insert-toolbar",t),null==(a=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||a.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,a;const n=null==(s=e.getPlugin("ui"))?void 0:s.provides();n&&(n.setActiveToolbar("top","secondary","form-toolbar",t),null==(a=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||a.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,a;const n=null==(s=e.getPlugin("ui"))?void 0:s.provides();n&&(n.setActiveToolbar("top","secondary","redaction-toolbar",t),null==(a=e.getPlugin(r.ANNOTATION_PLUGIN_ID))||a.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=[a.createPluginRegistration(n.DocumentManagerPluginPackage,{initialDocuments:[]}),a.createPluginRegistration(ae,{manifest:e.manifest,overlapStrategy:e.overlapStrategy,passwordProvider:e.passwordProvider,chapterPdfLoader:e.chapterPdfLoader,prefetchChapters:e.prefetchChapters,unloadTimeoutMs:e.unloadTimeoutMs}),a.createPluginRegistration(De,{placeholderPageHeight:e.placeholderPageHeight,placeholderPageWidth:e.placeholderPageWidth}),a.createPluginRegistration(o.InteractionManagerPluginPackage),a.createPluginRegistration(i.RenderPluginPackage),a.createPluginRegistration(l.RotatePluginPackage),a.createPluginRegistration(h.SelectionPluginPackage,{marquee:{enabled:!1},toleranceFactor:1.2,minSelectionDragDistance:4}),a.createPluginRegistration(d.HistoryPluginPackage),a.createPluginRegistration(r.AnnotationPluginPackage),a.createPluginRegistration(c.RedactionPluginPackage),a.createPluginRegistration(u.FormPluginPackage),a.createPluginRegistration(p.StampPluginPackage,!1===e.loadDefaultStampLibrary?{manifests:[]}:void 0),a.createPluginRegistration(g.SignaturePluginPackage),...Object.keys($).length>0?[a.createPluginRegistration(m.CommandsPluginPackage,{commands:$})]:[],...y?[a.createPluginRegistration(f.I18nPluginPackage),a.createPluginRegistration(v.UIPluginPackage,{schema:M})]:[]];return e.notes&&L.push(a.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(a.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=O();function Ir(e){return fr({...e,toolbar:e.toolbar??{enabledModes:[]},features:O(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 wr(e){return{...Cr,manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,overlapStrategy:e.overlapStrategy??Cr.overlapStrategy,notes:{callbacks:e.notes},bookmarks:{callbacks:e.bookmarks},features:O(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 a of e.pages){const e=(null==(r=null==a?void 0:a.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 a=xr(t,r);if(a<=0)return s;const n=Mr(e,a);return Math.min(s,n)}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 a=e.getDocument(t.chapterId);a&&r(a,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(n.DocumentManagerPlugin.id),{provides:d}=t.useCapability(se.id),c=e.ref(f()),u=e.ref(c.value),p=e.ref(0),g=()=>{var e;return null==(e=s.value)?void 0:e.pageWidth},m=()=>{return null!=(e=g())&&e>0;var e},f=()=>{var e;return(null==(e=s.value)?void 0:e.initial)??1},v=e.computed(()=>{var e;return function(e,t,r,s,a){if(!e||r<=0)return a;let n=a;for(const o of t.chapters)Lr(e,o,e=>{n=Math.min(n,$r(e,r,s,a))});return n}(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,n=3){const o=null==e?void 0:e.getStore();if(!o)return;const i=yr(r,s,n);o.dispatchToCore(a.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(a.setScale(i,t.documentId));else o.getState().core.documents[l.chapterId]&&o.dispatchToCore(a.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){m()?b(e):C(f())}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))}),a=()=>{const a=e.querySelector("[data-chapter-scroll-viewport]");a!==r?(r&&s.unobserve(r),r=a,r?(s.observe(r),t(Dr(r))):t(0)):t(Dr(r))};a();const n=new MutationObserver(a);n.observe(e,{childList:!0,subtree:!0});const o=requestAnimationFrame(a);return()=>{cancelAnimationFrame(o),n.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,()=>f(),()=>m()],()=>{l.value&&(m()||C(f()))},{immediate:!0}),e.watch(v,e=>{u.value>e&&C(e)}),e.watch([d,i,()=>m(),()=>f()],()=>{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,()=>m(),d,i],()=>{if(m()&&!(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,a=0;const n=()=>{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:a=3}){let n=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,a)),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()];n=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&&n>0)){e.preventDefault();const[t,i]=[...c.values()],l=Math.hypot(i.x-t.x,i.y-t.y);r(kr(o*(l/n),s,a))}},g=e=>{c.delete(e.pointerId),c.size<2&&(n=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 n()||(s=new MutationObserver(()=>{n()&&(null==s||s.disconnect(),s=null)}),s.observe(e,{childList:!0,subtree:!0}),a=requestAnimationFrame(()=>n())),()=>{a&&cancelAnimationFrame(a),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 Or(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)),a=Er(e.source)?e.source.urls:void 0,n=[];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;n.push({index:l,url:(null==a?void 0:a[l])??"",localPageStart:s,localPageEnd:o,documentId:Ar(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}function Nr(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 _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=Nr(e),s=_r(r,t),a=zr(e.source)?e.source.urls:void 0,n=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;n.push({index:o,url:(null==a?void 0:a[o])??"",localPageStart:s,localPageEnd:i,documentId:Vr(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}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:a}=e,n=Nr(e);r<=0&&s.push(`${a}: segmentPageThreshold must be > 0`);const o=e.source;if(!zr(o))return s;0===o.urls.length&&s.push(`${a}: source.urls must not be empty`);const i=_r(n,r);o.urls.length!==i&&s.push(`${a}: 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(`${a}: source.urls[${l}] is empty`);return s}const jr={kind:"first-wins"};function Zr(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 Yr{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 Jr=class e extends a.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=a.createBehaviorEmitter(),this.manifestChange$=a.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(n.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?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=[],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,a]=s.globalPageRange,[n,o]=s.localPageRange;if(e>a&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${a}]`),n>o&&t.push(`${s.chapterId}: invalid localPageRange [${n},${o}]`),a-e!==o-n&&t.push(`${s.chapterId}: page-count mismatch (global ${a-e+1} vs local ${o-n+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>a)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Wr(s))}return t}(t);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const s=new Set(this.chapterStatus.keys()),a=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=jr){const r=function(e,t=jr){const r=new Map;for(const a of e.chapters){const[e,t]=a.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(a):r.set(s,[a])}}const s=new Map;for(const[a,n]of r)s.set(a,Zr(a,n,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const a=Array.from(r.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of a){const e=r.get(i),t=s.get(e);if(!t)continue;const[a]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-a);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Yr(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=r.segments[t];return!!a&&s.isDocumentOpen(a.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 a=this.chapterStatus.get(e);"loaded"!==a&&"password-required"!==a&&"error"!==a&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,a=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);a.add(`${e.chapterId}:${r}`),a.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=n.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of a){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 a=s.segments[t],n=a.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(r,a).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,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 a=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,a),a}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 a=(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,a);try{return await a}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 a=this.config.chapterPdfLoader,n={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==a?void 0:a.openPdf)?a.openPdf(n):{url:s}}async resolvePdfPayload(t,r){const s=t.source,a=this.config.chapterPdfLoader,n=Gr(t);if(n){const s=_r(Nr(t),n);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const a=await this.resolveChapterUrls(t);return a.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${a.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,a)}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==a?void 0:a.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==a?void 0:a.loadPdf)return a.loadPdf(t,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const a=t.chapterId,n=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??a;0===n&&this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,i=await this.resolvePdfPayload(t,n),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(a),this.waitForTerminalStatus(a)}catch(i){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"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,a,n){if(a!==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?Br(t):null,a=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const n of s.segments)a(n.documentId);else a(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}}:{}}))}};Jr.id="chapter-manager";let Kr=Jr;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],a=t.items[r];if(s.globalPageIndex!==a.globalPageIndex||s.isPlaceholder!==a.isPlaceholder||s.chapterId!==a.chapterId||s.localPageIndex!==a.localPageIndex||s.pdfDocumentId!==a.pdfDocumentId||s.pdfPageIndex!==a.pdfPageIndex||s.offsetTop!==a.offsetTop||s.width!==a.width||s.height!==a.height)return!1}return!0}const Qr=class extends a.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=a.createBehaviorEmitter(void 0,Xr),this.visibleChange$=a.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(Kr.id),this.documentManager=this.registry.getPlugin(n.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 a=r.getChapter(e);if(!a)return!0;const n=function(e,t){const r=Or(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)}(a,t);return!r.isSegmentLoaded(e,n)}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:a}=this.getPageSize(s);this.offsets[s]=t,t+=a+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 a=this.pageSizes.get(t.globalPageIndex);a&&a.width===s.width&&a.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),a=this.virtualPageMap.pagesOfChapter(e);if(!s||0===a.length)return;const n=Or(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var a;const n=o.getDocument(e);if(!(null==(a=null==n?void 0:n.pages)?void 0:a.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=n.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(n)for(const h of n.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,a.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 a=s;for(;a<e;){const e=this.getPageSize(a),t=this.offsets[a];if(e.height,t>=r)break;a++}const n=[];let o=s,i=-1;for(let l=s;l<a;l++){n.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,a=Math.max(0,Math.min(s,r)-Math.max(e,t));a>i&&(i=a,o=l)}this.currentVisible=n,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:n,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(n),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const a=t+r>>1;this.offsets[a]<=e?(s=a,t=a+1):r=a-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),a=[];if(this.virtualPageMap&&this.offsets.length>0)for(let n=t;n<=s;n++){const e=this.virtualPageMap.atIndex(n);if(!e)continue;const t=this.getPageSize(n),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);a.push({globalPageIndex:n,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[n]??0,isPlaceholder:s})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:a,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 a=(null==r?void 0:r.marginTop)??80,n=this.virtualPageMap.atIndex(e);if(!n)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(n.chapterId,n.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-a;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),a=e.ref(null),n=e.ref(null);let o=null;const i=()=>{null==o||o(),o=null,s.value&&(s.value.registerViewport(a.value),o=s.value.onLayoutChange(e=>{n.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:a,"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=n.value)?void 0:s.totalWidth)??0}px`,height:`${(null==(o=n.value)?void 0:o.totalHeight)??0}px`,margin:"0 auto"})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList((null==(i=n.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,a)=>(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 as(e){const[t,r]=e.localPageRange;return r-t+1}function ns(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 ns(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=as(e),s=hs(r,t),a=ns(e.source)?e.source.urls:void 0,n=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;n.push({index:o,url:(null==a?void 0:a[o])??"",localPageStart:s,localPageEnd:i,documentId:is(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}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:a}=e,n=as(e);r<=0&&s.push(`${a}: segmentPageThreshold must be > 0`);const o=e.source;if(!ns(o))return s;0===o.urls.length&&s.push(`${a}: source.urls must not be empty`);const i=hs(n,r);o.urls.length!==i&&s.push(`${a}: 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(`${a}: 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 a.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=a.createBehaviorEmitter(),this.manifestChange$=a.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(n.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=[],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,a]=s.globalPageRange,[n,o]=s.localPageRange;if(e>a&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${a}]`),n>o&&t.push(`${s.chapterId}: invalid localPageRange [${n},${o}]`),a-e!==o-n&&t.push(`${s.chapterId}: page-count mismatch (global ${a-e+1} vs local ${o-n+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>a)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...ps(s))}return t}(t);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const s=new Set(this.chapterStatus.keys()),a=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=gs){const r=function(e,t=gs){const r=new Map;for(const a of e.chapters){const[e,t]=a.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(a):r.set(s,[a])}}const s=new Map;for(const[a,n]of r)s.set(a,ms(a,n,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const a=Array.from(r.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of a){const e=r.get(i),t=s.get(e);if(!t)continue;const[a]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-a);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new fs(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=r.segments[t];return!!a&&s.isDocumentOpen(a.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 a=this.chapterStatus.get(e);"loaded"!==a&&"password-required"!==a&&"error"!==a&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,a=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);a.add(`${e.chapterId}:${r}`),a.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=n.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of a){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 a=s.segments[t],n=a.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(r,a).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,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 a=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,a),a}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 a=(async()=>{const r=e.source;if(ns(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,a);try{return await a}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 a=this.config.chapterPdfLoader,n={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==a?void 0:a.openPdf)?a.openPdf(n):{url:s}}async resolvePdfPayload(t,r){const s=t.source,a=this.config.chapterPdfLoader,n=os(t);if(n){const s=hs(as(t),n);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const a=await this.resolveChapterUrls(t);return a.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${a.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,a)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(ns(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==a?void 0:a.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==a?void 0:a.loadPdf)return a.loadPdf(t,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const a=t.chapterId,n=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??a;0===n&&this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,i=await this.resolvePdfPayload(t,n),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(a),this.waitForTerminalStatus(a)}catch(i){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"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,a,n){if(a!==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,a=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const n of s.segments)a(n.documentId);else a(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)),a=Is(e.source)?e.source.urls:void 0,n=[];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;n.push({index:l,url:(null==a?void 0:a[l])??"",localPageStart:s,localPageEnd:o,documentId:Cs(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}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),a=ys(e.source)?e.source.urls:void 0,n=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;n.push({index:o,url:(null==a?void 0:a[o])??"",localPageStart:s,localPageEnd:i,documentId:xs(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}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:a}=e,n=Ss(e);r<=0&&s.push(`${a}: segmentPageThreshold must be > 0`);const o=e.source;if(!ys(o))return s;0===o.urls.length&&s.push(`${a}: source.urls must not be empty`);const i=Ls(n,r);o.urls.length!==i&&s.push(`${a}: 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(`${a}: 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 Os=class e extends a.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=a.createBehaviorEmitter(),this.manifestChange$=a.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(n.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=[],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,a]=s.globalPageRange,[n,o]=s.localPageRange;if(e>a&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${a}]`),n>o&&t.push(`${s.chapterId}: invalid localPageRange [${n},${o}]`),a-e!==o-n&&t.push(`${s.chapterId}: page-count mismatch (global ${a-e+1} vs local ${o-n+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>a)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Ts(s))}return t}(t);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const s=new Set(this.chapterStatus.keys()),a=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Es){const r=function(e,t=Es){const r=new Map;for(const a of e.chapters){const[e,t]=a.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(a):r.set(s,[a])}}const s=new Map;for(const[a,n]of r)s.set(a,As(a,n,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const a=Array.from(r.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of a){const e=r.get(i),t=s.get(e);if(!t)continue;const[a]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-a);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Fs(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=r.segments[t];return!!a&&s.isDocumentOpen(a.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 a=this.chapterStatus.get(e);"loaded"!==a&&"password-required"!==a&&"error"!==a&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,a=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);a.add(`${e.chapterId}:${r}`),a.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=n.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of a){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 a=s.segments[t],n=a.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(r,a).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,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 a=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,a),a}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 a=(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,a);try{return await a}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 a=this.config.chapterPdfLoader,n={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==a?void 0:a.openPdf)?a.openPdf(n):{url:s}}async resolvePdfPayload(t,r){const s=t.source,a=this.config.chapterPdfLoader,n=Ms(t);if(n){const s=Ls(Ss(t),n);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const a=await this.resolveChapterUrls(t);return a.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${a.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,a)}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==a?void 0:a.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==a?void 0:a.loadPdf)return a.loadPdf(t,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const a=t.chapterId,n=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??a;0===n&&this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,i=await this.resolvePdfPayload(t,n),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(a),this.waitForTerminalStatus(a)}catch(i){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"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,a,n){if(a!==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,a=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const n of s.segments)a(n.documentId);else a(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}}:{}}))}};Os.id="chapter-manager";let Ns=Os;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],a=t.items[r];if(s.globalPageIndex!==a.globalPageIndex||s.isPlaceholder!==a.isPlaceholder||s.chapterId!==a.chapterId||s.localPageIndex!==a.localPageIndex||s.pdfDocumentId!==a.pdfDocumentId||s.pdfPageIndex!==a.pdfPageIndex||s.offsetTop!==a.offsetTop||s.width!==a.width||s.height!==a.height)return!1}return!0}const Gs=class extends a.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=a.createBehaviorEmitter(void 0,zs),this.visibleChange$=a.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(Ns.id),this.documentManager=this.registry.getPlugin(n.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 a=r.getChapter(e);if(!a)return!0;const n=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)}(a,t);return!r.isSegmentLoaded(e,n)}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:a}=this.getPageSize(s);this.offsets[s]=t,t+=a+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 a=this.pageSizes.get(t.globalPageIndex);a&&a.width===s.width&&a.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),a=this.virtualPageMap.pagesOfChapter(e);if(!s||0===a.length)return;const n=ws(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var a;const n=o.getDocument(e);if(!(null==(a=null==n?void 0:n.pages)?void 0:a.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=n.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(n)for(const h of n.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,a.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 a=s;for(;a<e;){const e=this.getPageSize(a),t=this.offsets[a];if(e.height,t>=r)break;a++}const n=[];let o=s,i=-1;for(let l=s;l<a;l++){n.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,a=Math.max(0,Math.min(s,r)-Math.max(e,t));a>i&&(i=a,o=l)}this.currentVisible=n,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:n,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(n),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const a=t+r>>1;this.offsets[a]<=e?(s=a,t=a+1):r=a-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),a=[];if(this.virtualPageMap&&this.offsets.length>0)for(let n=t;n<=s;n++){const e=this.virtualPageMap.atIndex(n);if(!e)continue;const t=this.getPageSize(n),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);a.push({globalPageIndex:n,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[n]??0,isPlaceholder:s})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:a,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 a=(null==r?void 0:r.marginTop)??80,n=this.virtualPageMap.atIndex(e);if(!n)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(n.chapterId,n.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-a;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 a.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=a.createBehaviorEmitter([]),this.noteActivated$=a.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(Vs.id),this.chapterManager=this.registry.getPlugin(Ps.id),this.documentManager=this.registry.getPlugin(n.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 a=null;try{a=await s(r)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!a)return null;const n={...r,noteId:a.noteId};return this.registerNote(n),n}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(a){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",a)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,r){var s,a;const n=this.notes.get(t);if(!n)return;const o={...n,content:r};try{await(null==(a=(s=this.config.callbacks).onUpdateNote)?void 0:a.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(),a=this.chapterManager.provides();await a.ensureAllSegmentsLoaded(r.chapterId);const n=a.resolvePageDocument(r.chapterId,r.localPageIndex);(null==(t=this.documentManager.provides().getDocument(n.documentId))?void 0:t.pages[n.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(()=>{a(),r(null)},2500),a=t.onLayoutChange(t=>{const n=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);n&&(clearTimeout(s),a(),r(n))})})}};Rs.id="note";let _s=Rs;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:a,cssPageWidth:n,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*a+(l.size.height*a-o)/2):(h=t.x*s-o/2,d=t.y*a-o-i);const c=Math.max(0,n-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"],Zs=["onClick"],Ys=["onClick"],Js=["onClick"],Ks=e.defineComponent({__name:"NoteMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(r){const s=r,{provides:a}=t.useCapability(_s.id),n=e.ref([]),o=e.ref(null),i=e.ref(null);e.watch(a,e=>{if(e)return e.onNotesChange(e=>{n.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,a=h.value,{left:n,top:o}=qs({markerPdf:e.endAnchor,lineRects:e.rectsPdfCoord,sx:t,sy:r,cssPageWidth:s.cssPageWidth,iconSize:a}),l=function(e,t,r){let s=1/0,a=1/0,n=-1/0,o=-1/0;for(const i of e)s=Math.min(s,i.origin.x*t),a=Math.min(a,i.origin.y*r),n=Math.max(n,(i.origin.x+i.size.width)*t),o=Math.max(o,(i.origin.y+i.size.height)*r);return{left:s,top:a,width:n-s,height:o-a}}(e.rectsPdfCoord,t,r),d=i.value===e.noteId?72:0,c=Math.max(0,Math.min(l.left,n)-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,n+a)+8)-c,zoneH:Math.max(l.top+l.height,o+a+6+d)+8-u,iconLeft:n,iconTop:o,sx:t,sy:r}}return(t,s)=>e.unref(a)&&n.value.length&&r.pdfPageWidth&&r.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",Hs,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.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,Zs),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=a.value)||s.requestEditNote(r.noteId,r));var r,s}}," 编辑 ",8,Ys),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=a.value)||r.requestDeleteNote(s),void(i.value=null)}}," 删除 ",8,Js)],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"],ea=["onClick"],ta=e.defineComponent({__name:"BookmarkMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(r){const s=r,{provides:a}=t.useCapability(dr.id),n=e.ref([]),o=e.ref(null),i=e.ref(null);function l(){const e=a.value;e&&(n.value=e.listBookmarks().filter(e=>e.anchor.chapterId===s.chapterId&&e.anchor.localPageIndex===s.localPageIndex))}e.watch(a,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,a=s.cssPageHeight/s.pdfPageHeight,n=(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:n,sx:r,sy:a,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(a)&&n.value.length&&r.pdfPageWidth&&r.pdfPageHeight?(e.openBlock(),e.createElementBlock("div",Xs,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.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=a.value;t&&await t.requestRemoveBookmark(e)&&(o.value=null)}(t.id)}," 删除书签 ",8,ea)],512)):e.createCommentVNode("",!0)],36))),128))])):e.createCommentVNode("",!0)}});function ra(e){return e.pdfDocumentId??e.chapterId}function sa(e){return e.pdfPageIndex??e.localPageIndex}function aa(e,t){e.wait(t,()=>{})}const na={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)"},oa={padding:"6px 12px",fontSize:"12px",fontWeight:"500",border:"none",borderRadius:"6px",background:"transparent",color:"#dc2626",cursor:"pointer"};const ia=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,a=e.computed(()=>ra(s.item)),o=e.computed(()=>sa(s.item));!function(r){const{provides:s}=t.useCapability(n.DocumentManagerPlugin.id);e.watch([s,r],([e,t])=>{e&&t&&e.isDocumentOpen(t)&&e.setActiveDocument(t)},{immediate:!0})}(a);const{provides:i}=t.useCapability(n.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(a.value))?void 0:t.pages[o.value]});function c(t,r){var a,n,o,i;const h=s.createNote.value;if(h&&!1!==(null==(n=null==(a=s.features)?void 0:a.notes)?void 0:n.enabled)&&!1!==(null==(i=null==(o=s.features)?void 0:o.selectionToolbar)?void 0:i.enabled))return s=>{var a;const n={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==(a=s.placement)?void 0:a.suggestTop)?-40:s.rect.size.height+8};return e.h("div",s.menuWrapperProps,[e.h("div",{style:n},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(sa(t),r);aa(l.value.getSelectedText(r),r=>{var s,a,n;h((s=t,a=e,n=r.join("\n"),{chapterId:s.chapterId,localPageIndex:s.localPageIndex,globalPageIndex:s.globalPageIndex,globalPageNumber:s.globalPageNumber,rectsPdfCoord:a,selectedText:n}))})}},"添加附注"))])}}const u=e.computed(()=>{const e=s.buildSelectionMenu,t={item:s.item,defaultMenu:c(s.item,a.value),createNote:s.createNote.value};if(e){const r=e(t);if(r)return r}return t.defaultMenu}),p=function(t,r){var s,a;const{provides:n}=b.useAnnotationCapability(),o=null==(s=null==r?void 0:r.markup)?void 0:s.annotationMenu,i=!1!==(null==(a=null==r?void 0:r.markup)?void 0:a.enabled),l=!1!==(null==o?void 0:o.enabled);return e.computed(()=>{const r="string"==typeof t?t:t.value;if(i&&l&&n.value)return t=>{const{context:s,rect:a,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=n.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:`${a.size.height+8}px`,bottom:(null==i?void 0:i.suggestTop)?`${a.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:oa,onClick:g},"删除");return e.h("div",l,[e.h("div",{style:m},[e.h("div",{style:na,role:"toolbar","aria-label":"划线标注"},[f])])])}})}(a,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)});return(t,s)=>r.item.isPlaceholder?e.createCommentVNode("",!0):(e.openBlock(),e.createBlock(e.unref(P.GlobalPointerProvider),{key:0,"document-id":a.value},{default:e.withCtx(()=>[e.createVNode(e.unref(I.Rotate),{"document-id":a.value,"page-index":o.value,style:{backgroundColor:"#fff"}},{default:e.withCtx(()=>[e.createVNode(e.unref(P.PagePointerProvider),{"document-id":a.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":a.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":a.value,"page-index":o.value,"selection-menu":u.value},null,8,["document-id","page-index","selection-menu"]),r.showRedactionLayer?(e.openBlock(),e.createBlock(e.unref(w.RedactionLayer),{key:0,"document-id":a.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":a.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(ta,{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(Ks,{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"]))}}),la=e.defineComponent({__name:"HoverBookmarkLayer",props:{item:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},hoverUi:{}},setup(r){const s=r,a=e.computed(()=>ra(s.item)),{provides:n}=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=n.value;if(!e)return;const t=e.forDocument(a.value).getState().geometry[s.item.localPageIndex];t&&(l.value=t)}e.watch([n,a,()=>s.item.localPageIndex],([e])=>{if(null==g||g(),g=null,cancelAnimationFrame(m),l.value=null,!e)return;const t=e.forDocument(a.value);g=t.onSelectionChange(f);let r=!1;const n=()=>{if(!r){try{if(f(),t.getState().geometry[s.item.localPageIndex])return}catch{}m=requestAnimationFrame(n)}};return n(),()=>{r=!0,cancelAnimationFrame(m),null==g||g(),g=null}},{immediate:!0});let v=null;e.watch([l,()=>s.pdfPageWidth,c,n],()=>{v&&(document.removeEventListener("mousemove",v),v=null),l.value&&s.pdfPageWidth&&(v=e=>{if(c.value)return;const t=n.value;if(t)try{if(t.forDocument(a.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 a=h.rectsWithinSlice(e,s.from,s.to);return 0===a.length?null:{lineRects:a,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,a=s.cssPageHeight/s.pdfPageHeight,n=u.value;return{iconLeft:Math.min((t.origin.x+t.size.width)*r+6,Math.max(0,s.cssPageWidth-n-2)),iconTop:t.origin.y*a+(t.size.height*a-n)/2,zoneLeft:Math.max(0,(t.origin.x+t.size.width)*r-4),zoneTop:Math.max(0,t.origin.y*a-4),size:n}});return(t,s)=>{var a;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==(a=p.value[p.value.length-1])?void 0:a.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)}}}),ha={key:0,width:"20",height:"20",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},da={key:1,width:"24",height:"24",viewBox:"0 0 28 28",fill:"none","aria-hidden":""},ca={key:0,x:"5",y:"4",width:"18",height:"20",rx:"3",fill:"#fde047"},ua={key:1,d:"M6 22h16",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},pa={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"},ga={key:3,d:"M5 14h18",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},ma={key:2,width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},fa=e.defineComponent({__name:"SelectionToolbarIcons",props:{kind:{}},setup:t=>(r,s)=>"copy"===t.kind?(e.openBlock(),e.createElementBlock("svg",ha,[...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",da,["highlight"===t.kind?(e.openBlock(),e.createElementBlock("rect",ca)):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",ua)):"squiggly"===t.kind?(e.openBlock(),e.createElementBlock("path",pa)):"strikeout"===t.kind?(e.openBlock(),e.createElementBlock("path",ga)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("svg",ma,[...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)])]))}),va=["title","aria-label","onMouseenter","onClick"],Pa=["title","onMouseenter","onClick"],Ia={style:{"font-size":"11px","font-weight":"600"}},Ca=e.defineComponent({__name:"SelectionToolbarCard",props:{placementAbove:{type:Boolean},anchorHeight:{},hiddenBuiltinActions:{},extraActions:{},renderCopyIcon:{type:Function}},emits:["action"],setup(t,{emit:r}){const s=t,a=r,n=[{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(()=>n.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=>a("action","copy"))},[t.renderCopyIcon?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(t.renderCopyIcon),{key:0})):(e.openBlock(),e.createBlock(fa,{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=>a("action",t.id)},[e.createVNode(fa,{kind:t.id},null,8,["kind"])],44,va))),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=>a("action",t.id)},[e.createElementVNode("span",Ia,e.toDisplayString(t.label.slice(0,2)),1)],44,Pa))),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=>a("action","note"))},[e.createVNode(fa,{kind:"note"})],36)],64)):e.createCommentVNode("",!0)],4))}}),ba={highlight:"highlight",underline:"underline",squiggly:"squiggly",strikeout:"strikeout"},wa=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 a=s,o=e.computed(()=>a.features),{hostRef:i}=Tr(o),l=e.computed(()=>{var e,t;return{background:(null==(t=null==(e=a.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 a=null==(s=null==(t=null==(e=r.value)?void 0:e.getPlugin(ft.id))?void 0:t.provides)?void 0:s.call(t);return a?e=>a.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 a.showNoteMarkers&&c.value&&!1!==(null==(t=null==(e=a.features)?void 0:e.notes)?void 0:t.enabled)}),g=e.computed(()=>{var e,t;return a.showBookmarkMarkers&&u.value&&!1!==(null==(t=null==(e=a.features)?void 0:e.bookmarks)?void 0:t.enabled)}),m=e.computed(()=>{var e,t;return u.value&&!1!==(null==(t=null==(e=a.features)?void 0:e.bookmarks)?void 0:t.enabled)}),f=function(s,a){const n=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=n.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=n.value)?void 0:t.enabled)&&(o.value||i.value||l.value||(null==(h=null==(r=n.value)?void 0:r.extraActions)?void 0:h.length)))return t=>{const r=ra(t.item),h=sa(t.item);return p=>{var g,m,f,v;return e.h("div",p.menuWrapperProps,e.h(Ca,{placementAbove:!!(null==(g=p.placement)?void 0:g.suggestTop),anchorHeight:p.rect.size.height,hiddenBuiltinActions:null==(m=n.value)?void 0:m.hiddenBuiltinActions,extraActions:null==(f=n.value)?void 0:f.extraActions,renderCopyIcon:null==(v=n.value)?void 0:v.renderCopyIcon,onAction:e=>{var n,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 aa(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==(n=null==a?void 0:a.onExtraAction)||n.call(a,e,t)}else{if(!d.value||!c.value||!o.value)return;E(r,ba[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;aa(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"))})}}}))}}})}(()=>a.features,{onExtraAction:a.onExtraSelectionAction}),v=e.computed(()=>{if(a.buildSelectionMenu||f.value)return e=>{const t=f.value?f.value(e):e.defaultMenu;return a.buildSelectionMenu?a.buildSelectionMenu({...e,defaultMenu:t}):t}}),{provides:P}=t.useCapability(n.DocumentManagerPlugin.id);function I(t){var r;const s=[];if(m.value){const r=function(t){var r,s,n,o;const i=ra(t),l=sa(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(la,{item:t,pdfPageWidth:h.size.width,pdfPageHeight:h.size.height,cssPageWidth:t.width,cssPageHeight:t.height,hoverUi:null==(o=null==(n=a.features)?void 0:n.bookmarks)?void 0:o.hover})}(t);r&&s.push(r)}const n=null==(r=a.renderPageOverlay)?void 0:r.call(a,t);if(n&&s.push(n),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,a,n,o;return[e.createVNode(ia,{item:t,features:s.features,"show-note-markers":p.value,"show-bookmark-markers":g.value,"show-redaction-layer":s.showRedactionLayer,"note-marker-ui":null==(a=null==(r=s.features)?void 0:r.notes)?void 0:a.marker,"bookmark-marker-ui":null==(o=null==(n=s.features)?void 0:n.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))}}),Sa={key:0,style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,width:"100%"}},ya=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{},onExtraSelectionAction:{type:Function}},setup(r){const s=r,a=e.computed(()=>function(e){if(e.options)return Sr(e.options);if(!e.editorOptions)throw new Error("ChapterPdfViewer: 请传入 `options`(推荐),或同时传入 `editorOptions` 与 `features`");const t=O(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,n)=>(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:a.value.plugins},{default:e.withCtx(({pluginsReady:t})=>[t?(e.openBlock(),e.createElementBlock("div",Sa,[e.renderSlot(s.$slots,"prepend"),e.createVNode(wa,{class:e.normalizeClass(r.viewportClassName),style:{flex:1,minHeight:0},features:a.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))}}),Ma={class:"chapter-tree-row"},xa=["aria-expanded"],$a={key:1,class:"chapter-tree-toggle-spacer","aria-hidden":""},La={class:"chapter-tree-label"},Da={class:"chapter-tree-meta"},ka={key:0},Ua=(e,t)=>{const r=e.__vccOpts||e;for(const[s,a]of t)r[s]=a;return r},Ta=Ua(e.defineComponent({__name:"ChapterTreeItem",props:{node:{},depth:{},activeChapterId:{},chapterStatus:{}},emits:["select"],setup(t){const r={idle:"未加载",loading:"加载中",loaded:"已加载",closed:"已卸载",error:"失败","password-required":"需密码"},s=t,a=e.computed(()=>s.node.children??[]),n=e.computed(()=>a.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(()=>!n.value);return(s,d)=>(e.openBlock(),e.createElementBlock("li",null,[e.createElementVNode("div",Ma,[n.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,xa)):(e.openBlock(),e.createElementBlock("span",$a)),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",La,e.toDisplayString(t.node.title),1),e.createElementVNode("div",Da,[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",ka,e.toDisplayString(r[l.value]),1)):e.createCommentVNode("",!0)])],2)]),n.value&&o.value?(e.openBlock(),e.createBlock(Ea,{key:0,nodes:a.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"]]),Ea=Ua(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,a=>(e.openBlock(),e.createBlock(Ta,{key:a.id,node:a,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"]]),Aa={class:"chapter-tree"},Fa={class:"chapter-tree-nav","aria-label":"章节目录"},Oa=Ua(e.defineComponent({__name:"ChapterTreePanel",props:{tree:{},activeChapterId:{}},emits:["active-chapter-change"],setup(r,{emit:s}){const a=r,n=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 a of r)e[a.id]=i.value.getChapterStatus(a.id),(null==(s=a.children)?void 0:s.length)&&t(a.children)};t(a.tree),l.value=e}e.watch([i,()=>a.tree],h,{immediate:!0});let d=null;function c(e){var t;n("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",Aa,[s[0]||(s[0]=e.createElementVNode("h2",{class:"chapter-tree-title"},"章节目录",-1)),e.createElementVNode("nav",Fa,[e.createVNode(Ea,{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"]]),Na=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{}},setup:t=>(t,r)=>(e.openBlock(),e.createBlock(e.unref(ya),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 za(e){const[t,r]=e.localPageRange;return r-t+1}function Ga(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 Ga(t)?t.segmentPageThreshold:null}function Ra(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 Ba(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function qa(e){const t=Va(e);if(!t)return null;const r=za(e),s=Ba(r,t),a=Ga(e.source)?e.source.urls:void 0,n=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;n.push({index:o,url:(null==a?void 0:a[o])??"",localPageStart:s,localPageEnd:i,documentId:Ra(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}function Ha(e,t){const r=qa(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 Wa(e,t){const r=qa(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 ja(e){var t;const r=Va(e);if(!r)return[];const s=[],{chapterId:a}=e,n=za(e);r<=0&&s.push(`${a}: segmentPageThreshold must be > 0`);const o=e.source;if(!Ga(o))return s;0===o.urls.length&&s.push(`${a}: source.urls must not be empty`);const i=Ba(n,r);o.urls.length!==i&&s.push(`${a}: 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(`${a}: source.urls[${l}] is empty`);return s}const Za={kind:"first-wins"};function Ya(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 Ka=class e extends a.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=a.createBehaviorEmitter(),this.manifestChange$=a.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(n.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?qa(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=[],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,a]=s.globalPageRange,[n,o]=s.localPageRange;if(e>a&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${a}]`),n>o&&t.push(`${s.chapterId}: invalid localPageRange [${n},${o}]`),a-e!==o-n&&t.push(`${s.chapterId}: page-count mismatch (global ${a-e+1} vs local ${o-n+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>a)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...ja(s))}return t}(t);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const s=new Set(this.chapterStatus.keys()),a=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Za){const r=function(e,t=Za){const r=new Map;for(const a of e.chapters){const[e,t]=a.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(a):r.set(s,[a])}}const s=new Map;for(const[a,n]of r)s.set(a,Ya(a,n,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const a=Array.from(r.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of a){const e=r.get(i),t=s.get(e);if(!t)continue;const[a]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-a);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Ja(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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?qa(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const a=r.segments[t];return!!a&&s.isDocumentOpen(a.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 a=this.chapterStatus.get(e);"loaded"!==a&&"password-required"!==a&&"error"!==a&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,a=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=Wa(t,e.localPageIndex);a.add(`${e.chapterId}:${r}`),a.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=n.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of a){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=qa(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 a=s.segments[t],n=a.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(r,a).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,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 a=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,a),a}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 a=(async()=>{const r=e.source;if(Ga(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,a);try{return await a}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 a=this.config.chapterPdfLoader,n={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==a?void 0:a.openPdf)?a.openPdf(n):{url:s}}async resolvePdfPayload(t,r){const s=t.source,a=this.config.chapterPdfLoader,n=Va(t);if(n){const s=Ba(za(t),n);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const a=await this.resolveChapterUrls(t);return a.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${a.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,a)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(Ga(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==a?void 0:a.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==a?void 0:a.loadPdf)return a.loadPdf(t,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const a=t.chapterId,n=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??a;0===n&&this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,i=await this.resolvePdfPayload(t,n),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(a),this.waitForTerminalStatus(a)}catch(i){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"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,a,n){if(a!==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?qa(t):null,a=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const n of s.segments)a(n.documentId);else a(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}}:{}}))}};Ka.id="chapter-manager";let Xa=Ka;function Qa(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function en(e,t){return`${e}#s${t}`}function tn(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 rn(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Qa(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)),a=Qa(e.source)?e.source.urls:void 0,n=[];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;n.push({index:l,url:(null==a?void 0:a[l])??"",localPageStart:s,localPageEnd:o,documentId:en(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}function sn(e){const[t,r]=e.localPageRange;return r-t+1}function an(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function nn(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return an(t)?t.segmentPageThreshold:null}function on(e,t){return`${e}#s${t}`}function ln(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 hn(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function dn(e){const t=nn(e);if(!t)return null;const r=sn(e),s=hn(r,t),a=an(e.source)?e.source.urls:void 0,n=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;n.push({index:o,url:(null==a?void 0:a[o])??"",localPageStart:s,localPageEnd:i,documentId:on(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}function cn(e,t){const r=dn(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 un(e,t){const r=dn(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 pn(e){var t;const r=nn(e);if(!r)return[];const s=[],{chapterId:a}=e,n=sn(e);r<=0&&s.push(`${a}: segmentPageThreshold must be > 0`);const o=e.source;if(!an(o))return s;0===o.urls.length&&s.push(`${a}: source.urls must not be empty`);const i=hn(n,r);o.urls.length!==i&&s.push(`${a}: 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(`${a}: source.urls[${l}] is empty`);return s}const gn={kind:"first-wins"};function mn(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 fn{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 vn=class e extends a.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=a.createBehaviorEmitter(),this.manifestChange$=a.createEmitter(),this.overlapStrategy=gn,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(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??gn,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=ln(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=ln(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=ln(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?cn(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?dn(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=[],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,a]=s.globalPageRange,[n,o]=s.localPageRange;if(e>a&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${a}]`),n>o&&t.push(`${s.chapterId}: invalid localPageRange [${n},${o}]`),a-e!==o-n&&t.push(`${s.chapterId}: page-count mismatch (global ${a-e+1} vs local ${o-n+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>a)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...pn(s))}return t}(t);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const s=new Set(this.chapterStatus.keys()),a=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=gn){const r=function(e,t=gn){const r=new Map;for(const a of e.chapters){const[e,t]=a.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(a):r.set(s,[a])}}const s=new Map;for(const[a,n]of r)s.set(a,mn(a,n,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const a=Array.from(r.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of a){const e=r.get(i),t=s.get(e);if(!t)continue;const[a]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-a);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new fn(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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?dn(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const a=r.segments[t];return!!a&&s.isDocumentOpen(a.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 a=this.chapterStatus.get(e);"loaded"!==a&&"password-required"!==a&&"error"!==a&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,a=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=un(t,e.localPageIndex);a.add(`${e.chapterId}:${r}`),a.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=n.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of a){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=cn(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=dn(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 a=s.segments[t],n=a.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(r,a).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,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 a=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,a),a}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 a=(async()=>{const r=e.source;if(an(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,a);try{return await a}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 a=this.config.chapterPdfLoader,n={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==a?void 0:a.openPdf)?a.openPdf(n):{url:s}}async resolvePdfPayload(t,r){const s=t.source,a=this.config.chapterPdfLoader,n=nn(t);if(n){const s=hn(sn(t),n);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const a=await this.resolveChapterUrls(t);return a.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${a.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,a)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(an(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==a?void 0:a.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==a?void 0:a.loadPdf)return a.loadPdf(t,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const a=t.chapterId,n=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??a;0===n&&this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,i=await this.resolvePdfPayload(t,n),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(a),this.waitForTerminalStatus(a)}catch(i){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"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,a,n){if(a!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=ln(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?dn(t):null,a=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const n of s.segments)a(n.documentId);else a(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}}:{}}))}};vn.id="chapter-manager";let Pn=vn;function In(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],a=t.items[r];if(s.globalPageIndex!==a.globalPageIndex||s.isPlaceholder!==a.isPlaceholder||s.chapterId!==a.chapterId||s.localPageIndex!==a.localPageIndex||s.pdfDocumentId!==a.pdfDocumentId||s.pdfPageIndex!==a.pdfPageIndex||s.offsetTop!==a.offsetTop||s.width!==a.width||s.height!==a.height)return!1}return!0}function Cn(e){const[t,r]=e.localPageRange;return r-t+1}function bn(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function wn(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return bn(t)?t.segmentPageThreshold:null}function Sn(e,t){return`${e}#s${t}`}function yn(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 Mn(e,t){return e<=0||t<=0?0:Math.ceil(e/t)}function xn(e){const t=wn(e);if(!t)return null;const r=Cn(e),s=Mn(r,t),a=bn(e.source)?e.source.urls:void 0,n=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;n.push({index:o,url:(null==a?void 0:a[o])??"",localPageStart:s,localPageEnd:i,documentId:Sn(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}function $n(e,t){const r=xn(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 Ln(e,t){const r=xn(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 Dn(e){var t;const r=wn(e);if(!r)return[];const s=[],{chapterId:a}=e,n=Cn(e);r<=0&&s.push(`${a}: segmentPageThreshold must be > 0`);const o=e.source;if(!bn(o))return s;0===o.urls.length&&s.push(`${a}: source.urls must not be empty`);const i=Mn(n,r);o.urls.length!==i&&s.push(`${a}: 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(`${a}: source.urls[${l}] is empty`);return s}(class extends a.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=a.createBehaviorEmitter(void 0,In),this.visibleChange$=a.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(Pn.id),this.documentManager=this.registry.getPlugin(n.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 a=r.getChapter(e);if(!a)return!0;const n=function(e,t){const r=rn(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)}(a,t);return!r.isSegmentLoaded(e,n)}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}=tn(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}=tn(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:a}=this.getPageSize(s);this.offsets[s]=t,t+=a+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 a=this.pageSizes.get(t.globalPageIndex);a&&a.width===s.width&&a.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),a=this.virtualPageMap.pagesOfChapter(e);if(!s||0===a.length)return;const n=rn(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var a;const n=o.getDocument(e);if(!(null==(a=null==n?void 0:n.pages)?void 0:a.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=n.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(n)for(const h of n.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,a.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}=tn(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 a=s;for(;a<e;){const e=this.getPageSize(a),t=this.offsets[a];if(e.height,t>=r)break;a++}const n=[];let o=s,i=-1;for(let l=s;l<a;l++){n.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,a=Math.max(0,Math.min(s,r)-Math.max(e,t));a>i&&(i=a,o=l)}this.currentVisible=n,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:n,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(n),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const a=t+r>>1;this.offsets[a]<=e?(s=a,t=a+1):r=a-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),a=[];if(this.virtualPageMap&&this.offsets.length>0)for(let n=t;n<=s;n++){const e=this.virtualPageMap.atIndex(n);if(!e)continue;const t=this.getPageSize(n),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);a.push({globalPageIndex:n,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[n]??0,isPlaceholder:s})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:a,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 a=(null==r?void 0:r.marginTop)??80,n=this.virtualPageMap.atIndex(e);if(!n)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(n.chapterId,n.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-a;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 kn={kind:"first-wins"};function Un(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 Tn=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 En=class e extends a.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=a.createBehaviorEmitter(),this.manifestChange$=a.createEmitter(),this.overlapStrategy=kn,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(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??kn,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{const{chapterId:t}=yn(e.id);this.findChapter(t)&&(this.passwordAttempts.delete(t),this.syncChapterStatusFromDocuments(t))}),this.documentManager.provides().onDocumentClosed(e=>{const{chapterId:t}=yn(e);this.findChapter(t)&&this.syncChapterStatusFromDocuments(t)}),this.documentManager.provides().onDocumentError(e=>{const{chapterId:t}=yn(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?$n(r,t):null},getSegmentPlan:e=>{const t=this.findChapter(e);return t?xn(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=[],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,a]=s.globalPageRange,[n,o]=s.localPageRange;if(e>a&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${a}]`),n>o&&t.push(`${s.chapterId}: invalid localPageRange [${n},${o}]`),a-e!==o-n&&t.push(`${s.chapterId}: page-count mismatch (global ${a-e+1} vs local ${o-n+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>a)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Dn(s))}return t}(t);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const s=new Set(this.chapterStatus.keys()),a=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=kn){const r=function(e,t=kn){const r=new Map;for(const a of e.chapters){const[e,t]=a.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(a):r.set(s,[a])}}const s=new Map;for(const[a,n]of r)s.set(a,Un(a,n,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const a=Array.from(r.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of a){const e=r.get(i),t=s.get(e);if(!t)continue;const[a]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-a);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Tn(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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?xn(t):null}isSegmentDocumentOpen(e,t){const r=this.getSegmentPlanForChapter(e),s=this.documentManager.provides();if(!r)return 0===t&&s.isDocumentOpen(e);const a=r.segments[t];return!!a&&s.isDocumentOpen(a.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 a=this.chapterStatus.get(e);"loaded"!==a&&"password-required"!==a&&"error"!==a&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,a=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=Ln(t,e.localPageIndex);a.add(`${e.chapterId}:${r}`),a.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=n.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of a){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=$n(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=xn(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 a=s.segments[t],n=a.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(r,a).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,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 a=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,a),a}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 a=(async()=>{const r=e.source;if(bn(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,a);try{return await a}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 a=this.config.chapterPdfLoader,n={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==a?void 0:a.openPdf)?a.openPdf(n):{url:s}}async resolvePdfPayload(t,r){const s=t.source,a=this.config.chapterPdfLoader,n=wn(t);if(n){const s=Mn(Cn(t),n);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const a=await this.resolveChapterUrls(t);return a.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${a.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,a)}if(0!==r)throw new Error(`Chapter "${t.chapterId}" is not segmented`);if(s){if(bn(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==a?void 0:a.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==a?void 0:a.loadPdf)return a.loadPdf(t,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const a=t.chapterId,n=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??a;0===n&&this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,i=await this.resolvePdfPayload(t,n),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(a),this.waitForTerminalStatus(a)}catch(i){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"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,a,n){if(a!==s.PdfErrorCode.Password){const e=this.getSegmentPlanForChapter(r),{segmentIndex:s}=yn(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?xn(t):null,a=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const n of s.segments)a(n.documentId);else a(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}}:{}}))}};En.id="chapter-manager";let An=En;function Fn(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function On(e,t){return`${e}#s${t}`}function Nn(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 zn(e){const t=function(e){if(null!=e.segmentPageThreshold&&e.segmentPageThreshold>0)return e.segmentPageThreshold;const t=e.source;return Fn(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)),a=Fn(e.source)?e.source.urls:void 0,n=[];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;n.push({index:l,url:(null==a?void 0:a[l])??"",localPageStart:s,localPageEnd:o,documentId:On(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}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 _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=Rn(e);if(!t)return null;const r=Gn(e),s=qn(r,t),a=Vn(e.source)?e.source.urls:void 0,n=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;n.push({index:o,url:(null==a?void 0:a[o])??"",localPageStart:s,localPageEnd:i,documentId:_n(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}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 Zn(e){var t;const r=Rn(e);if(!r)return[];const s=[],{chapterId:a}=e,n=Gn(e);r<=0&&s.push(`${a}: segmentPageThreshold must be > 0`);const o=e.source;if(!Vn(o))return s;0===o.urls.length&&s.push(`${a}: source.urls must not be empty`);const i=qn(n,r);o.urls.length!==i&&s.push(`${a}: 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(`${a}: source.urls[${l}] is empty`);return s}const Yn={kind:"first-wins"};function Jn(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 Kn=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 a.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=a.createBehaviorEmitter(),this.manifestChange$=a.createEmitter(),this.overlapStrategy=Yn,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(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Yn,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=[],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,a]=s.globalPageRange,[n,o]=s.localPageRange;if(e>a&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${a}]`),n>o&&t.push(`${s.chapterId}: invalid localPageRange [${n},${o}]`),a-e!==o-n&&t.push(`${s.chapterId}: page-count mismatch (global ${a-e+1} vs local ${o-n+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>a)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Zn(s))}return t}(t);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const s=new Set(this.chapterStatus.keys()),a=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Yn){const r=function(e,t=Yn){const r=new Map;for(const a of e.chapters){const[e,t]=a.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(a):r.set(s,[a])}}const s=new Map;for(const[a,n]of r)s.set(a,Jn(a,n,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const a=Array.from(r.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of a){const e=r.get(i),t=s.get(e);if(!t)continue;const[a]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-a);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Kn(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=r.segments[t];return!!a&&s.isDocumentOpen(a.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 a=this.chapterStatus.get(e);"loaded"!==a&&"password-required"!==a&&"error"!==a&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,a=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);a.add(`${e.chapterId}:${r}`),a.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=n.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of a){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 a=s.segments[t],n=a.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(r,a).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,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 a=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,a),a}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 a=(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,a);try{return await a}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 a=this.config.chapterPdfLoader,n={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==a?void 0:a.openPdf)?a.openPdf(n):{url:s}}async resolvePdfPayload(t,r){const s=t.source,a=this.config.chapterPdfLoader,n=Rn(t);if(n){const s=qn(Gn(t),n);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const a=await this.resolveChapterUrls(t);return a.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${a.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,a)}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==a?void 0:a.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==a?void 0:a.loadPdf)return a.loadPdf(t,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const a=t.chapterId,n=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??a;0===n&&this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,i=await this.resolvePdfPayload(t,n),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(a),this.waitForTerminalStatus(a)}catch(i){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"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,a,n){if(a!==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,a=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const n of s.segments)a(n.documentId);else a(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 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],a=t.items[r];if(s.globalPageIndex!==a.globalPageIndex||s.isPlaceholder!==a.isPlaceholder||s.chapterId!==a.chapterId||s.localPageIndex!==a.localPageIndex||s.pdfDocumentId!==a.pdfDocumentId||s.pdfPageIndex!==a.pdfPageIndex||s.offsetTop!==a.offsetTop||s.width!==a.width||s.height!==a.height)return!1}return!0}const to=class extends a.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=a.createBehaviorEmitter(void 0,eo),this.visibleChange$=a.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(Qn.id),this.documentManager=this.registry.getPlugin(n.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 a=r.getChapter(e);if(!a)return!0;const n=function(e,t){const r=zn(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)}(a,t);return!r.isSegmentLoaded(e,n)}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}=Nn(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}=Nn(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:a}=this.getPageSize(s);this.offsets[s]=t,t+=a+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 a=this.pageSizes.get(t.globalPageIndex);a&&a.width===s.width&&a.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),a=this.virtualPageMap.pagesOfChapter(e);if(!s||0===a.length)return;const n=zn(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var a;const n=o.getDocument(e);if(!(null==(a=null==n?void 0:n.pages)?void 0:a.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=n.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(n)for(const h of n.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,a.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}=Nn(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 a=s;for(;a<e;){const e=this.getPageSize(a),t=this.offsets[a];if(e.height,t>=r)break;a++}const n=[];let o=s,i=-1;for(let l=s;l<a;l++){n.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,a=Math.max(0,Math.min(s,r)-Math.max(e,t));a>i&&(i=a,o=l)}this.currentVisible=n,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:n,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(n),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const a=t+r>>1;this.offsets[a]<=e?(s=a,t=a+1):r=a-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),a=[];if(this.virtualPageMap&&this.offsets.length>0)for(let n=t;n<=s;n++){const e=this.virtualPageMap.atIndex(n);if(!e)continue;const t=this.getPageSize(n),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);a.push({globalPageIndex:n,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[n]??0,isPlaceholder:s})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:a,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 a=(null==r?void 0:r.marginTop)??80,n=this.virtualPageMap.atIndex(e);if(!n)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(n.chapterId,n.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-a;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 a.BasePlugin{constructor(e,t){super(e,t),this.notesChange$=a.createBehaviorEmitter([]),this.noteActivated$=a.createEmitter(),this.notes=new Map,this.chapterScroll=this.registry.getPlugin(ro.id),this.chapterManager=this.registry.getPlugin(An.id),this.documentManager=this.registry.getPlugin(n.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:no(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 a=null;try{a=await s(r)}catch(o){return this.logger.error(e.id,"OnCreateNote","Callback failed",o),null}if(!a)return null;const n={...r,noteId:a.noteId};return this.registerNote(n),n}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(a){return void this.logger.error(e.id,"OnDeleteNote","Callback failed",a)}this.notes.delete(t),this.notesChange$.emit(this.listAll())}}async updateNoteContent(t,r){var s,a;const n=this.notes.get(t);if(!n)return;const o={...n,content:r};try{await(null==(a=(s=this.config.callbacks).onUpdateNote)?void 0:a.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(),a=this.chapterManager.provides();await a.ensureAllSegmentsLoaded(r.chapterId);const n=a.resolvePageDocument(r.chapterId,r.localPageIndex);(null==(t=this.documentManager.provides().getDocument(n.documentId))?void 0:t.pages[n.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(()=>{a(),r(null)},2500),a=t.onLayoutChange(t=>{const n=t.items.find(t=>t.globalPageIndex===e&&!t.isPlaceholder);n&&(clearTimeout(s),a(),r(n))})})}};so.id="note";let ao=so;function no(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),a=io(e.source)?e.source.urls:void 0,n=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;n.push({index:o,url:(null==a?void 0:a[o])??"",localPageStart:s,localPageEnd:i,documentId:ho(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}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:a}=e,n=oo(e);r<=0&&s.push(`${a}: segmentPageThreshold must be > 0`);const o=e.source;if(!io(o))return s;0===o.urls.length&&s.push(`${a}: source.urls must not be empty`);const i=uo(n,r);o.urls.length!==i&&s.push(`${a}: 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(`${a}: 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 a.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=a.createBehaviorEmitter(),this.manifestChange$=a.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(n.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=[],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,a]=s.globalPageRange,[n,o]=s.localPageRange;if(e>a&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${a}]`),n>o&&t.push(`${s.chapterId}: invalid localPageRange [${n},${o}]`),a-e!==o-n&&t.push(`${s.chapterId}: page-count mismatch (global ${a-e+1} vs local ${o-n+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>a)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...fo(s))}return t}(t);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const s=new Set(this.chapterStatus.keys()),a=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=vo){const r=function(e,t=vo){const r=new Map;for(const a of e.chapters){const[e,t]=a.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(a):r.set(s,[a])}}const s=new Map;for(const[a,n]of r)s.set(a,Po(a,n,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const a=Array.from(r.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of a){const e=r.get(i),t=s.get(e);if(!t)continue;const[a]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-a);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new Io(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=r.segments[t];return!!a&&s.isDocumentOpen(a.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 a=this.chapterStatus.get(e);"loaded"!==a&&"password-required"!==a&&"error"!==a&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,a=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);a.add(`${e.chapterId}:${r}`),a.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=n.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of a){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 a=s.segments[t],n=a.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(r,a).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,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 a=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,a),a}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 a=(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,a);try{return await a}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 a=this.config.chapterPdfLoader,n={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==a?void 0:a.openPdf)?a.openPdf(n):{url:s}}async resolvePdfPayload(t,r){const s=t.source,a=this.config.chapterPdfLoader,n=lo(t);if(n){const s=uo(oo(t),n);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const a=await this.resolveChapterUrls(t);return a.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${a.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,a)}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==a?void 0:a.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==a?void 0:a.loadPdf)return a.loadPdf(t,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const a=t.chapterId,n=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??a;0===n&&this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,i=await this.resolvePdfPayload(t,n),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(a),this.waitForTerminalStatus(a)}catch(i){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"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,a,n){if(a!==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,a=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const n of s.segments)a(n.documentId);else a(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)),a=wo(e.source)?e.source.urls:void 0,n=[];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;n.push({index:l,url:(null==a?void 0:a[l])??"",localPageStart:s,localPageEnd:o,documentId:So(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}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),a=$o(e.source)?e.source.urls:void 0,n=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;n.push({index:o,url:(null==a?void 0:a[o])??"",localPageStart:s,localPageEnd:i,documentId:Do(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}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:a}=e,n=xo(e);r<=0&&s.push(`${a}: segmentPageThreshold must be > 0`);const o=e.source;if(!$o(o))return s;0===o.urls.length&&s.push(`${a}: source.urls must not be empty`);const i=Uo(n,r);o.urls.length!==i&&s.push(`${a}: 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(`${a}: source.urls[${l}] is empty`);return s}const Oo={kind:"first-wins"};function No(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 a.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=a.createBehaviorEmitter(),this.manifestChange$=a.createEmitter(),this.overlapStrategy=Oo,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(n.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Oo,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=[],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,a]=s.globalPageRange,[n,o]=s.localPageRange;if(e>a&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${a}]`),n>o&&t.push(`${s.chapterId}: invalid localPageRange [${n},${o}]`),a-e!==o-n&&t.push(`${s.chapterId}: page-count mismatch (global ${a-e+1} vs local ${o-n+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>a)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Fo(s))}return t}(t);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const s=new Set(this.chapterStatus.keys()),a=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=function(e,t=Oo){const r=function(e,t=Oo){const r=new Map;for(const a of e.chapters){const[e,t]=a.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(a):r.set(s,[a])}}const s=new Map;for(const[a,n]of r)s.set(a,No(a,n,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const a=Array.from(r.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of a){const e=r.get(i),t=s.get(e);if(!t)continue;const[a]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-a);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new zo(n)}(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=r.segments[t];return!!a&&s.isDocumentOpen(a.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 a=this.chapterStatus.get(e);"loaded"!==a&&"password-required"!==a&&"error"!==a&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,a=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);a.add(`${e.chapterId}:${r}`),a.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=n.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of a){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 a=s.segments[t],n=a.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(r,a).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,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 a=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,a),a}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 a=(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,a);try{return await a}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 a=this.config.chapterPdfLoader,n={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==a?void 0:a.openPdf)?a.openPdf(n):{url:s}}async resolvePdfPayload(t,r){const s=t.source,a=this.config.chapterPdfLoader,n=Lo(t);if(n){const s=Uo(xo(t),n);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const a=await this.resolveChapterUrls(t);return a.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${a.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,a)}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==a?void 0:a.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==a?void 0:a.loadPdf)return a.loadPdf(t,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const a=t.chapterId,n=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??a;0===n&&this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,i=await this.resolvePdfPayload(t,n),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(a),this.waitForTerminalStatus(a)}catch(i){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"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,a,n){if(a!==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,a=e=>{r.isDocumentOpen(e)&&r.closeDocument(e).wait(()=>{},()=>{})};if(s)for(const n of s.segments)a(n.documentId);else a(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 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],a=t.items[r];if(s.globalPageIndex!==a.globalPageIndex||s.isPlaceholder!==a.isPlaceholder||s.chapterId!==a.chapterId||s.localPageIndex!==a.localPageIndex||s.pdfDocumentId!==a.pdfDocumentId||s.pdfPageIndex!==a.pdfPageIndex||s.offsetTop!==a.offsetTop||s.width!==a.width||s.height!==a.height)return!1}return!0}const _o=class extends a.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=a.createBehaviorEmitter(void 0,Ro),this.visibleChange$=a.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(n.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 a=r.getChapter(e);if(!a)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)}(a,t);return!r.isSegmentLoaded(e,n)}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:a}=this.getPageSize(s);this.offsets[s]=t,t+=a+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 a=this.pageSizes.get(t.globalPageIndex);a&&a.width===s.width&&a.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),a=this.virtualPageMap.pagesOfChapter(e);if(!s||0===a.length)return;const n=Mo(s),o=this.documentManager.provides(),i=[],l=(e,t,r,s)=>{var a;const n=o.getDocument(e);if(!(null==(a=null==n?void 0:n.pages)?void 0:a.length))return!1;const l=this.getDocumentScale(e);for(let o=0;o<s;o++){const e=n.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(n)for(const h of n.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,a.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 a=s;for(;a<e;){const e=this.getPageSize(a),t=this.offsets[a];if(e.height,t>=r)break;a++}const n=[];let o=s,i=-1;for(let l=s;l<a;l++){n.push(l);const e=this.offsets[l],s=e+this.getPageSize(l).height,a=Math.max(0,Math.min(s,r)-Math.max(e,t));a>i&&(i=a,o=l)}this.currentVisible=n,this.currentGlobalPageIndex=o,this.visibleChange$.emit({visibleGlobalPageIndices:n,currentGlobalPageIndex:o}),this.chapterManager.provides().setVisibleGlobalPages(n),this.layoutChange$.emit(this.computeLayout())}findFirstVisibleIndex(e){let t=0,r=this.offsets.length-1,s=0;for(;t<=r;){const a=t+r>>1;this.offsets[a]<=e?(s=a,t=a+1):r=a-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),a=[];if(this.virtualPageMap&&this.offsets.length>0)for(let n=t;n<=s;n++){const e=this.virtualPageMap.atIndex(n);if(!e)continue;const t=this.getPageSize(n),r=this.chapterManager.provides().resolvePageDocument(e.chapterId,e.localPageIndex),s=this.isChapterPagePlaceholder(e.chapterId,e.localPageIndex);a.push({globalPageIndex:n,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[n]??0,isPlaceholder:s})}return{totalHeight:this.totalHeight,totalWidth:this.totalWidth||this.config.placeholderPageWidth,items:a,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 a=(null==r?void 0:r.marginTop)??80,n=this.virtualPageMap.atIndex(e);if(!n)return void this.scrollToIndex(e,r);const o=this.pageSizes.get(e),i=this.chapterManager.provides().resolvePageDocument(n.chapterId,n.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-a;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,a=t.origin.y,n=t.origin.y+t.size.height,o=Math.max(s,n)-Math.min(r,a);return o<=0?0:Math.max(0,Math.min(s,n)-Math.max(r,a))/o}function Wo(e,t){var r,s;if(e.chapterId!==t.chapterId||e.localPageIndex!==t.localPageIndex)return!1;const a=(null==(r=e.rectsPdfCoord)?void 0:r.length)?e.rectsPdfCoord:[e.rectPdfCoord],n=(null==(s=t.rectsPdfCoord)?void 0:s.length)?t.rectsPdfCoord:[t.rectPdfCoord],o=e.markerAnchor??qo(a),i=t.markerAnchor??qo(n);if(Math.hypot(o.x-i.x,o.y-i.y)<=6)return!0;for(const l of a)for(const e of n){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 a.BasePlugin{constructor(e,t){super(e,t),this.change$=a.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(Bo.id),this.chapterManager=this.registry.getPlugin(bo.id),this.documentManager=this.registry.getPlugin(n.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 a=this.entries.get(t);if(!a)return!1;const n=null==(s=null==(r=this.config)?void 0:r.callbacks)?void 0:s.onRequestRemove;if(n)try{if(!(await n(a)))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 a=t.anchor.globalPageIndex;if(void 0===a){const e=this.chapterManager.provides().getVirtualPageMap().toGlobal(t.anchor.chapterId,t.anchor.localPageIndex);if(!e)return;a=e.globalPageIndex}const n=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 a=setTimeout(()=>{n(),s(null)},r),n=e.onLayoutChange(e=>{const r=e.items.find(e=>e.globalPageIndex===t&&!e.isPlaceholder);r&&(clearTimeout(a),n(),s(r))})})}(e,t),e.scrollToGlobalPdfPoint(t,r,{marginTop:80})}(r,a,n)}};jo.id="paragraph-bookmark";let Zo=jo;function Yo(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 Jo(e){return!!e&&"urls"in e&&Array.isArray(e.urls)}function Ko(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 Jo(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)),a=Jo(e.source)?e.source.urls:void 0,n=[];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;n.push({index:l,url:(null==a?void 0:a[l])??"",localPageStart:s,localPageEnd:o,documentId:Ko(e.chapterId,l)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}(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=Yo(void 0,{enabled:!0}),t=Yo(void 0,{enabled:!0}),r=Yo(void 0,{enabled:!0}),s=Yo(void 0,{enabled:!0,min:.5,max:3,initial:1}),a=Yo(!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,a,n;return{annotation:null==(t=e.getPlugin(r.AnnotationPlugin.id))?void 0:t.provides(),note:null==(s=e.getPlugin(ao.id))?void 0:s.provides(),bookmark:null==(a=e.getPlugin(Zo.id))?void 0:a.provides(),chapterManager:null==(n=e.getPlugin(Xa.id))?void 0:n.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 ai(e,t,r){const s=ei(r),{annotation:a,note:n,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(!n)throw new Error("note 插件未注册");l.notes=n.listNotesForChapter(t)}if(s.markup){if(!a)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 a=[];for(const n of s.segments){if(!t.isSegmentLoaded(r,n.index))continue;const s=await ti(e.forDocument(n.documentId).exportAnnotations());for(const e of s){const t=e.annotation.pageIndex;a.push({...e,annotation:{...e.annotation,pageIndex:t+n.localPageStart}})}}return a}(a,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 ni(e,t,r){const s=ei(r),a=(null==r?void 0:r.mode)??"replace",{annotation:n,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"===a)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"===a)o.replaceNotesForChapter(h,t.notes);else for(const e of t.notes)o.registerNote(e)}if(s.markup&&t.markup){if(!n)throw new Error("annotation 插件未注册");await si(l,h,!1!==(null==r?void 0:r.ensureChapterLoaded)),function(e,t,r,s,a){const n=t.getSegmentPlan(r);if(!n){const t=e.forDocument(r);return"replace"===a&&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=n.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 n.segments){const t=e.forDocument(l.documentId),r=i.get(l.index)??[];"replace"===a&&t.deleteAllAnnotations(),r.length>0&&t.importAnnotations(r)}}(n,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),a)}(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),a=document.createElement("a");a.href=s,a.download=e,a.click(),URL.revokeObjectURL(s)}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),a=di(e.source)?e.source.urls:void 0,n=[];for(let o=0;o<s;o++){const s=o*t,i=Math.min(s+t-1,r-1);if(s>=r)break;n.push({index:o,url:(null==a?void 0:a[o])??"",localPageStart:s,localPageEnd:i,documentId:ui(e.chapterId,o)})}return{chapterId:e.chapterId,threshold:t,pageCount:r,segments:n}}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:a}=e,n=hi(e);r<=0&&s.push(`${a}: segmentPageThreshold must be > 0`);const o=e.source;if(!di(o))return s;0===o.urls.length&&s.push(`${a}: source.urls must not be empty`);const i=gi(n,r);o.urls.length!==i&&s.push(`${a}: 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(`${a}: 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 a of e.chapters){const[e,t]=a.globalPageRange;for(let s=e;s<=t;s++){const e=r.get(s);e?e.push(a):r.set(s,[a])}}const s=new Map;for(const[a,n]of r)s.set(a,Ci(a,n,t));return s}(e,t),s=new Map;for(const i of e.chapters)s.set(i.chapterId,i);const a=Array.from(r.keys()).sort((e,t)=>e-t),n=[];let o=0;for(const i of a){const e=r.get(i),t=s.get(e);if(!t)continue;const[a]=t.globalPageRange,[l]=t.localPageRange,h=l+(i-a);n.push({globalPageIndex:o++,globalPageNumber:i,chapterId:e,localPageIndex:h})}return new bi(n)}const Si=class e extends a.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=a.createBehaviorEmitter(),this.manifestChange$=a.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(n.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),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=[],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,a]=s.globalPageRange,[n,o]=s.localPageRange;if(e>a&&t.push(`${s.chapterId}: invalid globalPageRange [${e},${a}]`),n>o&&t.push(`${s.chapterId}: invalid localPageRange [${n},${o}]`),a-e!==o-n&&t.push(`${s.chapterId}: page-count mismatch (global ${a-e+1} vs local ${o-n+1})`),s.ownedGlobalPages)for(const r of s.ownedGlobalPages)(r<e||r>a)&&t.push(`${s.chapterId}: ownedGlobalPages contains ${r} outside range`);t.push(...Pi(s))}return t}(t);r.length>0&&this.logger.warn(e.id,"ManifestValidation",`Chapter manifest has issues: ${r.join("; ")}`);const s=new Set(this.chapterStatus.keys()),a=new Set(t.chapters.map(e=>e.chapterId));for(const e of s)a.has(e)||(this.closeChapter(e),this.chapterStatus.delete(e),this.chapterUrlsCache.delete(e),this.pendingChapterUrlsPromises.delete(e));for(const e of t.chapters)this.chapterStatus.has(e.chapterId)||this.chapterStatus.set(e.chapterId,"idle");this.manifest=t,this.virtualPageMap=wi(t,this.overlapStrategy),this.manifestChange$.emit({manifest:t,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 a=r.segments[t];return!!a&&s.isDocumentOpen(a.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 a=this.chapterStatus.get(e);"loaded"!==a&&"password-required"!==a&&"error"!==a&&this.updateStatus(e,"idle")}handleVisibleChange(e){if(!this.virtualPageMap)return;const t=Date.now(),r=this.config.prefetchChapters??1,s=new Set,a=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);a.add(`${e.chapterId}:${r}`),a.add(`${e.chapterId}:${r+1}`)}if(0===s.size)return;const n=this.manifest.chapters.map(e=>e.chapterId),o=new Set;for(const i of s){const e=n.indexOf(i);if(-1!==e)for(let t=e-r;t<=e+r;t++)t>=0&&t<n.length&&o.add(t)}for(const i of o){const e=n[i];this.chapterLastUsed.set(e,t),this.ensureChapterLoaded(e)}for(const i of a){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 a=s.segments[t],n=a.documentId;if(this.documentManager.provides().isDocumentOpen(n))return this.chapterLastUsed.set(e,Date.now()),0===t&&this.syncChapterStatusFromDocuments(e),Promise.resolve("loaded");const o=this.pendingSegmentLoadPromises.get(n);if(o)return o;const i=this.startLoadSegment(r,a).finally(()=>{this.pendingSegmentLoadPromises.delete(n)});return this.pendingSegmentLoadPromises.set(n,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 a=this.startLoadSegment(e,null).finally(()=>{this.pendingChapterLoadPromises.delete(t)});return this.pendingChapterLoadPromises.set(t,a),a}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 a=(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,a);try{return await a}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 a=this.config.chapterPdfLoader,n={chapter:e,segmentIndex:t,segmentCount:r.length,urls:r,url:s};return(null==a?void 0:a.openPdf)?a.openPdf(n):{url:s}}async resolvePdfPayload(t,r){const s=t.source,a=this.config.chapterPdfLoader,n=ci(t);if(n){const s=gi(hi(t),n);if(r<0||r>=s)throw new Error(`Chapter "${t.chapterId}" invalid segmentIndex ${r} (expected 0..${s-1})`);const a=await this.resolveChapterUrls(t);return a.length!==s&&this.logger.warn(e.id,"SegmentUrlCount",`Chapter "${t.chapterId}" urls.length (${a.length}) != expected (${s})`),this.openPayloadFromUrl(t,r,a)}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==a?void 0:a.loadChapterUrls){const e=await this.resolveChapterUrls(t);return this.openPayloadFromUrl(t,0,e)}if(null==a?void 0:a.loadPdf)return a.loadPdf(t,r);throw new Error(`Chapter "${t.chapterId}" has no PDF source; configure source or chapterPdfLoader`)}async startLoadSegment(t,r){var s;const a=t.chapterId,n=(null==r?void 0:r.index)??0,o=(null==r?void 0:r.documentId)??a;0===n&&this.updateStatus(a,"loading"),this.chapterLastUsed.set(a,Date.now());try{const e=t.encrypted&&(null==(s=this.passwordProvider)?void 0:s.getCachedPassword)?this.passwordProvider.getCachedPassword(a):null,i=await this.resolvePdfPayload(t,n),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(a),this.waitForTerminalStatus(a)}catch(i){const t=this.chapterStatus.get(a);if("loaded"!==t&&"password-required"!==t){const t=i instanceof Error?i.message:`Failed to load chapter "${a}"`;this.logger.error(e.id,"LoadChapter",t,i),0===n&&this.updateStatus(a,"error",t)}return this.chapterStatus.get(a)??"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,a,n){if(a!==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,a=e=>{if(r.isDocumentOpen(e)){r.closeDocument(e).wait(()=>{},()=>{})}};if(s)for(const n of s.segments)a(n.documentId);else a(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 a of e)t.push(Mi(a)),(null==(s=a.children)?void 0:s.length)&&r(a.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=V,exports.ChapterManagerPlugin=yi,exports.ChapterPdfViewer=Na,exports.ChapterTreePanel=Oa,exports.DEFAULT_CHAPTER_VIEWER_CONFIG={},exports.DEFAULT_CHAPTER_VIEWER_FEATURES=Pr,exports.PdfChapterViewport=wa,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=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 a of t.chapters){const t=await ai(e,a.chapterId,r),{chapterId:n,...o}=t;s[a.chapterId]=o}return{version:1,exportedAt:(new Date).toISOString(),chapters:s}},exports.exportChapterAnnotations=ai,exports.flattenChapterTree=xi,exports.importChapterAnnotations=ni,exports.importChapterAnnotationsArchive=async function(e,t,r){if(1!==t.version)throw new Error(`不支持的归档版本 ${t.version},当前为 1`);for(const[s,a]of Object.entries(t.chapters))await ni(e,{chapterId:s,...a},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;
2
2
  //# sourceMappingURL=index.cjs.map