@embedpdf-editor/vue3-chapter-viewer 0.3.1 → 0.3.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"),I=require("@embedpdf/plugin-redaction/vue"),y=require("@embedpdf/plugin-render/vue"),M=require("@embedpdf/engines/vue"),S={position:"relative",height:"100%",width:"100%"},x={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:0},strikeout:{offsetY:0}},k={highlight:s.PdfAnnotationSubtype.HIGHLIGHT,underline:s.PdfAnnotationSubtype.UNDERLINE,squiggly:s.PdfAnnotationSubtype.SQUIGGLY,strikeout:s.PdfAnnotationSubtype.STRIKEOUT};function L(e,t){return 0===t?e:e.map(e=>({origin:{x:e.origin.x,y:e.origin.y+t},size:{...e.size}}))}function $(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 T(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={...x[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?L(a.segmentRects,l):a.segmentRects,d="underline"===t||"squiggly"===t||"strikeout"===t?$(h):a.rect;n.createAnnotation(a.pageIndex,{id:e,created:new Date,flags:["print"],type:k[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}function D(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 z(e){const t=D(null==e?void 0:e.markup,{enabled:!0}),a=D(null==e?void 0:e.bookmarks,{enabled:!0}),s=D(null==e?void 0:e.notes,{enabled:!0});return{markup:t,bookmarks:a,notes:s,zoom:D(null==e?void 0:e.zoom,{enabled:!0,min:.5,max:3,initial:1}),selectionToolbar:D(void 0===(null==e?void 0:e.selectionToolbar)?!1!==t.enabled||!1!==s.enabled:e.selectionToolbar,{enabled:!0})}}class N{constructor(e){this.cb=e}resolvePassword(e,t){return this.cb(e,t)}}const O="chapter-manager",E={id:O,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}},G={kind:"first-wins"};function A(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 V=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 _=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=G,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??G,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=G){const a=function(e,t=G){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,A(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 V(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}}:{}}))}};_.id="chapter-manager";let R=_;const B={manifest:E,create:e=>new R(O,e),reducer:e=>e,initialState:{}},F="chapter-scroll",U={id:F,name:"Chapter Scroll Plugin",version:"0.1.0",provides:["chapter-scroll"],requires:["chapter-manager"],optional:[],defaultConfig:{placeholderPageHeight:1200,placeholderPageWidth:900,bufferSize:2,pageGap:20}},q={kind:"first-wins"};function H(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 W=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 j=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=q,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.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=>{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=q){const a=function(e,t=q){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,H(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 W(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}}:{}}))}};j.id="chapter-manager";let Z=j;function Y(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 J=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,Y),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(Z.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)}};J.id="chapter-scroll";let K=J;const X={manifest:U,create:e=>new K(F,e),reducer:e=>e,initialState:{}},Q="note",ee={id:Q,name:"Note Plugin",version:"0.1.0",provides:["note"],requires:["selection","chapter-scroll","chapter-manager"],optional:[],defaultConfig:{callbacks:{onCreateNote:async()=>null,onActivateNote:()=>{}},markerSize:18}},te={kind:"first-wins"};function ae(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 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 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 re=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=te,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??te,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=te){const a=function(e,t=te){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,ae(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 se(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}}:{}}))}};re.id="chapter-manager";let ie=re;const oe={kind:"first-wins"};function ne(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 le=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 he=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=oe,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??oe,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=oe){const a=function(e,t=oe){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,ne(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 le(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}}:{}}))}};he.id="chapter-manager";let de=he;function ce(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 ue=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,ce),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(de.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)}};ue.id="chapter-scroll";let pe=ue;const ge=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(pe.id),this.chapterManager=this.registry.getPlugin(ie.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:me(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))})})}};ge.id="note";let fe=ge;function me(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}const ve={manifest:ee,create:e=>new fe(Q,e),reducer:e=>e,initialState:{}},be="paragraph-bookmark",Pe={id:be,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}},we={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 Ie=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 ye=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=we,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??we,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=we){const a=function(e,t=we){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 Ie(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}}:{}}))}};ye.id="chapter-manager";let Me=ye;const Se={kind:"first-wins"};function xe(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 ke=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=Se,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??Se,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=Se){const a=function(e,t=Se){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,xe(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 ke(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 $e=Le;function Te(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 De=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,Te),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($e.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)}};De.id="chapter-scroll";let ze=De;function Ne(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 Oe(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Ee(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 Ge(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??Oe(r),n=t.markerAnchor??Oe(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(Ee(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 Ae(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:Ne(r),rectsPdfCoord:r,markerAnchor:Oe(r)}}const Ve=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.change$=r.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(ze.id),this.chapterManager=this.registry.getPlugin(Me.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(Ge(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)}};Ve.id="paragraph-bookmark";let _e=Ve;const Re={manifest:Pe,create:e=>new _e(be,e),reducer:e=>e,initialState:{}},Be={"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 Fe{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(Be);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=Ue(a.items,s,t.position)}return e}}function Ue(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 qe={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function He(e){var t,s,b,P,w,C;const I=e.toolbar??{},y=I.enabledModes??["view","annotate","shapes","insert","form","redact"],M=y.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 Fe;(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=qe[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}}({...I,enabledModes:y}),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?We(x.list()):{},...e.commands??{}},L=[r.createPluginRegistration(i.DocumentManagerPluginPackage,{initialDocuments:[]}),r.createPluginRegistration(B,{manifest:e.manifest,overlapStrategy:e.overlapStrategy,passwordProvider:e.passwordProvider,chapterPdfLoader:e.chapterPdfLoader,prefetchChapters:e.prefetchChapters,unloadTimeoutMs:e.unloadTimeoutMs}),r.createPluginRegistration(X,{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(ve,{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(Re,{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 We(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 je=z();function Ze(e){return He({...e,toolbar:e.toolbar??{enabledModes:[]},features:z(e.features)})}const Ye={overlapStrategy:{kind:"first-wins"},passwordProvider:new N(async()=>null),prefetchChapters:1,loadDefaultStampLibrary:!1,unloadTimeoutMs:12e4,toolbar:{enabledModes:[]}};function Je(e){return"callbacks"in e.notes?{manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,notes:e.notes.callbacks,bookmarks:e.bookmarks.callbacks}:e}function Ke(e){return{...Ye,manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,overlapStrategy:e.overlapStrategy??Ye.overlapStrategy,notes:{callbacks:e.notes},bookmarks:{callbacks:e.bookmarks},features:z(e.features)}}function Xe(e){const t=Ke(Je(e)),{plugins:a}=Ze(t);return{plugins:a,features:t.features,editorOptions:t}}function Qe(e,t=.5,a=3){return Math.min(a,Math.max(t,e))}function et(e,t,a){return Math.min(a,Math.max(t,e))}const tt={chapters:[]};function at(a){const s=e.ref(null),{provides:o}=t.useCapability(R.id),n=e.computed(()=>{var e;return(null==(e=o.value)?void 0:e.getManifest())??tt}),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){var 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(R.id),c=e.ref((null==(o=s.value)?void 0:o.initial)??1),u=e.ref(c.value),p=()=>{var e;return(null==(e=s.value)?void 0:e.min)??.5},g=()=>{var e;return(null==(e=s.value)?void 0:e.max)??3},f=()=>{var e;return null==(e=s.value)?void 0:e.pageWidth};function m(e){const t=Qe(e,p(),g());u.value=t,c.value=t,function(e,t,a,s=.5,i=3){const o=null==e?void 0:e.getStore();if(!o)return;const n=Qe(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,t,p(),g())}function v(e){f()?function(e){const t=f();if(!t||!h.value)return;const a=h.value.getDocument(e);a&&m(function(e,t,a=0){var s;const r=e.pages[a];return(null==(s=null==r?void 0:r.size)?void 0:s.width)?t/r.size.width:1}(a,t))}(e):m(u.value)}return e.watch([l,()=>{var e;return null==(e=s.value)?void 0:e.initial},()=>{var e;return null==(e=s.value)?void 0:e.pageWidth}],()=>{var e;l.value&&(f()||m((null==(e=s.value)?void 0:e.initial)??1))},{immediate:!0}),e.watch([d,n,()=>{var e;return null==(e=s.value)?void 0:e.pageWidth}],()=>{const e=d.value;if(e){for(const t of n.value.chapters)"loaded"===e.getChapterStatus(t.chapterId)&&v(t.chapterId);return e.onChapterStatusChange(e=>{"loaded"===e.status&&v(e.chapterId)})}},{immediate:!0}),{scale:c,setScale:m,zoomEnabled:()=>{var e;return!1!==(null==(e=s.value)?void 0:e.enabled)},minZoom:p,maxZoom:g}}(n,l);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=et(l,.1,10),a(et(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(et(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(),maxZoom:p()}))),{hostRef:s,scale:h,setScale:d,zoomEnabled:c}}const st={kind:"first-wins"};function rt(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 it{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 ot=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=st,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??st,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=st){const a=function(e,t=st){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,rt(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 it(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}}:{}}))}};ot.id="chapter-manager";let nt=ot;function lt(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 ht=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,lt),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(nt.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)}};ht.id="chapter-scroll";let dt=ht;const ct=["data-global-page-index","data-chapter-id","data-local-page-index"],ut=(e=>{const t=e.__vccOpts||e;for(const[a,s]of[["__scopeId","data-v-8a737137"]])t[a]=s;return t})(e.defineComponent({__name:"ChapterScroller",props:{class:{},style:{}},setup(a){const{provides:s}=t.useCapability(dt.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",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,ct))),128))],4)],6)}}})),pt=e.defineComponent({__name:"ChapterRenderLayer",props:{chapterId:{},localPageIndex:{},scale:{},dpr:{},class:{}},setup:t=>(a,s)=>(e.openBlock(),e.createBlock(e.unref(y.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"]))}),gt={kind:"first-wins"};function ft(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 vt=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=gt,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??gt,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=gt){const a=function(e,t=gt){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,ft(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}}:{}}))}};vt.id="chapter-manager";let bt=vt;const Pt={kind:"first-wins"};function wt(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 Ct{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 It=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Pt,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??Pt,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=Pt){const a=function(e,t=Pt){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,wt(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 Ct(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}}:{}}))}};It.id="chapter-manager";let yt=It;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 St=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(yt.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)}};St.id="chapter-scroll";let xt=St;const kt=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(xt.id),this.chapterManager=this.registry.getPlugin(bt.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:$t(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))})})}};kt.id="note";let Lt=kt;function $t(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Tt(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 Dt={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none",zIndex:25}},zt=["onMouseenter"],Nt=["data-note-marker-zone","onMouseenter","onMouseleave"],Ot=["onClick"],Et=["onClick"],Gt=["onClick"],At=e.defineComponent({__name:"NoteMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(a){const s=a,{provides:r}=t.useCapability(Lt.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}=Tt({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",Dt,[(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,zt))),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,Ot),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,Et),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,Gt)],36)):e.createCommentVNode("",!0)],44,Nt)):e.createCommentVNode("",!0)],64))),128))])):e.createCommentVNode("",!0)}}),Vt={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none"}},_t=["title","onClick"],Rt=["onClick"],Bt=e.defineComponent({__name:"BookmarkMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(a){const s=a,{provides:r}=t.useCapability(_e.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 Tt({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",Vt,[(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,_t),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,Rt)],512)):e.createCommentVNode("",!0)],36))),128))])):e.createCommentVNode("",!0)}});function Ft(e){return e.chapterId}function Ut(e,t){e.wait(t,()=>{})}const qt=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(()=>Ft(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){const r=s.createNote.value;if(r)return s=>{var i;const o={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==(i=s.placement)?void 0:i.suggestTop)?-40:s.rect.size.height+8};return e.h("div",s.menuWrapperProps,[e.h("div",{style:o},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);Ut(n.value.getSelectedText(a),a=>{var s,i,o;r((s=t,i=e,o=a.join("\n"),{chapterId:s.chapterId,localPageIndex:s.localPageIndex,globalPageIndex:s.globalPageIndex,globalPageNumber:s.globalPageNumber,rectsPdfCoord:i,selectedText:o}))})}},"添加附注"))])}}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=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},{default:e.withCtx(()=>[e.createVNode(e.unref(pt),{"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(I.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":a.annotationSelectionMenu},null,8,["document-id","page-index","selection-menu"]),a.showBookmarkMarkers&&l.value?(e.openBlock(),e.createBlock(Bt,{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),u.value?(e.openBlock(),e.createBlock(e.resolveDynamicComponent(u.value),{key:2})):e.createCommentVNode("",!0),a.showNoteMarkers&&l.value?(e.openBlock(),e.createBlock(At,{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"])]),_:3},8,["document-id","page-index"])]),_:3},8,["document-id"]))}}),Ht=e.defineComponent({__name:"HoverBookmarkLayer",props:{item:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},hoverUi:{}},setup(a){const s=a,r=e.computed(()=>Ft(s.item)),{provides:i}=t.useCapability(h.SelectionPlugin.id),{provides:o}=t.useCapability(_e.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)?Ae(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=>Ge(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)}}}),Wt={key:0,width:"24",height:"24",viewBox:"0 0 28 28",fill:"none","aria-hidden":""},jt={key:0,x:"5",y:"4",width:"18",height:"20",rx:"3",fill:"#fde047"},Zt={key:1,d:"M6 22h16",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},Yt={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"},Jt={key:3,d:"M5 14h18",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},Kt={key:1,width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},Xt=e.defineComponent({__name:"SelectionToolbarIcons",props:{kind:{}},setup:t=>(a,s)=>"note"!==t.kind?(e.openBlock(),e.createElementBlock("svg",Wt,["highlight"===t.kind?(e.openBlock(),e.createElementBlock("rect",jt)):e.createCommentVNode("",!0),s[0]||(s[0]=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",Zt)):"squiggly"===t.kind?(e.openBlock(),e.createElementBlock("path",Yt)):"strikeout"===t.kind?(e.openBlock(),e.createElementBlock("path",Jt)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("svg",Kt,[...s[1]||(s[1]=[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)])]))}),Qt=["title","aria-label","onMouseenter","onClick"],ea=["title","onMouseenter","onClick"],ta={style:{"font-size":"11px","font-weight":"600"}},aa=e.defineComponent({__name:"SelectionToolbarCard",props:{placementAbove:{type:Boolean},anchorHeight:{},hiddenBuiltinActions:{},extraActions:{}},emits:["action"],setup(t,{emit:a}){const s=t,r=a,i=[{id:"highlight",label:"高亮背景"},{id:"underline",label:"下划线"},{id:"squiggly",label:"波浪线"},{id:"strikeout",label:"删除线"},{id:"note",label:"添加笔记"}],o=e.computed(()=>new Set(s.hiddenBuiltinActions??[])),n=e.computed(()=>i.filter(e=>"note"!==e.id&&!o.value.has(e.id))),l=e.computed(()=>!o.value.has("note")),h=e.computed(()=>[...s.extraActions??[]].sort((e,t)=>(e.order??0)-(t.order??0))),d=e.ref(null),c=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 u(e,t=!1){return{display:"flex",alignItems:"center",justifyContent:"center",width:"32px",height:"32px",padding:0,margin:0,border:"none",borderRadius:"8px",background:d.value===e?t?"#fffbeb":"#f1f5f9":"transparent",color:t?"#b45309":"#334155",cursor:"pointer",flexShrink:0,WebkitAppearance:"none",appearance:"none"}}const p={width:"1px",height:"20px",margin:"0 4px",background:"rgba(15, 23, 42, 0.1)",flexShrink:0};return(t,a)=>(e.openBlock(),e.createElementBlock("div",{role:"toolbar","aria-label":"选区工具",style:e.normalizeStyle(c.value)},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.value,t=>(e.openBlock(),e.createElementBlock("button",{key:t.id,type:"button",title:t.label,"aria-label":t.label,style:e.normalizeStyle(u(t.id)),onMouseenter:e=>d.value=t.id,onMouseleave:a[0]||(a[0]=e=>d.value=null),onClick:e=>r("action",t.id)},[e.createVNode(Xt,{kind:t.id},null,8,["kind"])],44,Qt))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(h.value,t=>(e.openBlock(),e.createElementBlock("button",{key:t.id,type:"button",title:t.label,style:e.normalizeStyle(u(t.id)),onMouseenter:e=>d.value=t.id,onMouseleave:a[1]||(a[1]=e=>d.value=null),onClick:e=>r("action",t.id)},[e.createElementVNode("span",ta,e.toDisplayString(t.label.slice(0,2)),1)],44,ea))),128)),l.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createElementVNode("span",{style:p,"aria-hidden":""}),e.createElementVNode("button",{type:"button",title:"添加笔记","aria-label":"添加笔记",style:e.normalizeStyle(u("note",!0)),onMouseenter:a[2]||(a[2]=e=>d.value="note"),onMouseleave:a[3]||(a[3]=e=>d.value=null),onClick:a[4]||(a[4]=e=>r("action","note"))},[e.createVNode(Xt,{kind:"note"})],36)],64)):e.createCommentVNode("",!0)],4))}}),sa={highlight:"highlight",underline:"underline",squiggly:"squiggly",strikeout:"strikeout"},ra=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}=at(o),l=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(fe.id))?void 0:t.provides)?void 0:s.call(t);return r?e=>r.createNoteFromSelection(e):null})}(),d=function(){const{registry:a}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=a.value)?void 0:e.getPlugin(fe.id))})}(),c=function(){const{registry:a}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=a.value)?void 0:e.getPlugin(_e.id))})}(),u=e.computed(()=>{var e,t;return r.showNoteMarkers&&d.value&&!1!==(null==(t=null==(e=r.features)?void 0:e.notes)?void 0:t.enabled)}),p=e.computed(()=>{var e,t;return r.showBookmarkMarkers&&c.value&&!1!==(null==(t=null==(e=r.features)?void 0:e.bookmarks)?void 0:t.enabled)}),g=e.computed(()=>{var e,t;return c.value&&!1!==(null==(t=null==(e=r.features)?void 0:e.bookmarks)?void 0:t.enabled)}),f=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)}),{provides:l}=t.useCapability(h.SelectionPlugin.id),{provides:d}=t.useCapability(a.AnnotationPlugin.id),{provides:c}=t.useCapability(fe.id);return e.computed(()=>{var t,a,h;if(!1!==(null==(t=i.value)?void 0:t.enabled)&&(o.value||n.value||(null==(h=null==(a=i.value)?void 0:a.extraActions)?void 0:h.length)))return t=>{const a=Ft(t.item);return h=>{var u,p,g;return e.h("div",h.menuWrapperProps,e.h(aa,{placementAbove:!!(null==(u=h.placement)?void 0:u.suggestTop),anchorHeight:h.rect.size.height,hiddenBuiltinActions:null==(p=i.value)?void 0:p.hiddenBuiltinActions,extraActions:null==(g=i.value)?void 0:g.extraActions,onAction:e=>{var i,h,u;if("highlight"!==e&&"underline"!==e&&"squiggly"!==e&&"strikeout"!==e){if("note"===e){if(!l.value||!c.value||!n.value)return;const e=l.value.getHighlightRectsForPage(t.item.localPageIndex,a);return void Ut(l.value.getSelectedText(a),a=>{var s;null==(s=c.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(!l.value||!d.value||!o.value)return;T(a,sa[e],d.value,l.value,null==(u=null==(h=s())?void 0:h.markup)?void 0:u.styles)}}}))}}})}(()=>r.features,{onExtraAction:r.onExtraSelectionAction}),m=e.computed(()=>{if(r.buildSelectionMenu||f.value)return e=>{const t=f.value?f.value(e):e.defaultMenu;return r.buildSelectionMenu?r.buildSelectionMenu({...e,defaultMenu:t}):t}}),{provides:v}=t.useCapability(i.DocumentManagerPlugin.id);function b(t){var a;const s=[];if(g.value){const a=function(t){var a,s,i,o;const n=Ft(t),l=null==(s=null==(a=v.value)?void 0:a.getDocument(n))?void 0:s.pages[t.localPageIndex];return t.isPlaceholder||!l?null:e.h(Ht,{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(ut),{class:e.normalizeClass(s.className)},{page:e.withCtx(({item:t})=>{var a,r,i,o;return[e.createVNode(qt,{item:t,features:s.features,"show-note-markers":u.value,"show-bookmark-markers":p.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":m.value,"create-note":e.unref(l),"annotation-selection-menu":s.annotationSelectionMenu,"redaction-selection-menu":s.redactionSelectionMenu,"render-page-overlay":b},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"]),e.renderSlot(t.$slots,"default")],6))}}),ia={key:0,style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,width:"100%"}},oa=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 Xe(e.options);if(!e.editorOptions)throw new Error("ChapterPdfViewer: 请传入 `options`(推荐),或同时传入 `editorOptions` 与 `features`");const t=z(e.features),{plugins:a}=Ze({...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",ia,[e.renderSlot(s.$slots,"prepend"),e.createVNode(ra,{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))}}),na={class:"chapter-tree-row"},la=["aria-expanded"],ha={key:1,class:"chapter-tree-toggle-spacer","aria-hidden":""},da={class:"chapter-tree-label"},ca={class:"chapter-tree-meta"},ua={key:0},pa=(e,t)=>{const a=e.__vccOpts||e;for(const[s,r]of t)a[s]=r;return a},ga=pa(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",na,[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,la)):(e.openBlock(),e.createElementBlock("span",ha)),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",da,e.toDisplayString(t.node.title),1),e.createElementVNode("div",ca,[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",ua,e.toDisplayString(a[l.value]),1)):e.createCommentVNode("",!0)])],2)]),i.value&&o.value?(e.openBlock(),e.createBlock(fa,{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"]]),fa=pa(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(ga,{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"]]),ma={class:"chapter-tree"},va={class:"chapter-tree-nav","aria-label":"章节目录"},ba=pa(e.defineComponent({__name:"ChapterTreePanel",props:{tree:{},activeChapterId:{}},emits:["active-chapter-change"],setup(a,{emit:s}){const r=a,i=s,{provides:o}=t.useCapability(K.id),{provides:n}=t.useCapability(R.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",ma,[s[0]||(s[0]=e.createElementVNode("h2",{class:"chapter-tree-title"},"章节目录",-1)),e.createElementVNode("nav",va,[e.createVNode(fa,{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"]]),Pa=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{}},setup:t=>(t,a)=>(e.openBlock(),e.createBlock(e.unref(oa),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 wa={kind:"first-wins"};function Ca(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 Ia{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 ya(e,t=wa){const a=function(e,t=wa){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,Ca(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 Ia(i)}const Ma=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=wa,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??wa,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=ya(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}}:{}}))}};Ma.id="chapter-manager";let Sa=Ma;const xa={kind:"first-wins"};function ka(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 La=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 $a=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=xa,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??xa,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=xa){const a=function(e,t=xa){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,ka(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 La(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}}:{}}))}};$a.id="chapter-manager";let Ta=$a;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}}const Oa=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=function(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)}(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}}:{}}))}};Oa.id="chapter-manager";let Ea=Oa;function Ga(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,Ga),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(Ea.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 Aa={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=Aa,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Aa,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=Aa){const a=function(e,t=Aa){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)}}let qa=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 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}const Za=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)}};Za.id="chapter-scroll";let Ya=Za;const Ja=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(Ya.id),this.chapterManager=this.registry.getPlugin(Ba.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:Xa(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))})})}};Ja.id="note";let Ka=Ja;function Xa(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}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;const rs={kind:"first-wins"};function is(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 os{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 ns=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=rs,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??rs,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=rs){const a=function(e,t=rs){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,is(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 os(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}}:{}}))}};ns.id="chapter-manager";let ls=ns;function hs(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 ds=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,hs),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(ls.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)}};ds.id="chapter-scroll";let cs=ds;function us(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function ps(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 gs(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??us(r),n=t.markerAnchor??us(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(ps(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 fs=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.change$=r.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(cs.id),this.chapterManager=this.registry.getPlugin(ss.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(gs(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)}};fs.id="paragraph-bookmark";let ms=fs;function vs(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,function(){const e=vs(void 0,{enabled:!0}),t=vs(void 0,{enabled:!0}),a=vs(void 0,{enabled:!0});vs(void 0,{enabled:!0,min:.5,max:3,initial:1}),vs(!1!==e.enabled||!1!==a.enabled,{enabled:!0})}();function bs(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 Ps(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 ws(e){var t,s,r,i;return{annotation:null==(t=e.getPlugin(a.AnnotationPlugin.id))?void 0:t.provides(),note:null==(s=e.getPlugin(Ka.id))?void 0:s.provides(),bookmark:null==(r=e.getPlugin(ms.id))?void 0:r.provides(),chapterManager:null==(i=e.getPlugin(Ta.id))?void 0:i.provides()}}async function Cs(e,t,a){if(!a||!e)return;const s=await e.ensureChapterLoaded(t);if("loaded"!==s)throw new Error(`章节 ${t} 未加载成功(${s}),无法导入/导出划线`)}async function Is(e,t,a){const s=Ps(a),{annotation:r,note:i,bookmark:o,chapterManager:n}=ws(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 Cs(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:bs(t.data),mimeType:t.mimeType}}})}(e)}var h;return l}async function ys(e,t,a){const s=Ps(a),r=(null==a?void 0:a.mode)??"replace",{annotation:i,note:o,bookmark:n,chapterManager:l}=ws(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 Cs(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 Ms(e){return JSON.stringify(e,null,2)}function Ss(e){return JSON.stringify(e,null,2)}function xs(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 ks(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 Ls(e){const t=[],a=e=>{var s;for(const r of e)t.push(ks(r)),(null==(s=r.children)?void 0:s.length)&&a(r.children)};return a(e),t}function $s(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)?$s(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=N,exports.ChapterManagerPlugin=Sa,exports.ChapterPdfViewer=Pa,exports.ChapterTreePanel=ba,exports.DEFAULT_CHAPTER_VIEWER_CONFIG={},exports.DEFAULT_CHAPTER_VIEWER_FEATURES=je,exports.PdfChapterViewport=ra,exports.applySelectionMarkup=T,exports.buildChapterViewerCatalog=function(e){return{tree:$s(e),manifest:{chapters:Ls(e)}}},exports.buildParagraphBookmarkAnchor=Ae,exports.chapterAnnotationsArchiveToJson=Ms,exports.chapterAnnotationsSnapshotToJson=Ss,exports.chapterDescriptorFromTreeNode=ks,exports.createChapterViewerBundle=Xe,exports.createChapterViewerEditor=Ze,exports.createChapterViewerEditorOptions=function(e){const{features:t,...a}=Ke(Je(e));return a},exports.createPdfChapterEditor=He,exports.defaultOverlapStrategy={kind:"first-wins"},exports.downloadChapterAnnotationsArchive=function(e,t="chapter-annotations.json"){xs(t,Ms(e))},exports.downloadChapterAnnotationsSnapshot=function(e,t){xs(t??`chapter-annotations-${e.chapterId}.json`,Ss(e))},exports.downloadJsonFile=xs,exports.exportAllChapterAnnotations=async function(e,t,a){const s={};for(const r of t.chapters){const t=await Is(e,r.chapterId,a),{chapterId:i,...o}=t;s[r.chapterId]=o}return{version:1,exportedAt:(new Date).toISOString(),chapters:s}},exports.exportChapterAnnotations=Is,exports.flattenChapterTree=Ls,exports.importChapterAnnotations=ys,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 ys(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=$s;
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"),I=require("@embedpdf/plugin-redaction/vue"),y=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={highlight:{offsetY:0},underline:{offsetY:2.5},squiggly:{offsetY:4},strikeout:{offsetY:0}},$={highlight:s.PdfAnnotationSubtype.HIGHLIGHT,underline:s.PdfAnnotationSubtype.UNDERLINE,squiggly:s.PdfAnnotationSubtype.SQUIGGLY,strikeout:s.PdfAnnotationSubtype.STRIKEOUT};function T(e,t){return 0===t?e:e.map(e=>({origin:{x:e.origin.x,y:e.origin.y+t},size:{...e.size}}))}function D(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 z(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={...L[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?T(a.segmentRects,l):a.segmentRects,d="underline"===t||"squiggly"===t||"strikeout"===t?D(h):a.rect;n.createAnnotation(a.pageIndex,{id:e,created:new Date,flags:["print"],type:$[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 N=new Set([s.PdfAnnotationSubtype.HIGHLIGHT,s.PdfAnnotationSubtype.UNDERLINE,s.PdfAnnotationSubtype.SQUIGGLY,s.PdfAnnotationSubtype.STRIKEOUT]);function O(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 E(e){const t=O(null==e?void 0:e.markup,{enabled:!0}),a=O(null==e?void 0:e.bookmarks,{enabled:!0}),s=O(null==e?void 0:e.notes,{enabled:!0});return{markup:t,bookmarks:a,notes:s,zoom:O(null==e?void 0:e.zoom,{enabled:!0,min:.5,max:3,initial:1}),selectionToolbar:O(void 0===(null==e?void 0:e.selectionToolbar)?!1!==t.enabled||!1!==s.enabled:e.selectionToolbar,{enabled:!0})}}class G{constructor(e){this.cb=e}resolvePassword(e,t){return this.cb(e,t)}}const A="chapter-manager",V={id:A,name:"Chapter Manager Plugin",version:"0.1.0",provides:["chapter-manager"],requires:["document-manager"],optional:[],defaultConfig:{manifest:{chapters:[]},prefetchChapters:1,unloadTimeoutMs:6e4,autoActivateOnLoad:!0}},_={kind:"first-wins"};function R(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 B=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 F=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=_,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??_,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=_){const a=function(e,t=_){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,R(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 B(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}}:{}}))}};F.id="chapter-manager";let U=F;const q={manifest:V,create:e=>new U(A,e),reducer:e=>e,initialState:{}},H="chapter-scroll",W={id:H,name:"Chapter Scroll Plugin",version:"0.1.0",provides:["chapter-scroll"],requires:["chapter-manager"],optional:[],defaultConfig:{placeholderPageHeight:1200,placeholderPageWidth:900,bufferSize:2,pageGap:20}},j={kind:"first-wins"};function Z(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 Y=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 J=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=j,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??j,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=j){const a=function(e,t=j){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,Z(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 Y(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}}:{}}))}};J.id="chapter-manager";let K=J;function X(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 Q=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,X),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(K.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)}};Q.id="chapter-scroll";let ee=Q;const te={manifest:W,create:e=>new ee(H,e),reducer:e=>e,initialState:{}},ae="note",se={id:ae,name:"Note Plugin",version:"0.1.0",provides:["note"],requires:["selection","chapter-scroll","chapter-manager"],optional:[],defaultConfig:{callbacks:{onCreateNote:async()=>null,onActivateNote:()=>{}},markerSize:18}},re={kind:"first-wins"};function ie(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 oe=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 ne=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=re,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??re,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=re){const a=function(e,t=re){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,ie(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 oe(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}}:{}}))}};ne.id="chapter-manager";let le=ne;const he={kind:"first-wins"};function de(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 ce=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 ue=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=he,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??he,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=he){const a=function(e,t=he){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,de(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 ce(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}}:{}}))}};ue.id="chapter-manager";let pe=ue;function ge(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 fe=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,ge),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(pe.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)}};fe.id="chapter-scroll";let me=fe;const ve=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(me.id),this.chapterManager=this.registry.getPlugin(le.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:Pe(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))})})}};ve.id="note";let be=ve;function Pe(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}const we={manifest:se,create:e=>new be(ae,e),reducer:e=>e,initialState:{}},Ce="paragraph-bookmark",Ie={id:Ce,name:"Paragraph Bookmark Plugin",version:"0.1.0",provides:["paragraph-bookmark"],requires:["chapter-scroll","chapter-manager"],optional:[],defaultConfig:{}},ye={kind:"first-wins"};function Me(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 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 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 xe=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=ye,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??ye,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=ye){const a=function(e,t=ye){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,Me(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 Se(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}}:{}}))}};xe.id="chapter-manager";let ke=xe;const Le={kind:"first-wins"};function $e(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 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 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 De=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Le,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??Le,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=Le){const a=function(e,t=Le){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,$e(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 Te(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}}:{}}))}};De.id="chapter-manager";let ze=De;function Ne(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 Oe=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,Ne),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(ze.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)}};Oe.id="chapter-scroll";let Ee=Oe;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 Ae(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Ve(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 _e(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??Ae(r),n=t.markerAnchor??Ae(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(Ve(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 Re(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:Ae(r)}}const Be=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.change$=r.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(Ee.id),this.chapterManager=this.registry.getPlugin(ke.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(_e(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)}};Be.id="paragraph-bookmark";let Fe=Be;const Ue={manifest:Ie,create:e=>new Fe(Ce,e),reducer:e=>e,initialState:{}},qe={"annotation-toolbar":{id:"annotation-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"],show:["overflow-annotation-tools"]},md:{minWidth:640,hide:["overflow-annotation-tools"],show:["add-text","add-ink","add-ink-highlighter","add-insert-text","add-replace-text","add-comment","add-callout"]}}},permanent:!1,categories:["annotation"],items:[{type:"spacer",id:"spacer-3",flex:!0},{type:"group",id:"annotation-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-highlight",commandId:"annotation:add-highlight",variant:"icon",categories:["annotation","annotation-markup","annotation-highlight"]},{type:"command-button",id:"add-strikeout",commandId:"annotation:add-strikeout",variant:"icon",categories:["annotation","annotation-markup","annotation-strikeout"]},{type:"command-button",id:"add-underline",commandId:"annotation:add-underline",variant:"icon",categories:["annotation","annotation-markup","annotation-underline"]},{type:"command-button",id:"add-squiggly",commandId:"annotation:add-squiggly",variant:"icon",categories:["annotation","annotation-markup","annotation-squiggly"]},{type:"command-button",id:"add-ink",commandId:"annotation:add-ink",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-ink-highlighter",commandId:"annotation:add-ink-highlighter",variant:"icon",categories:["annotation","annotation-ink"]},{type:"command-button",id:"add-text",commandId:"annotation:add-text",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"add-insert-text",commandId:"annotation:add-insert-text",variant:"icon",categories:["annotation","annotation-markup","annotation-insert-text"]},{type:"command-button",id:"add-replace-text",commandId:"annotation:add-replace-text",variant:"icon",categories:["annotation","annotation-markup","annotation-replace-text"]},{type:"command-button",id:"add-comment",commandId:"annotation:add-comment",variant:"icon",categories:["annotation","annotation-comment-tool"]},{type:"command-button",id:"add-callout",commandId:"annotation:add-callout",variant:"icon",categories:["annotation","annotation-text"]},{type:"command-button",id:"overflow-annotation-tools",commandId:"annotation:overflow-tools",variant:"icon",categories:["annotation","annotation-overflow"]},{type:"divider",id:"annotation-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"annotation-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-4",flex:!0}]},"shapes-toolbar":{id:"shapes-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-polygon","add-polyline"],show:["overflow-shapes-tools"]},md:{minWidth:640,hide:["overflow-shapes-tools"],show:["add-polygon","add-polyline"]}}},permanent:!1,categories:["annotation","annotation-shape"],items:[{type:"spacer",id:"spacer-5",flex:!0},{type:"group",id:"shapes-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rectangle",commandId:"annotation:add-rectangle",variant:"icon",categories:["annotation","annotation-shape","annotation-rectangle"]},{type:"command-button",id:"add-circle",commandId:"annotation:add-circle",variant:"icon",categories:["annotation","annotation-shape","annotation-circle"]},{type:"command-button",id:"add-line",commandId:"annotation:add-line",variant:"icon",categories:["annotation","annotation-shape","annotation-line"]},{type:"command-button",id:"add-arrow",commandId:"annotation:add-arrow",variant:"icon",categories:["annotation","annotation-shape","annotation-arrow"]},{type:"command-button",id:"add-polygon",commandId:"annotation:add-polygon",variant:"icon",categories:["annotation","annotation-shape","annotation-polygon"]},{type:"command-button",id:"add-polyline",commandId:"annotation:add-polyline",variant:"icon",categories:["annotation","annotation-shape","annotation-polyline"]},{type:"command-button",id:"overflow-shapes-tools",commandId:"annotation:overflow-shapes",variant:"icon",categories:["annotation","annotation-shape","annotation-overflow"]},{type:"divider",id:"shapes-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"shapes-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-6",flex:!0}]},"form-toolbar":{id:"form-toolbar",position:{placement:"top",slot:"secondary",order:0},responsive:{breakpoints:{sm:{maxWidth:640,hide:["add-form-select","add-form-listbox"],show:["overflow-forms-tools"]},md:{minWidth:640,hide:["overflow-forms-tools"],show:["add-form-select","add-form-listbox"]}}},permanent:!1,categories:["form"],items:[{type:"spacer",id:"spacer-form-1",flex:!0},{type:"group",id:"form-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-form-textfield",commandId:"form:add-textfield",variant:"icon",categories:["form","form-textfield"]},{type:"command-button",id:"add-form-checkbox",commandId:"form:add-checkbox",variant:"icon",categories:["form","form-checkbox"]},{type:"command-button",id:"add-form-radio",commandId:"form:add-radio",variant:"icon",categories:["form","form-radio"]},{type:"command-button",id:"add-form-select",commandId:"form:add-select",variant:"icon",categories:["form","form-select"]},{type:"command-button",id:"add-form-listbox",commandId:"form:add-listbox",variant:"icon",categories:["form","form-listbox"]},{type:"command-button",id:"overflow-forms-tools",commandId:"form:overflow-tools",variant:"icon",categories:["form","form-overflow"]},{type:"divider",id:"form-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"command-button",id:"toggle-form-fill-mode",commandId:"form:toggle-fill-mode",variant:"icon",categories:["form","form-fill-mode"]},{type:"divider",id:"form-tools-divider-2",orientation:"vertical"},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-form-2",flex:!0}]},"insert-toolbar":{id:"insert-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["insert"],items:[{type:"spacer",id:"spacer-insert-1",flex:!0},{type:"group",id:"insert-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"add-rubber-stamp",commandId:"insert:add-rubber-stamp",variant:"icon",categories:["insert","insert-rubber-stamp"]},{type:"command-button",id:"add-signature",commandId:"insert:add-signature",variant:"icon",categories:["insert","insert-signature"]},{type:"command-button",id:"add-image",commandId:"insert:add-image",variant:"icon",categories:["insert","insert-image"]},{type:"divider",id:"insert-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"insert-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-insert-2",flex:!0}]},"redaction-toolbar":{id:"redaction-toolbar",position:{placement:"top",slot:"secondary",order:0},permanent:!1,categories:["redaction"],items:[{type:"spacer",id:"spacer-7",flex:!0},{type:"group",id:"redaction-tools",alignment:"start",gap:2,items:[{type:"command-button",id:"redact",commandId:"redaction:redact",variant:"icon",categories:["redaction","redaction-combined"]},{type:"divider",id:"redaction-tools-divider-1",orientation:"vertical"},{type:"command-button",id:"toggle-redaction-panel",commandId:"panel:toggle-redaction",variant:"icon",categories:["panel","panel-redaction"]},{type:"command-button",id:"toggle-annotation-style",commandId:"panel:toggle-annotation-style",variant:"icon",categories:["panel","panel-annotation-style"]},{type:"divider",id:"redaction-tools-divider-2",orientation:"vertical",visibilityDependsOn:{itemIds:["toggle-annotation-style"]}},{type:"command-button",id:"undo-button",commandId:"history:undo",variant:"icon",categories:["history","history-undo"]},{type:"command-button",id:"redo-button",commandId:"history:redo",variant:"icon",categories:["history","history-redo"]}]},{type:"spacer",id:"spacer-8",flex:!0}]}};class He{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(qe);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=We(a.items,s,t.position)}return e}}function We(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 je={annotate:"annotation-toolbar",shapes:"shapes-toolbar",insert:"insert-toolbar",form:"form-toolbar",redact:"redaction-toolbar"};function Ze(e){var t,s,b,P,w,C;const I=e.toolbar??{},y=I.enabledModes??["view","annotate","shapes","insert","form","redact"],M=y.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 He;(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=je[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}}({...I,enabledModes:y}),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?Ye(x.list()):{},...e.commands??{}},L=[r.createPluginRegistration(i.DocumentManagerPluginPackage,{initialDocuments:[]}),r.createPluginRegistration(q,{manifest:e.manifest,overlapStrategy:e.overlapStrategy,passwordProvider:e.passwordProvider,chapterPdfLoader:e.chapterPdfLoader,prefetchChapters:e.prefetchChapters,unloadTimeoutMs:e.unloadTimeoutMs}),r.createPluginRegistration(te,{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(we,{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(Ue,{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 Ye(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 Je=E();function Ke(e){return Ze({...e,toolbar:e.toolbar??{enabledModes:[]},features:E(e.features)})}const Xe={overlapStrategy:{kind:"first-wins"},passwordProvider:new G(async()=>null),prefetchChapters:1,loadDefaultStampLibrary:!1,unloadTimeoutMs:12e4,toolbar:{enabledModes:[]}};function Qe(e){return"callbacks"in e.notes?{manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,notes:e.notes.callbacks,bookmarks:e.bookmarks.callbacks}:e}function et(e){return{...Xe,manifest:e.manifest,chapterPdfLoader:e.chapterPdfLoader,overlapStrategy:e.overlapStrategy??Xe.overlapStrategy,notes:{callbacks:e.notes},bookmarks:{callbacks:e.bookmarks},features:E(e.features)}}function tt(e){const t=et(Qe(e)),{plugins:a}=Ke(t);return{plugins:a,features:t.features,editorOptions:t}}function at(e,t=.5,a=3){return Math.min(a,Math.max(t,e))}function st(e,t,a){return Math.min(a,Math.max(t,e))}const rt={chapters:[]};function it(a){const s=e.ref(null),{provides:o}=t.useCapability(U.id),n=e.computed(()=>{var e;return(null==(e=o.value)?void 0:e.getManifest())??rt}),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){var 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(U.id),c=e.ref((null==(o=s.value)?void 0:o.initial)??1),u=e.ref(c.value),p=()=>{var e;return(null==(e=s.value)?void 0:e.min)??.5},g=()=>{var e;return(null==(e=s.value)?void 0:e.max)??3},f=()=>{var e;return null==(e=s.value)?void 0:e.pageWidth};function m(e){const t=at(e,p(),g());u.value=t,c.value=t,function(e,t,a,s=.5,i=3){const o=null==e?void 0:e.getStore();if(!o)return;const n=at(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,t,p(),g())}function v(e){f()?function(e){const t=f();if(!t||!h.value)return;const a=h.value.getDocument(e);a&&m(function(e,t,a=0){var s;const r=e.pages[a];return(null==(s=null==r?void 0:r.size)?void 0:s.width)?t/r.size.width:1}(a,t))}(e):m(u.value)}return e.watch([l,()=>{var e;return null==(e=s.value)?void 0:e.initial},()=>{var e;return null==(e=s.value)?void 0:e.pageWidth}],()=>{var e;l.value&&(f()||m((null==(e=s.value)?void 0:e.initial)??1))},{immediate:!0}),e.watch([d,n,()=>{var e;return null==(e=s.value)?void 0:e.pageWidth}],()=>{const e=d.value;if(e){for(const t of n.value.chapters)"loaded"===e.getChapterStatus(t.chapterId)&&v(t.chapterId);return e.onChapterStatusChange(e=>{"loaded"===e.status&&v(e.chapterId)})}},{immediate:!0}),{scale:c,setScale:m,zoomEnabled:()=>{var e;return!1!==(null==(e=s.value)?void 0:e.enabled)},minZoom:p,maxZoom:g}}(n,l);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=st(l,.1,10),a(st(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(st(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(),maxZoom:p()}))),{hostRef:s,scale:h,setScale:d,zoomEnabled:c}}const ot={kind:"first-wins"};function nt(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 lt{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 ht=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=ot,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??ot,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=ot){const a=function(e,t=ot){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,nt(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 lt(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}}:{}}))}};ht.id="chapter-manager";let dt=ht;function ct(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 ut=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,ct),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)}};ut.id="chapter-scroll";let pt=ut;const gt=["data-global-page-index","data-chapter-id","data-local-page-index"],ft=(e=>{const t=e.__vccOpts||e;for(const[a,s]of[["__scopeId","data-v-8a737137"]])t[a]=s;return t})(e.defineComponent({__name:"ChapterScroller",props:{class:{},style:{}},setup(a){const{provides:s}=t.useCapability(pt.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",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,gt))),128))],4)],6)}}})),mt=e.defineComponent({__name:"ChapterRenderLayer",props:{chapterId:{},localPageIndex:{},scale:{},dpr:{},class:{}},setup:t=>(a,s)=>(e.openBlock(),e.createBlock(e.unref(y.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"]))}),vt={kind:"first-wins"};function bt(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 Pt=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 wt=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=vt,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??vt,this.documentManagerUnsubs.push(this.documentManager.provides().onDocumentOpened(e=>{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=vt){const a=function(e,t=vt){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,bt(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}}:{}}))}};wt.id="chapter-manager";let Ct=wt;const It={kind:"first-wins"};function yt(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 Mt{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=It,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.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=>{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=It){const a=function(e,t=It){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,yt(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;function kt(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 Lt=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,kt),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(xt.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)}};Lt.id="chapter-scroll";let $t=Lt;const Tt=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($t.id),this.chapterManager=this.registry.getPlugin(Ct.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:zt(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))})})}};Tt.id="note";let Dt=Tt;function zt(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function Nt(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 Ot={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none",zIndex:25}},Et=["onMouseenter"],Gt=["data-note-marker-zone","onMouseenter","onMouseleave"],At=["onClick"],Vt=["onClick"],_t=["onClick"],Rt=e.defineComponent({__name:"NoteMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(a){const s=a,{provides:r}=t.useCapability(Dt.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}=Nt({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",Ot,[(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,Et))),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,At),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,Vt),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,_t)],36)):e.createCommentVNode("",!0)],44,Gt)):e.createCommentVNode("",!0)],64))),128))])):e.createCommentVNode("",!0)}}),Bt={key:0,style:{position:"absolute",inset:"0",pointerEvents:"none"}},Ft=["title","onClick"],Ut=["onClick"],qt=e.defineComponent({__name:"BookmarkMarkerLayer",props:{chapterId:{},localPageIndex:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},ui:{}},setup(a){const s=a,{provides:r}=t.useCapability(Fe.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 Nt({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",Bt,[(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,Ft),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,Ut)],512)):e.createCommentVNode("",!0)],36))),128))])):e.createCommentVNode("",!0)}});function Ht(e){return e.chapterId}function Wt(e,t){e.wait(t,()=>{})}const jt={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)"},Zt={padding:"6px 12px",fontSize:"12px",fontWeight:"500",border:"none",borderRadius:"6px",background:"transparent",color:"#dc2626",cursor:"pointer"};const Yt=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(()=>Ht(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){const r=s.createNote.value;if(r)return s=>{var i;const o={position:"absolute",pointerEvents:"auto",left:"50%",transform:"translateX(-50%)",top:(null==(i=s.placement)?void 0:i.suggestTop)?-40:s.rect.size.height+8};return e.h("div",s.menuWrapperProps,[e.h("div",{style:o},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);Wt(n.value.getSelectedText(a),a=>{var s,i,o;r((s=t,i=e,o=a.join("\n"),{chapterId:s.chapterId,localPageIndex:s.localPageIndex,globalPageIndex:s.globalPageIndex,globalPageNumber:s.globalPageNumber,rectsPdfCoord:i,selectedText:o}))})}},"添加附注"))])}}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,!N.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:Zt,onClick:g},"删除");return e.h("div",l,[e.h("div",{style:f},[e.h("div",{style:jt,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(mt),{"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(I.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(qt,{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(Rt,{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"]))}}),Jt=e.defineComponent({__name:"HoverBookmarkLayer",props:{item:{},pdfPageWidth:{},pdfPageHeight:{},cssPageWidth:{},cssPageHeight:{},hoverUi:{}},setup(a){const s=a,r=e.computed(()=>Ht(s.item)),{provides:i}=t.useCapability(h.SelectionPlugin.id),{provides:o}=t.useCapability(Fe.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)?Re(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=>_e(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)}}}),Kt={key:0,width:"24",height:"24",viewBox:"0 0 28 28",fill:"none","aria-hidden":""},Xt={key:0,x:"5",y:"4",width:"18",height:"20",rx:"3",fill:"#fde047"},Qt={key:1,d:"M6 22h16",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},ea={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"},ta={key:3,d:"M5 14h18",stroke:"#dc2626","stroke-width":"2.2","stroke-linecap":"round"},aa={key:1,width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":""},sa=e.defineComponent({__name:"SelectionToolbarIcons",props:{kind:{}},setup:t=>(a,s)=>"note"!==t.kind?(e.openBlock(),e.createElementBlock("svg",Kt,["highlight"===t.kind?(e.openBlock(),e.createElementBlock("rect",Xt)):e.createCommentVNode("",!0),s[0]||(s[0]=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",Qt)):"squiggly"===t.kind?(e.openBlock(),e.createElementBlock("path",ea)):"strikeout"===t.kind?(e.openBlock(),e.createElementBlock("path",ta)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("svg",aa,[...s[1]||(s[1]=[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)])]))}),ra=["title","aria-label","onMouseenter","onClick"],ia=["title","onMouseenter","onClick"],oa={style:{"font-size":"11px","font-weight":"600"}},na=e.defineComponent({__name:"SelectionToolbarCard",props:{placementAbove:{type:Boolean},anchorHeight:{},hiddenBuiltinActions:{},extraActions:{}},emits:["action"],setup(t,{emit:a}){const s=t,r=a,i=[{id:"highlight",label:"高亮背景"},{id:"underline",label:"下划线"},{id:"squiggly",label:"波浪线"},{id:"strikeout",label:"删除线"},{id:"note",label:"添加笔记"}],o=e.computed(()=>new Set(s.hiddenBuiltinActions??[])),n=e.computed(()=>i.filter(e=>"note"!==e.id&&!o.value.has(e.id))),l=e.computed(()=>!o.value.has("note")),h=e.computed(()=>[...s.extraActions??[]].sort((e,t)=>(e.order??0)-(t.order??0))),d=e.ref(null),c=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 u(e,t=!1){return{display:"flex",alignItems:"center",justifyContent:"center",width:"32px",height:"32px",padding:0,margin:0,border:"none",borderRadius:"8px",background:d.value===e?t?"#fffbeb":"#f1f5f9":"transparent",color:t?"#b45309":"#334155",cursor:"pointer",flexShrink:0,WebkitAppearance:"none",appearance:"none"}}const p={width:"1px",height:"20px",margin:"0 4px",background:"rgba(15, 23, 42, 0.1)",flexShrink:0};return(t,a)=>(e.openBlock(),e.createElementBlock("div",{role:"toolbar","aria-label":"选区工具",style:e.normalizeStyle(c.value)},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.value,t=>(e.openBlock(),e.createElementBlock("button",{key:t.id,type:"button",title:t.label,"aria-label":t.label,style:e.normalizeStyle(u(t.id)),onMouseenter:e=>d.value=t.id,onMouseleave:a[0]||(a[0]=e=>d.value=null),onClick:e=>r("action",t.id)},[e.createVNode(sa,{kind:t.id},null,8,["kind"])],44,ra))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(h.value,t=>(e.openBlock(),e.createElementBlock("button",{key:t.id,type:"button",title:t.label,style:e.normalizeStyle(u(t.id)),onMouseenter:e=>d.value=t.id,onMouseleave:a[1]||(a[1]=e=>d.value=null),onClick:e=>r("action",t.id)},[e.createElementVNode("span",oa,e.toDisplayString(t.label.slice(0,2)),1)],44,ia))),128)),l.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createElementVNode("span",{style:p,"aria-hidden":""}),e.createElementVNode("button",{type:"button",title:"添加笔记","aria-label":"添加笔记",style:e.normalizeStyle(u("note",!0)),onMouseenter:a[2]||(a[2]=e=>d.value="note"),onMouseleave:a[3]||(a[3]=e=>d.value=null),onClick:a[4]||(a[4]=e=>r("action","note"))},[e.createVNode(sa,{kind:"note"})],36)],64)):e.createCommentVNode("",!0)],4))}}),la={highlight:"highlight",underline:"underline",squiggly:"squiggly",strikeout:"strikeout"},ha=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}=it(o),l=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(be.id))?void 0:t.provides)?void 0:s.call(t);return r?e=>r.createNoteFromSelection(e):null})}(),d=function(){const{registry:a}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=a.value)?void 0:e.getPlugin(be.id))})}(),c=function(){const{registry:a}=t.useRegistry();return e.computed(()=>{var e;return!!(null==(e=a.value)?void 0:e.getPlugin(Fe.id))})}(),u=e.computed(()=>{var e,t;return r.showNoteMarkers&&d.value&&!1!==(null==(t=null==(e=r.features)?void 0:e.notes)?void 0:t.enabled)}),p=e.computed(()=>{var e,t;return r.showBookmarkMarkers&&c.value&&!1!==(null==(t=null==(e=r.features)?void 0:e.bookmarks)?void 0:t.enabled)}),g=e.computed(()=>{var e,t;return c.value&&!1!==(null==(t=null==(e=r.features)?void 0:e.bookmarks)?void 0:t.enabled)}),f=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)}),{provides:l}=t.useCapability(h.SelectionPlugin.id),{provides:d}=t.useCapability(a.AnnotationPlugin.id),{provides:c}=t.useCapability(be.id);return e.computed(()=>{var t,a,h;if(!1!==(null==(t=i.value)?void 0:t.enabled)&&(o.value||n.value||(null==(h=null==(a=i.value)?void 0:a.extraActions)?void 0:h.length)))return t=>{const a=Ht(t.item);return h=>{var u,p,g;return e.h("div",h.menuWrapperProps,e.h(na,{placementAbove:!!(null==(u=h.placement)?void 0:u.suggestTop),anchorHeight:h.rect.size.height,hiddenBuiltinActions:null==(p=i.value)?void 0:p.hiddenBuiltinActions,extraActions:null==(g=i.value)?void 0:g.extraActions,onAction:e=>{var i,h,u;if("highlight"!==e&&"underline"!==e&&"squiggly"!==e&&"strikeout"!==e){if("note"===e){if(!l.value||!c.value||!n.value)return;const e=l.value.getHighlightRectsForPage(t.item.localPageIndex,a);return void Wt(l.value.getSelectedText(a),a=>{var s;null==(s=c.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(!l.value||!d.value||!o.value)return;z(a,la[e],d.value,l.value,null==(u=null==(h=s())?void 0:h.markup)?void 0:u.styles)}}}))}}})}(()=>r.features,{onExtraAction:r.onExtraSelectionAction}),m=e.computed(()=>{if(r.buildSelectionMenu||f.value)return e=>{const t=f.value?f.value(e):e.defaultMenu;return r.buildSelectionMenu?r.buildSelectionMenu({...e,defaultMenu:t}):t}}),{provides:v}=t.useCapability(i.DocumentManagerPlugin.id);function b(t){var a;const s=[];if(g.value){const a=function(t){var a,s,i,o;const n=Ht(t),l=null==(s=null==(a=v.value)?void 0:a.getDocument(n))?void 0:s.pages[t.localPageIndex];return t.isPlaceholder||!l?null:e.h(Jt,{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(ft),{class:e.normalizeClass(s.className)},{page:e.withCtx(({item:t})=>{var a,r,i,o;return[e.createVNode(Yt,{item:t,features:s.features,"show-note-markers":u.value,"show-bookmark-markers":p.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":m.value,"create-note":e.unref(l),"annotation-selection-menu":s.annotationSelectionMenu,"redaction-selection-menu":s.redactionSelectionMenu,"render-page-overlay":b},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"]),e.renderSlot(t.$slots,"default")],6))}}),da={key:0,style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,width:"100%"}},ca=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 tt(e.options);if(!e.editorOptions)throw new Error("ChapterPdfViewer: 请传入 `options`(推荐),或同时传入 `editorOptions` 与 `features`");const t=E(e.features),{plugins:a}=Ke({...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",da,[e.renderSlot(s.$slots,"prepend"),e.createVNode(ha,{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))}}),ua={class:"chapter-tree-row"},pa=["aria-expanded"],ga={key:1,class:"chapter-tree-toggle-spacer","aria-hidden":""},fa={class:"chapter-tree-label"},ma={class:"chapter-tree-meta"},va={key:0},ba=(e,t)=>{const a=e.__vccOpts||e;for(const[s,r]of t)a[s]=r;return a},Pa=ba(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",ua,[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",ga)),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",fa,e.toDisplayString(t.node.title),1),e.createElementVNode("div",ma,[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",va,e.toDisplayString(a[l.value]),1)):e.createCommentVNode("",!0)])],2)]),i.value&&o.value?(e.openBlock(),e.createBlock(wa,{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"]]),wa=ba(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(Pa,{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"]]),Ca={class:"chapter-tree"},Ia={class:"chapter-tree-nav","aria-label":"章节目录"},ya=ba(e.defineComponent({__name:"ChapterTreePanel",props:{tree:{},activeChapterId:{}},emits:["active-chapter-change"],setup(a,{emit:s}){const r=a,i=s,{provides:o}=t.useCapability(ee.id),{provides:n}=t.useCapability(U.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",Ca,[s[0]||(s[0]=e.createElementVNode("h2",{class:"chapter-tree-title"},"章节目录",-1)),e.createElementVNode("nav",Ia,[e.createVNode(wa,{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"]]),Ma=e.defineComponent({__name:"ChapterPdfViewer",props:{engine:{},options:{},editorOptions:{},features:{},className:{},viewportClassName:{}},setup:t=>(t,a)=>(e.openBlock(),e.createBlock(e.unref(ca),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 Sa={kind:"first-wins"};function xa(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 ka{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 La(e,t=Sa){const a=function(e,t=Sa){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,xa(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 ka(i)}const $a=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=Sa,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??Sa,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=La(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}}:{}}))}};$a.id="chapter-manager";let Ta=$a;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)}}let Na=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 Oa=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=function(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)}(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}}:{}}))}};Oa.id="chapter-manager";let Ea=Oa;const Ga={kind:"first-wins"};function Aa(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 Va{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 _a=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,Aa(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 Va(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}}:{}}))}};_a.id="chapter-manager";let Ra=_a;function Ba(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,Ba),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(Ra.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 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)}}let qa=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 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;const ja={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)}}let Ya=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 Ja=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=ja,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??ja,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=ja){const a=function(e,t=ja){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 Ya(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}}:{}}))}};Ja.id="chapter-manager";let Ka=Ja;function Xa(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 Qa=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,Xa),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(Ka.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)}};Qa.id="chapter-scroll";let es=Qa;const ts=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(es.id),this.chapterManager=this.registry.getPlugin(Wa.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:ss(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))})})}};ts.id="note";let as=ts;function ss(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}const rs={kind:"first-wins"};function is(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 os=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 ns=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=rs,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??rs,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=rs){const a=function(e,t=rs){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,is(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 os(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}}:{}}))}};ns.id="chapter-manager";let ls=ns;const hs={kind:"first-wins"};function ds(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 cs{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 us=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.statusChange$=r.createBehaviorEmitter(),this.manifestChange$=r.createEmitter(),this.overlapStrategy=hs,this.chapterStatus=new Map,this.chapterLastUsed=new Map,this.passwordAttempts=new Map,this.pendingLoadPromises=new Map,this.unloadTimer=null,this.documentManagerUnsubs=[],this.documentManager=this.registry.getPlugin(i.DocumentManagerPlugin.id)}async initialize(e){if(this.config=e,this.passwordProvider=e.passwordProvider,this.overlapStrategy=e.overlapStrategy??hs,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=hs){const a=function(e,t=hs){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,ds(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 cs(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}}:{}}))}};us.id="chapter-manager";let ps=us;function gs(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 fs=class extends r.BasePlugin{constructor(e,t){super(e,t),this.layoutChange$=r.createBehaviorEmitter(void 0,gs),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)}};fs.id="chapter-scroll";let ms=fs;function vs(e){const t=e[e.length-1];return{x:t.origin.x+t.size.width,y:t.origin.y+t.size.height}}function bs(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 Ps(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??vs(r),n=t.markerAnchor??vs(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(bs(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 ws=class e extends r.BasePlugin{constructor(e,t){super(e,t),this.change$=r.createBehaviorEmitter([]),this.entries=new Map,this.chapterScroll=this.registry.getPlugin(ms.id),this.chapterManager=this.registry.getPlugin(ls.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(Ps(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)}};ws.id="paragraph-bookmark";let Cs=ws;function Is(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=Is(void 0,{enabled:!0}),t=Is(void 0,{enabled:!0}),a=Is(void 0,{enabled:!0});Is(void 0,{enabled:!0,min:.5,max:3,initial:1}),Is(!1!==e.enabled||!1!==a.enabled,{enabled:!0})}();function ys(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 Ms(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 Ss(e){var t,s,r,i;return{annotation:null==(t=e.getPlugin(a.AnnotationPlugin.id))?void 0:t.provides(),note:null==(s=e.getPlugin(as.id))?void 0:s.provides(),bookmark:null==(r=e.getPlugin(Cs.id))?void 0:r.provides(),chapterManager:null==(i=e.getPlugin(Ea.id))?void 0:i.provides()}}async function xs(e,t,a){if(!a||!e)return;const s=await e.ensureChapterLoaded(t);if("loaded"!==s)throw new Error(`章节 ${t} 未加载成功(${s}),无法导入/导出划线`)}async function ks(e,t,a){const s=Ms(a),{annotation:r,note:i,bookmark:o,chapterManager:n}=Ss(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 xs(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:ys(t.data),mimeType:t.mimeType}}})}(e)}var h;return l}async function Ls(e,t,a){const s=Ms(a),r=(null==a?void 0:a.mode)??"replace",{annotation:i,note:o,bookmark:n,chapterManager:l}=Ss(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 xs(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 $s(e){return JSON.stringify(e,null,2)}function Ts(e){return JSON.stringify(e,null,2)}function Ds(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 zs(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 Ns(e){const t=[],a=e=>{var s;for(const r of e)t.push(zs(r)),(null==(s=r.children)?void 0:s.length)&&a(r.children)};return a(e),t}function Os(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)?Os(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=Ta,exports.ChapterPdfViewer=Ma,exports.ChapterTreePanel=ya,exports.DEFAULT_CHAPTER_VIEWER_CONFIG={},exports.DEFAULT_CHAPTER_VIEWER_FEATURES=Je,exports.PdfChapterViewport=ha,exports.applySelectionMarkup=z,exports.buildChapterViewerCatalog=function(e){return{tree:Os(e),manifest:{chapters:Ns(e)}}},exports.buildParagraphBookmarkAnchor=Re,exports.chapterAnnotationsArchiveToJson=$s,exports.chapterAnnotationsSnapshotToJson=Ts,exports.chapterDescriptorFromTreeNode=zs,exports.createChapterViewerBundle=tt,exports.createChapterViewerEditor=Ke,exports.createChapterViewerEditorOptions=function(e){const{features:t,...a}=et(Qe(e));return a},exports.createPdfChapterEditor=Ze,exports.defaultOverlapStrategy={kind:"first-wins"},exports.downloadChapterAnnotationsArchive=function(e,t="chapter-annotations.json"){Ds(t,$s(e))},exports.downloadChapterAnnotationsSnapshot=function(e,t){Ds(t??`chapter-annotations-${e.chapterId}.json`,Ts(e))},exports.downloadJsonFile=Ds,exports.exportAllChapterAnnotations=async function(e,t,a){const s={};for(const r of t.chapters){const t=await ks(e,r.chapterId,a),{chapterId:i,...o}=t;s[r.chapterId]=o}return{version:1,exportedAt:(new Date).toISOString(),chapters:s}},exports.exportChapterAnnotations=ks,exports.flattenChapterTree=Ns,exports.importChapterAnnotations=Ls,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 Ls(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=Os;
2
2
  //# sourceMappingURL=index.cjs.map