react-iiif-vault 2.0.14 → 2.0.15

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.
@@ -21,7 +21,7 @@ Error generating stack: `+i.message+`
21
21
  [zustand devtools middleware] Unsupported __setState action format.
22
22
  When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
23
23
  and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
24
- `);let T=E.state[u];if(T==null)return;JSON.stringify(a.getState())!==JSON.stringify(T)&&g(T);return}a.dispatchFromDevtools&&typeof a.dispatch=="function"&&a.dispatch(E)});case"DISPATCH":switch(w.payload.type){case"RESET":return g(b),u===void 0?d?.init(a.getState()):d?.init(wg(f.name));case"COMMIT":if(u===void 0){d?.init(a.getState());return}return d?.init(wg(f.name));case"ROLLBACK":return P1(w.state,E=>{if(u===void 0){g(E),d?.init(a.getState());return}g(E[u]),d?.init(wg(f.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return P1(w.state,E=>{if(u===void 0){g(E);return}JSON.stringify(a.getState())!==JSON.stringify(E[u])&&g(E[u])});case"IMPORT_STATE":{let{nextLiftedState:E}=w.payload,T=E.computedStates.slice(-1)[0]?.state;if(!T)return;g(u===void 0?T:T[u]),d?.send(null,E);return}case"PAUSE_RECORDING":return y=!y}return}}),b},P1=(t,e)=>{let n;try{n=JSON.parse(t)}catch(i){console.error("[zustand devtools middleware] Could not parse the received json",i)}n!==void 0&&e(n)},nF=t=>(e,n,i)=>{let a=i.subscribe;return i.subscribe=(r,l,u)=>{let f=r;if(l){let h=u?.equalityFn||Object.is,d=r(i.getState());f=m=>{let y=r(m);if(!h(d,y)){let g=d;l(d=y,g)}},u?.fireImmediately&&l(d,d)}return a(f)},t(e,n,i)},iF=(t={},e)=>{switch(e.type){case pg:return{...t,[e.payload.id]:e.payload.type};case mg:return{...t,...e.payload.mapping};default:return t}};function Nf(t,e,n,i){return!(!t[n]||!t[n][e]||!t[n][e][i]||!Array.isArray(t[n][e][i]))}function aF(t,e){let n={},i=[];for(let[a,r]of Object.entries(t||{})){i.push(a);let l=(e||{})[a];if(!l||l.length===0){n[a]=r;continue}n[a]=l}for(let[a,r]of Object.entries(e||{}))i.indexOf(a)===-1&&(n[a]=r);return n}function Dt(t){return t.payload||{}}function rF(t,e,n){if(!t[e]||!Array.isArray(t[e]))return null;let i=n.index===void 0?t[e].findIndex(a=>a?mc(a)?.id===n.id:!1):n.index;return i===-1?null:{entity:t[e][i],index:i}}function FM(t,e){if(!(!e?.id||!e?.type))return t[e.type]?.[e.id]}function Tg(t,e){return t===void 0?e:t}var qM=(t=D1(),e)=>{let n=(i,a)=>({...t,[Dt(e).type]:{...t[Dt(e).type],[Dt(e).id]:{...i,...a}}});switch(e.type){case ag:{if(!t[Dt(e).type]||!t[Dt(e).type][Dt(e).id])return t;let i=t[Dt(e).type][Dt(e).id];return typeof i=="string"?t:n(i,{[Dt(e).key]:Dt(e).value})}case rg:{if(!Nf(t,Dt(e).id,Dt(e).type,Dt(e).key))return t;let i=t[Dt(e).type][Dt(e).id];if(typeof i=="string")return t;let a=Array.from(i[Dt(e).key]),[r]=a.splice(Dt(e).startIndex,1);return a.splice(Dt(e).endIndex,0,r),n(i,{[Dt(e).key]:a})}case Mf:{let i=Dt(e).subjects,a=Dt(e).from,r=Dt(e).to||a,l=FM(t,a),u=r?.key||a.key;if(!Nf(t,a.id,a.type,a.key)||!Nf(t,r.id,r.type,r.key))return t;let f=[],h=[];if(i.type==="slice"){let E=i.startIndex,T=i.length;f=Array.from(l[a.key]),h=f.splice(E,T)}else{let E=Array.from(l[a.key]);for(let T of i.items){let S=rF(l,a.key,T);S&&(h.push(S.entity),E[S.index]=null),f=E.filter(R=>R!==null)}}let d={...l,[a.key]:f},m={...t,[a.type]:{...t[a.type],[a.id]:d}},y=FM(m,r);if(!y)return t;let g=r?.index===void 0?y[u].length:r.index,b=Array.from(y[r.key]);b.splice(g,0,...h);let w={...y,[u]:b};return{...m,[r.type]:{...m[r.type],[r.id]:w}}}case og:return qM(t,{type:Mf,payload:{subjects:{type:"list",items:[Dt(e).subject]},from:Dt(e).from,to:Dt(e).to}});case lg:{let{id:i,index:a,key:r,newIdentifier:l,reference:u,type:f}=Dt(e),h=t[f][i],d=mc(u);if(!h||!h[r]||!d||a<0)return t;let m=h[r],y=m[a],g=t[d.type]?.[d.id];if(!g||!y)return t;let b=EM(y,l),w=Array.from(m);w.splice(Tg(a,w.length+1),1,b);let E=n(h,{[r]:w}),T={...g,id:l};T["iiif-parser:hasPart"]&&(T["iiif-parser:hasPart"]=T["iiif-parser:hasPart"].filter(R=>R["iiif-parser:partOf"]===i).map(R=>({...R,id:l})));let S={...E[d.type],[l]:T};return E[d.type]=S,E}case ig:{let i=Object.keys(Dt(e).entities),a={...t};for(let r of i){let l=Dt(e).entities[r],u={...t[r]||{}},f=!1,h=Object.keys(l||{})||[];if(l&&h){for(let d of h)f=!0,u[d]=t[r][d]?aF(t[r][d],l[d]):l[d];f&&(a[r]=u)}}return a}case sg:{if(!Nf(t,Dt(e).id,Dt(e).type,Dt(e).key))return t;let i=t[Dt(e).type][Dt(e).id],a=Array.from(i[Dt(e).key]);return a.splice(Tg(Dt(e).index,a.length+1),0,Dt(e).reference),n(i,{[Dt(e).key]:a})}case Of:case ug:{if(!Nf(t,Dt(e).id,Dt(e).type,Dt(e).key))return t;let i=t[Dt(e).type][Dt(e).id],a=Array.from(i[Dt(e).key]),r=Tg(Dt(e).index,a.findIndex(l=>l&&l.id===Dt(e).reference.id));return r===-1||a[r]?.id!==Dt(e).reference.id?t:(e.type===Of?a.splice(r,1,Dt(e).reference):a.splice(r,1),n(i,{[Dt(e).key]:a}))}case cg:{let i=t[Dt(e).type][Dt(e).id];if(!i)return t;let a=Array.from(i.metadata||[]),r=Dt(e);return a.splice(Tg(e.payload.beforeIndex,a.length+1),0,{label:r.label,value:r.label}),n(i,{metadata:a})}case fg:{let i=t[Dt(e).type][Dt(e).id];if(typeof i=="string"||!i)return t;let a=Array.from(i.metadata||[]),[r]=a.splice(Dt(e).startIndex,1);return a.splice(Dt(e).endIndex,0,r),n(i,{metadata:a})}case _f:case dg:{let i=t[Dt(e).type][Dt(e).id],a=Array.from(i.metadata||[]),r=Dt(e).atIndex;return r===void 0||r===-1||!a[r]?t:(e.type===_f?a.splice(r,1,{label:Dt(e).label,value:Dt(e).value}):a.splice(r,1),n(i,{metadata:a}))}default:return t}},oF=(t={},e)=>{switch(e.type){case gg:case Sg:return{...t,[e.payload.id]:{requestUri:e.payload.id,loadingState:zf,uriMismatch:!1,resourceUri:e.payload.id}};case vg:return{...t,[e.payload.requestId]:{...t[e.payload.requestId]||{},uriMismatch:!0,resourceUri:e.payload.actualId},[e.payload.actualId]:{requestUri:e.payload.requestId,loadingState:t[e.payload.requestId].loadingState,uriMismatch:!0,resourceUri:e.payload.actualId}};case yg:return{...t,[e.payload.id]:{...t[e.payload.id]||{},loadingState:yc,error:e.payload.message}};case bg:return{...t,[e.payload.id]:{...t[e.payload.id]||{},loadingState:vc,error:void 0}}}return t},sF=(t={},e)=>{let{id:n,updateValue:i,value:a,meta:r,key:l}=e&&e.payload||{};switch(e.type){case M1:return{...t,[n]:{...t[n]||{},[r]:{...t[n]&&t[n][r]||{},[l]:a}}};case O1:return{...t,[n]:{...t[n]||{},[r]:{...t[n]&&t[n][r]||{},[l]:t[n]&&t[n][r]?i(t[n][r][l]):i(void 0)}}};case _1:return t[n]&&t[n][r]&&t[n][r][l]?{...t,[n]:{...t[n]||{},[r]:{...t[n]&&t[n][r]||{},[l]:void 0}}}:t;default:return t}};function VM(t={}){let e=Object.keys(t);return function(n={},i){let a=!1,r={};for(let l=0;l<e.length;l++){let u=e[l];r[u]=t[u](n[u],i),a=a||r[u]!==n[u]}return a?r:n}}function lF(t){return(e,n)=>n&&n.type===bc?n.payload.actions.reduce(t,e):n&&n.type===xg?{...e,iiif:{...e.iiif,...n.payload.state}}:t(e,n)}var uF=VM({mapping:iF,entities:qM,requests:oF,meta:sF});function cF(){return{iiif:{entities:D1(),meta:{},mapping:{},requests:{}}}}function UM(t={}){let{enableDevtools:e=!1,iiifStoreName:n="iiif",defaultState:i=cF(),customReducers:a={}}=t,r=lF(VM({[n]:uF,...a}));return Qm(nF((typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION__?eF:(l,u)=>l)($H(r,i),{enabled:e})))}function Pi(t,e,n,i=!0){e[wc]=e[wc]||[],e[wc].push(t);let a=new Map;Object.defineProperty(e,t,{enumerable:i,get(){if(e[Hl][t]===void 0)return;let r=e[Hl][t];if(!r)return r;let l=n.get(e[Hl][t],{parent:this.id?{id:this.id,type:this.type}:void 0});return a.has(l)||(a.clear(),a.set(l,Fl(l,n))),a.get(l)},set(r){e[Hl][t]!==r&&(this[Bl]?n.modifyEntityField({id:this.id,type:this.type},t,GM(r)):this[Hl][t]=r)}})}var Hl=Symbol.for("_refs_"),Bl=Symbol.for("_reactive_"),wc=Symbol.for("_defined_"),jM=Symbol.for("_parent_");function dF(t,e=!1,n){let i={id:"",type:"unknown",[wc]:[],[Hl]:{},[jM]:n||null,[Bl]:null,is(a){return typeof a=="string"?this.id===a:a.id?a.id===this.id:!1},reactive(){if(!this[Bl])return this[Bl]=this.subscribe(()=>this.refresh(),!0),()=>{this.unreactive()}},refresh(){if(this.id){let a=this.unwrap();for(let r of Object.keys(a||{}))this[wc].includes(r)?this[Hl][r]=a[r]:this[r]=a[r]}},unreactive(){this[Bl]&&(this[Bl](),this[Bl]=null)},unwrap(){if(!this.id)throw Error("Invalid object");let a=this[jM];return t.get(this.id,{parent:a?{id:a,type:"unknown"}:void 0})},toPresentation3(){return t.toPresentation3(this.unwrap())},toPresentation2(){return t.toPresentation2(this.unwrap())},valueOf(){return this.unwrap()},toJSON(){let a=this;return{...a,items:a.items,annotations:a.annotations,structures:a.structures,seeAlso:a.seeAlso,service:a.service,services:a.services,rendering:a.rendering,partOf:a.partOf,start:a.start,supplementary:a.supplementary,homepage:a.homepage,thumbnail:a.thumbnail,placeholderCanvas:a.placeholderCanvas,accompanyingCanvas:a.accompanyingCanvas,provider:a.provider}},subscribe(a,r=!0){return t.subscribe(()=>this.id?t.get(this.id):null,a,r)}};return Pi("items",i,t),Pi("annotations",i,t),Pi("structures",i,t),Pi("seeAlso",i,t),Pi("rendering",i,t),Pi("partOf",i,t),Pi("start",i,t,!1),Pi("supplementary",i,t),Pi("homepage",i,t),Pi("thumbnail",i,t),Pi("placeholderCanvas",i,t,!1),Pi("accompanyingCanvas",i,t,!1),Pi("provider",i,t),Pi("body",i,t),Pi("logo",i,t),i}function fF(t){return!!t[wc]}function GM(t){return Array.isArray(t)?t.map(e=>GM(e)):!t||!t.type?t:{id:t.id,type:t.type}}function Fl(t,e,n=!1,i){if(Array.isArray(t))return t.map(u=>Fl(u,e,n));if(!t||!t.type||!t.id)return t;let a=dF(e,n),r=Object.create(a),l=Object.assign(r,t);return n&&l.reactive(),l}function kM(t){switch(t){case"Image":case"Video":case"Sound":case"Dataset":case"Text":case"Composite":case"List":case"Independents":case"Audience":return"ContentResource";case"ImageService1":case"ImageService2":case"ImageService3":return"Service"}return t}var Tc=class{constructor(t,e){kn(this,"options",void 0),kn(this,"store",void 0),kn(this,"emitter",void 0),kn(this,"isBatching",!1),kn(this,"batchQueue",[]),kn(this,"remoteFetcher",void 0),kn(this,"staticFetcher",void 0),kn(this,"defaultFetcher",n=>fetch(n).then(i=>{if(i.status===200)return i.json();{let a=Error(`${i.status} ${i.statusText}`);throw a.name="HTTPError",a}})),this.options=Object.assign({reducers:{},customFetcher:this.defaultFetcher,enableDevtools:!0},t||{}),this.store=e||UM({customReducers:this.options.reducers,defaultState:this.options.defaultState,enableDevtools:this.options.enableDevtools}),this.emitter=Km(),this.remoteFetcher=L1(this,this.options.customFetcher),this.staticFetcher=L1(this,(n,i)=>i)}batch(t){this.isBatching=!0;try{t(this),this.isBatching=!1,this.dispatch(Sc({actions:this.batchQueue}))}catch(e){throw this.batchQueue=[],this.isBatching=!1,e}this.batchQueue=[]}async asyncBatch(t){this.isBatching=!0;try{await t(this),this.isBatching=!1,this.dispatch(Sc({actions:this.batchQueue}))}catch(e){throw this.batchQueue=[],this.isBatching=!1,e}this.batchQueue=[]}modifyEntityField(t,e,n){this.dispatch(Pl.modifyEntityField({id:t.id,type:t.type,key:e,value:n}))}dispatch(t){if(this.isBatching)this.batchQueue.push(t);else{if(t.type===bc){for(let i of t.payload.actions)this.emitter.emit(i.type,{action:i,state:this.store.getState()});this.store.dispatch(t);let n=this.getState();for(let i of t.payload.actions)this.emitter.emit(`after:${i.type}`,{action:i,state:n});return}this.emitter.emit(t.type,{action:t,state:this.store.getState()}),this.store.dispatch(t);let e=this.store.getState();this.emitter.emit(`after:${t.type}`,{action:t,state:e});return}}on(t,e){return this.emitter.on(t,e),()=>{this.emitter.off(t,e)}}serialize(t,e){return S1(this.getState().iiif,t,e)}toPresentation2(t){return this.serialize(t,x1)}toPresentation3(t){return this.serialize(t,w1)}hydrate(t,e,n={}){return this.get(t,e,{...n,skipSelfReturn:!1})}get(t,e,n={}){typeof e!="string"&&(n=e||{},e=void 0);let{skipSelfReturn:i=!0}=n||{},a=n.parent?typeof n.parent=="string"?n.parent:n.parent.id:void 0;if(Array.isArray(t))return t.map(d=>this.get(d,n));let r=this.getState();if(ga(t)&&!n.preserveSpecificResources&&(t=t.source),typeof t=="string"){let d=kM(e||r.iiif.mapping[t]);if(!d)return i?null:{id:t,type:"unknown"};t={id:t,type:d}}if(t&&t.partOf&&!a&&!n.skipPartOfCheck){let d=Array.isArray(t.partOf)?t.partOf[0]:t.partOf;d&&(typeof d=="string"&&(a=d),typeof d.id=="string"&&(a=d.id))}let l=kM(e||t?.type),u=t?.id,f=r.iiif.entities[l];if(!f){let d=r.iiif.requests[u];return d&&d.resourceUri!==u?this.get(d.resourceUri,n):i?null:t}let h=f[t.id];return h&&h[mn]?gc(h,h[mn].find(d=>a?d[ya]===a:d[ya]===h.id)):f[t.id]||(i?null:t)}select(t){return t(this.getState())}getStore(){return this.store}getState(){return this.store.getState()}deep(t,e){if(t===void 0)return this.get(e,{skipSelfReturn:!1});if(typeof t=="function")try{let i=t(this.get(e,{skipSelfReturn:!1})),a=r=>this.deep(r,i);return a.size=Array.isArray(i)?i.length:1,a}catch{let i=a=>this.deep(a,void 0);return i.size=0,i}let n=i=>this.deep(i,t);return n.size=Array.isArray(t)?t.length:1,n}loadManifest(t,e,n){let i=typeof t=="string"?t:t.id;return this.load(i,e,n)}loadCollection(t,e,n){let i=typeof t=="string"?t:t.id;return this.load(i,e,n)}load(t,e,n){let i=typeof t=="string"?t:t.id;return e?Promise.resolve(this.staticFetcher(i,e,n)):Promise.resolve(this.remoteFetcher(i,{},n))}loadSync(t,e,n){let i=typeof t=="string"?t:t.id;return this.staticFetcher(i,e,n)}loadManifestSync(t,e,n){let i=typeof t=="string"?t:t.id;return this.loadSync(i,e,n)}loadCollectionSync(t,e,n){let i=typeof t=="string"?t:t.id;return this.loadSync(i,e,n)}areInputsEqual(t,e){return N1(t,e)}subscribe(t,e,n){return n===void 0&&(e===void 0||e===!1||e===!0)&&(n=e,e=t,t=i=>i),this.store.subscribe(t,i=>e(i,this),{equalityFn:N1,fireImmediately:!n})}async ensureLoaded(t){let e=typeof t=="string"?t:t.id;this.requestStatus(e)||await this.load(e)}requestStatus(t){return this.select(e=>e.iiif.requests[t])}getPaginationState(t){let e=typeof t=="string"?t:t.id;if(!e)return null;let n=this.getResourceMeta(e,"@vault/pagination");if(n?.state)return n.state;let i=this.get(t);if(i.first){let a={currentPage:null,currentPageIndex:null,isFetching:!1,isFullyLoaded:!1,next:i.first,page:1,pages:[],previous:null,totalItems:i.total,currentLength:0};return this.setMetaValue([e,"@vault/pagination","state"],a),a}return null}async loadNextPage(t,e){let n=typeof t=="string"?t:t.id;if(!n)return[null,null];let i=this.getPaginationState(t);if(!i||i.isFullyLoaded||!i.next)return[null,null];if(i.isFetching)return[i,null];let a=typeof i.next=="string"?i.next:i.next.id,r=i.currentPage,l={...i,isFetching:!0};this.setMetaValue([n,"@vault/pagination","state"],l);let u;try{u=await this.loadCollection(a,e,y=>{let{id:g,"@id":b,...w}=y||{};return b?{"@id":a,...w}:{id:a,...w}})}catch(y){let g={...i,isFetching:!1,error:y};return this.setMetaValue([n,"@vault/pagination","state"],g),[g,null]}if(!u){let y={...i,isFetching:!1,error:Error("Collection not found")};return this.setMetaValue([n,"@vault/pagination","state"],y),[y,null]}let f=this.get(n),h=[...f.items||[],...u.items||[]].map(y=>({id:y.id,type:y.type}));this.modifyEntityField({id:n,type:"Collection"},"items",h);let d=this.getPaginationState(t);if(!d)throw Error("Pagination state not found");let m={...d,isFetching:!1,error:null,currentPage:u.id,next:u.next?.id||null,currentPageIndex:d.pages.length,currentLength:h.length,pages:[...d.pages,{id:u.id,type:"Collection",startIndex:f.items.length,pageLength:u.items.length,order:typeof d.currentPageIndex=="number"?d.currentPageIndex+1:0}],isFullyLoaded:!u.next,previous:r,page:d.pages.length+1};return this.setMetaValue([n,"@vault/pagination","state"],m),[m,u]}getResourceMeta(t,e){let n=this.getState().iiif.meta[t];if(n)return e?n[e]:n}getObject(t,e,n={}){let{reactive:i,...a}=n;return Fl(this.get(t,e,a),this,i)}async loadObject(t,e){return Fl(await this.load(t,e),this)}async loadManifestObject(t,e){return Fl(await this.loadManifest(t,e),this)}async loadCollectionObject(t,e){return Fl(await this.loadCollection(t,e),this)}wrapObject(t){return Fl(this.get(t,{skipSelfReturn:!1}),this)}isWrapped(t){return fF(t)}setMetaValue([t,e,n],i){this.dispatch(typeof i=="function"?z1.setMetaValueDynamic({id:t,meta:e,key:n,updateValue:i}):z1.setMetaValue({id:t,meta:e,key:n,value:i}))}};function YM(){return typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}function Lf(t){let e=YM();try{let i=e.IIIF_VAULT;if(i)return i}catch{}let n=new Tc(t);try{e.IIIF_VAULT=n}catch{}return n}var H1=I(Z(),1),ms=Rg.default.createContext({vault:null,setVaultInstance:t=>{}});function ho({vault:t,vaultOptions:e,useGlobal:n,resources:i,children:a}){let[r,l]=(0,Rg.useState)(()=>t||(n?Lf(e):e?new Tc(e):new Tc));return(0,H1.jsx)(ms.Provider,{value:{vault:r,setVaultInstance:l},children:(0,H1.jsx)(Di,{value:i||{},children:a})})}var QM=I(ut(),1),KM=I(ut(),1);var XM=I(ut(),1),ce=()=>{let{vault:t}=(0,XM.useContext)(ms);if(t===null)throw new Error("Vault not found. Ensure you have your provider set up correctly.");return t};var Eg=I(ut(),1);function _e(t,e=[]){let n=ce(),[i,a]=(0,Eg.useState)(()=>t(n.getState(),n));return(0,Eg.useEffect)(()=>n.subscribe(r=>t(r,n),r=>{a(r)},!1),e),i}var ql=KM.default.createContext([]);function Vl(){let t=(0,QM.useContext)(ql);return _e(e=>t.map(n=>e.iiif.entities.Canvas[n]).filter(Boolean),[t])}var ZM=I(ut(),1);function po(t){let e=(0,ZM.useContext)(ms);return t||(e&&e.vault?e.vault:Lf())}var WM=I(ut(),1);function Tn(t={},e=[]){let{id:n,selector:i}=t,a=wi(),r=ce(),l=n||a.manifest,u=_e(f=>l?f.iiif.entities.Manifest[l]:void 0,[l]);return(0,WM.useMemo)(()=>{if(u)return i?i(u):u},[u,i,...e])}var RO=I(ut(),1),Ng=I(ut(),1);var gs=I(ut(),1);function Df(t,{noCache:e=!1}={}){let n=typeof t=="string"?t:t.id,i=po(),[a,r]=(0,gs.useState)(n),[l,u]=(0,gs.useState)(void 0),f=(0,gs.useMemo)(()=>i.get(n,{skipSelfReturn:!0})||void 0,[n,i]),[h,d]=(0,gs.useState)(f);return(0,gs.useEffect)(()=>{(async()=>{try{let m=f&&!e?f:await i.load(n),y=m?m.id||m["@id"]:null;m&&a!==y&&r(y),d(m)}catch(m){u(m)}})()},[n,e]),{isLoaded:!!h,id:a,requestId:n,error:l,resource:h,cached:!!(h&&h===f)}}function F1(t,e){let{id:n,isLoaded:i,error:a,resource:r,requestId:l,cached:u}=Df(t,e);return{id:n,isLoaded:i,error:a,manifest:r,requestId:l,cached:u}}var JM=I(Z(),1);function q1({manifest:t,children:e}){return(0,JM.jsx)(Di,{value:{manifest:t},children:e})}var $M=I(Z(),1);function V1({range:t,children:e}){return(0,$M.jsx)(Di,{value:{range:t},children:e})}function tO(t,e){for(let n of e.items){if(n.type==="Canvas")return n;if(n.type==="SpecificResource")return n.source;if(n.type==="Range"){let i=tO(t,t.get(n));if(i)return i}}return null}function Ag(t,e){let n=[];for(let i of e.items)if(i.type==="SpecificResource"&&i.source?.type==="Canvas"&&(i.source.id.indexOf("#")!==-1?n.push({id:i.source.id.split("#")[0],type:"Canvas"}):n.push(i.source)),i.type==="Range"&&n.push(...Ag(t,t.get(i))),i.type==="SpecificResource"){let a=typeof i.source=="string"?i.source:i.source.id;n.push({id:a,type:"Canvas"})}return n}function hF(t,e,n){for(let i of e.structures){let a=U1(t,t.get(i),n);if(a)return a}return null}function U1(t,e,n){for(let i of e.items){let a=i?.source?.id?.split("#")[0];if(i.type==="SpecificResource"&&i.source===n||i.type==="SpecificResource"&&i.source?.type==="Canvas"&&n===a)return e;if(i.type==="Range"){let r=U1(t,t.get(i),n);if(r)return r}}return null}function pF(t,e,n,i=!1){let a=e.behavior,r=n?t.get(n):null;if(!r)return[];let l=r.behavior,u=i?!1:a.includes("paged"),f=u?!1:a.includes("continuous"),h=u||f?!1:a.includes("individuals"),d=l.includes("facing-pages"),m=l.includes("non-paged");if(d||m||h||i)return[{id:r.id,type:"Canvas"}];let[y,g]=Cg(t,e);if(f)return y;let b=y.findIndex(w=>w.id===n);if(b===-1)return[];for(let w of g)if(w.includes(b))return w.map(E=>y[E]);return[{id:r.id,type:"Canvas"}]}function Cg(t,e,{disablePaging:n,skipNonPaged:i}={}){let a=e.behavior,r=a.includes("paged"),l=r?!1:a.includes("continuous"),u=r||l?!1:a.includes("individuals"),f=e.type==="Manifest"?e.items:Ag(t,e);if(l)return[f,[f.map((b,w)=>w)]];if(u||!r||n)return[f,f.map((b,w)=>[w])];let h=[],d=[],m=()=>{d.length&&(h.push([...d]),d=[])},y=0,g=!1;for(let b=0;b<f.length;b++){let w=t.get(f[b]);if(w.behavior.includes("non-paged")){b===y&&y++,i||(m(),h.push([b]),m());continue}if(b===y||w.behavior.includes("facing-pages")){d.length&&(g=!0),m(),h.push([b]),m();continue}if(d.push(b),g){m(),g=!1;continue}d.length>1&&m()}return d.length&&m(),[f,h]}var cr=I(ut(),1);var eO=I(ut(),1);function Pf(t={},e=[]){let{id:n,selector:i}=t,a=wi(),r=n||a.range,l=_e(u=>r?u.iiif.entities.Range[r]:void 0,[r]);return(0,eO.useMemo)(()=>{if(l)return i?i(l):l},[l,i,...e])}function j1({startCanvas:t,disablePaging:e}){let n=ce(),i=Tn(),a=Pf(),[r,l]=(0,cr.useState)(void 0),u=a||i;if(!u)throw new Error("Nothing selected");let[f,h]=(0,cr.useMemo)(()=>Cg(n,u,{disablePaging:e}),[n,u,e]),d=(0,cr.useRef)(h);if(d.current!==h){let E=d.current[r][0],T=h.findIndex(S=>S.includes(E));d.current=h,l(T)}let m=(0,cr.useCallback)(w=>{let E=h.findIndex(T=>T.includes(w));l(E===-1?0:E)},[f,h]),y=(0,cr.useCallback)(w=>{let E=f.findIndex(T=>T.id===w);E!==-1?m(E):l(0)},[f,h]),g=(0,cr.useCallback)(()=>{l(w=>w>=h.length-1?w:w+1)},[h]),b=(0,cr.useCallback)(()=>{l(w=>w<=0?0:w-1)},[h]);return typeof r>"u"&&(t?y(t):l(0)),{visibleItems:h[r]?.map(w=>f[w].id)||[],cursor:r,items:f,sequence:h,hasPrevious:r>0,hasNext:r<h.length-1,setSequenceIndex:l,setCanvasIndex:m,setCanvasId:y,next:g,previous:b}}var fr=I(ut(),1);var iO={},nO=t=>{let e,n=new Set,i=(d,m)=>{let y=typeof d=="function"?d(e):d;if(!Object.is(y,e)){let g=e;e=m??(typeof y!="object"||y===null)?y:Object.assign({},e,y),n.forEach(b=>b(e,g))}},a=()=>e,f={setState:i,getState:a,getInitialState:()=>h,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(iO.env?iO.env.MODE:void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},h=e=t(i,a,f);return f},va=t=>t?nO(t):nO;var pO=I(ut(),1),mO=I(dO(),1),Og={},{useDebugValue:IF}=pO.default,{useSyncExternalStoreWithSelector:NF}=mO.default,fO=!1,LF=t=>t;function zt(t,e=LF,n){(Og.env?Og.env.MODE:void 0)!=="production"&&n&&!fO&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),fO=!0);let i=NF(t.subscribe,t.getState,t.getServerState||t.getInitialState,e,n);return IF(i),i}var hO=t=>{(Og.env?Og.env.MODE:void 0)!=="production"&&typeof t!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");let e=typeof t=="function"?va(t):t,n=(i,a)=>zt(e,i,a);return Object.assign(n,e),n},_g=t=>t?hO(t):hO;function DF(t){let e=t.service||t.services||[];for(let n of e)if(n.type==="AuthProbeService2")return!0;return!1}function dr(t,e,n){let i=e.findIndex(l=>l.service.id===t);if(i===-1)return e;let a=[...e],r=n(a[i]);return r===a[i]?e:(a[i]=r,a)}var Y1=()=>va((t,e)=>({currentAuth:-1,authItems:[],login:()=>{let n=e().authItems[e().currentAuth];if(!n||n.isPending||n.isLoggedIn)return;if(n.type!=="active")throw new Error("Cannot login to non-active service");let i=n.service.service.find(a=>a.type==="AuthAccessTokenService2");if(!i)throw new Error("Token service not found");t(()=>({authItems:dr(n.id,e().authItems,a=>({...a,isPending:!0}))})),G1(n.service).then(()=>{zg(i).then(a=>{let r=a.expiresIn,l=Date.now()+r*1e3;t(()=>({authItems:dr(n.id,e().authItems,u=>({...u,isLoggedIn:!0,isPending:!1,session:{token:a.accessToken,expires:l}}))}))}).catch(a=>{t(()=>({authItems:dr(n.id,e().authItems,r=>({...r,isLoggedIn:!1,isPending:!1,error:a.message}))}))})})},logout:()=>{let n=e().authItems[e().currentAuth];if(!n||n.isPending||!n.isLoggedIn)return;if(n.type!=="active")throw new Error("Cannot logout of non-active service");let i=n.service.service.find(l=>l.type==="AuthLogoutService2");if(!i)return;let a=`${i.id}?origin=${gO()}`,r=window.open(a);t(()=>({authItems:dr(n.id,e().authItems,l=>({...l,isLoggedIn:!1,session:null,isPending:!1}))}))},nextAuth:()=>{let n=e().authItems.length,i=e().currentAuth+1;i>=n||t(()=>({currentAuth:i}))},previousAuth:()=>{let n=e().currentAuth-1;n<0||t(()=>({currentAuth:n}))},setAuth:n=>{n!==-1&&(n<0||n>=e().authItems.length)||t(()=>({currentAuth:n}))},addService:(n,i)=>{if(!n.service)return;let a=n.service.find(u=>u.type==="AuthAccessTokenService2"),r=n;if(e().authItems.find(u=>u.service.id===n.id)){t(()=>({authItems:dr(n.id,e().authItems,u=>({...u,instances:u.instances+1}))}));return}if(t(()=>({currentAuth:r.profile==="active"?0:e().currentAuth,authItems:[{id:n.id,type:n.profile,service:n,probeId:i,canAuthenticate:!0,instances:1,isPending:!1,isLoggedIn:!1,session:null},...e().authItems]})),n.profile==="external"){if(!a)throw new Error("Token service not found");zg(a).then(u=>{t(()=>({authItems:dr(n.id,e().authItems,f=>({...f,isLoggedIn:!0,isPending:!1,session:{token:u.accessToken,expires:u.expiresIn}}))}))}).catch(u=>{t(()=>({authItems:dr(n.id,e().authItems,f=>({...f,isLoggedIn:!1,isPending:!1,canAuthenticate:!1,error:u.message}))}))})}if(n.profile==="kiosk"){if(!a)throw new Error("Token service not found");t(()=>({authItems:dr(n.id,e().authItems,u=>({...u,isPending:!0}))})),G1(r).then(()=>{zg(a).then(u=>{t(()=>({authItems:dr(n.id,e().authItems,f=>({...f,isLoggedIn:!0,isPending:!1,session:{token:u.accessToken,expires:u.expiresIn}}))}))}).catch(u=>{t(()=>({authItems:dr(n.id,e().authItems,f=>({...f,isLoggedIn:!1,isPending:!1,error:u.message}))}))})})}n.profile},removeService:(n,i)=>{let a=e().currentAuth===e().authItems.findIndex(l=>l.service.id===n.id),r=e().currentAuth;if(a){let l=e().authItems.find(f=>f.service.id===n.id);l&&l.instances>1||(r=e().authItems.findIndex(h=>h.service.id!==n.id&&h.instances>0))}t(()=>({authItems:dr(n.id,e().authItems,l=>({...l,instances:l.instances-1})),currentAuth:r}))}})),X1=(t,e)=>va((n,i)=>({service:t,status:t?"unknown":"success",shouldRedirect:!1,redirectResource:null,shouldSubstitute:!1,substituteResource:null,error:null,errorHeading:null,errorNote:null,shouldDisplayResource:!1,token:e||null,async probe(){if(!i().service)return;let a=i().service?.id;if(!a){n({status:"error",error:"Service ID not found",errorHeading:{en:["Service ID not found"]}});return}n({status:"probing"});let r=i().token;try{let l=await fetch(a,{headers:r?{Authorization:`Bearer ${i().token}`,Accept:"application/json"}:{Accept:"application/json"}}).then(u=>u.json());if(l.status===200)n({status:"success",shouldDisplayResource:!0,error:null,errorHeading:null,errorNote:null,shouldSubstitute:!1,shouldRedirect:!1});else if(l.status<400&&l.status>=300){if(!l.location)throw new Error("Redirect location not found");n({status:"error",shouldDisplayResource:!1,shouldRedirect:!0,redirectResource:l.location||null})}else if(l.status===401)n({status:"error",shouldDisplayResource:!1,shouldRedirect:!1,shouldSubstitute:!!l.substitute,substituteResource:l.substitute||null,error:"Unauthorized",errorHeading:l.heading||{en:["Unauthorized"]},errorNote:l.note||null});else throw new Error("Unknown error")}catch(l){n({status:"error",error:l.message,errorHeading:{en:["Unknown error"]}})}},setToken(a){n({token:a})}}));function Q1(t){let e=t.service||t.services||[],n={hasAuth:!1,services:{}};for(let i of e)if(i.type==="AuthProbeService2"){n.services.probe=i,n.hasAuth=!0;let a=i.service.filter(r=>r.type==="AuthAccessService2");a[0]&&(n.services.access=a[0])}return n}async function zg(t,{strict:e=!0}={}){return new Promise((n,i)=>{let a=Math.random().toString(36).substring(7),r=`${t.id}?messageId=${a}&origin=${window.location.origin}`,l=h=>{let d=h.data;if(d.messageId===a){if(e&&d.type!=="AuthAccessToken2"){u(),i("Invalid response, expected type=AuthAccessToken2");return}if(!d.accessToken){u(),i("Invalid response, expected accessToken");return}u(),n(d)}},u=()=>window.removeEventListener("message",l),f=document.createElement("iframe");f.src=r,f.style.display="none",document.body.appendChild(f),window.addEventListener("message",l)})}function gO(t){let e=window.location;if(t){let n=document.createElement("a");return n.href=t,n.protocol+"//"+n.hostname+(n.port?":"+n.port:"")}return e.protocol+"//"+e.hostname+(e.port?":"+e.port:"")}async function G1(t){let e=`${t.id}?origin=${gO()}`,n=window.open(e);if(!n)throw new Error("Failed to open window");return new Promise((i,a)=>{let r=setInterval(()=>{n.closed&&(clearInterval(r),i())},500)})}var Ec=I(ut(),1);function yO(t){let e=(0,Ec.useMemo)(()=>Q1(t),[t]),n=K1(e.services.access?.id),i=(0,Ec.useMemo)(()=>X1(e.services.probe,n),[e.services.probe]),a=zt(i);return(0,Ec.useEffect)(()=>{a.status==="unknown"&&!n&&a.probe()},[e.services.probe,a.status]),(0,Ec.useEffect)(()=>{n&&(a.setToken(n),a.probe())},[n]),[t,a,e.hasAuth]}var Bf=I(Z(),1),Ul=(0,fr.createContext)(null),vO=(0,fr.createContext)(null);vO.displayName="CurrentAuth";var bO=(0,fr.createContext)(null);bO.displayName="AuthActions";function W1({children:t}){let e=(0,fr.useMemo)(()=>Y1(),[]);return(0,Bf.jsx)(Ul.Provider,{value:e,children:t})}function J1(){return!!(0,fr.useContext)(Ul)}function Ac(){let t=(0,fr.useContext)(Ul);if(!t)throw new Error("useAuthActions must be used within a AuthProvider");return t}function SO(){let t=Ac();return zt(t,n=>({login:n.login,logout:n.logout,nextAuth:n.nextAuth,previousAuth:n.previousAuth,setAuth:n.setAuth,addService:n.addService,removeService:n.removeService}))}function PF(){let t=Ac();return zt(t,e=>e)}function xO(t){let e=Ac();return zt(e,i=>i.authItems.find(a=>a.service.id===t))}function K1(t){let e=Ac();return zt(e,i=>i.authItems.find(a=>a.id===t)?.session?.token)}function BF(t){let e=Ac();return zt(e,i=>{let a=i.authItems.find(r=>r.service.id===t);return!a||!a.isLoggedIn||!a.session?null:a.session?.token||null})}function HF(t){let e=SO(),n=xO(t.service.id);return(0,fr.useEffect)(()=>(e?.addService(t.service,t.probeId),()=>{e?.removeService(t.service,t.probeId)}),[t.service]),n?(n.error||!n.isLoggedIn,t.children):null}function Z1(){return null}function $1(t){let[e,n,i]=yO(t.resource),a=t.fallbackComponent||Z1,r=t.loadingComponent||Z1,l=t.errorComponent||Z1,u=n.service,f=null;if(!i||!u)return t.children(e);let h=u.service.filter(d=>d.type==="AuthAccessService2");n.status==="error"&&(f=(0,Bf.jsx)(l,{resource:t.resource,error:n.error||"",heading:n.errorHeading,note:n.errorNote,extra:t.extra})),(n.status==="unknown"||n.status==="probing")&&(f=(0,Bf.jsx)(r,{})),n.status==="success"&&(f=t.children(e));for(let d of h)f=(0,Bf.jsx)(HF,{service:d,probeId:u.id,children:f},d.id);return f}var Hf=I(ut(),1);var FF=t=>t.id||t["@id"];function qF(t){return(Array.isArray(t.service)?t.service:[t.service]).find(n=>n.profile==="http://iiif.io/api/search/0/autocomplete"||n.profile==="http://iiif.io/api/search/1/autocomplete"||n.profile==="AutoCompleteService1")}var wO=t=>{let e;typeof t=="string"?e={"@context":"http://iiif.io/api/search/1/context.json",profile:"http://iiif.io/api/search/1/search","@id":t,id:t,service:[]}:e=t;let n=e?FF(e):void 0,i=null;return va((a,r)=>({service:e,resources:[],lastQuery:{},loading:!1,error:!1,highlight:null,hasSearch:!!e,hasAutocomplete:e?!!qF(e):!1,errorMessage:"",search(l,u={}){if(!n)throw new Error("No search service found.");i&&!i.signal.aborted&&i.abort(),i=new AbortController;let f=new URLSearchParams;l.q&&f.set("q",l.q),l.motivation&&f.set("motivation",l.motivation),l.date&&f.set("date",l.date),l.user&&f.set("user",l.user),a({loading:!0}),fetch(`${n}?${f.toString()}`,{signal:i.signal,headers:{"Content-Type":"application/json",Accept:"application/json",...u.headers||{}}}).then(async h=>{if(!i?.signal.aborted)if(h.ok){let d=await h.json();a({resources:d.resources,error:!1,errorMessage:""})}else a({resources:[],error:!0,errorMessage:h.statusText})})},clearSearch(){a({resources:[],error:!1,errorMessage:""})},highlightResult(l){let u=r().resources.find(f=>f["@id"]===l);a({highlight:u})},nextResult(){let l=r().resources,u=r().highlight;if(!u){a({highlight:l[0]||null});return}let f=l.findIndex(h=>h["@id"]===u["@id"]);if(f===-1){a({highlight:l[0]||null});return}a({highlight:l[f+1]||l[0]||null})},previousResult(){let l=r().resources,u=r().highlight;if(!u){a({highlight:l[l.length-1]||null});return}let f=l.findIndex(h=>h["@id"]===u["@id"]);if(f===-1){a({highlight:l[l.length-1]||null});return}if(f===0){a({highlight:l[l.length-1]||null});return}a({highlight:l[f-1]||l[l.length-1]||null})}}))};function tx(){let t=Tn();return t?t.service.find(e=>e.profile==="SearchService1"||e.profile==="http://iiif.io/api/search/1/search"):void 0}var Ig=I(Z(),1),Cc=(0,Hf.createContext)(null);Cc.displayName="Search";function TO(t){let e=tx();return t.store?(0,Ig.jsx)(Cc.Provider,{value:t.store,children:t.children}):(0,Ig.jsx)(VF,{service:e,children:t.children})}function VF({service:t,children:e}){let n=(0,Hf.useMemo)(()=>wO(t),[t]);return(0,Ig.jsx)(Cc.Provider,{value:n,children:e})}var Yi=I(Z(),1),Ff=()=>{},Mc=(0,Ng.createContext)({setCurrentCanvasId:Ff,setCurrentCanvasIndex:Ff,nextCanvas:Ff,previousCanvas:Ff,items:[],sequence:[],setSequenceIndex:Ff,currentSequenceIndex:0,hasNext:!1,hasPrevious:!1});function EO(t){let e=Tn(),{cursor:n,visibleItems:i,next:a,sequence:r,items:l,setCanvasIndex:u,setCanvasId:f,previous:h,setSequenceIndex:d,hasNext:m,hasPrevious:y}=j1({startCanvas:t.startCanvas,disablePaging:t.pagingEnabled===!1}),g=(0,Ng.useMemo)(()=>({sequence:r,items:l,setCurrentCanvasId:f,nextCanvas:a,previousCanvas:h,totalCanvases:l.length,setCurrentCanvasIndex:u,setSequenceIndex:d,currentSequenceIndex:n,hasNext:m,hasPrevious:y}),[r,l,f,a,h,l,u,d,n]);return e?i.length===0?null:(0,Yi.jsx)(Mc.Provider,{value:g,children:(0,Yi.jsx)(ql.Provider,{value:i,children:(0,Yi.jsx)(qa,{canvas:i[0],children:t.children})})}):(console.warn("The manifest passed to the provider is not a valid IIIF manifest."),(0,Yi.jsx)("div",{children:"Sorry, something went wrong."}))}function ex(t){let e=po(t.vault),n=F1(t.manifest);if(!n)return console.warn("The manifest passed to the provider is not a valid IIIF manifest."),(0,Yi.jsx)("div",{children:"Sorry, something went wrong."});if(n.error)return(0,Yi.jsx)("div",{children:n.error.toString()});if(!n.isLoaded)return(0,Yi.jsx)("div",{children:"Loading..."});let i=(0,Yi.jsx)(EO,{...t,children:t.children});return(0,Yi.jsx)(ho,{vault:e,children:(0,Yi.jsx)(q1,{manifest:n.id,children:(0,Yi.jsx)(W1,{children:(0,Yi.jsx)(TO,{children:t.rangeId?(0,Yi.jsx)(V1,{range:t.rangeId,children:i}):i})})})})}function jl(){return(0,RO.useContext)(Mc)}var Oc=(t,e,n)=>{let i=t.length,a=n||It(i);for(let r=0;r<i;r++)a[r]=r%5===0?t[r+1]<e[3]&&t[r+3]>e[1]&&t[r+2]<e[4]&&t[r+4]>e[2]?1:0:t[r];return a};function It(t,e,n){return new Float32Array(t,e,n)}var AO=(t,e,n)=>{let i=t[1]<=e[3]&&t[3]>=e[1]&&t[2]<=e[4]&&t[4]>=e[2],a=n||It(5);return i?(a[0]=1,a[1]=Math.max(t[1],e[1]),a[2]=Math.max(t[2],e[2]),a[3]=Math.min(t[3],e[3]),a[4]=Math.min(t[4],e[4]),a):(a[0]=0,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a)},CO=t=>t.length/5;var Dr=(t,e,n)=>{let i=n||It(9);return i[0]=t[0]*e[0]+t[1]*e[3]+t[2]*e[6],i[1]=t[0]*e[1]+t[1]*e[4]+t[2]*e[7],i[2]=t[0]*e[2]+t[1]*e[5]+t[2]*e[8],i[3]=t[3]*e[0]+t[4]*e[3]+t[5]*e[6],i[4]=t[3]*e[1]+t[4]*e[4]+t[5]*e[7],i[5]=t[3]*e[2]+t[4]*e[5]+t[5]*e[8],i[6]=t[6]*e[0]+t[7]*e[3]+t[8]*e[6],i[7]=t[6]*e[1]+t[7]*e[4]+t[8]*e[7],i[8]=t[6]*e[2]+t[7]*e[5]+t[8]*e[8],i},de=class t{constructor(e){this.index=0,this.length=e,this.points=It(this.length)}static grid(e=1,n=1){return new t(5*e*n)}static point(e,n){let i=It(5);return i[0]=1,i[1]=e,i[2]=n,i[3]=e,i[4]=n,i}static positionPair(e){let n=It(5);return n[0]=1,n[1]=e.x1,n[2]=e.y1,n[3]=e.x2,n[4]=e.y2,n}static projection(e){return t.singleBox(e.width,e.height,e.x,e.y)}static singleBox(e,n,i=0,a=0){let r=It(5);return r[0]=1,r[1]=i,r[2]=a,r[3]=e+i,r[4]=n+a,r}row(e){return e(this)}addPoints(e,n,i,a){return this.points[this.index]=1,this.points[1+this.index]=e,this.points[2+this.index]=n,this.points[3+this.index]=i,this.points[4+this.index]=a,this.index+=5,this}addBox(e,n,i,a){return this.addPoints(e,n,e+i,n+a),this}build(){return this.points}};var hr=(t,e)=>{let n=t.length;for(let i=0;i<n;i++)t[i]=i%5===0?e[6]*t[i+1]+e[7]*t[i+2]+e[8]*t[i]:i%5%2===1?e[0]*t[i]+e[1]*t[i+1]+e[2]:e[3]*t[i-1]+e[4]*t[i]+e[5];return t},mo=t=>{let e=It(9);return e[0]=t,e[4]=t,e[8]=1,e},ci=(t,e)=>{let n=It(9);return n[0]=1,n[2]=t,n[4]=1,n[5]=e,n[8]=1,n},kl=(t,e,n)=>Dr(ci((1-t)*e,(1-t)*n),mo(t)),Xi=(t,e,n)=>{let i=t.length,a=n&&n.length>=i?n.slice(0,i):It(i);for(let r=0;r<i;r++)a[r]=r%5===0?e[6]*t[r+1]+e[7]*t[r+2]+e[8]*t[r]:r%5%2===1?e[0]*t[r]+e[1]*t[r+1]+e[2]:e[3]*t[r-1]+e[4]*t[r]+e[5];return a};var UF=Object.defineProperty,jF=(t,e,n)=>e in t?UF(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Lg=(t,e,n)=>(jF(t,typeof e!="symbol"?e+"":e,n),n);function Gl(t){return t.endsWith("info.json")?t:t.endsWith("/")?`${t}info.json`:`${t}/info.json`}var kF="http://library.stanford.edu/iiif/image-api/compliance.html#level0",zO="http://library.stanford.edu/iiif/image-api/compliance.html#level1",IO="http://library.stanford.edu/iiif/image-api/compliance.html#level2",GF="http://library.stanford.edu/iiif/image-api/conformance.html#level0",NO="http://library.stanford.edu/iiif/image-api/conformance.html#level1",LO="http://library.stanford.edu/iiif/image-api/conformance.html#level2",YF="http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level0",DO="http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level1",PO="http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level2",XF="http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level0",BO="http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level1",HO="http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level2",QF="http://iiif.io/api/image/1/level0.json",KF="http://iiif.io/api/image/1/profiles/level0.json",FO="http://iiif.io/api/image/1/level1.json",qO="http://iiif.io/api/image/1/profiles/level1.json",VO="http://iiif.io/api/image/1/level2.json",UO="http://iiif.io/api/image/1/profiles/level2.json",ZF="http://iiif.io/api/image/2/level0.json",WF="http://iiif.io/api/image/2/profiles/level0.json",jO="http://iiif.io/api/image/2/level1.json",kO="http://iiif.io/api/image/2/profiles/level1.json",GO="http://iiif.io/api/image/2/level2.json",YO="http://iiif.io/api/image/2/profiles/level2.json",JF="level0",XO="level1",QO="level2",$F="http://iiif.io/api/image/2/level0",KO="http://iiif.io/api/image/2/level1",ZO="http://iiif.io/api/image/2/level2",tq="https://iiif.io/api/image/1.1/compliance/#level0",WO="https://iiif.io/api/image/1.1/compliance/#level1",JO="https://iiif.io/api/image/1.1/compliance/#level2",$O=[ZO,IO,LO,PO,HO,VO,UO,GO,YO,QO,JO],t_=[...$O,KO,zO,NO,DO,BO,FO,qO,jO,kO,XO,WO],eq=[$F,KO,ZO,kF,zO,IO,GF,NO,LO,YF,DO,PO,XF,BO,HO,QF,KF,FO,qO,VO,UO,ZF,WF,jO,kO,GO,YO,JF,XO,QO,tq,WO,JO];var nq={extraFormats:["jpg"],extraQualities:["default"],extraFeatures:["sizeByWhListed"]},iq={extraFormats:["jpg"],extraQualities:["default"],extraFeatures:["baseUriRedirect","cors","jsonldMediaType","regionByPx","regionSquare","sizeByWhListed","sizeByH","sizeByW","sizeByWh"]},aq={extraFormats:["jpg","png"],extraQualities:["default"],extraFeatures:["baseUriRedirect","cors","jsonldMediaType","regionByPct","regionByPx","regionSquare","rotationBy90s","sizeByWhListed","sizeByConfinedWh","sizeByH","sizeByPct","sizeByW","sizeByWh"]};function rq(t){return $O.indexOf(t)!==-1?aq:t_.indexOf(t)!==-1?iq:nq}function oq(t){let e=t?Array.isArray(t.profile)?t.profile:[t.profile]:[],n={extraQualities:[],extraFormats:[],extraFeatures:[]};for(let i of e)if(typeof i=="string"&&(i=rq(i)),!!i){if(i.formats)for(let a of i.formats)n.extraFormats.indexOf(a)===-1&&n.extraFormats.push(a);if(i.qualities)for(let a of i.qualities)n.extraQualities.indexOf(a)===-1&&n.extraQualities.push(a);if(i.supports)for(let a of i.supports)n.extraFeatures.indexOf(a)===-1&&n.extraFeatures.push(a);if(i.maxHeight&&(n.maxHeight=i.maxHeight),i.maxWidth&&(n.maxWidth=i.maxWidth),i.maxArea&&(n.maxArea=i.maxArea),i.extraFormats)for(let a of i.extraFormats)n.extraFormats.indexOf(a)===-1&&n.extraFormats.push(a);if(i.extraQualities)for(let a of i.extraQualities)n.extraQualities.indexOf(a)===-1&&n.extraQualities.push(a);if(i.extraFeatures)for(let a of i.extraFeatures)n.extraFeatures.indexOf(a)===-1&&n.extraFeatures.push(a);i.maxHeight&&(n.maxHeight=i.maxHeight),i.maxWidth&&(n.maxWidth=i.maxWidth),i.maxArea&&(n.maxArea=i.maxArea)}if(t.extraFormats)for(let i of t.extraFormats)n.extraFormats.indexOf(i)===-1&&n.extraFormats.push(i);if(t.extraFeatures)for(let i of t.extraFeatures)n.extraFeatures.indexOf(i)===-1&&n.extraFeatures.push(i);if(t.extraQualities)for(let i of t.extraQualities)n.extraQualities.indexOf(i)===-1&&n.extraQualities.push(i);return n}function sq(t){try{if(t==="full")return{full:!0};if(t==="square")return{square:!0};let e=t.startsWith("pct:"),n=t.substr(e?4:0).split(",").map(i=>parseFloat(i));return{x:n[0],y:n[1],w:n[2],h:n[3],percent:e}}catch{throw new Error("Expected 'full', 'square' or 'x,y,w,h'. Found "+t)}}function lq(t){let e={upscaled:!1,max:!1,confined:!1};if(t[0]==="^"&&(e.upscaled=!0,t=t.slice(1)),t==="max"||t==="full")return e.max=!0,e.serialiseAsFull=t==="full",e;if(t[0]==="!"&&(e.confined=!0,t=t.slice(1)),t[0]==="p")return e.percentScale=parseFloat(t.slice(4)),e;let n=t.split(",").map(i=>i.trim());return n.length&&typeof n[0]<"u"&&(n[0]!==""&&(e.width=parseInt(n[0],10)),typeof n[1]<"u"&&n[1]!==""?(e.height=parseInt(n[1],10),e.version=2):e.version=3),e}function uq(t){let e={angle:0};if(t[0]==="!"&&(e.mirror=!0,t=t.substr(1)),e.angle=parseFloat(t)%360,Number.isNaN(e.angle))throw new Error(`Invalid rotation ${t}`);return e}function cq(t,e=""){let n=t.match(/^(([a-zA-Z]+):\/\/([^/]+))?((.*)+)/);if(!n)throw new Error(`Invalid or unknown input ${t}`);let i=n[2],a=n[3],r=n[4];if(r[0]==="/"&&(r=r.substring(1)),e.length>0){if(e[0]==="/"&&(e=e.substring(1)),e!==r.substring(0,e.length))throw new Error(`Path does not start with prefix (path: ${r}, prefix: ${e})`);r=r.substring(e.length)}return{scheme:i,server:a,path:r,prefix:e}}function dq(t,e=""){let{path:n,scheme:i,server:a,prefix:r}=cq(t,e),l=(n||"").split("/").reverse(),[u,f,h,d,...m]=l,y=m.reverse().filter(Boolean).join("/");if(l.length===1||u==="")return{type:"base",scheme:i,server:a,prefix:r,identifier:y};if(u==="info.json"){let[,...b]=l;return{type:"info",scheme:i,server:a,prefix:r,identifier:b.reverse().filter(Boolean).join("/")}}let g=(u||"").split(".");if(typeof g[1]>"u"||typeof g[0]>"u"||typeof d>"u"||typeof h>"u"||typeof f>"u")throw new Error("Invalid image request");return{type:"image",scheme:i,server:a,prefix:r,identifier:y,originalPath:n,region:sq(d),size:lq(h),rotation:uq(f),quality:g[0],format:g[1]}}function fq(t){let e=dq(Gl(t.id));if(e.type!=="info")throw new Error("Invalid service URL");let n=oq(t);return{identifier:e.identifier,originalPath:"",server:e.server,prefix:e.prefix,scheme:e.scheme,type:"image",quality:n.extraQualities.indexOf("default")===-1?n.extraQualities[0]:"default",region:{full:!0},size:{max:!0,upscaled:!1,confined:!1},format:"jpg",rotation:{angle:0}}}function hq(t,e,n){let i=n.length,a=[];for(let r=0;r<i;r++){let l=n[r];if(l){let u=l.width;a.push(t/u)}}return a}function pq(t,e,n){let i=n.length,a=[];for(let r=0;r<i;r++){let l=n[r];l&&a.push({width:Math.floor(t/l),height:Math.floor(e/l)})}return a}function gn(t){if(t["@id"])return t["@id"];if(t.id)return t.id}function Pg(t){if(!t||!t.profile||!gn(t))return!1;let e=Array.isArray(t.profile)?t.profile:[t.profile];for(let n of e)if(typeof n=="string"&&eq.indexOf(n)!==-1)return!0;return!1}function mq(t){if(!Pg(t))return!1;let e=Array.isArray(t.profile)?t.profile:[t.profile];for(let n of e)if(typeof n=="string"){if(t_.indexOf(n)!==-1)return!0}else{let i=[...n.supports||[],...n.extraFeatures||[]];if(i.indexOf("regionByPx")!==-1&&(i.indexOf("sizeByW")!==-1||i.indexOf("sizeByWh")!==-1))return!0}return!1}function Dg(t,e){if(e&&e.profile){let n=e.profile;if(n){let i=Array.isArray(n)?n:[n];return i.includes(`level${t}`)||i.includes(`http://iiif.io/api/image/2/level${t}.json`)||i.includes(`http://iiif.io/api/image/1/level${t}.json`)||i.includes(`http://iiif.io/api/image/1/profiles/level${t}.json`)}}return!1}function ix(t){return Pg(t)?Dg(0,t)?0:Dg(1,t)?1:Dg(2,t)?2:null:null}function e_(t){return(t["@context"]?Array.isArray(t["@context"])?t["@context"]:[t["@context"]]:[]).indexOf("http://iiif.io/api/image/3/context.json")!==-1}function gq(t){if(!mq(t))return[];let e=[],n=Array.isArray(t.profile)?t.profile:[t.profile],i=n.length;for(let a=0;a<i;a++){let r=n[a];if(r&&typeof r!="string"&&(r.maxHeight||r.maxWidth))return[{id:gn(t),type:"variable",minWidth:0,minHeight:0,maxHeight:r.maxHeight||r.maxWidth,maxWidth:r.maxWidth||r.maxHeight,level:ix(t),version:t["@context"]==="http://iiif.io/api/image/3/context.json"?3:2}]}if(t.tiles){let a=t.tiles.length;for(let r=0;r<a;r++){let l=t.tiles[r];l&&(l.height||l.width)&&e.push({id:gn(t),type:"variable",minHeight:0,minWidth:0,maxHeight:l.height||l.width,maxWidth:l.width,level:ix(t),version:e_(t)?3:2})}}return e}function MO(t){let e=/^.*\/(full)\/(((\d+),(\d+)?)|max)\/(\d+)\/default\.(jpg|png|jpeg)$/,n=t.match(e);if(n&&n[4]&&n[5]){let i=n[1],a=parseInt(n[4],10),r=parseInt(n[5],10),l=n[7];if((i==="max"||i==="full")&&a&&r&&l)return{type:"fixed",id:t,height:r,width:a}}return{type:"unknown",id:t}}function yq(t){if(t["@type"])return t["@type"];if(t.type)return t.type}function vq(t){if(typeof t=="string")return MO(t);let e=yq(t);if(e!=="Image"&&e!=="sc:Image")return null;let n=t,i=gn(n);return i?i&&n.width&&n.height?{id:i,type:"fixed",width:n.width,height:n.height,unsafe:!0}:MO(i):null}function bq(t){return Pg(t)?(t&&t.sizes?t.sizes:[]).map(e=>({id:gn(t),type:"fixed-service",height:e.height,width:e.width,level:ix(t),version:e_(t)?3:2})):[]}function OO(t){let e=[],n=t.length;for(let i=0;i<n;i++){let a=t[i];if(!a)continue;let r=bq(a);r.length&&e.push(...r);let l=gq(a);l.length&&e.push(...l)}return e}function n_(t){let e=t.service?Array.isArray(t.service)?t.service:[t.service]:[],n=e.length,i=[];for(let a=0;a<n;a++)Pg(e[a])&&i.push(e[a]);return i}function Sq(t,e=!0,n){let i=[],a=vq(t);if(a===null)return i;let r=t;if(i.push(a),e&&r&&r.width&&r.height){let l=[],u=n_(r);for(let f of u){let h={id:gn(f),width:r.width,height:r.height};if(n.canLoadSync(h)){let d=n.loadServiceSync(h);d&&(d.height||(d.height=r.height),d.width||(d.width=r.width),l.push(...OO([d])))}}if(l.length)return i.push(...l),i}return r.service&&i.push(...OO(r.service)),i}function xq({x:t=0,y:e=0,w:n,h:i,full:a,square:r,percent:l}){if(a)return"full";if(r)return"square";if(typeof n>"u"||typeof i>"u")throw new Error("RegionParameter: invalid region");let u=`${t},${e},${n},${i}`;return l?`pct:${u}`:u}function wq({max:t,percentScale:e,upscaled:n,confined:i,width:a,height:r,serialiseAsFull:l,version:u}){let f=[];return n&&f.push("^"),t?(f.push(l?"full":"max"),f.join("")):(i&&f.push("!"),e&&f.push(`pct:${e}`),a&&f.push(`${a}`),f.push(","),r&&u===3&&f.push(`${r}`),f.join(""))}function Tq(t){return`${t.mirror?"!":""}${(t.angle||0)%360}`}function Rq(t,e){let n=t.prefix.startsWith("/")?t.prefix.substr(1):t.prefix,i=`${t.scheme}://${t.server}/${n?`${n}/`:""}${t.identifier}`;if(t.type==="base")return i;if(t.type==="info")return`${i}/info.json`;let{size:a}=t,{region:r,rotation:l,format:u,quality:f}=t;if(e){let h=e["@context"]?Array.isArray(e["@context"])?e["@context"]:[e["@context"]]:[],d=e.profile,m=h.indexOf("http://iiif.io/api/image/2/context.json")!==-1||d==="level2",y=h.indexOf("http://iiif.io/api/image/3/context.json")!==-1;if((a.width===e.width&&!a.height||a.height===e.height&&!a.width||a.width===e.width&&a.height===e.height)&&(a={...a,max:!0}),m&&(a.max&&!a.serialiseAsFull&&(a={...a,serialiseAsFull:!0}),!a.max&&a.width&&a.height&&(a={...a,height:void 0}),a={...a,version:2}),y){if(a.max&&a.serialiseAsFull&&(a={...a,serialiseAsFull:!1}),a.width&&!a.height&&e.width&&e.height){let g=e.height/e.width;a={...a,height:Math.ceil(a.width*g)}}a={...a,version:3}}}return[i,xq(r),wq(a),Tq(l),`${f}.${u}`].filter(Boolean).join("/")}function nx(t,e,n){let i=fq({"@context":t.version===3?"http://iiif.io/api/image/3/context.json":"http://iiif.io/api/image/2/context.json",id:Gl(gn(t)),profile:t.level===null||typeof t.level>"u"?"level0":`level${t.level}`,type:t.version===3?"ImageService3":"ImageService2"});if(i.type!=="image")throw new Error("Invalid service");return i.size.max=!1,i.size.width=e,i.size.height=n,{id:Rq(i),type:"fixed",width:e,height:n||t.height/(t.width||1)*e,unsafe:t.width>e}}function _c(t){let e=t.replace(/(https?:\/\/)?(www.)?/i,"");return e.indexOf("/")!==-1?e.split("/")[0]:e}function Eq(t,e,n){let i=t.width?t.width:t.maxWidth;return n.height<=t.maxHeight&&n.width<=t.maxWidth&&n.height>=t.minHeight&&n.width>=t.minWidth&&(!e||Math.abs(n.width-i)<Math.abs(e.width-i))}function Aq(t,e){let n=[],i=Object.assign({unsafeImageService:!1,atAnyCost:!0,fallback:!0,minHeight:64,minWidth:64,maxHeight:1/0,maxWidth:1/0,returnAllOptions:!1,preferFixedSize:!1,allowUnsafe:!1,explain:!1,height:0,width:0},t),a=(d,m=0)=>i.explain?n.push(new Array(m).fill(0).map(y=>" ").join("")+d().trim()):void 0,r=[],l=[],u=null;a(()=>`Using configuration: ${JSON.stringify(i,null,2)}`);let f=(d,m)=>{if(a(()=>"Swapping choice",3),Eq(i,m,d)){if(i.preferFixedSize&&d.unsafe){a(()=>`We found an image that was marked as unsafe, but it was the best size. (${d.id})`,4),l.push(d);return}i.returnAllOptions&&m&&l.push(m),a(()=>`We found a new image that was the best size. (${d.id})`,4),u=d}else i.returnAllOptions&&l.push(d)};a(()=>`The input shows we have ${e.length} list(s) of candidates to choose from.`);let h=e.length;for(let d=0;d<h;d++){let m=e[d]();a(()=>`Candidate group ${d}: ${JSON.stringify(m,null,2)}`,1);let y=m.length;a(()=>`Checking candidate list number ${d} and found ${y} potential ways of creating image(s)`,1);for(let g=0;g<y;g++){let b=m[g];if(a(()=>`-> Checking candidate ${g}`,1),b.type==="unknown"&&i.atAnyCost&&(a(()=>`We've found an unknown image type, adding this to the "last resort" list`,2),r.push(b)),b.type==="fixed"&&(b.unsafe?(a(()=>`We've found an unsafe fixed image type, adding this to the "last resort" list`,2),r.push(b)):(a(()=>"We've found a fixed size image, checking if it matches the request",2),f(b,u))),b.type==="fixed-service")if(i.unsafeImageService){a(()=>"Checking for an image from the tile source, without calculating the right height and width (unsafeImageService)",2);let w=nx(b,i.width,i.height);f(w,u)}else{a(()=>"Checking for an image from the tile source 3",2);let w=nx(b,b.width,b.height);f(w,u)}if(b.type==="variable"&&b.maxWidth){let w=nx({id:b.id,type:"fixed-service",width:b.maxWidth,height:b.maxWidth,level:b.level,version:b.version},b.maxWidth);f(w,u)}}if(u&&!i.returnAllOptions){if(u.unsafe||i.allowUnsafe)continue;a(()=>`We found a match in choice list number ${d}, no searching any more`);break}}return i.atAnyCost&&l.length===0?(a(()=>u?`We found an image! ${u.id} of type ${u.type}`:'We found no images, but "atAnyCost" is set, so returning that'),{best:u||r[0]||null,fallback:r.slice(1),log:n}):i.returnAllOptions?(a(()=>"Returning all options that we have found"),{best:(i.atAnyCost?u||l[0]||r[0]:u||l[0])||null,fallback:[...l,...r],log:n}):(a(()=>"Returning the best image that we found, and a fallback"),{best:u||l[0]||null,fallback:u?l:l.slice(1),log:n})}function Cq(t,e,n){let i=t>e?t:e,a=n.length,r=[];for(let l=0;l<a;l++){let u=n[l];if(!u||u.scaleFactors.length===0)continue;let f=u.scaleFactors[0];if(!f)continue;let h=i/f,d=[f];for(;h>=u.width;)f=f*2,d.push(f),h=h/2;r.push({...u,scaleFactors:d})}return r}function Mq(t,e){if(t.length!==e.length)return!1;if(t.length===0&&e.length===0)return!0;let n=t.length,i=!0;for(let r=0;r<n;r++){let l=t[r],u=e[r];if(l.width!==u.width||l.height!==u.height){i=!1;break}}if(i)return!0;let a=0;for(let r=0;r<n;r++)for(let l=0;l<n;l++)if(t[r].width===e[l].width&&t[r].height===e[l].height){a++;break}return a===n}function _O(t){return Dg(0,t)}var i_=class{constructor(t={}){Lg(this,"config",{verificationsRequired:1,approximateServices:!1,enableFetching:!0,disableThrottling:!1}),Lg(this,"fetchingCount",0),Lg(this,"imageServices",{}),Lg(this,"knownImageServers",{}),this.config=Object.assign(this.config,t)}setConfig(t){Object.assign(this.config,t)}sample(t,e,n=!0){let i=_c(gn(t)),a=Gl(gn(t)),r=this.knownImageServers[i];return this.imageServices[a]=Object.assign(t,{real:!0}),!r&&t.tiles&&!_O(t)?(this.knownImageServers[i]={verifications:0,malformed:!1,root:i,preLoaded:n,sampledId:gn(t),verified:!1,server:null,result:{context:t["@context"]||[],sampledProfile:t.profile,resourceServiceRatio:e&&t.height?e.height/t.height:1,sampledSizes:t.sizes||[],sizeRatios:hq(t.width,t.height,t.sizes||[]),sampledTiles:t.tiles||[]}},!0):this.verify(t)}preLoad(t,e=!0){this.knownImageServers[t.root]=t,e&&(this.knownImageServers[t.root].malformed=!1,this.knownImageServers[t.root].verifications=this.config.verificationsRequired)}predict(t,e=!1,n=!1){let i=t?.source,a=_c(gn(t)),r=this.knownImageServers[a],l=Gl(gn(t));return this.imageServices[l]?this.imageServices[l]||null:!this.config.approximateServices||!r||!r.result||!(i?.height||t.height)||!(i?.width||t.width)||!n&&(r.malformed||r.verifications<this.config.verificationsRequired)||_O(t.source)?null:(this.imageServices[l]||(this.imageServices[l]={"@context":r.result.context,"@id":gn(t),id:gn(t),protocol:"http://iiif.io/api/image",tiles:i?.tiles||Cq(t.width,t.height,r.result.sampledTiles),sizes:i?.sizes||pq(Math.round(t.width/r.result.resourceServiceRatio),Math.round(t.height/r.result.resourceServiceRatio),r.result.sizeRatios),profile:i?.profile||r.result.sampledProfile,height:i?.height||t.height,width:i?.width||t.width,real:!1}),this.imageServices[l]||null)}async getThumbnailFromResource(t,e,n=!0,i=[]){let a=t?await this.getImageCandidates(t,n):[];return Aq(e,[()=>i,()=>a])}async getImageCandidates(t,e=!0){let n=t;if(e&&n&&n.height&&n.width){let i=n_(n);for(let a of i){let r={id:gn(a),width:a.width?a.width:n.width,height:a.height?a.height:n.height,source:a};await this.loadService(r)}}return Sq(t,e,this)}async verify(t){let e=this.predict(t,!1,!0),n=await this.fetchService(gn(t));if(!e)return!1;let i=e.height===n.height&&e.width===n.width&&e["@context"]===n["@context"]&&Mq(e.sizes||[],n.sizes||[]);if(i){let a=_c(gn(t)),r=this.knownImageServers[a];r&&(r.verifications+=1,r.verifications>=this.config.verificationsRequired&&(r.verified=!0))}return i}canLoadSync(t){let e=typeof t=="string"?t:gn(t),n=Gl(e);if(this.imageServices[n])return!0;let i=this.knownImageServers[_c(e)];return!!(i&&!i.malformed&&i.verifications>=this.config.verificationsRequired)}async markAsMalformed(t){return this.knownImageServers[_c(gn(t))].malformed=!0,this.loadService(t,!0)}async fetchService(t,e=!1){let n=Gl(t),i=this.imageServices[n];if(i&&(!e||i.real))return i;if(!this.config.enableFetching)throw new Error("Fetching is not enabled");let a=await this.fetch(n).then(r=>r.json());return!a.id&&a["@id"]&&(a.id=a["@id"]),a.id!==t&&(a.id=t,a["@id"]&&(a["@id"]=t)),this.imageServices[n]=Object.assign(a,{real:!0}),this.imageServices[n]}async fetch(t,e){return fetch(t,e)}async loadService(t,e=!1){if(!this.config.disableThrottling){let a=!0;for(;a;)if(this.fetchingCount>=this.config.verificationsRequired)await new Promise(r=>setTimeout(r,500));else{a=!1;break}}let n=this.knownImageServers[_c(gn(t))];if(n&&!n.malformed&&!e){await n.result;let a=this.loadServiceSync(t);if(a)return a}this.fetchingCount++;let i=await this.fetchService(gn(t),e);return this.fetchingCount--,i.real&&this.sample(i,t),i}loadServiceSync(t){let e=Gl(gn(t));return this.imageServices[e]?this.imageServices[e]:this.config.approximateServices?this.predict(t):null}},uQ=new i_;var Bg={},go={get(t){return t},setMetaValue([t,e,n],i){let a=go.getResourceMeta(t,e),r=a?a[n]:void 0,l=typeof i=="function"?i(r):i;Bg[t]={...Bg[t]||{},[e]:{...(Bg[t]||{})[e]||{},[n]:l}}},getResourceMeta:(t,e)=>{let n=Bg[t];if(n)return e?n[e]:n},async load(t){let e=typeof t=="string"?t:t.id;return fetch(e).then(n=>n.json())},subscribe(t){return()=>{}},requestStatus(t){}};function Oq(t){try{if(t==="full")return{full:!0};if(t==="square")return{square:!0};let e=t.startsWith("pct:"),n=t.substr(e?4:0).split(","),i=n.map(a=>parseFloat(a));return{x:i[0],y:i[1],w:i[2],h:i[3],percent:e}}catch{throw Error("Expected 'full', 'square' or 'x,y,w,h'. Found "+t)}}function _q(t){let e={upscaled:!1,max:!1,confined:!1};if(t[0]==="^"&&(e.upscaled=!0,t=t.slice(1)),t==="max"||t==="full")return e.max=!0,e.serialiseAsFull=t==="full",e;if(t[0]==="!"&&(e.confined=!0,t=t.slice(1)),t[0]==="p")return e.percentScale=parseFloat(t.slice(4)),e;let n=t.split(",").map(i=>i.trim());return n.length&&(n[0]!==""&&(e.width=parseInt(n[0],10)),n[1]!==""&&(e.height=parseInt(n[1],10))),e}function zq(t){let e={angle:0};if(t[0]==="!"&&(e.mirror=!0,t=t.substr(1)),e.angle=parseFloat(t)%360,Number.isNaN(e.angle))throw Error(`Invalid rotation ${t}`);return e}function Iq(t,e=""){let n=t.match(/^(([a-zA-Z]+):\/\/([^/]+))?((.*)+)/);if(!n)throw Error(`Invalid or unknown input ${t}`);let i=n[2],a=n[3],r=n[4];if(r[0]==="/"&&(r=r.substring(1)),e.length>0){if(e[0]==="/"&&(e=e.substring(1)),e!==r.substring(0,e.length))throw Error(`Path does not start with prefix (path: ${r}, prefix: ${e})`);r=r.substring(e.length)}return{scheme:i,server:a,path:r,prefix:e}}function Nq(t,e=""){let{path:n,scheme:i,server:a,prefix:r}=Iq(t,e),l=n.split("/").reverse(),[u,f,h,d,...m]=l,y=m.reverse().filter(Boolean).join("/");if(l.length===1||u==="")return{type:"base",scheme:i,server:a,prefix:r,identifier:y};if(u==="info.json"){let[,...w]=l;return{type:"info",scheme:i,server:a,prefix:r,identifier:w.reverse().filter(Boolean).join("/")}}if(i===void 0||a===void 0||n===void 0||d===void 0||h===void 0||f===void 0||u===void 0)throw Error("Invalid image service URL");let[g="",b=""]=u.split(".");return{type:"image",scheme:i,server:a,prefix:r,identifier:y,originalPath:n,region:Oq(d),size:_q(h),rotation:zq(f),quality:g,format:b}}function Lq(t){return cc.indexOf(t)!==-1?J2:Wm.indexOf(t)!==-1?W2:Z2}function Dq(t){let e=t?Array.isArray(t.profile)?t.profile:[t.profile]:[],n={extraQualities:[],extraFormats:[],extraFeatures:[]};for(let i of e)if(typeof i=="string"&&(i=Lq(i)),!!i){if(i.formats)for(let a of i.formats)n.extraFormats.indexOf(a)===-1&&n.extraFormats.push(a);if(i.qualities)for(let a of i.qualities)n.extraQualities.indexOf(a)===-1&&n.extraQualities.push(a);if(i.supports)for(let a of i.supports)n.extraFeatures.indexOf(a)===-1&&n.extraFeatures.push(a);if(i.maxHeight&&(n.maxHeight=i.maxHeight),i.maxWidth&&(n.maxWidth=i.maxWidth),i.maxArea&&(n.maxArea=i.maxArea),i.extraFormats)for(let a of i.extraFormats)n.extraFormats.indexOf(a)===-1&&n.extraFormats.push(a);if(i.extraQualities)for(let a of i.extraQualities)n.extraQualities.indexOf(a)===-1&&n.extraQualities.push(a);if(i.extraFeatures)for(let a of i.extraFeatures)n.extraFeatures.indexOf(a)===-1&&n.extraFeatures.push(a);i.maxHeight&&(n.maxHeight=i.maxHeight),i.maxWidth&&(n.maxWidth=i.maxWidth),i.maxArea&&(n.maxArea=i.maxArea)}if(t.extraFormats)for(let i of t.extraFormats)n.extraFormats.indexOf(i)===-1&&n.extraFormats.push(i);if(t.extraFeatures)for(let i of t.extraFeatures)n.extraFeatures.indexOf(i)===-1&&n.extraFeatures.push(i);if(t.extraQualities)for(let i of t.extraQualities)n.extraQualities.indexOf(i)===-1&&n.extraQualities.push(i);return n}function ax(t){let e=Array.isArray(t.profile)?t.profile:[t.profile];for(let n of e)if(typeof n=="string"&&d1.indexOf(n)!==-1)return!0;return!1}function ke(t){if(t["@id"])return t["@id"];if(t.id)return t.id}function qf(t){if(!t||!t.profile||!ke(t))return!1;let e=Array.isArray(t.profile)?t.profile:[t.profile];for(let n of e)if(typeof n=="string"&&u1.indexOf(n)!==-1)return!0;return!1}function a_(t){if(!qf(t))return!1;let e=Array.isArray(t.profile)?t.profile:[t.profile];for(let n of e)if(typeof n=="string"){if(Wm.indexOf(n)!==-1)return!0}else{let i=[...n.supports||[],...n.extraFeatures||[]];if(i.indexOf("regionByPx")!==-1&&(i.indexOf("sizeByW")!==-1||i.indexOf("sizeByWh")!==-1))return!0}return!1}function Pq({x:t=0,y:e=0,w:n,h:i,full:a,square:r,percent:l}){if(a)return"full";if(r)return"square";if(n===void 0||i===void 0)throw Error("RegionParameter: invalid region");let u=`${t},${e},${n},${i}`;return l?`pct:${u}`:u}function Bq({max:t,percentScale:e,upscaled:n,confined:i,width:a,height:r,serialiseAsFull:l,version:u}){let f=[];return n&&f.push("^"),t?(f.push(l?"full":"max"),f.join("")):(i&&f.push("!"),e&&f.push(`pct:${e}`),a&&f.push(`${a}`),f.push(","),r&&u===3&&f.push(`${r}`),f.join(""))}function Hq(t){return`${t.mirror?"!":""}${(t.angle||0)%360}`}function Hg(t,e){let n=t.prefix.startsWith("/")?t.prefix.substring(1):t.prefix,i=`${t.scheme}://${t.server}/${n?`${n}/`:""}${t.identifier}`;if(t.type==="base")return i;if(t.type==="info")return`${i}/info.json`;let{size:a}=t,{region:r,rotation:l,format:u,quality:f}=t;if(e){let h=e["@context"]?Array.isArray(e["@context"])?e["@context"]:[e["@context"]]:[],d=h.indexOf("http://iiif.io/api/image/2/context.json")!==-1,m=h.indexOf("http://iiif.io/api/image/3/context.json")!==-1;if((a.width===e.width&&!a.height||a.height===e.height&&!a.width||a.width===e.width&&a.height===e.height)&&(a={...a,max:!0}),d&&(a.max&&!a.serialiseAsFull&&(a={...a,serialiseAsFull:!0}),!a.max&&a.width&&a.height&&(a={...a,height:void 0}),a={...a,version:2}),m){if(a.max&&a.serialiseAsFull&&(a={...a,serialiseAsFull:!1}),a.width&&!a.height&&e.width&&e.height){let y=e.height/e.width;a={...a,height:Math.ceil(a.width*y)}}a={...a,version:3}}}return[i,Pq(r),Bq(a),Hq(l),`${f}.${u}`].filter(Boolean).join("/")}function ys(t){return t.endsWith("info.json")?t:t.endsWith("/")?`${t}info.json`:`${t}/info.json`}function Fg(t){let e=Nq(ys(t.id));if(e.type!=="info")throw Error("Invalid service URL");let n=Dq(t);return{identifier:e.identifier,originalPath:"",server:e.server,prefix:e.prefix,scheme:e.scheme,type:"image",quality:n.extraQualities.indexOf("default")===-1?n.extraQualities[0]:"default",region:{full:!0},size:{max:!0,upscaled:!1,confined:!1},format:"jpg",rotation:{angle:0}}}function r_(t,e,n){let i=n.length,a=[];for(let r=0;r<i;r++){let l=n[r];if(!l)continue;let u=l.width;a.push(t/u)}return a}function o_(t,e,n){let i=n.length,a=[];for(let r=0;r<i;r++){let l=n[r];l&&a.push({width:Math.floor(t/l),height:Math.floor(e/l)})}return a}function zc(t,e){if(e&&e.profile){let n=e.profile;if(n){let i=Array.isArray(n)?n:[n];if(i.includes(`level${t}`)||i.includes(`http://iiif.io/api/image/2/level${t}.json`)||i.includes(`http://iiif.io/api/image/1/level${t}.json`)||i.includes(`http://iiif.io/api/image/1/profiles/level${t}.json`))return!0;if(t===2){for(let a of i)if(cc.includes(a))return!0}if(t===1){for(let a of i)if(Wm.includes(a))return!0}if(t===0){for(let a of i)if(d1.includes(a))return!0}}}return!1}function qg(t){return qf(t)?zc(2,t)?2:zc(1,t)?1:zc(0,t)?0:null:null}function vs(t){let e=t.service?Array.isArray(t.service)?t.service:[t.service]:[],n=e.length,i=[];for(let a=0;a<n;a++)qf(e[a])&&i.push(e[a]);return i}function s_(t){if(t["@type"])return t["@type"];if(t.type)return t.type}function Yl(t){let e=t.replace(/(https?:\/\/)?(www.)?/i,"");return e.indexOf("/")===-1?e:e.split("/")[0]}function l_(t,e,n){let i=t>e?t:e,a=n.length,r=[];for(let l=0;l<a;l++){let u=n[l];if(!u||u.scaleFactors.length===0)continue;let f=u.scaleFactors[0];if(!f)continue;let h=i/f,d=[f];for(;h>=u.width;)f*=2,d.push(f),h/=2;r.push({...u,scaleFactors:d})}return r}function Vg(t,e,n){let i=Fg({"@context":t.version===3?"http://iiif.io/api/image/3/context.json":"http://iiif.io/api/image/2/context.json",id:ys(ke(t)),profile:t.level===null||t.level===void 0?"level0":`level${t.level}`,type:t.version===3?"ImageService3":"ImageService2"});if(i.type!=="image")throw Error("Invalid service");return i.size.max=!1,i.size.width=e,i.size.height=n,{id:Hg(i),type:"fixed",width:e,height:n||t.height/(t.width||1)*e,unsafe:t.width>e}}function u_(t,e,n){let i=t.width?t.width:t.maxWidth;return n.height<=t.maxHeight&&n.width<=t.maxWidth&&n.height>=t.minHeight&&n.width>=t.minWidth&&(!e||Math.abs(n.width-i)<Math.abs(e.width-i))}function c_(t,e){let n=[],i=Object.assign({unsafeImageService:!1,atAnyCost:!0,fallback:!0,minHeight:64,minWidth:64,maxHeight:1/0,maxWidth:1/0,returnAllOptions:!1,preferFixedSize:!1,allowUnsafe:!1,explain:!1,height:0,width:0},t),a=(d,m=0)=>i.explain?n.push(Array(m).fill(0).map(y=>" ").join("")+d().trim()):void 0,r=[],l=[],u=null;a(()=>`Using configuration: ${JSON.stringify(i,null,2)}`);let f=(d,m)=>{if(a(()=>"Swapping choice",3),u_(i,m,d)){if(i.preferFixedSize&&d.unsafe){a(()=>`We found an image that was marked as unsafe, but it was the best size. (${d.id})`,4),l.push(d);return}i.returnAllOptions&&m&&l.push(m),a(()=>`We found a new image that was the best size. (${d.id})`,4),u=d}else i.returnAllOptions&&l.push(d)};a(()=>`The input shows we have ${e.length} list(s) of candidates to choose from.`);let h=e.length;for(let d=0;d<h;d++){let m=e[d]();a(()=>`Candidate group ${d}: ${JSON.stringify(m,null,2)}`,1);let y=m.length;a(()=>`Checking candidate list number ${d} and found ${y} potential ways of creating image(s)`,1);for(let g=0;g<y;g++){let b=m[g];a(()=>`-> Checking candidate ${g}`,1),b.type==="unknown"&&i.atAnyCost&&(a(()=>`We've found an unknown image type, adding this to the "last resort" list`,2),r.push(b)),b.type==="fixed"&&(b.unsafe?(a(()=>`We've found an unsafe fixed image type, adding this to the "last resort" list`,2),r.push(b)):(a(()=>"We've found a fixed size image, checking if it matches the request",2),f(b,u))),b.type==="fixed-service"&&(i.unsafeImageService?(a(()=>"Checking for an image from the tile source, without calculating the right height and width (unsafeImageService)",2),f(Vg(b,i.width,i.height),u)):(a(()=>"Checking for an image from the tile source 3",2),f(Vg(b,b.width,b.height),u))),b.type==="variable"&&b.maxWidth&&f(Vg({id:b.id,type:"fixed-service",width:b.maxWidth,height:b.maxWidth,level:b.level,version:b.version},b.maxWidth),u)}if(u&&!i.returnAllOptions){if(u.unsafe||i.allowUnsafe)continue;a(()=>`We found a match in choice list number ${d}, no searching any more`);break}}return i.atAnyCost&&l.length===0?(a(()=>u?`We found an image! ${u.id} of type ${u.type}`:'We found no images, but "atAnyCost" is set, so returning that'),{best:u||r[0]||null,fallback:r.slice(1),log:n}):i.returnAllOptions?(a(()=>"Returning all options that we have found"),{best:(i.atAnyCost?u||l[0]||r[0]:u||l[0])||null,fallback:[...l,...r],log:n}):(a(()=>"Returning the best image that we found, and a fallback"),{best:u||l[0]||null,fallback:u?l:l.slice(1),log:n})}function sx(t){return(t["@context"]?Array.isArray(t["@context"])?t["@context"]:[t["@context"]]:[]).indexOf("http://iiif.io/api/image/3/context.json")!==-1}function d_(t){return qf(t)?(t&&t.sizes?t.sizes:[]).map(e=>({id:ke(t),type:"fixed-service",height:e.height,width:e.width,level:qg(t),version:sx(t)?3:2})):[]}function f_(t){if(!a_(t))return[];let e=[],n=Array.isArray(t.profile)?t.profile:[t.profile],i=n.length;for(let a=0;a<i;a++){let r=n[a];if(r&&typeof r!="string"&&(r.maxHeight||r.maxWidth))return[{id:ke(t),type:"variable",minWidth:0,minHeight:0,maxHeight:r.maxHeight||r.maxWidth,maxWidth:r.maxWidth||r.maxHeight,level:qg(t),version:t["@context"]==="http://iiif.io/api/image/3/context.json"?3:2}]}if(t.tiles){let a=t.tiles.length;for(let r=0;r<a;r++){let l=t.tiles[r];l&&(l.height||l.width)&&e.push({id:ke(t),type:"variable",minHeight:0,minWidth:0,maxHeight:l.height||l.width,maxWidth:l.width,level:qg(t),version:sx(t)?3:2})}}return e}function rx(t){let e=[],n=t.length;for(let i=0;i<n;i++){let a=t[i];if(!a)continue;let r=d_(a);r.length&&e.push(...r);let l=f_(a);l.length&&e.push(...l)}return e}function ox(t){let e=t.match(/^.*\/(full)\/(((\d+),(\d+)?)|max)\/(\d+)\/default\.(jpg|png|jpeg)$/);if(e&&e[4]&&e[5]){let n=e[1],i=parseInt(e[4],10),a=parseInt(e[5],10),r=e[7];if((n==="max"||n==="full")&&i&&a&&r)return{type:"fixed",id:t,height:a,width:i}}return{type:"unknown",id:t}}function Vf(t){if(typeof t=="string")return ox(t);let e=s_(t);if(e!=="Image"&&e!=="sc:Image")return null;let n=t,i=ke(n);return i?i&&n.width&&n.height?{id:i,type:"fixed",width:n.width,height:n.height,unsafe:!0}:ox(i):null}function h_(t,e=!0,n){let i=[],a=Vf(t);if(a===null)return i;let r=t;if(i.push(a),e&&r&&r.width&&r.height){let l=[],u=vs(r);for(let f of u){let h={id:ke(f),width:r.width,height:r.height};if(n.canLoadSync(h)){let d=n.loadServiceSync(h);d&&(d.height||(d.height=r.height),d.width||(d.width=r.width),l.push(...rx([d])))}}if(l.length)return i.push(...l),i}return r.service&&i.push(...rx(r.service)),i}function p_(t,e){if(t.length!==e.length)return!1;if(t.length===0&&e.length===0)return!0;let n=t.length,i=!0;for(let r=0;r<n;r++){let l=t[r],u=e[r];if(l.width!==u.width||l.height!==u.height){i=!1;break}}if(i)return!0;let a=0;for(let r=0;r<n;r++)for(let l=0;l<n;l++)if(t[r].width===e[l].width&&t[r].height===e[l].height){a++;break}return a===n}var Ic=class{constructor(t={}){kn(this,"config",{verificationsRequired:1,approximateServices:!1,enableFetching:!0,disableThrottling:!1}),kn(this,"fetchingCount",0),kn(this,"imageServices",{}),kn(this,"knownImageServers",{}),this.config=Object.assign(this.config,t)}setConfig(t){Object.assign(this.config,t)}sample(t,e,n=!0){let i=Yl(ke(t)),a=ys(ke(t)),r=this.knownImageServers[i];return this.imageServices[a]=Object.assign(t,{real:!0}),!r&&t.tiles&&!ax(t)?(this.knownImageServers[i]={verifications:0,malformed:!1,root:i,preLoaded:n,sampledId:ke(t),verified:!1,server:null,result:{context:t["@context"]||[],sampledProfile:t.profile,resourceServiceRatio:e&&t.height?e.height/t.height:1,sampledSizes:t.sizes||[],sizeRatios:r_(t.width,t.height,t.sizes||[]),sampledTiles:t.tiles||[]}},!0):this.verify(t)}preLoad(t,e=!0){this.knownImageServers[t.root]=t,e&&(this.knownImageServers[t.root].malformed=!1,this.knownImageServers[t.root].verifications=this.config.verificationsRequired)}predict(t,e=!1,n=!1){let i=t?.source,a=Yl(ke(t)),r=this.knownImageServers[a],l=ys(ke(t));return this.imageServices[l]?this.imageServices[l]||null:!this.config.approximateServices||!r||!r.result||!(i?.height||t.height)||!(i?.width||t.width)||!n&&(r.malformed||r.verifications<this.config.verificationsRequired)||t.source&&ax(t.source)?null:(this.imageServices[l]||(this.imageServices[l]={"@context":r.result.context,"@id":ke(t),id:ke(t),protocol:"http://iiif.io/api/image",tiles:i?.tiles||l_(t.width,t.height,r.result.sampledTiles),sizes:i?.sizes||o_(Math.round(t.width/r.result.resourceServiceRatio),Math.round(t.height/r.result.resourceServiceRatio),r.result.sizeRatios),profile:i?.profile||r.result.sampledProfile,height:i?.height||t.height,width:i?.width||t.width,real:!1}),this.imageServices[l]||null)}async getThumbnailFromResource(t,e,n=!0,i=[]){let a=t?await this.getImageCandidates(t,n):[];return c_(e,[()=>i,()=>a])}async getImageCandidates(t,e=!0){let n=t;if(e&&n&&n.height&&n.width){let i=vs(n);for(let a of i){let r={id:ke(a),width:a.width?a.width:n.width,height:a.height?a.height:n.height,source:a};await this.loadService(r)}}return h_(t,e,this)}async verify(t){let e=this.predict(t,!1,!0),n=await this.fetchService(ke(t));if(!e)return!1;let i=e.height===n.height&&e.width===n.width&&e["@context"]===n["@context"]&&p_(e.sizes||[],n.sizes||[]);if(i){let a=Yl(ke(t)),r=this.knownImageServers[a];r&&(r.verifications+=1,r.verifications>=this.config.verificationsRequired&&(r.verified=!0))}return i}canLoadSync(t){let e=typeof t=="string"?t:ke(t),n=ys(e);if(this.imageServices[n])return!0;let i=this.knownImageServers[Yl(e)];return!!(i&&!i.malformed&&i.verifications>=this.config.verificationsRequired)}async markAsMalformed(t){return this.knownImageServers[Yl(ke(t))].malformed=!0,this.loadService(t,!0)}async fetchService(t,e=!1){let n=ys(t),i=this.imageServices[n];if(i&&(!e||i.real))return i;if(!this.config.enableFetching)throw Error("Fetching is not enabled");let a=await this.fetch(n).then(r=>r.json());return!a.id&&a["@id"]&&(a.id=a["@id"]),a.id!==t&&(a.id=t,a["@id"]&&(a["@id"]=t)),this.imageServices[n]=Object.assign(a,{real:!0}),this.imageServices[n]}async fetch(t,e){return fetch(t,e)}async loadService(t,e=!1){if(!this.config.disableThrottling){let a=!0;for(;a;)if(this.fetchingCount>=this.config.verificationsRequired)await new Promise(r=>setTimeout(r,500));else{a=!1;break}}let n=this.knownImageServers[Yl(ke(t))];if(n&&!n.malformed&&!e){await n.result;let a=this.loadServiceSync(t);if(a)return a}this.fetchingCount++;let i=await this.fetchService(ke(t),e);return this.fetchingCount--,i.real&&this.sample(i,t),i}loadServiceSync(t){let e=ys(ke(t));return this.imageServices[e]?this.imageServices[e]:this.config.approximateServices?this.predict(t):null}};function m_(t={}){let e=t.events||Km(),n=t.loader||new Ic;return{store:Qm((i,a)=>({loaded:{},loadServiceSync:(r,l,u)=>{let f=r.id||r["@id"],h=a().loaded[f];if(h&&h.status==="done")return h.service;if(h&&h.status==="loading")return null;if(h&&h.status==="error")throw Error("Failed to load image service");let d={id:ke(r),width:r.width||l?.width||0,height:r.height||l?.height||0,source:r},m=n.loadServiceSync(d);return m?(i(y=>({loaded:{...y.loaded,[f]:{status:"done",service:m,real:!0}}})),e.emit("image-service.loaded",{id:f,service:m})):u&&a().loadService(r,l).then(()=>{}),m},loadService:async(r,l)=>{let u=r.id||r["@id"],f=a().loaded[u];if(f&&f.status==="done")return f.service;if(f&&f.status==="loading")return new Promise((h,d)=>{let m=y=>{y.id===u&&(e.off("image-service.loaded",m),h(y.service||r))};e.on("image-service.loaded",m)});if(f&&f.status==="error"&&!l?.force)throw Error("Failed to load image service");e.emit("image-service.loading",{id:u});try{let h={id:ke(r),width:r.width||0,height:r.height||0,source:r},d=await n.loadService(h,l?.force);return i(m=>({loaded:{...m.loaded,[u]:{status:"done",service:d,real:d.real}}})),e.emit("image-service.loaded",{id:u,service:d}),d}catch(h){throw e.emit("image-service.error",{id:u,error:h}),h}}})),events:e}}var lx=m_();var g_=new Ic;function ux(t=go,e={}){let n=e.imageServiceLoader||g_;async function i(a,r,l=!1,u=[],f){let h=()=>n.getThumbnailFromResource(void 0,r,l,u);if(!a)return await n.getThumbnailFromResource(void 0,r,l,u);if(typeof a=="string"){let m=Vf(a);return m&&u.push(m),await n.getThumbnailFromResource(void 0,r,l,u)}let d=t.get(a,{skipSelfReturn:!1});if(typeof d=="string")return{best:Vf(d),fallback:[],log:[]};if(!d)return await h();switch(await(async m=>{if(m&&m.thumbnail&&m.thumbnail.length){let y=t.get(m.thumbnail[0]),g=await n.getImageCandidates(y,l);g&&g.length&&u.push(...g)}})(d),d.type){case"Annotation":{let m=Array.isArray(d.body)?d.body:[d.body],y=t.get(m[0]);return f&&!y.width&&(y.width=f.width,y.height=f.height),await n.getThumbnailFromResource(y,r,l,u)}case"Canvas":{let m=d;return i(m.items[0],r,l,u,{width:m.width,height:m.height})}case"AnnotationPage":return i(d.items[0],r,l,u,f);case"Choice":{let m=d;return!m.items||m.items[0]?await h():i(m.items[0],r,l,u,f)}case"Collection":{let m=d.items[0];return m?i(m,r,l,u,f):await h()}case"Manifest":{let m=d.items[0];return m?i(m,r,l,u,f):await h()}case"SpecificResource":case"Image":case"Dataset":case"Sound":case"Text":case"TextualBody":case"Video":return f&&!d.width&&(d.width=f.width,d.height=f.height),n.getThumbnailFromResource(d,r,l,u)}return await h()}return{getBestThumbnailAtSize:i}}var Fv=I(ut(),1),k=I(ut(),1);var ba=I(ut(),1);function y_(t,e){let n;return(...i)=>{window.clearTimeout(n),n=window.setTimeout(()=>t(...i),e)}}function cx({debounce:t,scroll:e,polyfill:n,offsetSize:i}={debounce:0,scroll:!1,offsetSize:!1}){let a=n||(typeof window>"u"?class{}:window.ResizeObserver);if(!a)throw new Error("This browser does not support ResizeObserver out of the box. See: https://github.com/react-spring/react-use-measure/#resize-observer-polyfills");let[r,l]=(0,ba.useState)({left:0,top:0,width:0,height:0,bottom:0,right:0,x:0,y:0}),u=(0,ba.useRef)({element:null,scrollContainers:null,resizeObserver:null,lastBounds:r,orientationHandler:null}),f=t?typeof t=="number"?t:t.scroll:null,h=t?typeof t=="number"?t:t.resize:null,d=(0,ba.useRef)(!1);(0,ba.useEffect)(()=>(d.current=!0,()=>void(d.current=!1)));let[m,y,g]=(0,ba.useMemo)(()=>{let T=()=>{if(!u.current.element)return;let{left:S,top:R,width:A,height:M,bottom:z,right:N,x:L,y:H}=u.current.element.getBoundingClientRect(),U={left:S,top:R,width:A,height:M,bottom:z,right:N,x:L,y:H};u.current.element instanceof HTMLElement&&i&&(U.height=u.current.element.offsetHeight,U.width=u.current.element.offsetWidth),Object.freeze(U),d.current&&!Uq(u.current.lastBounds,U)&&l(u.current.lastBounds=U)};return[T,h?y_(T,h):T,f?y_(T,f):T]},[l,i,f,h]);function b(){u.current.scrollContainers&&(u.current.scrollContainers.forEach(T=>T.removeEventListener("scroll",g,!0)),u.current.scrollContainers=null),u.current.resizeObserver&&(u.current.resizeObserver.disconnect(),u.current.resizeObserver=null),u.current.orientationHandler&&("orientation"in screen&&"removeEventListener"in screen.orientation?screen.orientation.removeEventListener("change",u.current.orientationHandler):"onorientationchange"in window&&window.removeEventListener("orientationchange",u.current.orientationHandler))}function w(){u.current.element&&(u.current.resizeObserver=new a(g),u.current.resizeObserver.observe(u.current.element),e&&u.current.scrollContainers&&u.current.scrollContainers.forEach(T=>T.addEventListener("scroll",g,{capture:!0,passive:!0})),u.current.orientationHandler=()=>{g()},"orientation"in screen&&"addEventListener"in screen.orientation?screen.orientation.addEventListener("change",u.current.orientationHandler):"onorientationchange"in window&&window.addEventListener("orientationchange",u.current.orientationHandler))}let E=T=>{!T||T===u.current.element||(b(),u.current.element=T,u.current.scrollContainers=v_(T),w())};return qq(g,!!e),Fq(y),(0,ba.useEffect)(()=>{b(),w()},[e,g,y]),(0,ba.useEffect)(()=>b,[]),[E,r,m]}function Fq(t){(0,ba.useEffect)(()=>{let e=t;return window.addEventListener("resize",e),()=>void window.removeEventListener("resize",e)},[t])}function qq(t,e){(0,ba.useEffect)(()=>{if(e){let n=t;return window.addEventListener("scroll",n,{capture:!0,passive:!0}),()=>void window.removeEventListener("scroll",n,!0)}},[t,e])}function v_(t){let e=[];if(!t||t===document.body)return e;let{overflow:n,overflowX:i,overflowY:a}=window.getComputedStyle(t);return[n,i,a].some(r=>r==="auto"||r==="scroll")&&e.push(t),[...e,...v_(t.parentElement)]}var Vq=["x","y","top","bottom","left","right","width","height"],Uq=(t,e)=>Vq.every(n=>t[n]===e[n]);var W=I(Z(),1),Gh=I(I_(),1),m8=Object.create,R3=Object.defineProperty,g8=Object.getOwnPropertyDescriptor,y8=Object.getOwnPropertyNames,v8=Object.getPrototypeOf,b8=Object.prototype.hasOwnProperty,tp=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),S8=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(var a=y8(e),r=0,l=a.length,u;r<l;r++)u=a[r],!b8.call(t,u)&&u!==n&&R3(t,u,{get:(f=>e[f]).bind(null,u),enumerable:!(i=g8(e,u))||i.enumerable});return t},E3=(t,e,n)=>(n=t==null?{}:m8(v8(t)),S8(e||!t||!t.__esModule?R3(n,"default",{value:t,enumerable:!0}):n,t)),qv="onMouseDown.onMouseEnter.onMouseLeave.onMouseMove.onMouseOut.onMouseOver.onMouseUp.onTouchCancel.onTouchEnd.onTouchMove.onTouchStart.onPointerDown.onPointerMove.onPointerUp.onPointerCancel.onPointerEnter.onPointerLeave.onPointerOver.onPointerOut.onScroll.onWheel.onClick.onDragStart.onDragEnd.onDragEnter.onDragExit.onDrag.onDragOver.onContextMenu".split(".");function x8(){return qv.reduce((t,e)=>(t[e]=[],t),{})}var Rd=qv.reduce((t,e)=>(t[e.slice(2).toLowerCase()]=e,t[e]=e,t),{});function w8(t,e,n=1){let i=e.length;if(i===0)throw Error("No resources passed in.");let a=0,r=1/0;for(let l=0;l<i&&!(!e[l]||!e[l].display);l++){let u=JT(e[l].display.scale,t/(n||1));u<r&&(r=u,a=l)}return a}function JT(t,e){return Math.abs(t-e)}function Qh(t,e){let n=JT(t.x,e.x),i=JT(t.y,e.y);return Math.sqrt(n**2+i**2)}function T8(t){let e=t.length;return t.indexOf("/info.json")===e-10?t.slice(0,-10):t}function Wh(t){"@babel/helpers - typeof";return Wh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Wh(t)}function R8(t,e){if(Wh(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var i=n.call(t,e||"default");if(Wh(i)!="object")return i;throw TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function E8(t){var e=R8(t,"string");return Wh(e)=="symbol"?e:e+""}function C(t,e,n){return(e=E8(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var sR=class Mv{constructor(e,n,i){C(this,"element",void 0),C(this,"runtime",void 0),C(this,"unsubscribe",void 0),C(this,"activatedEvents",[]),C(this,"eventHandlers",[]),C(this,"bounds",void 0),C(this,"listening",void 0),C(this,"pointerMoveEvent",void 0),C(this,"pointerEventState",{isClicking:!1,isDragging:!1,isPressed:!1,mousedOver:[],itemsBeingDragged:[],mouseDownStart:{x:0,y:0},lastTouches:[]}),C(this,"options",void 0),C(this,"_realPointerMove",r=>{this.pointerMoveEvent=r}),C(this,"onWheelEvent",r=>{r.preventDefault(),this.onPointerEvent(r)}),C(this,"onContextMenu",r=>{r.preventDefault();let l="onContextMenu";if(this.runtime.world.activatedEvents.indexOf(l)!==-1){let{x:u,y:f}=this.runtime.viewerToWorld(r.clientX-this.bounds.left,r.clientY-this.bounds.top);this.assignToEvent(r,u,f),this.runtime.world.propagatePointerEvent(l,r,u,f)}}),C(this,"onTouchEvent",r=>{let l=Rd[r.type],u=[],f=r.touches.length;for(let h=0;h<f;h++){let d=r.touches.item(h);if(!d)continue;let{x:m,y}=this.runtime.viewerToWorld(d.clientX-this.bounds.left,d.clientY-this.bounds.top),g={id:d.identifier,x:m,y};u.push(g)}u.length&&this.assignToEvent(r,u[0].x,u[0].y),l!=="onTouchEnd"&&l!=="onTouchCancel"?(this.pointerEventState.lastTouches=u,r.atlasTouches=u,this.runtime.world.propagateTouchEvent(l,r,u)):(r.atlasTouches=[],this.runtime.world.propagateTouchEvent(l,r,this.pointerEventState.lastTouches),this.pointerEventState.lastTouches=[])}),C(this,"onPointerEvent",r=>{if(r.button===2)return;let l=Rd[r.type];if(l&&this.runtime.world.activatedEvents.indexOf(l)!==-1){let{x:u,y:f}=this.runtime.viewerToWorld(r.clientX-this.bounds.left,r.clientY-this.bounds.top);this.assignToEvent(r,u,f),this.runtime.world.propagatePointerEvent(l,r,u,f)}}),C(this,"onPointerDown",r=>{r.button!==2&&(this.pointerEventState.isPressed=!0,this.pointerEventState.isClicking=!0,this.pointerEventState.mouseDownStart.x=r.clientX,this.pointerEventState.mouseDownStart.y=r.clientY,setTimeout(()=>{this.runtime&&(this.pointerEventState.isClicking=!1)},250),setTimeout(()=>{if(this.runtime&&this.pointerEventState.isPressed&&!this.pointerEventState.isDragging){let l=this.runtime.viewerToWorld(this.pointerEventState.mouseDownStart.x-this.bounds.left,this.pointerEventState.mouseDownStart.y-this.bounds.top);this.pointerEventState.isDragging=!0,this.pointerEventState.itemsBeingDragged=this.runtime.world.propagatePointerEvent("onDragStart",r,l.x,l.y)}},800),this.onPointerEvent(r))}),C(this,"onPointerUp",r=>{if(r.button!==2){if(this.pointerEventState.isClicking){let{x:l,y:u}=this.runtime.viewerToWorld(r.clientX-this.bounds.left,r.clientY-this.bounds.top);this.assignToEvent(r,l,u),this.runtime.world.propagatePointerEvent("onClick",r,l,u)}if(this.pointerEventState.isDragging){for(let l of this.pointerEventState.itemsBeingDragged)l.dispatchEvent("onDragEnd",r);this.pointerEventState.isDragging=!1}this.pointerEventState.isClicking=!1,this.pointerEventState.isPressed=!1,this.pointerEventState.itemsBeingDragged=[],this.onPointerEvent(r)}}),C(this,"onPointerMove",r=>{this.pointerMoveEvent=void 0;let{x:l,y:u}=this.runtime.viewerToWorld(r.clientX-this.bounds.left,r.clientY-this.bounds.top);if(Number.isNaN(l)||Number.isNaN(u))return;this.assignToEvent(r,l,u),this.runtime.world.propagatePointerEvent("onPointerMove",r,l,u);let f=this.runtime.world.propagatePointerEvent("onMouseMove",r,l,u),h=[],d=[];for(let m of f)h.push(m.id),d.push(m),this.pointerEventState.mousedOver.indexOf(m)===-1&&(m.dispatchEvent("onMouseEnter",r),m.dispatchEvent("onPointerEnter",r),m.dispatchEvent("onMouseOver",r),m.dispatchEvent("onPointerOver",r));for(let m of this.pointerEventState.mousedOver)h.indexOf(m.id)===-1&&(m.dispatchEvent("onMouseLeave",r),m.dispatchEvent("onPointerLeave",r),m.dispatchEvent("onMouseOut",r),m.dispatchEvent("onPointerOut",r));if(this.pointerEventState.isDragging)for(let m of this.pointerEventState.itemsBeingDragged)m.dispatchEvent("onDrag",r);if(this.pointerEventState.isPressed&&!this.pointerEventState.isDragging&&Qh(this.pointerEventState.mouseDownStart,{x:r.clientX,y:r.clientY})>50){let m=this.runtime.viewerToWorld(this.pointerEventState.mouseDownStart.x-this.bounds.left,this.pointerEventState.mouseDownStart.y-this.bounds.top);this.pointerEventState.isDragging=!0,this.pointerEventState.itemsBeingDragged=this.runtime.world.propagatePointerEvent("onDragStart",{...r,atlas:{x:m.x,y:m.y}},m.x,m.y)}this.pointerEventState.mousedOver=d}),this.element=e,this.runtime=n,this.unsubscribe=n.world.addLayoutSubscriber(this.layoutSubscriber.bind(this)),this.bounds=e.getBoundingClientRect(),this.listening=!1,this.options={simulationRate:0,...i||{}};let a=0;n.registerHook("useFrame",r=>{a+=r,a>this.options.simulationRate&&this.pointerMoveEvent&&(a=0,n.updateNextFrame())}),n.registerHook("useBeforeFrame",()=>{this.pointerMoveEvent&&this.onPointerMove(this.pointerMoveEvent)}),this.activateEvents()}updateBounds(){this.bounds=this.element.getBoundingClientRect(),this.runtime.updateRendererScreenPosition()}layoutSubscriber(e){e==="event-activation"&&this.listening==0&&this.activateEvents()}assignToEvent(e,n,i){Mv.eventPool.atlas.x=n,Mv.eventPool.atlas.y=i,e.atlas=Mv.eventPool.atlas}activateEvents(){this.listening=!0,this.element.addEventListener("pointermove",this._realPointerMove),this.element.addEventListener("pointerup",this.onPointerUp),this.element.addEventListener("pointerdown",this.onPointerDown),this.element.addEventListener("mousedown",this.onPointerEvent),this.element.addEventListener("mouseup",this.onPointerEvent),this.element.addEventListener("pointercancel",this.onPointerEvent),this.element.addEventListener("wheel",this.onWheelEvent),this.element.addEventListener("contextmenu",this.onContextMenu),this.element.addEventListener("touchstart",this.onTouchEvent),this.element.addEventListener("touchcancel",this.onTouchEvent),this.element.addEventListener("touchend",this.onTouchEvent),this.element.addEventListener("touchmove",this.onTouchEvent)}normalizeEventName(e){return e.startsWith("on")?e.slice(2).toLowerCase():e.toLowerCase()}stop(){this.listening=!1,this.element.removeEventListener("pointermove",this._realPointerMove),this.element.removeEventListener("pointerup",this.onPointerUp),this.element.removeEventListener("pointerdown",this.onPointerDown),this.element.removeEventListener("mousedown",this.onPointerEvent),this.element.removeEventListener("mouseup",this.onPointerEvent),this.element.removeEventListener("pointercancel",this.onPointerEvent),this.element.removeEventListener("wheel",this.onWheelEvent),this.element.removeEventListener("touchstart",this.onTouchEvent),this.element.removeEventListener("touchcancel",this.onTouchEvent),this.element.removeEventListener("touchend",this.onTouchEvent),this.element.removeEventListener("touchmove",this.onTouchEvent),this.unsubscribe();for(let[e,n]of this.eventHandlers)this.element.removeEventListener(this.normalizeEventName(e),n)}};C(sR,"eventPool",{atlas:{x:0,y:0}});var jh=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Nv=typeof AbortController=="function"?AbortController:class{constructor(){this.signal=new A3}abort(t=Error("This operation was aborted")){this.signal.reason=this.signal.reason||t,this.signal.aborted=!0,this.signal.dispatchEvent({type:"abort",target:this.signal})}},A8=typeof AbortSignal=="function",C8=typeof Nv.AbortSignal=="function",A3=A8?AbortSignal:C8?Nv.AbortController:class{constructor(){this.reason=void 0,this.aborted=!1,this._listeners=[]}dispatchEvent(t){t.type==="abort"&&(this.aborted=!0,this.onabort(t),this._listeners.forEach(e=>e(t),this))}onabort(){}addEventListener(t,e){t==="abort"&&this._listeners.push(e)}removeEventListener(t,e){t==="abort"&&(this._listeners=this._listeners.filter(n=>n!==e))}},lR=new Set,kT=(t,e)=>{let n=`LRU_CACHE_OPTION_${t}`;Vv(n)&&uR(n,`${t} option`,`options.${e}`,Uv)},GT=(t,e)=>{let n=`LRU_CACHE_METHOD_${t}`;if(Vv(n)){let{prototype:i}=Uv,{get:a}=Object.getOwnPropertyDescriptor(i,t);uR(n,`${t} method`,`cache.${e}()`,a)}},M8=(t,e)=>{let n=`LRU_CACHE_PROPERTY_${t}`;if(Vv(n)){let{prototype:i}=Uv,{get:a}=Object.getOwnPropertyDescriptor(i,t);uR(n,`${t} property`,`cache.${e}`,a)}},C3=(...t)=>{typeof process=="object"&&process&&typeof process.emitWarning=="function"?process.emitWarning(...t):console.error(...t)},Vv=t=>!lR.has(t),uR=(t,e,n,i)=>{lR.add(t),C3(`The ${e} is deprecated. Please use ${n} instead.`,"DeprecationWarning",t,i)},Qs=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),M3=t=>Qs(t)?t<=2**8?Uint8Array:t<=2**16?Uint16Array:t<=2**32?Uint32Array:t<=2**53-1?Ov:null:null,Ov=class extends Array{constructor(t){super(t),this.fill(0)}},O8=class{constructor(t){if(t===0)return[];this.heap=new(M3(t))(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},Uv=class $T{constructor(e={}){let{max:n=0,ttl:i,ttlResolution:a=1,ttlAutopurge:r,updateAgeOnGet:l,updateAgeOnHas:u,allowStale:f,dispose:h,disposeAfter:d,noDisposeOnSet:m,noUpdateTTL:y,maxSize:g=0,maxEntrySize:b=0,sizeCalculation:w,fetchMethod:E,fetchContext:T,noDeleteOnFetchRejection:S,noDeleteOnStaleGet:R,allowStaleOnFetchRejection:A,allowStaleOnFetchAbort:M,ignoreFetchAbort:z}=e,{length:N,maxAge:L,stale:H}=e instanceof $T?{}:e;if(n!==0&&!Qs(n))throw TypeError("max option must be a nonnegative integer");let U=n?M3(n):Array;if(!U)throw Error("invalid max value: "+n);if(this.max=n,this.maxSize=g,this.maxEntrySize=b||this.maxSize,this.sizeCalculation=w||N,this.sizeCalculation){if(!this.maxSize&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw TypeError("sizeCalculation set to non-function")}if(this.fetchMethod=E||null,this.fetchMethod&&typeof this.fetchMethod!="function")throw TypeError("fetchMethod must be a function if specified");if(this.fetchContext=T,!this.fetchMethod&&T!==void 0)throw TypeError("cannot set fetchContext without fetchMethod");if(this.keyMap=new Map,this.keyList=Array(n).fill(null),this.valList=Array(n).fill(null),this.next=new U(n),this.prev=new U(n),this.head=0,this.tail=0,this.free=new O8(n),this.initialFill=1,this.size=0,typeof h=="function"&&(this.dispose=h),typeof d=="function"?(this.disposeAfter=d,this.disposed=[]):(this.disposeAfter=null,this.disposed=null),this.noDisposeOnSet=!!m,this.noUpdateTTL=!!y,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!A,this.allowStaleOnFetchAbort=!!M,this.ignoreFetchAbort=!!z,this.maxEntrySize!==0){if(this.maxSize!==0&&!Qs(this.maxSize))throw TypeError("maxSize must be a positive integer if specified");if(!Qs(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.initializeSizeTracking()}if(this.allowStale=!!f||!!H,this.noDeleteOnStaleGet=!!R,this.updateAgeOnGet=!!l,this.updateAgeOnHas=!!u,this.ttlResolution=Qs(a)||a===0?a:1,this.ttlAutopurge=!!r,this.ttl=i||L||0,this.ttl){if(!Qs(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.initializeTTLTracking()}if(this.max===0&&this.ttl===0&&this.maxSize===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.max&&!this.maxSize){let nt="LRU_CACHE_UNBOUNDED";Vv(nt)&&(lR.add(nt),C3("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",nt,$T))}H&&kT("stale","allowStale"),L&&kT("maxAge","ttl"),N&&kT("length","sizeCalculation")}getRemainingTTL(e){return this.has(e,{updateAgeOnHas:!1})?1/0:0}initializeTTLTracking(){this.ttls=new Ov(this.max),this.starts=new Ov(this.max),this.setItemTTL=(i,a,r=jh.now())=>{if(this.starts[i]=a===0?0:r,this.ttls[i]=a,a!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.isStale(i)&&this.delete(this.keyList[i])},a+1);l.unref&&l.unref()}},this.updateItemAge=i=>{this.starts[i]=this.ttls[i]===0?0:jh.now()},this.statusTTL=(i,a)=>{i&&(i.ttl=this.ttls[a],i.start=this.starts[a],i.now=e||n(),i.remainingTTL=i.now+i.ttl-i.start)};let e=0,n=()=>{let i=jh.now();if(this.ttlResolution>0){e=i;let a=setTimeout(()=>e=0,this.ttlResolution);a.unref&&a.unref()}return i};this.getRemainingTTL=i=>{let a=this.keyMap.get(i);return a===void 0?0:this.ttls[a]===0||this.starts[a]===0?1/0:this.starts[a]+this.ttls[a]-(e||n())},this.isStale=i=>this.ttls[i]!==0&&this.starts[i]!==0&&(e||n())-this.starts[i]>this.ttls[i]}updateItemAge(e){}statusTTL(e,n){}setItemTTL(e,n,i){}isStale(e){return!1}initializeSizeTracking(){this.calculatedSize=0,this.sizes=new Ov(this.max),this.removeItemSize=e=>{this.calculatedSize-=this.sizes[e],this.sizes[e]=0},this.requireSize=(e,n,i,a)=>{if(this.isBackgroundFetch(n))return 0;if(!Qs(i))if(a){if(typeof a!="function")throw TypeError("sizeCalculation must be a function");if(i=a(n,e),!Qs(i))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.addItemSize=(e,n,i)=>{if(this.sizes[e]=n,this.maxSize){let a=this.maxSize-this.sizes[e];for(;this.calculatedSize>a;)this.evict(!0)}this.calculatedSize+=this.sizes[e],i&&(i.entrySize=n,i.totalCalculatedSize=this.calculatedSize)}}removeItemSize(e){}addItemSize(e,n){}requireSize(e,n,i,a){if(i||a)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache")}*indexes({allowStale:e=this.allowStale}={}){if(this.size)for(let n=this.tail;!(!this.isValidIndex(n)||((e||!this.isStale(n))&&(yield n),n===this.head));)n=this.prev[n]}*rindexes({allowStale:e=this.allowStale}={}){if(this.size)for(let n=this.head;!(!this.isValidIndex(n)||((e||!this.isStale(n))&&(yield n),n===this.tail));)n=this.next[n]}isValidIndex(e){return e!==void 0&&this.keyMap.get(this.keyList[e])===e}*entries(){for(let e of this.indexes())this.valList[e]!==void 0&&this.keyList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield[this.keyList[e],this.valList[e]])}*rentries(){for(let e of this.rindexes())this.valList[e]!==void 0&&this.keyList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield[this.keyList[e],this.valList[e]])}*keys(){for(let e of this.indexes())this.keyList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield this.keyList[e])}*rkeys(){for(let e of this.rindexes())this.keyList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield this.keyList[e])}*values(){for(let e of this.indexes())this.valList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield this.valList[e])}*rvalues(){for(let e of this.rindexes())this.valList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield this.valList[e])}[Symbol.iterator](){return this.entries()}find(e,n){for(let i of this.indexes()){let a=this.valList[i],r=this.isBackgroundFetch(a)?a.__staleWhileFetching:a;if(r!==void 0&&e(r,this.keyList[i],this))return this.get(this.keyList[i],n)}}forEach(e,n=this){for(let i of this.indexes()){let a=this.valList[i],r=this.isBackgroundFetch(a)?a.__staleWhileFetching:a;r!==void 0&&e.call(n,r,this.keyList[i],this)}}rforEach(e,n=this){for(let i of this.rindexes()){let a=this.valList[i],r=this.isBackgroundFetch(a)?a.__staleWhileFetching:a;r!==void 0&&e.call(n,r,this.keyList[i],this)}}get prune(){return GT("prune","purgeStale"),this.purgeStale}purgeStale(){let e=!1;for(let n of this.rindexes({allowStale:!0}))this.isStale(n)&&(this.delete(this.keyList[n]),e=!0);return e}dump(){let e=[];for(let n of this.indexes({allowStale:!0})){let i=this.keyList[n],a=this.valList[n],r=this.isBackgroundFetch(a)?a.__staleWhileFetching:a;if(r===void 0)continue;let l={value:r};if(this.ttls){l.ttl=this.ttls[n];let u=jh.now()-this.starts[n];l.start=Math.floor(Date.now()-u)}this.sizes&&(l.size=this.sizes[n]),e.unshift([i,l])}return e}load(e){this.clear();for(let[n,i]of e){if(i.start){let a=Date.now()-i.start;i.start=jh.now()-a}this.set(n,i.value,i)}}dispose(e,n,i){}set(e,n,{ttl:i=this.ttl,start:a,noDisposeOnSet:r=this.noDisposeOnSet,size:l=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:f=this.noUpdateTTL,status:h}={}){if(l=this.requireSize(e,n,l,u),this.maxEntrySize&&l>this.maxEntrySize)return h&&(h.set="miss",h.maxEntrySizeExceeded=!0),this.delete(e),this;let d=this.size===0?void 0:this.keyMap.get(e);if(d===void 0)d=this.newIndex(),this.keyList[d]=e,this.valList[d]=n,this.keyMap.set(e,d),this.next[this.tail]=d,this.prev[d]=this.tail,this.tail=d,this.size++,this.addItemSize(d,l,h),h&&(h.set="add"),f=!1;else{this.moveToTail(d);let m=this.valList[d];if(n!==m){if(this.isBackgroundFetch(m)?m.__abortController.abort(Error("replaced")):r||(this.dispose(m,e,"set"),this.disposeAfter&&this.disposed.push([m,e,"set"])),this.removeItemSize(d),this.valList[d]=n,this.addItemSize(d,l,h),h){h.set="replace";let y=m&&this.isBackgroundFetch(m)?m.__staleWhileFetching:m;y!==void 0&&(h.oldValue=y)}}else h&&(h.set="update")}if(i!==0&&this.ttl===0&&!this.ttls&&this.initializeTTLTracking(),f||this.setItemTTL(d,i,a),this.statusTTL(h,d),this.disposeAfter)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift());return this}newIndex(){return this.size===0?this.tail:this.size===this.max&&this.max!==0?this.evict(!1):this.free.length===0?this.initialFill++:this.free.pop()}pop(){if(this.size){let e=this.valList[this.head];return this.evict(!0),e}}evict(e){let n=this.head,i=this.keyList[n],a=this.valList[n];return this.isBackgroundFetch(a)?a.__abortController.abort(Error("evicted")):(this.dispose(a,i,"evict"),this.disposeAfter&&this.disposed.push([a,i,"evict"])),this.removeItemSize(n),e&&(this.keyList[n]=null,this.valList[n]=null,this.free.push(n)),this.head=this.next[n],this.keyMap.delete(i),this.size--,n}has(e,{updateAgeOnHas:n=this.updateAgeOnHas,status:i}={}){let a=this.keyMap.get(e);if(a!==void 0)if(this.isStale(a))i&&(i.has="stale",this.statusTTL(i,a));else return n&&this.updateItemAge(a),i&&(i.has="hit"),this.statusTTL(i,a),!0;else i&&(i.has="miss");return!1}peek(e,{allowStale:n=this.allowStale}={}){let i=this.keyMap.get(e);if(i!==void 0&&(n||!this.isStale(i))){let a=this.valList[i];return this.isBackgroundFetch(a)?a.__staleWhileFetching:a}}backgroundFetch(e,n,i,a){let r=n===void 0?void 0:this.valList[n];if(this.isBackgroundFetch(r))return r;let l=new Nv;i.signal&&i.signal.addEventListener("abort",()=>l.abort(i.signal.reason));let u={signal:l.signal,options:i,context:a},f=(g,b=!1)=>{let{aborted:w}=l.signal,E=i.ignoreFetchAbort&&g!==void 0;return i.status&&(w&&!b?(i.status.fetchAborted=!0,i.status.fetchError=l.signal.reason,E&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),w&&!E&&!b?d(l.signal.reason):(this.valList[n]===y&&(g===void 0?y.__staleWhileFetching?this.valList[n]=y.__staleWhileFetching:this.delete(e):(i.status&&(i.status.fetchUpdated=!0),this.set(e,g,u.options))),g)},h=g=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=g),d(g)),d=g=>{let{aborted:b}=l.signal,w=b&&i.allowStaleOnFetchAbort,E=w||i.allowStaleOnFetchRejection,T=E||i.noDeleteOnFetchRejection;if(this.valList[n]===y&&(!T||y.__staleWhileFetching===void 0?this.delete(e):w||(this.valList[n]=y.__staleWhileFetching)),E)return i.status&&y.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),y.__staleWhileFetching;if(y.__returned===y)throw g},m=(g,b)=>{this.fetchMethod(e,r,u).then(w=>g(w),b),l.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(g(),i.allowStaleOnFetchAbort&&(g=w=>f(w,!0)))})};i.status&&(i.status.fetchDispatched=!0);let y=new Promise(m).then(f,h);return y.__abortController=l,y.__staleWhileFetching=r,y.__returned=null,n===void 0?(this.set(e,y,{...u.options,status:void 0}),n=this.keyMap.get(e)):this.valList[n]=y,y}isBackgroundFetch(e){return e&&typeof e=="object"&&typeof e.then=="function"&&Object.prototype.hasOwnProperty.call(e,"__staleWhileFetching")&&Object.prototype.hasOwnProperty.call(e,"__returned")&&(e.__returned===e||e.__returned===null)}async fetch(e,{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,ttl:r=this.ttl,noDisposeOnSet:l=this.noDisposeOnSet,size:u=0,sizeCalculation:f=this.sizeCalculation,noUpdateTTL:h=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:m=this.allowStaleOnFetchRejection,ignoreFetchAbort:y=this.ignoreFetchAbort,allowStaleOnFetchAbort:g=this.allowStaleOnFetchAbort,fetchContext:b=this.fetchContext,forceRefresh:w=!1,status:E,signal:T}={}){if(!this.fetchMethod)return E&&(E.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:a,status:E});let S={allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:a,ttl:r,noDisposeOnSet:l,size:u,sizeCalculation:f,noUpdateTTL:h,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:m,allowStaleOnFetchAbort:g,ignoreFetchAbort:y,status:E,signal:T},R=this.keyMap.get(e);if(R===void 0){E&&(E.fetch="miss");let A=this.backgroundFetch(e,R,S,b);return A.__returned=A}else{let A=this.valList[R];if(this.isBackgroundFetch(A)){let H=n&&A.__staleWhileFetching!==void 0;return E&&(E.fetch="inflight",H&&(E.returnedStale=!0)),H?A.__staleWhileFetching:A.__returned=A}let M=this.isStale(R);if(!w&&!M)return E&&(E.fetch="hit"),this.moveToTail(R),i&&this.updateItemAge(R),this.statusTTL(E,R),A;let z=this.backgroundFetch(e,R,S,b),N=z.__staleWhileFetching!==void 0,L=N&&n;return E&&(E.fetch=N&&M?"stale":"refresh",L&&M&&(E.returnedStale=!0)),L?z.__staleWhileFetching:z.__returned=z}}get(e,{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,status:r}={}){let l=this.keyMap.get(e);if(l!==void 0){let u=this.valList[l],f=this.isBackgroundFetch(u);return this.statusTTL(r,l),this.isStale(l)?(r&&(r.get="stale"),f?(r&&(r.returnedStale=n&&u.__staleWhileFetching!==void 0),n?u.__staleWhileFetching:void 0):(a||this.delete(e),r&&(r.returnedStale=n),n?u:void 0)):(r&&(r.get="hit"),f?u.__staleWhileFetching:(this.moveToTail(l),i&&this.updateItemAge(l),u))}else r&&(r.get="miss")}connect(e,n){this.prev[n]=e,this.next[e]=n}moveToTail(e){e!==this.tail&&(e===this.head?this.head=this.next[e]:this.connect(this.prev[e],this.next[e]),this.connect(this.tail,e),this.tail=e)}get del(){return GT("del","delete"),this.delete}delete(e){let n=!1;if(this.size!==0){let i=this.keyMap.get(e);if(i!==void 0)if(n=!0,this.size===1)this.clear();else{this.removeItemSize(i);let a=this.valList[i];this.isBackgroundFetch(a)?a.__abortController.abort(Error("deleted")):(this.dispose(a,e,"delete"),this.disposeAfter&&this.disposed.push([a,e,"delete"])),this.keyMap.delete(e),this.keyList[i]=null,this.valList[i]=null,i===this.tail?this.tail=this.prev[i]:i===this.head?this.head=this.next[i]:(this.next[this.prev[i]]=this.next[i],this.prev[this.next[i]]=this.prev[i]),this.size--,this.free.push(i)}}if(this.disposed)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift());return n}clear(){for(let e of this.rindexes({allowStale:!0})){let n=this.valList[e];if(this.isBackgroundFetch(n))n.__abortController.abort(Error("deleted"));else{let i=this.keyList[e];this.dispose(n,i,"delete"),this.disposeAfter&&this.disposed.push([n,i,"delete"])}}if(this.keyMap.clear(),this.valList.fill(null),this.keyList.fill(null),this.ttls&&(this.ttls.fill(0),this.starts.fill(0)),this.sizes&&this.sizes.fill(0),this.head=0,this.tail=0,this.initialFill=1,this.free.length=0,this.calculatedSize=0,this.size=0,this.disposed)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift())}get reset(){return GT("reset","clear"),this.clear}get length(){return M8("length","size"),this.size}static get AbortController(){return Nv}static get AbortSignal(){return A3}},_8=Uv,jv=(t=21)=>{let e="",n=crypto.getRandomValues(new Uint8Array(t));for(;t--;)e+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[n[t]&63];return e},Yr=class{get crop(){return this._crop}set crop(t){this._crop=t}getObjectsAt(t){return[]}getAllPointsAt(t,e,n){return[]}getScheduledUpdates(t,e){return[]}constructor(){C(this,"__id",void 0),C(this,"__revision",0),C(this,"__host",void 0),C(this,"__onCreate",void 0),C(this,"__parent",void 0),C(this,"__owner",{value:void 0}),C(this,"__state",{}),C(this,"eventHandlers",void 0),C(this,"scale",1),C(this,"layers",[]),C(this,"time",[]),C(this,"_crop",void 0),C(this,"cropData",void 0),C(this,"id",void 0),C(this,"addEventListener",(t,e,n)=>{let i=Rd[t];if(!this.eventHandlers[i])throw Error(`Unknown event ${i}`);this.eventHandlers[i].indexOf(e)===-1&&this.eventHandlers[i].push(e)}),C(this,"removeEventListener",(t,e)=>{let n=Rd[t];if(!this.eventHandlers[n]){console.warn(`Unknown event ${n}`);return}this.eventHandlers[n].indexOf(e)!==-1&&(this.eventHandlers[n]=this.eventHandlers[n].filter(i=>i!==e))}),this.id=this.__id=jv(),this.eventHandlers=x8()}dispatchEvent(t,e){let n=this.eventHandlers[t],i=n?n.length:0,a=!1;if(i)for(let r=0;r<i;r++)try{n[r]?.(e),a=!0}catch(l){console.error(t,l)}return a}get x(){return this.points[1]}get y(){return this.points[2]}get width(){return this.points[3]-this.points[1]}get height(){return this.points[4]-this.points[2]}translate(t,e){hr(this.points,ci(t,e))}atScale(t){hr(this.points,kl(t,this.x,this.y)),this.scale*=t}transform(t){hr(this.points,t)}applyProps(t){this.__revision++}appendChild(t){}removeChild(t){}insertBefore(t,e){}hideInstance(){}},gv=/([0-9]+(px|em)\s+)+(solid)\s+(.*)/g,yv={},z8=["backgroundColor","opacity","boxShadow","borderColor","borderWidth","borderStyle","outlineColor","outlineWidth","outlineOffset","outlineStyle"],Td=class extends Yr{constructor(){super(),C(this,"id",void 0),C(this,"type","spacial-content"),C(this,"points",void 0),C(this,"hoverEvents",!1),C(this,"activeEvents",!1),C(this,"display",{x:0,y:0,scale:1,width:-1,height:-1,points:It(5)}),C(this,"_parsed",{border:{id:null,match:[]},outline:{id:null,match:[]}}),C(this,"hovering",void 0),C(this,"pressing",void 0),C(this,"props",{}),C(this,"addHover",()=>{this.hovering=!0,this.__revision++}),C(this,"removeHover",()=>{this.hovering=!1,this.pressing=!1,this.__revision++}),C(this,"addPress",()=>{this.pressing=!0,this.__revision++}),C(this,"removePress",()=>{this.pressing=!1,this.__revision++}),this.id=jv(12),this.points=It(5)}getAllPointsAt(t,e){return[[this,this.points,e]]}applyProps(t={}){let e=!1;if(t.interactive!==this.props.interactive&&(e=!0,this.props.interactive=t.interactive),t.style){let n=t.border||t.style.border;if(n!==this._parsed.border.id)if(!n)this._parsed.border.id=null,this._parsed.border.match=[];else{let i=yv[n]||gv.exec(n)||gv.exec(n);i&&(this._parsed.border.id=n,this._parsed.border.match=yv[n]=i)}if(this._parsed.border.id&&(t.style.borderWidth=this._parsed.border.match[1],t.style.borderStyle="solid",t.style.borderColor=this._parsed.border.match[4]),t.style.outline!==this._parsed.outline.id)if(!t.style.outline)this._parsed.outline.id=null,this._parsed.outline.match=[];else{let i=yv[t.style.outline]||gv.exec(t.style.outline)||gv.exec(t.style.outline);i&&(this._parsed.outline.id=t.style.outline,this._parsed.outline.match=yv[t.style.outline]=i)}this._parsed.outline.id&&(t.style.outlineWidth=this._parsed.outline.match[1],t.style.outlineStyle="solid",t.style.outlineColor=this._parsed.outline.match[4]),this.props.style=t.style,t.backgroundColor&&!this.props.style.backgroundColor&&(this.props.style.backgroundColor=t.backgroundColor,e=!0),t.style.background&&!this.props.style.backgroundColor&&(this.props.style.backgroundColor=t.style.background,e=!0);for(let i of z8)if(this.props.style[i]!==t.style[i]){e=!0;break}t.style[":hover"]!==this.props.hoverStyles&&(this.props.hoverStyles=t.style[":hover"],this.hoverEvents||(this.hoverEvents=!0,this.addEventListener("pointerenter",this.addHover),this.addEventListener("pointerleave",this.removeHover)),e=!0),t.style[":active"]!==this.props.pressStyles&&(this.props.pressStyles=t.style[":active"],this.activeEvents||(this.activeEvents=!0,this.addEventListener("mousedown",this.addPress),this.addEventListener("mouseup",this.removePress)),e=!0)}t.href!==this.props.href&&(this.props.href=t.href,e=!0),t.hrefTarget!==this.props.hrefTarget&&(this.props.hrefTarget=t.hrefTarget,e=!0),t.title!==this.props.title&&(this.props.title=t.title,e=!0),t.className!==this.props.className&&(this.props.className=t.className,t.className&&!this.hoverEvents&&(this.hoverEvents=!0,this.addEventListener("pointerenter",this.addHover),this.addEventListener("pointerleave",this.removeHover)),t.className&&!this.activeEvents&&(this.activeEvents=!0,this.addEventListener("mousedown",this.addPress),this.addEventListener("mouseup",this.removePress)),e=!0),t.relativeSize!==this.props.relativeSize&&(this.props.relativeSize=t.relativeSize,e=!0),t.relativeStyle!==this.props.relativeStyle&&(this.props.relativeStyle=t.relativeStyle,e=!0),t.html!==this.props.html&&(this.props.html=t.html,e=!0),t.target&&(t.target.width!==this.display.width||t.target.height!==this.display.height||t.target.x!==this.points[1]||t.target.y!==this.points[2])&&(e=!0,this.points=de.singleBox(t.target.width,t.target.height,t.target.x,t.target.y),this.display.points=de.singleBox(t.target.width,t.target.height,t.target.x,t.target.y),this.display.width=t.target.width,this.display.height=t.target.height),e&&this.__revision++}},vv=/([0-9]+(px|em)\s+)+(solid)\s+(.*)/g,bv={},I8=["backgroundColor","opacity","boxShadow","borderColor","borderWidth","borderStyle","outlineColor","outlineWidth","outlineOffset","outlineStyle"],cR=class extends Yr{constructor(){super(),C(this,"id",void 0),C(this,"type","spacial-content"),C(this,"isShape",!0),C(this,"points",void 0),C(this,"hoverEvents",!1),C(this,"activeEvents",!1),C(this,"display",{x:0,y:0,scale:1,width:-1,height:-1,points:It(5)}),C(this,"boundingBox",null),C(this,"_parsed",{border:{id:null,match:[]},outline:{id:null,match:[]}}),C(this,"hovering",void 0),C(this,"pressing",void 0),C(this,"props",{}),C(this,"shape",{type:"none"}),C(this,"addHover",()=>{this.hovering=!0,this.__revision++}),C(this,"removeHover",()=>{this.hovering=!1,this.pressing=!1,this.__revision++}),C(this,"addPress",()=>{this.pressing=!0,this.__revision++}),C(this,"removePress",()=>{this.pressing=!1,this.__revision++}),this.id=jv(12),this.points=It(5),this.shape={type:"none"}}updateBoundingBox(){if(this.shape.type==="none")return;let t=this.shape.points;if(this.shape.points.length>2){let e=Math.min(...t.map(r=>r[0])),n=Math.min(...t.map(r=>r[1])),i=Math.max(0,...t.map(r=>r[0])),a=Math.max(0,...t.map(r=>r[1]));this.boundingBox={x:e,y:n,width:i-e,height:a-n};return}this.boundingBox=null}intersects(t){if(!t||this.shape.type==="none")return!1;let[e,n]=t,i=this.shape.points,a=this.boundingBox;if(a||(this.updateBoundingBox(),a=this.boundingBox),!a||e<a.x||e>a.x+a.width||n<a.y||n>a.height+a.y)return!1;let r=!1;for(let l=0,u=i.length-1;l<i.length;u=l++)i[l][1]>n!=i[u][1]>n&&e<(i[u][0]-i[l][0])*(n-i[l][1])/(i[u][1]-i[l][1])+i[l][0]&&(r=!r);return r}getAllPointsAt(t,e){return t[3]-t[1]===1&&t[4]-t[2]===1?this.intersects([t[1],t[2]])?[[this,this.points,e]]:[]:[[this,this.points,e]]}applyProps(t={}){let e=!1;if(t.points)if(this.shape.type!=="polygon"||this.shape.points.length!==t.points.length)this.shape={type:"polygon",points:t.points,open:t.open},this.updateBoundingBox();else{let n=!1,i=t.points.length;for(let a=0;a<i;a++)if(t.points[a][0]!==this.shape.points[a][0]||t.points[a][1]!==this.shape.points[a][1]){n=!0;break}n&&(this.shape={type:"polygon",points:t.points,open:t.open},this.updateBoundingBox())}if(t.interactive!==this.props.interactive&&(e=!0,this.props.interactive=t.interactive),(t.open||t.open===!1)&&(e=!0,this.shape.open=t.open),t.style){let n=t.border||t.style.border;if(n!==this._parsed.border.id)if(!n)this._parsed.border.id=null,this._parsed.border.match=[];else{let i=bv[n]||vv.exec(n)||vv.exec(n);i&&(this._parsed.border.id=n,this._parsed.border.match=bv[n]=i)}if(this._parsed.border.id&&(t.style.borderWidth=this._parsed.border.match[1],t.style.borderStyle="solid",t.style.borderColor=this._parsed.border.match[4]),t.style.outline!==this._parsed.outline.id)if(!t.style.outline)this._parsed.outline.id=null,this._parsed.outline.match=[];else{let i=bv[t.style.outline]||vv.exec(t.style.outline)||vv.exec(t.style.outline);i&&(this._parsed.outline.id=t.style.outline,this._parsed.outline.match=bv[t.style.outline]=i)}this._parsed.outline.id&&(t.style.outlineWidth=this._parsed.outline.match[1],t.style.outlineStyle="solid",t.style.outlineColor=this._parsed.outline.match[4]),this.props.style=t.style,t.backgroundColor&&!this.props.style.backgroundColor&&(this.props.style.backgroundColor=t.backgroundColor,e=!0),t.style.background&&!this.props.style.backgroundColor&&(this.props.style.backgroundColor=t.style.background,e=!0);for(let i of I8)if(this.props.style[i]!==t.style[i]){e=!0;break}t.style[":hover"]!==this.props.hoverStyles&&(this.props.hoverStyles=t.style[":hover"],this.hoverEvents||(this.hoverEvents=!0,this.addEventListener("pointerenter",this.addHover),this.addEventListener("pointerleave",this.removeHover)),e=!0),t.style[":active"]!==this.props.pressStyles&&(this.props.pressStyles=t.style[":active"],this.activeEvents||(this.activeEvents=!0,this.addEventListener("mousedown",this.addPress),this.addEventListener("mouseup",this.removePress)),e=!0)}t.href!==this.props.href&&(this.props.href=t.href,e=!0),t.hrefTarget!==this.props.hrefTarget&&(this.props.hrefTarget=t.hrefTarget,e=!0),t.title!==this.props.title&&(this.props.title=t.title,e=!0),t.className!==this.props.className&&(this.props.className=t.className,t.className&&!this.hoverEvents&&(this.hoverEvents=!0,this.addEventListener("pointerenter",this.addHover),this.addEventListener("pointerleave",this.removeHover)),t.className&&!this.activeEvents&&(this.activeEvents=!0,this.addEventListener("mousedown",this.addPress),this.addEventListener("mouseup",this.removePress)),e=!0),t.relativeSize!==this.props.relativeSize&&(this.props.relativeSize=t.relativeSize,e=!0),t.relativeStyle!==this.props.relativeStyle&&(this.props.relativeStyle=t.relativeStyle,e=!0),t.html!==this.props.html&&(this.props.html=t.html,e=!0),t.target&&(t.target.width!==this.display.width||t.target.height!==this.display.height||t.target.x!==this.points[1]||t.target.y!==this.points[2])&&(e=!0,this.points=de.singleBox(t.target.width,t.target.height,t.target.x,t.target.y),this.display.points=de.singleBox(t.target.width,t.target.height,t.target.x,t.target.y),this.display.width=t.target.width,this.display.height=t.target.height),e&&this.__revision++}},gi=class tR extends Yr{constructor(e){if(super(),C(this,"type","spacial-content"),C(this,"id",void 0),C(this,"uri",void 0),C(this,"display",void 0),C(this,"points",void 0),C(this,"priority",void 0),C(this,"style",{opacity:1}),!e)this.id="",this.uri="",this.display={x:0,y:0,scale:1,width:0,height:0,points:It(5)},this.points=It(5);else{let n=e.scale||1;this.id=e.id||e.uri,this.uri=e.uri,this.points=de.singleBox(e.width,e.height,e.x,e.y),this.display={x:0,y:0,scale:n,width:e.width/n,height:e.height/n,points:de.singleBox(e.width/n,e.height/n),rotation:e?.rotation}}}applyProps(e){let n=e.display?e.display.width:e.target.width,i=e.target.width/n;if(this.id=e.id||e.uri,this.uri=e.uri,this.points.set(de.singleBox(e.target.width,e.target.height,e.target.x,e.target.y)),e.style&&e.style.opacity!==void 0&&(this.style.opacity=e.style.opacity),e.crop){this.cropData=e.crop;let a=de.singleBox(e.crop.width,e.crop.height,e.crop.x,e.crop.y);hr(a,ci(-e.crop.x,-e.crop.y)),this.crop?this.crop.set(a):this.crop=It(a)}e.display?(this.display.scale=i,this.display.width=e.display.width,this.display.height=e.display.height,this.display.rotation=e.display.rotation,this.display.points=de.singleBox(e.display.width,e.display.height)):(this.display.scale=i,this.display.width=e.target.width/i,this.display.height=e.target.height/i,this.display.points=de.singleBox(e.target.width/i,e.target.height/i))}getAllPointsAt(e,n,i){return[[this,this.crop||this.points,n]]}static fromSvg(e,n,i,a){return tR.fromImage("data:image/svg+xml;base64,"+btoa(e),n,i,a)}static fromImage(e,n,i,a){let r=new tR;return r.applyProps({uri:e,id:a,display:i,target:n}),r}getImageUrl(){return this.uri}};function Sv(t,e,n){return Math.min(Math.max(t,e),n)}var Ri=class O3 extends Yr{constructor(e){super(),C(this,"id",void 0),C(this,"type","spacial-content"),C(this,"display",void 0),C(this,"tileWidth",void 0),C(this,"tileHeight",void 0),C(this,"columns",void 0),C(this,"rows",void 0),C(this,"style",{opacity:1}),C(this,"points",void 0),C(this,"service",void 0),C(this,"format","jpg"),C(this,"crop2",void 0),C(this,"version3",void 0),C(this,"tileUrl",void 0),this.tileUrl=T8(e.url),this.id=e.id||`${this.tileUrl}--${e.scaleFactor}--${e.tileWidth}x${e.tileHeight}`,this.points=e.displayPoints?e.displayPoints:Xi(e.points,mo(e.scaleFactor)),this.tileWidth=e.tileWidth,this.tileHeight=e.tileHeight,this.columns=e.columns,this.rows=e.rows,this.version3=e.version3,this.display={x:0,y:0,width:e.width/e.scaleFactor,height:e.height/e.scaleFactor,points:e.points,scale:e.scaleFactor},e.format&&(this.format=e.format)}applyProps(e){if(e.style&&e.style.opacity!==void 0&&(this.style.opacity=e.style.opacity),e.service!==this.service&&(this.service=e.service),e.format?this.format=e.format:this.format="jpg",e.version3!==void 0&&(this.version3=e.version3),e.crop){this.cropData=e.crop;let n=It([...this.points]),i=n.length/5,a=e.crop.x||0,r=e.crop.y||0,l=e.crop.x+e.crop.width,u=e.crop.y+e.crop.height;for(let f=0;f<i;f++){let h=f*5;n[h+1]<l&&n[h+3]>a&&n[h+2]<u&&n[h+4]>r?(n[h+1]=Sv(n[h+1],a,l),n[h+3]=Sv(n[h+3],a,l),n[h+2]=Sv(n[h+2],r,u),n[h+4]=Sv(n[h+4],r,u)):n[h]=0}hr(n,ci(-e.crop.x,-e.crop.y)),this.crop?this.crop.set(n):this.crop=n}}static fromTile(e,n,i,a,r,l,u,f){let h=i.height?i.height:i.width,d=u?Math.floor(n.width/a):Math.ceil(n.width/a),m=u?Math.floor(n.height/a):Math.ceil(n.height/a),y=Math.ceil(d/i.width),g=Math.ceil(m/h),b=de.grid(y,g),w=de.grid(y,g),E=r&&r["@context"]?Array.isArray(r["@context"])?r["@context"]:[r["@context"]]:[],T=f===void 0?E.indexOf("http://iiif.io/api/image/3/context.json")!==-1:f;for(let R=0;R<g;R++)for(let A=0;A<y;A++){let M=A*i.width,z=R*h;w.addPoints(M*a,z*a,A===y-1?n.width:(M+i.width)*a,R===g-1?n.height:(z+h)*a),b.addPoints(M,z,A===y-1?d:M+i.width,R===g-1?m:z+h)}let S=new O3({url:e,scaleFactor:a,points:b.build(),displayPoints:w.build(),width:n.width,height:n.height,tileWidth:i.width,tileHeight:h,columns:y,rows:g,format:l,version3:T});return S.applyProps({service:r}),S}getImageUrl(e){let n=this.points.slice(e*5,e*5+5),i=n[3]-n[1],a=n[4]-n[2],r=Math.ceil(i/this.display.scale),l=Math.ceil(a/this.display.scale),u=`${r>this.tileWidth?this.tileWidth:r},`;return this.version3&&(u+=`${l>this.tileHeight?this.tileHeight:l}`),`${this.tileUrl}/${n[1]},${n[2]},${i},${a}/${u}/0/default.${this.format||"jpg"}`}getAllPointsAt(e,n,i){let a=Oc(this.crop||this.points,e);return[[this,a,n]]}transform(e){hr(this.points,e)}getScheduledUpdates(e,n){return[]}};function _3(t,e,n){if(!e||e[0]===0)return null;let i=t[3]-t[1],a=t[4]-t[2],r=e[3]-e[1],l=e[4]-e[2],u=i<r,f=a<l,h=e[1]+r/2-i/2,d=e[2]+l/2-a/2;return{minX:u?e[1]-n:h,maxX:u?e[3]-i+n:h,minY:f?e[2]-n:d,maxY:f?e[4]-a+n:d}}function z3(t){if(!t.enableFilters||!t.filters.brightness&&!t.filters.contrast&&!t.filters.grayscale&&!t.filters.invert&&!t.filters.sepia&&!t.filters.saturate&&!t.filters.hueRotate&&!t.filters.blur)return"none";let e="";return t.filters.brightness&&(e+=`brightness(${~~(100+t.filters.brightness*100)}%) `),t.filters.contrast&&(e+=`contrast(${~~(100+t.filters.contrast*100)}%) `),t.filters.grayscale&&(e+=`grayscale(${~~(t.filters.grayscale*100)}%) `),t.filters.invert&&(e+=`invert(${~~(t.filters.invert*100)}%) `),t.filters.sepia&&(e+=`sepia(${~~(t.filters.sepia*100)}%) `),t.filters.saturate&&(e+=`saturate(${~~(100+t.filters.saturate*100)}%) `),t.filters.hueRotate&&(e+=`hue-rotate(${t.filters.hueRotate}deg) `),t.filters.blur&&(e+=`blur(${t.filters.blur}px) `),e.trim()}function I3(t,e,n){return Math.max(e,Math.min(n,t))}function N8(){if(typeof navigator>"u")return;let t=navigator;return t.connection||t.mozConnection||t.webkitConnection}function L8(t){let e=10;return typeof navigator<"u"&&typeof navigator.hardwareConcurrency=="number"&&(e=I3(Math.round(navigator.hardwareConcurrency*.75),4,10)),t?.saveData?3:t?.effectiveType==="slow-2g"||t?.effectiveType==="2g"?2:t?.effectiveType==="3g"?Math.min(e,4):e}function D8(t,e){return e?.saveData||e?.effectiveType==="slow-2g"||e?.effectiveType==="2g"?0:e?.effectiveType==="3g"?2:Math.min(t+2,12)}function N3(t={}){let e=N8(),n=L8(e),i=typeof t.maxConcurrentRequests=="number"?Math.max(1,Math.floor(t.maxConcurrentRequests)):n;return{maxConcurrentRequests:i,maxPrefetchPerFrame:typeof t.maxPrefetchPerFrame=="number"?Math.max(0,Math.floor(t.maxPrefetchPerFrame)):D8(i,e),timeoutMs:typeof t.timeoutMs=="number"?Math.max(250,Math.floor(t.timeoutMs)):8e3,maxAttempts:typeof t.maxAttempts=="number"?Math.max(1,Math.floor(t.maxAttempts)):3,baseDelayMs:typeof t.baseDelayMs=="number"?Math.max(0,Math.floor(t.baseDelayMs)):250,maxDelayMs:typeof t.maxDelayMs=="number"?Math.max(0,Math.floor(t.maxDelayMs)):3e3,jitterRatio:typeof t.jitterRatio=="number"?I3(t.jitterRatio,0,1):.2,errorRetryIntervalMs:typeof t.errorRetryIntervalMs=="number"?Math.max(0,Math.floor(t.errorRetryIntervalMs)):3e4,revealDelayFrames:typeof t.revealDelayFrames=="number"?Math.max(0,Math.floor(t.revealDelayFrames)):1,revealBatchWindowFrames:typeof t.revealBatchWindowFrames=="number"?Math.max(0,Math.floor(t.revealBatchWindowFrames)):1,skipFadeIfLoadedWithinMs:typeof t.skipFadeIfLoadedWithinMs=="number"?Math.max(0,Math.floor(t.skipFadeIfLoadedWithinMs)):120}}function L3(t,e,n=Math.random){let i=Math.max(1,Math.floor(e)),a=t.baseDelayMs*2**(i-1),r=Math.min(t.maxDelayMs,a),l=r*t.jitterRatio;return l?Math.max(0,Math.floor(r+(n()*2-1)*l)):r}var D3=class extends Error{constructor(t="Image request cancelled",e=!0){super(t),C(this,"silent",void 0),this.name="ImageRequestCancelledError",this.silent=e}};function P3(t){return t instanceof D3}var KL=0;function P8(t){return KL+=1,`${KL}:${t}`}function B3(t){return Error(`Image load timeout: ${t}`)}function ZL(t,e){let n,i=document.createElement("img");i.decoding="async",e.crossOrigin&&(i.crossOrigin=e.crossOrigin);let a=!1;return{promise:new Promise((r,l)=>{let u=()=>{n&&clearTimeout(n),i.onload=null,i.onerror=null};i.onload=()=>{a||(a=!0,u(),r(i))},i.onerror=f=>{a||(a=!0,u(),l(f))},n=setTimeout(()=>{a||(a=!0,u(),l(B3(t)))},e.timeoutMs),i.src=t,i.complete&&i.naturalWidth>0&&(a=!0,u(),r(i))}),abort:()=>{a||(a=!0,n&&clearTimeout(n),i.onload=null,i.onerror=null,i.src="")}}}var H3=class{constructor(t){C(this,"timeoutMs",void 0),C(this,"crossOrigin",void 0),C(this,"useFetch",void 0),C(this,"cache",void 0),C(this,"inFlight",new Map),C(this,"knownConsumers",new Map),this.timeoutMs=t.timeoutMs,this.crossOrigin=t.crossOrigin,this.useFetch=!!t.useFetch&&typeof fetch<"u"&&typeof AbortController<"u",this.cache=t.cache||new Map}acquire(t,e){let n=this.cache.get(t);if(n&&n.naturalWidth>0)return{requestKey:`cached:${t}`,promise:Promise.resolve(n),release:()=>{}};let i=this.inFlight.get(t);i||(i={url:t,requestKey:P8(t),consumers:new Set,promise:Promise.resolve(document.createElement("img")),settled:!1,cancelled:!1,silentCancellation:!0},i.promise=this.createRequest(i).then(r=>(i.settled=!0,this.cache.set(t,r),r)).catch(r=>{throw i.settled=!0,i.cancelled?new D3("Image request cancelled",i.silentCancellation):r}).finally(()=>{i&&i.consumers.size===0&&this.inFlight.delete(t)}),this.inFlight.set(t,i)),i.consumers.add(e);let a=this.knownConsumers.get(e)||new Set;return a.add(t),this.knownConsumers.set(e,a),{requestKey:i.requestKey,promise:i.promise,release:r=>{this.release(t,e,r)}}}release(t,e,n={}){let i=this.knownConsumers.get(e);i&&(i.delete(t),i.size===0&&this.knownConsumers.delete(e));let a=this.inFlight.get(t);if(a&&(a.consumers.delete(e),n.silent===!1&&(a.silentCancellation=!1),!(a.consumers.size>0))){if(!a.settled){a.cancelled=!0,a.abortController&&a.abortController.abort(),a.abortDomImage&&a.abortDomImage();return}this.inFlight.delete(t)}}releaseConsumer(t,e={}){let n=this.knownConsumers.get(t);if(n)for(let i of[...n])this.release(i,t,e)}cancelAll(t={}){let e=[...this.knownConsumers.keys()];for(let n of e)this.releaseConsumer(n,t)}async createRequest(t){if(this.useFetch){let i=new AbortController;t.abortController=i;let a=setTimeout(()=>{i.abort(B3(t.url))},this.timeoutMs);try{let r=this.crossOrigin==="use-credentials"?"include":"same-origin",l=await fetch(t.url,{signal:i.signal,credentials:r});if(!l.ok)throw Error(`Image request failed (${l.status}): ${t.url}`);let u=await l.blob(),f=URL.createObjectURL(u);try{let{promise:h,abort:d}=ZL(f,{timeoutMs:this.timeoutMs,crossOrigin:void 0});return t.abortDomImage=d,await h}finally{URL.revokeObjectURL(f)}}finally{clearTimeout(a)}}let{promise:e,abort:n}=ZL(t.url,{timeoutMs:this.timeoutMs,crossOrigin:this.crossOrigin});return t.abortDomImage=n,e}},WL=/(-?[0-9]+(px|em)\s+|0\s+)(-?[0-9]+(px|em)\s+|0\s+)(-?[0-9]+(px|em)\s+|0\s+)?(-?[0-9]+(px|em)\s+|0\s+)?(.*)/g,JL={},B8=typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes("firefox"),H8=new Map,xv=class{constructor(t,e){C(this,"canvas",void 0),C(this,"ctx",void 0),C(this,"options",void 0),C(this,"imagesPending",0),C(this,"imagesLoaded",0),C(this,"imageIdsLoaded",[]),C(this,"frameIsRendering",!1),C(this,"pendingDrawCall",!1),C(this,"firstMeaningfulPaint",!1),C(this,"parallelTasks",6),C(this,"maxPrefetchPerFrame",8),C(this,"imageLoadingConfig",void 0),C(this,"imageRequestPool",void 0),C(this,"frameTasks",0),C(this,"loadingQueueOrdered",!0),C(this,"loadingQueue",[]),C(this,"currentTask",Promise.resolve()),C(this,"tasksRunning",0),C(this,"inFlightImageLoads",new Map),C(this,"requiredTileKeys",new Set),C(this,"requiredPrefetchTileKeys",new Set),C(this,"requestGeneration",0),C(this,"frameCounter",0),C(this,"pendingTileReveals",new Map),C(this,"stats",void 0),C(this,"averageJobTime",64),C(this,"lastKnownScale",1),C(this,"visible",[]),C(this,"previousVisible",[]),C(this,"rendererPosition",void 0),C(this,"dpi",void 0),C(this,"drawCalls",[]),C(this,"lastPaintedObject",void 0),C(this,"hostCache",void 0),C(this,"invalidated",[]),C(this,"fallbackRevealTimeout",null),C(this,"framePrefetchCount",0),C(this,"hasTilesFading",!1),C(this,"hasActiveLayerClip",!1),C(this,"_worker",()=>{if(this.loadingQueue.length&&this.tasksRunning<this.parallelTasks&&this.frameTasks<this.parallelTasks){let n=this.loadingQueue.pop();n&&(this.tasksRunning++,this.frameTasks++,this.currentTask=n.task().then(()=>{this.tasksRunning--}).catch(()=>{this.tasksRunning--}))}}),C(this,"_scheduled",0),C(this,"_doWork",()=>{this.loadingQueue.length===0&&this.tasksRunning===0&&this._scheduled&&(clearInterval(this._scheduled),this._scheduled=0);let n=this.parallelTasks||1;!this.firstMeaningfulPaint&&this.loadingQueue.length&&(n=this.loadingQueue.length);for(let i=0;i<n;i++)this._worker()}),this.canvas=t,this.rendererPosition=t.getBoundingClientRect(),this.ctx=t.getContext("2d",{alpha:!0}),this.ctx.imageSmoothingEnabled=!0,this.options=e||{},this.imageLoadingConfig=N3(this.options.imageLoading),this.parallelTasks=this.imageLoadingConfig.maxConcurrentRequests,this.maxPrefetchPerFrame=this.imageLoadingConfig.maxPrefetchPerFrame,this.imageRequestPool=new H3({timeoutMs:this.imageLoadingConfig.timeoutMs,crossOrigin:this.options.crossOrigin?"anonymous":void 0,useFetch:!!this.options.crossOrigin,cache:H8}),this.canvas.style.transition="opacity .3s",this.dpi=e?.dpi||1,this.options.readiness==="immediate"&&(this.firstMeaningfulPaint=!0,this.canvas.style.opacity="1"),this.hostCache=e?.lruCache?new _8({maxSize:1024*512*512,dispose:(n,i,a)=>{this.invalidated.push(i),n.width=0,n.height=0},sizeCalculation:(n,i)=>n.width*n.height}):{store:{},get(n){return this.store[n]},set(n,i){this.store[n]=i}}}getCanvasDims(){return{width:this.canvas.width/this.dpi,height:this.canvas.height/this.dpi}}resize(){this.rendererPosition=this.canvas.getBoundingClientRect()}getCompositeOwner(t){let e=t?.__parent;return e&&e.renderOptions?e:void 0}compareCompositeLoadPriority(t,e){let n=this.getCompositeOwner(t),i=this.getCompositeOwner(e);return!n||n!==i?0:(t?.display.scale||0)-(e?.display.scale||0)}isReady(){return this.firstMeaningfulPaint}afterFrame(t){if(this.clearTransform(),this.lastPaintedObject=void 0,this.frameIsRendering=!1,this.imagesPending=this.loadingQueue.length+this.tasksRunning+this.inFlightImageLoads.size+this.pendingTileReveals.size,this.imagesLoaded=0,this.loadingQueueOrdered||(this.loadingQueue=this.loadingQueue.sort((e,n)=>{let i=this.compareCompositeLoadPriority(e.paint,n.paint);return i===0?e.network&&n.network&&e.scale===n.scale?n.distance-e.distance:e.scale-n.scale:i}),this.loadingQueueOrdered=!0),this.scheduleSingleImageLookahead(t),this.previousVisible=this.visible,this.pruneStaleTileWork(),this.pendingDrawCall=!!this.drawCalls.length,this.pendingDrawCall)for(let e=0;e<this.drawCalls.length;e++){let n=this.drawCalls.shift();n&&n()}this.doOffscreenWork(),this.options.debug&&this.stats&&this.stats.end()}doOffscreenWork(){this.frameTasks=0,this.loadingQueue.length&&(this._worker(),this.loadingQueue.length&&this.tasksRunning<this.parallelTasks&&(this._scheduled||(this._scheduled=setInterval(this._doWork,0))))}getScale(t,e,n){if(Number.isNaN(t)||Number.isNaN(e))return this.lastKnownScale;let i=this.getCanvasDims(),a=i.width/t,r=i.height/e,l=(a<r?r:a)*(n&&this.dpi||1);return Number.isNaN(l)||(this.lastKnownScale=l),this.lastKnownScale}beforeFrame(t,e,n,i){this.options.debug&&this.stats&&this.stats.begin(),this.frameIsRendering=!0,this.frameCounter+=1,this.visible=[],this.framePrefetchCount=0,this.hasTilesFading=!1,this.requiredTileKeys.clear(),this.requiredPrefetchTileKeys.clear(),this.flushTileRevealBatch(),this.options.beforeFrame&&this.options.beforeFrame(e);let a=this.getCanvasDims();this.ctx.globalAlpha=1,this.canvas.dataset.background==="transparent"?this.ctx.clearRect(0,0,a.width,a.height):(this.ctx.fillStyle=this.canvas.dataset.background??"rgb(0, 0, 0)",this.ctx.fillRect(0,0,a.width,a.height));let r=z3(i);this.ctx.filter!==r&&(this.ctx.filter=r)}applyTransform(t,e,n,i,a){let r=t.__owner.value;if(r&&r.rotation){this.ctx.save();let l=e+i/2,u=n+a/2;this.ctx.translate(l,u),this.ctx.rotate(r.rotation*Math.PI/180),this.ctx.translate(-l,-u),this.lastPaintedObject=r}}clearTransform(){this.lastPaintedObject&&(this.lastPaintedObject.rotation&&this.ctx.restore(),this.lastPaintedObject=void 0)}getTileKey(t,e){return`${t.id}::${t.display.scale}::${e}`}nextRequestKey(t){return this.requestGeneration+=1,`${t}::${this.requestGeneration}`}markTileRequired(t,e){if(e){this.requiredPrefetchTileKeys.add(t);return}this.requiredTileKeys.add(t)}isTileRequired(t){return this.requiredTileKeys.has(t)||this.requiredPrefetchTileKeys.has(t)}shouldSkipFade(t,e=performance.now()){return t?.requestedAt?e-t.requestedAt<=this.imageLoadingConfig.skipFadeIfLoadedWithinMs:!1}enqueueTileReveal(t,e,n){let i=performance.now();if(this.imageLoadingConfig.revealDelayFrames===0&&this.imageLoadingConfig.revealBatchWindowFrames===0){let a=this.getTileState(e,n);this.setTileState(e,n,{...a,loadedAt:i,skipFade:this.shouldSkipFade(a,i)});return}this.pendingTileReveals.set(t,{imageBuffer:e,index:n,queuedFrame:this.frameCounter})}flushTileRevealBatch(){if(this.pendingTileReveals.size===0)return;let t=this.imageLoadingConfig.revealDelayFrames,e=this.imageLoadingConfig.revealBatchWindowFrames,n=performance.now(),i=[...this.pendingTileReveals.entries()].sort((r,l)=>r[1].queuedFrame-l[1].queuedFrame),a=0;for(;a<i.length;){let r=i[a];if(this.frameCounter-r[1].queuedFrame<t)break;let l=r[1].queuedFrame+e;for(;a<i.length&&i[a][1].queuedFrame<=l;){let[u,f]=i[a],h=this.getTileState(f.imageBuffer,f.index);h.state==="decoded"&&!h.loadedAt&&this.setTileState(f.imageBuffer,f.index,{...h,loadedAt:n,skipFade:this.shouldSkipFade(h,n)}),this.pendingTileReveals.delete(u),a+=1}}}emitImageError(t){this.options.onImageError&&this.options.onImageError({renderer:"canvas",...t})}releaseInFlightTileLoad(t,e={}){let n=this.inFlightImageLoads.get(t);n&&(n.release(e),this.inFlightImageLoads.delete(t))}pruneStaleTileWork(){let t=[];for(let n of this.loadingQueue){if(!n.tileKey||this.isTileRequired(n.tileKey)){t.push(n);continue}if(n.paint&&typeof n.index=="number"){let i=this.ensureImageBuffer(n.paint),a=this.getTileState(i,n.index);a.lastRequestKey===n.requestKey&&(a.state==="queued"||a.state==="loading")&&this.setTileState(i,n.index,{...a,state:"idle",cancelledAt:performance.now()})}n.tileKey&&this.pendingTileReveals.delete(n.tileKey)}this.loadingQueue=t;let e=[];for(let[n,i]of this.inFlightImageLoads.entries()){if(this.isTileRequired(n))continue;e.push(n);let a=this.getTileState(i.imageBuffer,i.index);a.lastRequestKey===i.requestKey&&a.state==="loading"&&this.setTileState(i.imageBuffer,i.index,{...a,state:"idle",cancelledAt:performance.now()}),this.pendingTileReveals.delete(n)}for(let n of e)this.releaseInFlightTileLoad(n,{silent:!0})}ensureImageBuffer(t){(!t.__host||!t.__host.canvas)&&this.createImageHost(t);let e=t.__host.canvas;return e.tiles||(e.tiles={}),e.indices||(e.indices=[]),e.loaded||(e.loaded=[]),e.canvases||(e.canvases=[]),e}getTileState(t,e){return t.tiles||(t.tiles={}),t.tiles[e]||(t.tiles[e]={state:"idle"},this.syncBufferState(t)),t.tiles[e]}setTileState(t,e,n){t.tiles||(t.tiles={}),t.tiles[e]=n,this.syncBufferState(t)}syncBufferState(t){let e=[],n=[],i=t.tiles||{},a=Object.keys(i);for(let r=0;r<a.length;r++){let l=parseInt(a[r],10),u=i[l].state;(u==="queued"||u==="loading")&&e.push(l),u==="decoded"&&n.push(l)}t.indices=e,t.loaded=n,t.loading=e.length>0}getCompositeRenderOptions(t){return t.__parent?.renderOptions}shouldClipLayerToBounds(t){return t instanceof gi||t instanceof Ri?!!this.getCompositeRenderOptions(t)?.clipToBounds:!1}getBoundsFromPoints(t){let e=1/0,n=1/0,i=-1/0,a=-1/0;for(let r=0;r<t.length;r+=5)t[r]&&(e=Math.min(e,t[r+1]),n=Math.min(n,t[r+2]),i=Math.max(i,t[r+3]),a=Math.max(a,t[r+4]));if(!(!Number.isFinite(e)||!Number.isFinite(n)||!Number.isFinite(i)||!Number.isFinite(a))&&!(i<=e||a<=n))return{x:e,y:n,width:i-e,height:a-n}}getLayerPolicy(t){return this.getCompositeRenderOptions(t)?.layerPolicy||"fallback-only"}isLayerActive(t){let e=t.__parent;return!e||this.getLayerPolicy(t)==="always-blend"?!0:typeof e.isImageActive=="function"?!!e.isImageActive(t):!0}getPrefetchRadius(t){let e=this.getCompositeRenderOptions(t);return e?typeof e.prefetchRadius=="number"?Math.max(0,e.prefetchRadius):e.loadingBias==="speed"?2:e.loadingBias==="data"?0:1:0}getFadeAlpha(t,e,n){if(e?.skipFade)return 1;if(e?.state==="decoded"&&!e.loadedAt&&(this.imageLoadingConfig.revealDelayFrames>0||this.imageLoadingConfig.revealBatchWindowFrames>0))return 0;let i=this.getCompositeRenderOptions(t);if(!i||!i.fadeInMs||i.fadeInMs<=0)return 1;let a=performance.now(),r=1;if(n&&i.fadeOnLayerChange&&i.layerPolicy!=="active-only"){let l=t.__parent;if(l&&typeof l.getImageActivatedAt=="function"){let u=l.getImageActivatedAt(t);typeof u=="number"&&(r=Math.min(r,Math.max(0,Math.min(1,(a-u)/i.fadeInMs))))}}return e?.loadedAt&&(n||i.fadeFallbackTiles)&&(r=Math.min(r,Math.max(0,Math.min(1,(a-e.loadedAt)/i.fadeInMs)))),r}schedulePrefetchNeighbours(t,e,n,i){if(!(e instanceof Ri)||this.framePrefetchCount>=this.maxPrefetchPerFrame||this.getCompositeRenderOptions(e)?.loadingBias==="data")return;let a=this.getPrefetchRadius(e);if(a<=0)return;let r=e.columns,l=e.rows;if(!r||!l)return;let u=n%r,f=Math.floor(n/r);for(let h=1;h<=a;h++)for(let d=-h;d<=h;d++)for(let m=-h;m<=h;m++){if(Math.max(Math.abs(m),Math.abs(d))!==h)continue;let y=u+m,g=f+d;if(y<0||g<0||y>=r||g>=l)continue;let b=g*r+y,w=this.getTileKey(e,b);if(this.markTileRequired(w,!0),this.schedulePaintToCanvas(t,e,b,i+h*1e3,!0)&&(this.framePrefetchCount++,this.framePrefetchCount>=this.maxPrefetchPerFrame))return}}scheduleSingleImageLookahead(t){if(this.maxPrefetchPerFrame<=0||this.framePrefetchCount>=this.maxPrefetchPerFrame||t.hasActiveZone())return;let e=1/0,n=-1/0,i=new Set;for(let y=0;y<this.visible.length;y++){let g=this.visible[y].__owner?.value;!g||g.type!=="world-object"||g.points[0]===0||(i.add(g),e=Math.min(e,g.points[2]),n=Math.max(n,g.points[4]))}if(!Number.isFinite(e)||!Number.isFinite(n))return;let a=n-e;if(a<=0)return;let r=a*1.5,l=n+r,u=e-r,f,h,d=t.getObjects();for(let y=0;y<d.length;y++){let g=d[y];if(!g||g.type!=="world-object"||g.points[0]===0||i.has(g))continue;let b=g.points[2],w=g.points[4],E=b>=n&&b<=l,T=w<=e&&w>=u;if(!E&&!T)continue;let S;for(let R=0;R<g.layers.length;R++){let A=g.layers[R];if(A instanceof gi){S=A;break}}if(S){if(E){let R=b-n;(!f||R<f.distance)&&(f={image:S,distance:R})}if(T){let R=e-w;(!h||R<h.distance)&&(h={image:S,distance:R})}}}let m=[f,h].filter(Boolean);for(let y of m){if(this.framePrefetchCount>=this.maxPrefetchPerFrame)break;let g=this.ensureImageBuffer(y.image);this.schedulePaintToCanvas(g,y.image,0,1e4+y.distance,!0)&&this.framePrefetchCount++}}paint(t,e,n,i,a,r){let l=this.ctx.globalAlpha,u=typeof t.__zoneVisibilityAlpha=="number"?t.__zoneVisibilityAlpha:1;if(t instanceof gi||t instanceof Ri){let d=t.display.rotation||0,m=d!==0;try{if(m){this.ctx.save();let L=n+a/2,H=i+r/2;t.crop&&(L-=t.crop[e*5+1],H-=t.crop[e*5+2]),this.ctx.translate(L,H),this.ctx.rotate(d*Math.PI/180),this.ctx.translate(-L,-H)}let y=this.options.paintImages!==!1,g=this.options.shouldPaintImage?this.options.shouldPaintImage(t,e):!0;if(!y||!g)return;this.visible.push(t);let b=(t.style?.opacity===void 0?1:t.style.opacity)*u;if(!b)return;this.ctx.globalAlpha=l*b;let w=this.ensureImageBuffer(t),E=this.getTileState(w,e);E.lastUsedAt=performance.now(),this.setTileState(w,e,E);let T=this.getTileKey(t,e);this.markTileRequired(T,!1);let S=this.isLayerActive(t),R=this.getCanvasDims(),A=Qh({x:n+a/2,y:i+r/2},{x:R.width/2,y:R.height/2}),M=this.invalidated.indexOf(w.canvases[e])!==-1,z=this.hostCache.get(w.canvases[e]),N=!!z&&!M;if(M&&this.setTileState(w,e,{...E,state:"idle"}),(M||!N||E.state==="idle"||E.state==="error")&&S&&(this.schedulePaintToCanvas(w,t,e,A,!1),this.schedulePrefetchNeighbours(w,t,e,A)),!this.firstMeaningfulPaint)return;if(z&&!M){let L=this.getFadeAlpha(t,E,S);if(L<1&&(this.hasTilesFading=!0),this.ctx.globalAlpha=l*b*L,t.crop&&t.cropData){if(t.crop[e*5]){let H=[t.crop[e*5+1]/t.display.scale-t.display.points[e*5+1],t.crop[e*5+2]/t.display.scale-t.display.points[e*5+2],1+(t.crop[e*5+3]-t.crop[e*5+1])/t.display.scale,1+(t.crop[e*5+4]-t.crop[e*5+2])/t.display.scale];H[0]+=t.cropData.x/t.display.scale,H[1]+=t.cropData.y/t.display.scale;let U=t.x*this.lastKnownScale,nt=t.y*this.lastKnownScale,Q=[n+U,i+nt,a,r];Q[0]+=U,Q[1]+=nt,this.ctx.drawImage(z,H[0],H[1],H[2],H[3],Q[0],Q[1],Q[2]+1,Q[3]+1)}}else B8?this.ctx.drawImage(z,0,0,t.display.points[e*5+3]-t.display.points[e*5+1],t.display.points[e*5+4]-t.display.points[e*5+2],n,i,a+1,r+1):this.ctx.drawImage(z,0,0,t.display.points[e*5+3]-t.display.points[e*5+1],t.display.points[e*5+4]-t.display.points[e*5+2],n,i,a+Number.MIN_VALUE+.5,r+Number.MIN_VALUE+.5)}}catch{}finally{m&&this.ctx.restore(),this.ctx.globalAlpha=l}}let f=t instanceof Td&&this.options.box,h=t instanceof cR&&this.options.polygon;if((f||h)&&!t.props.className&&!t.props.html&&!t.props.href){if(this.visible.push(t),t.props.style){let d=Object.assign({},t.props.style||{},t.hovering?t.props.hoverStyles:{},t.pressing?t.props.pressStyles:{}),m=t.props.relativeStyle?1:a/t.width,y=d.opacity===void 0?1:d.opacity;this.ctx.globalAlpha=l*y*u;let g=0;d.borderWidth!==void 0&&(g=parseInt(d.borderWidth,10)*m);let b=0;d.outlineWidth!==void 0&&(b=parseInt(d.outlineWidth,10)*m);let w=0;if(d.outlineOffset!==void 0&&(w=parseInt(d.outlineOffset,10)*m),d.borderColor&&(this.ctx.strokeStyle=d.borderColor),d.boxShadow){let E=d.boxShadow.split(/,(?![^(]*\))/);for(let T of E){let S=JL[T]||WL.exec(T)||WL.exec(T);JL[T]=S,S&&(this.ctx.save(),this.ctx.shadowOffsetX=parseInt(S[1])*this.dpi*m,this.ctx.shadowOffsetY=parseInt(S[3])*this.dpi*m,this.ctx.shadowBlur=parseInt(S[5])*this.dpi*m,this.ctx.shadowColor=S[9],this.ctx.fillStyle="rgba(0,0,0,1)",this.ctx.fillRect(n+g,i+g,a,r),this.ctx.restore())}}if(this.ctx.fillStyle=d.backgroundColor||"transparent",this.ctx.lineWidth=g,h){let E=t.shape,T=E.points||[],S=T.length;this.ctx.beginPath();for(let R=0;R<S;R++)this.ctx.lineTo(n+T[R][0]*this.lastKnownScale,i+T[R][1]*this.lastKnownScale);E.open||this.ctx.closePath(),g&&this.ctx.stroke(),E.open||this.ctx.fill()}else g&&this.ctx.strokeRect(n+g/2,i+g/2,a+g,r+g),this.ctx.fillRect(n+g,i+g,a,r);b&&(d.outlineColor&&(this.ctx.strokeStyle=d.outlineColor),this.ctx.lineWidth=b,this.ctx.strokeRect(n-b/2-w,i-b/2-w,a+g*2+b+w*2,r+g*2+b+w*2))}this.ctx.globalAlpha=l}}schedulePaintToCanvas(t,e,n,i,a=!1){let r=this.getTileState(t,n),l=performance.now(),u=this.getTileKey(e,n);if(this.markTileRequired(u,a),this.pendingTileReveals.delete(u),r.nextRetryAt&&r.nextRetryAt>l||r.state==="queued"||r.state==="loading"||r.state==="decoded")return!1;let f=`${e.id}--${e.display.scale}-${n}`,h=this.nextRequestKey(u);t.canvases[n]=f;let d=this.invalidated.indexOf(f);return d!==-1&&this.invalidated.splice(d,1),this.setTileState(t,n,{...r,state:"queued",requestedAt:l,error:void 0,lastRequestKey:h,cancelledAt:void 0,skipFade:!1}),this.loadingQueueOrdered=!1,this.loadingQueue.push({id:f,scale:e.display.scale,kind:"network",tileKey:u,requestKey:h,network:!0,distance:i,paint:e,index:n,prefetch:a,task:async()=>{let m=this.getTileState(t,n);if(m.lastRequestKey!==h||m.state!=="queued"&&m.state!=="loading")return;let y=this.visible.indexOf(e)!==-1,g=this.previousVisible.indexOf(e)!==-1;if(!a&&!y&&!g){this.setTileState(t,n,{...m,state:"idle",cancelledAt:performance.now()}),this.pendingTileReveals.delete(u);return}let b=e.getImageUrl(n);this.setTileState(t,n,{...m,state:"loading",url:b,requestedAt:m.requestedAt||performance.now(),error:void 0});try{let w=`${u}::${h}`,E=this.imageRequestPool.acquire(b,w);this.inFlightImageLoads.set(u,{tileKey:u,requestKey:h,url:b,consumerId:w,paint:e,imageBuffer:t,index:n,release:E.release});let T=await E.promise;this.releaseInFlightTileLoad(u,{silent:!0});let S=this.getTileState(t,n);if(S.lastRequestKey!==h||S.state!=="loading")return;this.loadingQueueOrdered=!1,this.loadingQueue.push({id:`${f}--decode`,scale:e.display.scale,kind:"decode",tileKey:u,requestKey:h,distance:i,paint:e,index:n,prefetch:a,task:()=>new Promise(R=>{let A=this.getTileState(t,n);if(A.lastRequestKey!==h||A.state!=="loading"){R();return}let M=e.display.points.slice(n*5,n*5+5),z=document.createElement("canvas"),N=z.getContext("2d");z.width=M[3]-M[1],z.height=M[4]-M[2],this.hostCache.set(t.canvases[n],z),this.drawCalls.push(()=>{let L=this.getTileState(t,n);if(L.lastRequestKey!==h||L.state!=="loading"){R();return}N.drawImage(T,0,0,M[3]-M[1],M[4]-M[2]);let H=this.getTileState(t,n);this.setTileState(t,n,{...H,state:"decoded",loadedAt:void 0,error:void 0,attempts:0,nextRetryAt:void 0}),this.enqueueTileReveal(u,t,n),this.imagesLoaded++,R()})})})}catch(w){if(this.releaseInFlightTileLoad(u,{silent:!0}),P3(w)){let A=this.getTileState(t,n);A.lastRequestKey===h&&this.setTileState(t,n,{...A,state:"idle",cancelledAt:performance.now()}),this.pendingTileReveals.delete(u);return}let E=this.getTileState(t,n);if(E.lastRequestKey!==h)return;let T=(E.attempts||0)+1,S=T<this.imageLoadingConfig.maxAttempts,R=S?performance.now()+L3(this.imageLoadingConfig,T):performance.now()+this.imageLoadingConfig.errorRetryIntervalMs;this.setTileState(t,n,{...E,state:S?"idle":"error",error:w,attempts:T,nextRetryAt:R}),this.pendingTileReveals.delete(u),this.emitImageError({severity:"recoverable",imageUrl:b,contentId:e.id,tileIndex:n,attempt:T,maxAttempts:this.imageLoadingConfig.maxAttempts,willRetry:S,nextRetryAt:R,error:w})}}}),!0}afterPaintLayer(t,e){}prepareLayer(t,e){if(this.hasActiveLayerClip=!1,t.__owner.value&&(t.cropData&&this.lastKnownScale*(1/t.display.scale),this.applyTransform(t,e[1],e[2],e[3]-e[1],e[4]-e[2])),this.shouldClipLayerToBounds(t)){let n=this.getBoundsFromPoints(e);n&&(this.ctx.save(),this.ctx.beginPath(),this.ctx.rect(n.x,n.y,n.width,n.height),this.ctx.clip(),this.hasActiveLayerClip=!0)}(!t.__host||!t.__host.canvas)&&(t instanceof gi||t instanceof Ri)&&this.createImageHost(t)}finishLayer(){this.hasActiveLayerClip&&(this.ctx.restore(),this.hasActiveLayerClip=!1),this.lastPaintedObject&&this.clearTransform()}createImageHost(t){t.__host=t.__host?t.__host:{},t.__host.canvas={canvas:void 0,canvases:[],tiles:{},indices:[],loaded:[],loading:!1}}getPointsAt(t,e,n,i){return t.getPointsAt(e,n,i)}getViewportBounds(t,e,n){let i=t.getActiveZone();if(i){i.recalculateBounds();let a=_3(e,i.points,n);if(a){let r=e[3]-e[1],l=e[4]-e[2];return{x1:a.minX,y1:a.minY,x2:a.maxX+r,y2:a.maxY+l}}}return null}pendingUpdate(){this.imagesPending=this.loadingQueue.length+this.tasksRunning+this.inFlightImageLoads.size+this.pendingTileReveals.size;let t=!this.pendingDrawCall&&this.drawCalls.length===0&&this.loadingQueue.length===0&&this.tasksRunning===0&&this.inFlightImageLoads.size===0&&this.pendingTileReveals.size===0;return!t&&this.visible.length===0&&this.options.readiness!=="immediate"&&this.fallbackRevealTimeout===null&&(this.fallbackRevealTimeout=setTimeout(()=>{this.canvas.style.opacity="1",this.firstMeaningfulPaint=!0,this.fallbackRevealTimeout=null},500)),!this.firstMeaningfulPaint&&t&&(this.visible.length||this.options.readiness==="immediate")?(this.canvas.style.opacity="1",this.firstMeaningfulPaint=t,!0):this.options.debug||this.hasTilesFading?!0:!t}getRendererScreenPosition(){return this.rendererPosition}resetReadyState(){this.options.readiness!=="immediate"&&(this.firstMeaningfulPaint=!1,this.fallbackRevealTimeout&&(clearTimeout(this.fallbackRevealTimeout),this.fallbackRevealTimeout=null))}reset(){this.loadingQueue=[],this.drawCalls=[],this._scheduled&&(clearInterval(this._scheduled),this._scheduled=0);for(let t of[...this.inFlightImageLoads.keys()])this.releaseInFlightTileLoad(t,{silent:!0});this.imageRequestPool.cancelAll({silent:!0}),this.inFlightImageLoads.clear(),this.requiredTileKeys.clear(),this.requiredPrefetchTileKeys.clear(),this.pendingTileReveals.clear(),this.requestGeneration+=1,this.frameCounter=0,this.fallbackRevealTimeout&&(clearTimeout(this.fallbackRevealTimeout),this.fallbackRevealTimeout=null),this.imagesPending=0,this.imagesLoaded=0,this.hasTilesFading=!1}},F3=class{constructor(t){C(this,"renderers",[]),C(this,"length",void 0);for(let e of t)e&&this.renderers.push(e);this.length=this.renderers.length}afterFrame(t,e,n,i){for(let a=0;a<this.length;a++)this.renderers[a].afterFrame(t,e,n,i)}afterPaintLayer(t,e){for(let n=0;n<this.length;n++)this.renderers[n].afterPaintLayer(t,e)}beforeFrame(t,e,n,i){for(let a=0;a<this.length;a++)this.renderers[a].beforeFrame(t,e,n,i)}triggerResize(){for(let t=0;t<this.length;t++){let e=this.renderers[t];e.triggerResize&&e.triggerResize()}}getPointsAt(t,e,n,i){return this.renderers[0].getPointsAt(t,e,n,i)}getScale(t,e){return this.renderers[0].getScale(t,e)}getViewportBounds(t,e,n){return this.renderers[0].getViewportBounds(t,e,n)}getRendererScreenPosition(){return this.renderers[0].getRendererScreenPosition()}isReady(){for(let t=0;t<this.length;t++)if(!this.renderers[t].isReady())return!1;return!0}paint(t,e,n,i,a,r){for(let l=0;l<this.length;l++)this.renderers[l].paint(t,e,n,i,a,r)}pendingUpdate(){for(let t=0;t<this.length;t++)if(this.renderers[t].pendingUpdate())return!0;return!1}prepareLayer(t,e){for(let n=0;n<this.length;n++)this.renderers[n].prepareLayer(t,e)}finishLayer(t,e){for(let n=0;n<this.length;n++)this.renderers[n].finishLayer(t,e)}resize(t,e){for(let n=0;n<this.length;n++)this.renderers[n].resize(t,e)}reset(){for(let t=0;t<this.length;t++)this.renderers[t].reset()}resetReadyState(){for(let t=0;t<this.length;t++)this.renderers[t].resetReadyState&&this.renderers[t].resetReadyState()}},F8=class extends Yr{constructor(...t){super(...t),C(this,"type","spacial-content")}getAllPointsAt(t,e,n){return[[this,this.points,e]]}},dR=class extends F8{constructor(t){super(),C(this,"id",void 0),C(this,"display",void 0),C(this,"points",void 0),C(this,"images",[]),C(this,"allImages",[]),C(this,"scaleFactors",[]),C(this,"aggregateBuffer",It(9)),C(this,"lazyLoader",void 0),C(this,"isFullyLoaded",!1),C(this,"isLoadingFullResource",!1),C(this,"maxScaleFactor",0),C(this,"layerSelection",new WeakMap),C(this,"layerSelectionFrame",0),C(this,"renderOptions",void 0),C(this,"_scheduleSortByScales",!1),C(this,"_sortByScales",()=>{this._scheduleSortByScales=!1,this.allImages.sort((n,i)=>i.display.width-n.display.width),this.images=[];let e=.1;for(let n of this.allImages)if(!(n.display.width<this.renderOptions.minSize&&n.display.height<this.renderOptions.minSize&&!n.priority)&&!(n instanceof gi&&(n.display.width>this.renderOptions.maxImageSize||n.display.height>this.renderOptions.maxImageSize)&&!n.priority)){if(Math.abs(n.display.scale-e)<.25||n.priority){let i=this.images.pop();i&&(i instanceof gi||i.priority)?(n.priority&&this.images.push(n),this.images.push(i)):n&&this.images.push(n)}else n&&this.images.push(n);e=n.display.scale}this.images.length===0&&(this.images=[...this.allImages]),this.scaleFactors=this.images.map(n=>n.display.scale),this.maxScaleFactor=this.scaleFactors.length?Math.max(...this.scaleFactors):0}),C(this,"loadFullResource",async()=>{if(!(this.isFullyLoaded||this.isLoadingFullResource)&&this.lazyLoader){this.isLoadingFullResource=!0;try{let e=await this.lazyLoader();this.addImages(e||[]),this.isFullyLoaded=!0}finally{this.isLoadingFullResource=!1}}}),C(this,"fallback",[this.loadFullResource]),this.id=t.id,this.points=de.singleBox(t.width,t.height),this.lazyLoader=t.loadFullImages,t.loadFullImages||(this.isFullyLoaded=!0),this.display={x:0,y:0,points:de.singleBox(t.width,t.height),height:t.height,width:t.width,scale:1},this.renderOptions={renderSmallestFallback:!0,renderLayers:2,minSize:255,maxImageSize:2048,quality:1.3,useDevicePixelRatio:!0,layerPolicy:"always-blend",loadingBias:"balanced",prefetchRadius:1,fadeInMs:300,fadeFallbackTiles:!1,fadeOnLayerChange:!1,clipToBounds:!1,...t.renderOptions||{}},this.addImages(t.images)}applyProps(t){let e=!1;t.renderSmallestFallback!==void 0&&t.renderSmallestFallback!==this.renderOptions.renderSmallestFallback&&(this.renderOptions.renderSmallestFallback=t.renderSmallestFallback),t.renderLayers!==void 0&&t.renderLayers!==this.renderOptions.renderLayers&&(this.renderOptions.renderLayers=t.renderLayers),t.minSize!==void 0&&t.minSize!==this.renderOptions.minSize&&(this.renderOptions.minSize=t.minSize,e=!0),t.maxImageSize!==void 0&&t.maxImageSize!==this.renderOptions.maxImageSize&&(this.renderOptions.maxImageSize=t.maxImageSize,e=!0),t.quality!==void 0&&t.quality!==this.renderOptions.quality&&(this.renderOptions.quality=t.quality),t.useDevicePixelRatio!==void 0&&t.useDevicePixelRatio!==this.renderOptions.useDevicePixelRatio&&(this.renderOptions.useDevicePixelRatio=t.useDevicePixelRatio),t.layerPolicy!==void 0&&t.layerPolicy!==this.renderOptions.layerPolicy&&(this.renderOptions.layerPolicy=t.layerPolicy),t.loadingBias!==void 0&&t.loadingBias!==this.renderOptions.loadingBias&&(this.renderOptions.loadingBias=t.loadingBias),t.prefetchRadius!==void 0&&t.prefetchRadius!==this.renderOptions.prefetchRadius&&(this.renderOptions.prefetchRadius=t.prefetchRadius),t.fadeInMs!==void 0&&t.fadeInMs!==this.renderOptions.fadeInMs&&(this.renderOptions.fadeInMs=t.fadeInMs),t.fadeFallbackTiles!==void 0&&t.fadeFallbackTiles!==this.renderOptions.fadeFallbackTiles&&(this.renderOptions.fadeFallbackTiles=t.fadeFallbackTiles),t.fadeOnLayerChange!==void 0&&t.fadeOnLayerChange!==this.renderOptions.fadeOnLayerChange&&(this.renderOptions.fadeOnLayerChange=t.fadeOnLayerChange),t.clipToBounds!==void 0&&t.clipToBounds!==this.renderOptions.clipToBounds&&(this.renderOptions.clipToBounds=t.clipToBounds),e&&this.sortByScales()}appendChild(t){this.addImages([t])}removeChild(t){if(this.images.indexOf(t)===-1&&this.allImages.indexOf(t)===-1)return;let e=this.getImageDedupeKey(t);this.images=this.images.filter(n=>n!==t&&this.getImageDedupeKey(n)!==e),this.allImages=this.allImages.filter(n=>n!==t&&this.getImageDedupeKey(n)!==e),this.sortByScales()}insertBefore(t,e){this.addImages([t])}hideInstance(){}addImages(t){let e=new Set(this.allImages),n=new Set(this.allImages.map(i=>this.getImageDedupeKey(i)));for(let i of t){if(!i||e.has(i))continue;let a=this.getImageDedupeKey(i);n.has(a)||(i.__parent=this,i.__owner=this.__owner,this.allImages.push(i),e.add(i),n.add(a))}this.sortByScales()}getImageDedupeKey(t){return`${t.id}::${t.display.scale}`}sortByScales(){this._scheduleSortByScales=!0}getScheduledUpdates(t,e){return this._scheduleSortByScales?[this._sortByScales]:this.isFullyLoaded?[]:e>1/this.maxScaleFactor?this.fallback:[]}getAllPointsAt(t,e,n){if(this.images.length===0)return[];let i=this.renderOptions.useDevicePixelRatio&&typeof window<"u"&&window.devicePixelRatio||1,a=w8(1/(n||1)/i,this.images,this.renderOptions.quality),r=this.images.length,l=e?Dr(e,ci(this.x,this.y)):ci(this.x,this.y),u=[a];if(a!==this.images.length-1&&this.images[a+1]){u=[];for(let b=r-1;b>=a;b--)u.push(b);let g=u[0];this.renderOptions.renderLayers&&(u=u.slice(-Math.min(u.length,this.renderOptions.renderLayers))),this.renderOptions.renderSmallestFallback&&u.indexOf(g)===-1&&u.unshift(g)}u.sort((g,b)=>{let w=this.images[g],E=this.images[b],T=w?w.display.scale:0;return(E?E.display.scale:0)-T});let f=new Set;switch(this.renderOptions.layerPolicy){case"always-blend":for(let g of u)f.add(g);break;case"active-only":f.add(a),u=[a];break;case"fallback-only":default:f.add(a),this.renderOptions.renderSmallestFallback&&u.length&&f.add(u[0]);break}let h=new Set;for(let g of f){let b=this.images[g];b&&h.add(b)}this.layerSelectionFrame+=1;let d=this.getNow(),m=d-Math.max(0,this.renderOptions.fadeInMs);for(let g of this.allImages){let b=this.layerSelection.get(g);if(!h.has(g)){this.layerSelection.set(g,{active:!1,frame:this.layerSelectionFrame});continue}let w=!!b&&b.frame===this.layerSelectionFrame-1,E=w&&b.active;this.layerSelection.set(g,{active:!0,frame:this.layerSelectionFrame,activatedAt:E&&typeof b.activatedAt=="number"?b.activatedAt:w?d:m})}let y=[];for(let g=0;g<u.length;g++){let b=u[g],w=this.images[b];y.push(...w.getAllPointsAt(t,l,n))}return y}isImageActive(t){let e=this.layerSelection.get(t);return!!e&&e.frame===this.layerSelectionFrame&&e.active}getImageActivatedAt(t){let e=this.layerSelection.get(t);if(!(!e||e.frame!==this.layerSelectionFrame||!e.active))return e.activatedAt}getNow(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}},Lv=class extends Yr{constructor(t){if(super(),C(this,"type","spacial-content"),C(this,"id",void 0),C(this,"uri",void 0),C(this,"display",void 0),C(this,"points",void 0),C(this,"getTexture",void 0),this.getTexture=()=>({source:void 0,hash:-1}),!t)this.id="",this.uri="",this.display={x:0,y:0,scale:1,width:0,height:0,points:It(5)},this.points=It(5);else{let e=t.scale||1;this.id=t.id||t.uri,this.uri=t.uri,this.points=de.singleBox(t.width,t.height),this.display={x:0,y:0,scale:e,width:t.width/e,height:t.height/e,points:e===1?this.points:de.singleBox(t.width/e,t.height/e)}}}applyProps(t){let e=t.display?t.display.width:t.target.width,n=t.target.width/e;this.id=t.id,this.points.set(de.singleBox(t.target.width,t.target.height)),this.display.scale=n,this.display.width=t.target.width/n,this.display.height=t.target.height/n,this.getTexture=t.getTexture,this.display.points=n===1?this.points:de.singleBox(t.target.width/n,t.target.height/n)}getAllPointsAt(t,e,n){return[[this,this.points,e]]}},wv=85.05112878;function yr(t,e){if(!Number.isFinite(t))throw Error(`${e} must be a finite number`)}function $L(t,e){if(yr(t,e),t<=0)throw Error(`${e} must be greater than 0`)}function q8(t){if(!Number.isFinite(t))throw Error("Latitude must be a finite number");return t>wv?wv:t<-wv?-wv:t}function Dv(t){if(yr(t.west,"Map bounds west"),yr(t.south,"Map bounds south"),yr(t.east,"Map bounds east"),yr(t.north,"Map bounds north"),t.west<-180||t.west>180)throw Error("Map bounds west must be within [-180, 180]");if(t.east<-180||t.east>180)throw Error("Map bounds east must be within [-180, 180]");if(t.south<-90||t.south>90)throw Error("Map bounds south must be within [-90, 90]");if(t.north<-90||t.north>90)throw Error("Map bounds north must be within [-90, 90]");if(t.west>=t.east)throw Error("Map bounds must satisfy west < east (antimeridian crossing is not supported)");if(t.south>=t.north)throw Error("Map bounds must satisfy south < north");return t}function _v(t){if(!Number.isFinite(t))throw Error("Longitude must be a finite number");return(t+180)/360}function zv(t){let e=q8(t)*Math.PI/180;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}function q3(t){if(!Number.isFinite(t))throw Error("Mercator X must be a finite number");return t*360-180}function V3(t){if(!Number.isFinite(t))throw Error("Mercator Y must be a finite number");let e=Math.PI*(1-2*t);return 180/Math.PI*Math.atan(Math.sinh(e))}function t3(t,e){return _v(t)*2**e}function e3(t,e){return zv(t)*2**e}function n3(t,e){return q3(t/2**e)}function i3(t,e){return V3(t/2**e)}function V8(t){let e=Dv(t.bounds);$L(t.width,"Map world width"),$L(t.height,"Map world height");let n=_v(e.west),i=_v(e.east),a=zv(e.north),r=zv(e.south),l=i-n,u=r-a;if(!(l>0))throw Error("Map bounds produce an invalid mercator X span");if(!(u>0))throw Error("Map bounds produce an invalid mercator Y span");let f=(d,m)=>{let y=_v(d),g=zv(m);return{x:(y-n)/l*t.width,y:(g-a)/u*t.height}},h=(d,m)=>{yr(d,"World x"),yr(m,"World y");let y=n+d/t.width*l,g=a+m/t.height*u;return{lng:q3(y),lat:V3(g)}};return{lngLatToWorld:f,worldToLngLat:h,lngLatBoundsToWorldRect:d=>{Dv(d);let m=f(d.west,d.north),y=f(d.east,d.south);return{x:m.x,y:m.y,width:y.x-m.x,height:y.y-m.y}},worldRectToLngLatBounds:d=>{yr(d.x,"World rect x"),yr(d.y,"World rect y"),yr(d.width,"World rect width"),yr(d.height,"World rect height");let m=h(d.x,d.y),y=h(d.x+d.width,d.y+d.height);return{west:m.lng,south:y.lat,east:y.lng,north:m.lat}},projectRing:d=>{let m=[];for(let[y,g]of d){let b=f(y,g);m.push([b.x,b.y])}return m}}}var U3="https://tile.openstreetmap.org/{z}/{x}/{y}.png";function U8(t){if(t.s)return t.s;let e=t.subdomains||[];if(e.length!==0)return e[Math.abs(t.x+t.y+t.z)%e.length]}function j8(t,e){let n=U8(e)||"";return t.replace(/\{z\}/g,`${e.z}`).replace(/\{x\}/g,`${e.x}`).replace(/\{y\}/g,`${e.y}`).replace(/\{s\}/g,n)}function k8(t,e){let n=t||U3;return typeof n=="function"?n(e):j8(n,e)}function Ys(t,e,n){return Math.min(n,Math.max(e,t))}function G8(t){Dv(t.bounds);let e=Math.max(0,Math.floor(t.zoom)),n=2**e,i=n-1,a=t3(t.bounds.west,e),r=t3(t.bounds.east,e),l=e3(t.bounds.north,e),u=e3(t.bounds.south,e),f=Ys(a,0,n),h=Ys(r,0,n),d=Ys(l,0,n),m=Ys(u,0,n),y=Math.max(1e-9,h-f),g=Math.max(1e-9,m-d),b=Ys(Math.floor(a),0,i),w=Ys(Math.ceil(r)-1,0,i),E=Ys(Math.floor(l),0,i),T=Ys(Math.ceil(u)-1,0,i),S=Math.max(1,w-b+1),R=Math.max(1,T-E+1);return{columns:S,rows:R,count:S*R,minTileX:b,maxTileX:w,minTileY:E,maxTileY:T,westTile:f,eastTile:h,northTile:d,southTile:m,tileSpanX:y,tileSpanY:g}}function Y8(t){Dv(t.bounds);let e=Math.max(0,Math.floor(t.zoom)),n=V8({bounds:t.bounds,width:t.worldWidth,height:t.worldHeight}),i=G8({bounds:t.bounds,zoom:e}),a=typeof t.maxTiles=="number"?t.maxTiles:1/0;if(i.count>a)throw Error(`Map tile grid too large at zoom ${e}: ${i.count} tiles exceeds the configured max (${a})`);let r=[],l=[];for(let u=i.minTileY;u<=i.maxTileY;u++)for(let f=i.minTileX;f<=i.maxTileX;f++){let h=n3(f,e),d=n3(f+1,e),m=i3(u,e),y=i3(u+1,e),g=n.lngLatToWorld(h,m),b=n.lngLatToWorld(d,y);r.push(1,g.x,g.y,b.x,b.y),l.push({x:f,y:u,z:e})}return{points:It(r.length?r:[0]),tiles:l,columns:i.columns,rows:i.rows,count:i.count,minTileX:i.minTileX,maxTileX:i.maxTileX,minTileY:i.minTileY,maxTileY:i.maxTileY}}var X8=class extends Ri{constructor(t){let e=t.scaleFactor||1,n=t.tileSize||256,i=t.tileSource||t.tileUrlTemplate||U3,a=Y8({bounds:t.bounds,zoom:t.zoom,worldWidth:t.worldWidth,worldHeight:t.worldHeight}),r=t.id||`map-tiled-image-z${t.zoom}-${t.worldWidth}x${t.worldHeight}-${a.minTileX}:${a.maxTileX}-${a.minTileY}:${a.maxTileY}`;super({id:r,url:"map://tile-source",scaleFactor:e,points:a.points,displayPoints:a.points,tileWidth:n,tileHeight:n,width:t.worldWidth,height:t.worldHeight,columns:a.columns,rows:a.rows,format:"png",version3:!1}),C(this,"zoom",void 0),C(this,"bounds",void 0),C(this,"worldWidth",void 0),C(this,"worldHeight",void 0),C(this,"tileSize",void 0),C(this,"tileSource",void 0),C(this,"subdomains",void 0),C(this,"tileCoordinates",void 0),C(this,"minTileX",void 0),C(this,"maxTileX",void 0),C(this,"minTileY",void 0),C(this,"maxTileY",void 0),this.zoom=Math.max(0,Math.floor(t.zoom)),this.bounds={...t.bounds},this.worldWidth=t.worldWidth,this.worldHeight=t.worldHeight,this.tileSize=n,this.tileSource=i,this.subdomains=[...t.subdomains||[]],this.tileCoordinates=a.tiles,this.minTileX=a.minTileX,this.maxTileX=a.maxTileX,this.minTileY=a.minTileY,this.maxTileY=a.maxTileY}getImageUrl(t){let e=this.tileCoordinates[t];return e?k8(this.tileSource,{z:e.z,x:e.x,y:e.y,tileSize:this.tileSize,subdomains:this.subdomains}):""}},Q8=class{constructor(t){C(this,"canvas",void 0),C(this,"context",void 0),C(this,"heightRatio",1),C(this,"widthRatio",1),C(this,"target",new Float32Array(5)),C(this,"initialWidth",void 0),C(this,"initialHeight",void 0),C(this,"bounds",void 0),C(this,"aggregate",void 0),C(this,"delta",0),C(this,"renderNextFrame",!0),this.canvas=t,this.initialWidth=t.width,this.initialHeight=t.height,this.context=t.getContext("2d"),this.context.globalAlpha=.5,this.aggregate=mo(1)}isReady(){return!0}resize(){this.initialWidth=this.canvas.width,this.initialHeight=this.canvas.height,this.renderNextFrame=!0}afterFrame(t,e,n){if(this.renderNextFrame){this.context.clearRect(0,0,this.canvas.width,this.canvas.height);let i=this.initialWidth/t.width,a=this.initialHeight/t.height,r=this.widthRatio>this.heightRatio?i:a;if(this.target=n,this.bounds){let l=t.getPointsAt(this.bounds,this.aggregate,r);for(let[u,f]of l)if(u instanceof gi&&u.__host.canvas){let h=f.length/5;for(let d=0;d<h;d++)u.__host.canvas.canvases[d]&&(f[d+1]*r,f[d+2]*r,(f[d+3]-f[d+1])*r,(f[d+4]-f[d+2])*r)}}t.getPoints().forEach((l,u,f)=>{if(u%5==0&&l){let h={x1:f[u+1]*r,y1:f[u+2]*r,x2:f[u+3]*r,y2:f[u+4]*r,width:(f[u+3]-f[u+1])*r,height:(f[u+4]-f[u+2])*r};this.context.strokeStyle="red",this.context.strokeRect(h.x1,h.y1,h.width,h.height)}}),n&&(this.context.strokeStyle="red",this.context.lineWidth=window.devicePixelRatio||1,this.context.strokeRect(n[1]*r,n[2]*r,(n[3]-n[1])*r,(n[4]-n[2])*r))}}getActiveZone(t){return null}getPointsAt(t,e,n,i){return t.getPointsAt(e,n,i)}getScale(t,e){return 1}beforeFrame(t,e){this.bounds=de.singleBox(t.width,t.height)}drawImage(){}afterPaintLayer(t,e){}paint(t,e,n,i,a,r){this.renderNextFrame=!0}prepareLayer(t){}pendingUpdate(){return!1}hasActiveZone(){return!1}getViewportBounds(t,e,n){return null}getRendererScreenPosition(){return this.canvas.getBoundingClientRect()}finishLayer(){}reset(){}};function Tv(t,e,n,i,a){let r=Math.PI/180*a,l=Math.cos(r),u=Math.sin(r);return[l*(n-t)+u*(i-e)+t,l*(i-e)-u*(n-t)+e]}var Bo=class j3 extends Yr{constructor(e,n){super(),C(this,"id",void 0),C(this,"type","world-object"),C(this,"scale",void 0),C(this,"layers",void 0),C(this,"points",void 0),C(this,"worldPoints",void 0),C(this,"intersectionBuffer",It(5)),C(this,"aggregateBuffer",It(9)),C(this,"invertedBuffer",It(9)),C(this,"rotation",0),C(this,"filteredPointsBuffer",void 0),C(this,"_updatedList",[]),C(this,"geometry",void 0);let{x:i=0,y:a=0}=n||{};e?(this.id=e.id||"",this.scale=1,this.layers=e.layers,this.points=It([1,i,a,i+e.width,a+e.height]),this.worldPoints=It([1,i,a,i+e.width,a+e.height]),this.filteredPointsBuffer=It(e.layers.length*5)):(this.id="",this.scale=1,this.layers=[],this.points=It(5),this.worldPoints=It(5),this.filteredPointsBuffer=It(5))}static createWithProps(e){let n=new j3;return n.applyProps(e),n}applyProps(e){let n=e.x||0,i=e.y||0;e.id!==void 0&&(this.id=e.id);let a=e.scale===void 0?this.scale:e.scale;this.points[0]=1,this.points[1]=n,this.points[2]=i,this.points[3]=n+e.width,this.points[4]=i+e.height,this.rotation=e.rotation||0,this.worldPoints[3]=this.worldPoints[1]+e.width,this.worldPoints[4]=this.worldPoints[2]+e.height,e.scale&&e.scale!==1&&this.atScale(a),this.scale=a}appendChild(e){e.points[0]===0&&e.points.set(this.points),e.__owner.value=this,this.addLayers([e])}removeChild(e){this.layers=this.layers.filter(n=>n!==e),this.filteredPointsBuffer=It(this.layers.length*5)}insertBefore(e,n){let i=this.layers.indexOf(n);if(i===-1||this.layers.indexOf(e)!==-1)return;let a=this.layers.slice(0,i),r=this.layers.slice(i);this.layers=[...a,e,...r]}hideInstance(){console.warn("hideInstance: not yet implemented")}getObjectsAt(e,n){if(this.rotation&&(e=this.applyRotation(e)),Oc(this.points,e,this.filteredPointsBuffer)[0]===0)return[];let i=this.layers.length,a=[];for(let r=0;r<i;r++){let l=this.layers[r];if(n&&l.isShape){let u=Xi(l.points,ci(this.x,this.y));if(!l.intersects([e[1]-u[1],e[2]-u[2]]))continue}if(Oc(Xi(l.points,ci(this.x,this.y)),e,this.filteredPointsBuffer)[0]!==0&&a.push(l),n){let u=l;a.push(...u.getObjectsAt(e,n))}}return a}applyRotation(e){if(this.rotation){let n={x:e[1],y:e[2]},i={x:e[1],y:e[4]},a={x:e[3],y:e[2]},r={x:e[3],y:e[4]},l=this.points[1]+(this.points[3]-this.points[1])/2,u=this.points[2]+(this.points[4]-this.points[2])/2,[f,h]=Tv(l,u,n.x,n.y,this.rotation),[d,m]=Tv(l,u,i.x,i.y,this.rotation),[y,g]=Tv(l,u,a.x,a.y,this.rotation),[b,w]=Tv(l,u,r.x,r.y,this.rotation),E=Math.min(f,d,y,b),T=Math.max(f,d,y,b),S=Math.min(h,m,g,w),R=Math.max(h,m,g,w);return It([e[0],E,S,T,R])}return e}getAllPointsAt(e,n,i){let a=Dr(ci(this.x,this.y),mo(this.scale),this.aggregateBuffer);this.rotation&&(e=this.applyRotation(e));let r=AO(e,this.points,this.intersectionBuffer),l=this.layers.length,u=[],f=Xi(r,Dr(mo(1/this.scale),ci(-this.x,-this.y),this.invertedBuffer)),h=n?Dr(n,a,this.aggregateBuffer):a,d=i*this.scale;for(let m=0;m<l;m++)u.push(...this.layers[m].getAllPointsAt(f,h,d));return u}addLayers(e){let n=[];for(let i of e)this.layers.indexOf(i)===-1&&(n.push(i),i.points.length===5&&(i.points[1]<this.worldPoints[1]/this.scale||i.points[2]<this.worldPoints[2]/this.scale||i.points[3]>this.worldPoints[3]/this.scale||i.points[4]>this.worldPoints[4]/this.scale)&&(i.crop=i.crop||It([1,Math.max(this.worldPoints[1]/this.scale,i.points[1]),Math.max(this.worldPoints[2]/this.scale,i.points[2]),Math.min(this.worldPoints[3]/this.scale,i.points[3]),Math.min(this.worldPoints[4]/this.scale,i.points[4])])));this.layers=this.layers.concat(n),this.filteredPointsBuffer=It(this.layers.length*5)}getScheduledUpdates(e,n){let i=this.layers.length;this._updatedList=[];let a=n*this.scale;for(let r=0;r<i;r++){let l=this.layers[r].getScheduledUpdates(e,a);l&&this._updatedList.push(...l)}return this._updatedList}},mu=class k3 extends Yr{get x(){return 0}get y(){return 0}get width(){return this._width}get height(){return this._height}constructor(e=0,n=0,i=100,a="left-to-right"){super(),C(this,"id","world"),C(this,"_width",void 0),C(this,"_height",void 0),C(this,"aspectRatio",void 0),C(this,"viewingDirection",void 0),C(this,"aggregateBuffer",It(9)),C(this,"isDirty",!1),C(this,"zones",[]),C(this,"filteredPointsBuffer",void 0),C(this,"selectedZone",void 0),C(this,"triggerQueue",[]),C(this,"activatedEvents",[]),C(this,"_updatedList",[]),C(this,"translationBuffer",It(9)),C(this,"needsRecalculate",!0),C(this,"emptyPaintables",[]),C(this,"renderOrder",[]),C(this,"debugSubscribers",new Set),C(this,"zoneVisibilityFadeDurationMs",220),C(this,"zoneOutsideOpacity",.2),C(this,"zoneVisibilityFade",void 0),C(this,"points",void 0),C(this,"objects",[]),C(this,"subscriptions",[]),C(this,"_propagateEventTargets",[]),C(this,"_alreadyFlushed",[]),this._width=e,this._height=n,this.aspectRatio=Number.isNaN(e/n)?1:e/n,this.viewingDirection=a,this.points=It(i*5),this.filteredPointsBuffer=It(i*5)}static withProps(e){let n=new k3;return n.applyProps(e),n}applyProps(e){e.width!==void 0&&e.height!==void 0&&(e.width!==this._width||e.height!==this._height)&&this.resize(e.width,e.height),e.viewingDirection!==this.viewingDirection&&(this.viewingDirection=e.viewingDirection,this.triggerRepaint())}propagateTouchEvent(e,n,i){let a=[];for(let r of i)if(r.x&&r.y){let l=de.singleBox(1,1,r.x,r.y);a.push(this.getObjectsAt(l,!0).reverse())}return this.emitDebug({type:"touch",at:performance.now(),event:e,touches:i.length}),a.map(r=>this.propagateEvent(e,n,r,{bubbles:!0,cancelable:!0}))}propagatePointerEvent(e,n,i,a,r={}){let l=de.singleBox(1,1,i,a),u=this.getObjectsAt(l,!0).reverse(),f=this.propagateEvent(e,n,u,r);return this.emitDebug({type:"pointer",at:performance.now(),event:e,x:i,y:a,targets:f.length}),f}propagateEvent(e,n,i,{bubbles:a=!1,cancelable:r=!1}={}){n.atlasTarget=this,this._propagateEventTargets.length=1,this._propagateEventTargets[0]=this;let l=!1;n.stopPropagation=()=>{l=!0};let u=i.length;for(let d=u-1;d>=0;d--){this._propagateEventTargets.unshift(i[d][0]);let m=i[d][1].length;if(m)for(let y=0;y<m;y++)this._propagateEventTargets.unshift(i[d][1][y])}let f=this._propagateEventTargets.length,h=!1;for(let d=0;d<f&&(n.atlasTarget=this._propagateEventTargets[d],n.atlasWorld=this,h=this._propagateEventTargets[d].dispatchEvent(e,n)||h,!l);d++);return h&&this.triggerRepaint(),this._propagateEventTargets}appendChild(e){let n=this.appendWorldObject(e);this.renderOrder.push(n/5)}removeChild(e){let n=this.objects.indexOf(e);if(n===-1){for(let i of this.objects)if(i&&i.id===e.id){this.removeChild(i);return}return}this.objects[n]=null,this.renderOrder=this.renderOrder.filter(i=>i!==n),this.points[n*5]=0;for(let i of this.zones){let a=i.objects.indexOf(e);a!==-1&&(i.objects.splice(a,1),i.recalculateBounds())}this.triggerRepaint(),this.needsRecalculate=!0}insertBefore(e,n){let i=this.objects.indexOf(n);if(i===-1)return;let a=this.appendWorldObject(e);this.renderOrder.splice(i-1,0,a/5)}hideInstance(){}asWorldObject(){return null}addZone(e){this.zones.push(e)}removeZone(e){let n=this.zones.indexOf(e);if(n!==-1&&(this.zones.splice(n,1),this.selectedZone!==void 0)){if(this.selectedZone===n){this.selectedZone=void 0,this.trigger("zone-changed");return}this.selectedZone>n&&--this.selectedZone}}getZoneById(e){for(let n of this.zones)if(n.id===e)return n}hasZone(e){return this.getZoneById(e)!==void 0}selectZone(e){if(typeof e=="string"){let n=this.getZoneById(e);n&&(this.selectedZone=this.zones.indexOf(n),this.zoneVisibilityFade={zoneId:n.id,startedAt:performance.now()},this.trigger("zone-changed"))}else this.zones[e]&&(this.selectedZone=e,this.zoneVisibilityFade={zoneId:this.zones[e].id,startedAt:performance.now()},this.trigger("zone-changed"))}deselectZone(){this.selectedZone=void 0,this.zoneVisibilityFade=void 0,this.trigger("zone-changed")}getActiveZone(){if(this.selectedZone!==void 0)return this.zones[this.selectedZone]}hasActiveZone(){return this.selectedZone!==void 0}checkResizeInternalBuffer(){if(CO(this.points)===this.objects.length){let e=this.points,n=It(this.points.length*2);n.set(e,0),this.points=n}}appendWorldObject(e){this.checkResizeInternalBuffer();let n=this.objects.length*5,i=e.points;return e.points=this.points.subarray(this.objects.length*5,this.objects.length*5+5),e.points[1]=i[1],e.points[2]=i[2],e.points[3]=i[3],e.points[4]=i[4],this.objects.push(e),this.filteredPointsBuffer=It(this.objects.length*5),this.needsRecalculate=!0,this.triggerRepaint(),n}recalculateWorldSize(){let e=!1;if(this.needsRecalculate){let n=new Int32Array(this.objects.length),i=new Int32Array(this.objects.length),a=this.renderOrder.length;for(let u=0;u<a;u++){let f=this.renderOrder[u];this.objects[f]&&(n[u]=this.points[f*5+3],i[u]=this.points[f*5+4])}let r=Math.max(...n);r!==this._width&&(this._width=r,e=!0);let l=Math.max(...i);l!==this._height&&(this._height=l,e=!0),e&&this.trigger("recalculate-world-size",{width:r,height:l}),this.needsRecalculate=!1}return e}addObjectAt(e,n){n.width&&!n.height?n.height=n.width/e.width*e.height:n.height&&!n.width&&(n.width=n.height/e.height*e.width),(!n||!n.width||!n.height)&&(n.width=e.width,n.height=e.height);let{width:i,x:a,y:r}=n,l=i/e.width;this.checkResizeInternalBuffer(),this.points.set(de.singleBox(e.width,e.height,0,0),this.objects.length*5);let u=new Bo(e);return u.points=this.points.subarray(this.objects.length*5,this.objects.length*5+5),this.objects.push(u),this.scaleWorldObject(this.objects.length-1,l),this.translateWorldObject(this.objects.length-1,a,r),this.filteredPointsBuffer=It(this.points.length*2),this.triggerRepaint(),this.needsRecalculate=!0,u}scaleWorldObject(e,n){hr(this.points.subarray(e*5,e*5+5),kl(n,this.points[e*5+1],this.points[e*5+2]));let i=this.objects[e];i&&(i.atScale(n),this.triggerRepaint())}translateWorldObject(e,n,i){hr(this.points.subarray(e*5,e*5+5),ci(n,i));let a=this.objects[e];a&&(a.translate(n,i),this.triggerRepaint())}resize(e,n){return this._width=e,this._height=n,this.aspectRatio=e/n,this.triggerRepaint(),this}getObjects(){return this.objects}getPoints(){return this.points}getPointsFromViewer(e,n){let i=de.singleBox(e.width,e.height,e.x,e.y);return this.getPointsAt(i,n,e.scale)}addLayoutSubscriber(e){return this.subscriptions.push(e),()=>{this.subscriptions.splice(this.subscriptions.indexOf(e),1)}}getScheduledUpdates(e,n){let i=Oc(this.points,e,this.filteredPointsBuffer),a=this.objects.length;this._updatedList=[];for(let r=0;r<a;r++)if(i[r*5]!==0){if(!this.objects[r])continue;this._updatedList.push(...this.objects[r].getScheduledUpdates(e,n))}return this._updatedList}isZoneOutsideVisibilityFading(e){return!!(this.zoneVisibilityFade&&this.zoneVisibilityFade.zoneId===e.id&&performance.now()-this.zoneVisibilityFade.startedAt<this.zoneVisibilityFadeDurationMs)}getZoneOutsideVisibility(e){let n=this.zoneOutsideOpacity;if(!this.zoneVisibilityFade||this.zoneVisibilityFade.zoneId!==e.id)return n;let i=performance.now()-this.zoneVisibilityFade.startedAt;return i>=this.zoneVisibilityFadeDurationMs?n:1-Math.max(0,Math.min(1,i/this.zoneVisibilityFadeDurationMs))*(1-n)}getObjectsAt(e,n=!1,i=!1){let a=this.getActiveZone(),r=a&&i?this.getZoneOutsideVisibility(a)>0:!1,l=Oc(this.points,e,this.filteredPointsBuffer),u=this.renderOrder.length,f=[];for(let h=0;h<u;h++){let d=this.renderOrder[h];if(l[d*5]!==0){let m=this.objects[d],y=!a||a.objects.indexOf(m)!==-1;if(!m||!y&&!r)continue;if(m.type!=="world-object"){f.push([m,[m]]);continue}n?f.push([m,m.getObjectsAt(e,n)]):f.push([m,this.emptyPaintables])}}return f}getPointsAt(e,n,i=1){let a=this.getActiveZone(),r=a?this.getZoneOutsideVisibility(a):0,l=this.getObjectsAt(e,!1,!0),u=Dr(mo(i),ci(-e[1],-e[2]),this.translationBuffer),f=n?Dr(n,u,this.aggregateBuffer):u,h=l.length,d=[];for(let m=0;m<h;m++)if(l[m]){let y=l[m][0],g=y.getAllPointsAt(e,f,i),b=!a||a.objects.indexOf(y)!==-1?1:r;for(let w=0;w<g.length;w++)g[w][0].__zoneVisibilityAlpha=b;d.push(...g)}return a&&this.isZoneOutsideVisibilityFading(a)&&this.triggerRepaint(),d}flushSubscriptions(){if(this.triggerQueue.length){this._alreadyFlushed=[];let e=this.triggerQueue.length;for(let n=0;n<e;n++){if(this._alreadyFlushed.indexOf(this.triggerQueue[n][0])!==-1)continue;this.triggerQueue[n][1]===void 0&&this._alreadyFlushed.push(this.triggerQueue[n][0]);let i=this.subscriptions.length;for(let a=0;a<i;a++)this.subscriptions[a].apply(null,this.triggerQueue[n])}this.triggerQueue=[]}}trigger(e,n){this.emitDebug({type:"trigger",at:performance.now(),event:e,data:n}),this.triggerQueue.push([e,n])}triggerEventActivation(){this.trigger("event-activation")}triggerRepaint(){this.trigger("repaint")}gotoRegion(e){this.trigger("goto-region",e)}goHome(e=!1,n){this.trigger("go-home",{immediate:e,paddingPx:n})}zoomTo(e,n,i){this.trigger("zoom-to",{point:n,factor:e,stream:i})}zoomIn(e){this.trigger("zoom-to",{point:e,factor:.5})}zoomOut(e){this.trigger("zoom-to",{point:e,factor:2})}constraintBounds(e){this.trigger("constrain-bounds",{immediate:e})}hasPendingAnimation(){return!!(this.zoneVisibilityFade&&performance.now()-this.zoneVisibilityFade.startedAt<this.zoneVisibilityFadeDurationMs)}addDebugSubscriber(e){return this.debugSubscribers.add(e),()=>{this.removeDebugSubscriber(e)}}removeDebugSubscriber(e){this.debugSubscribers.delete(e)}emitDebug(e){if(this.debugSubscribers.size!==0)for(let n of this.debugSubscribers)n(e)}};var K8={background:"rgba(15, 23, 42, 0.7)",objectFill:"rgba(56, 189, 248, 0.22)",objectStroke:"rgba(56, 189, 248, 0.62)",viewportFill:"rgba(251, 191, 36, 0.22)",viewportStroke:"rgba(250, 204, 21, 1)",viewportLineWidth:2};function YT(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.floor(t)}function Z8(t,e){if(!t||e<=1)return null;let n=YT(t.total),i=YT(t.before),a=YT(t.after),r=n===void 0?i!==void 0||a!==void 0?Math.max(1,Math.max(0,i||0)+Math.max(0,a||0)+1):9:Math.max(1,n),l=i===void 0?void 0:Math.max(0,i),u=a===void 0?void 0:Math.max(0,a);l===void 0&&u===void 0?(l=Math.floor((r-1)/2),u=r-l-1):l===void 0?l=Math.max(0,r-(u||0)-1):u===void 0&&(u=Math.max(0,r-l-1));let f=l+u+1;return f!==r&&(r=f),r=Math.max(1,Math.min(e,r)),l=Math.min(l,r-1),u=r-l-1,{total:r,before:l,after:u}}function W8(t){let e=[];for(let n=0;n<t.zones.length;n++){let i=t.zones[n];i.recalculateBounds(),i.points[0]!==0&&e.push({zone:i,minX:i.points[1],minY:i.points[2],maxX:i.points[3],maxY:i.points[4]})}return e.sort((n,i)=>n.minY===i.minY?n.minX===i.minX?(n.zone?.id||"").localeCompare(i.zone?.id||""):n.minX-i.minX:n.minY-i.minY),e}function G3(t,e){let n=Z8(e.zoneWindow,t.zones.length);if(!n)return null;let i=W8(t);if(i.length<=n.total)return i;let a=$8(i,e.target)-n.before,r=a+n.total-1;return a<0&&(a=0,r=n.total-1),r>=i.length&&(r=i.length-1,a=Math.max(0,r-n.total+1)),i.slice(a,r+1)}function J8(t){if(!t)return null;if(Array.isArray(t)||ArrayBuffer.isView(t)){let e=t;return e[0]===0?null:{x:(e[1]+e[3])/2,y:(e[2]+e[4])/2}}return{x:t.x+t.width/2,y:t.y+t.height/2}}function $8(t,e){if(t.length===0)return 0;let n=J8(e);if(!n)return 0;for(let r=0;r<t.length;r++){let l=t[r];if(n.x>=l.minX&&n.x<=l.maxX&&n.y>=l.minY&&n.y<=l.maxY)return r}let i=0,a=1/0;for(let r=0;r<t.length;r++){let l=t[r],u=(l.minY+l.maxY)/2,f=Math.abs(n.y-u);f<a&&(a=f,i=r)}return i}function tj(t){if(t.length===0)return null;let e=t[0].minX,n=t[0].minY,i=t[0].maxX,a=t[0].maxY;for(let r=1;r<t.length;r++){let l=t[r];e=Math.min(e,l.minX),n=Math.min(n,l.minY),i=Math.max(i,l.maxX),a=Math.max(a,l.maxY)}return{x:e,y:n,width:Math.max(1,i-e),height:Math.max(1,a-n)}}function eR(t,e,n,i,a=0,r=0){let l=Math.max(1,t),u=Math.max(1,e),f=Math.min(n/l,i/u),h=l*f,d=u*f;return{scale:f,offsetX:(n-h)/2,offsetY:(i-d)/2,worldX:a,worldY:r,worldWidth:l,worldHeight:u}}function Y3(t,e={}){let n=t.getActiveZone();if(n&&(n.recalculateBounds(),n.points[0]!==0))return{x:n.points[1],y:n.points[2],width:Math.max(1,n.points[3]-n.points[1]),height:Math.max(1,n.points[4]-n.points[2])};let i=G3(t,e);if(i&&i.length>0){let a=tj(i);if(a)return a}return{x:0,y:0,width:Math.max(1,t.width),height:Math.max(1,t.height)}}function ej(t,e={}){let n=t.getActiveZone();if(n)return n.recalculateBounds(),n.points[0]===0?new Set:new Set([n.id]);let i=G3(t,e);if(!i)return null;let a=new Set;for(let r of i)a.add(r.zone.id);return a}function nj(t,e,n){if(!t.scale||!Number.isFinite(t.scale))return{x:t.worldX,y:t.worldY};let i=t.worldX+(e-t.offsetX)/t.scale,a=t.worldY+(n-t.offsetY)/t.scale;return{x:Math.max(t.worldX,Math.min(t.worldX+t.worldWidth,i)),y:Math.max(t.worldY,Math.min(t.worldY+t.worldHeight,a))}}var ij=class extends Q8{constructor(t,e={}){super(t),C(this,"style",void 0),C(this,"maxRects",void 0),C(this,"minVisibleRectSize",void 0),C(this,"drawFallbackBoxes",void 0),C(this,"zoneWindow",void 0),C(this,"sharedCanvasRenderer",void 0),C(this,"onRequestRender",void 0),C(this,"onDebugEvent",void 0),C(this,"baseCanvas",void 0),C(this,"baseContext",void 0),C(this,"worldTarget",de.singleBox(1,1,0,0)),C(this,"previewImageCache",new Map),C(this,"worldLayerDirty",!0),C(this,"lastWorldWidth",0),C(this,"lastWorldHeight",0),C(this,"lastTargetX",NaN),C(this,"lastTargetY",NaN),C(this,"lastTargetX2",NaN),C(this,"lastTargetY2",NaN),C(this,"lastRegionX",NaN),C(this,"lastRegionY",NaN),C(this,"lastRegionWidth",NaN),C(this,"lastRegionHeight",NaN),C(this,"worldLayerInvalidationVersion",0),C(this,"sharedCanvasResourcesPending",!1),this.style={...K8,...e.style||{}},this.maxRects=Math.max(100,e.maxRects||5e3),this.minVisibleRectSize=Math.max(1,e.minVisibleRectSize||1),this.drawFallbackBoxes=e.drawFallbackBoxes!==!1,this.zoneWindow=e.zoneWindow,this.sharedCanvasRenderer=e.sharedCanvasRenderer,this.onRequestRender=e.onRequestRender,this.onDebugEvent=e.onDebugEvent,this.context.globalAlpha=1,this.context.imageSmoothingEnabled=!1,this.baseCanvas=document.createElement("canvas"),this.baseContext=this.baseCanvas.getContext("2d"),this.baseContext.imageSmoothingEnabled=!0,this.syncBaseLayerCanvas()}emitDebugEvent(t){this.onDebugEvent&&this.onDebugEvent(t)}requestRender(t){this.onRequestRender&&(this.emitDebugEvent({type:"render-request-forwarded",reason:t}),this.onRequestRender())}invalidateWorldLayer(t="manual"){this.worldLayerInvalidationVersion++,this.worldLayerDirty=!0,this.renderNextFrame=!0,this.emitDebugEvent({type:"world-layer-invalidated",reason:t}),this.requestRender(t)}resize(){super.resize(),this.syncBaseLayerCanvas(),this.invalidateWorldLayer("resize")}beforeFrame(t){(t.width!==this.lastWorldWidth||t.height!==this.lastWorldHeight)&&(this.lastWorldWidth=t.width,this.lastWorldHeight=t.height,this.invalidateWorldLayer("world-size-changed"))}paint(){this.renderNextFrame=!0}pendingUpdate(){return this.renderNextFrame||this.worldLayerDirty}afterFrame(t,e,n){let i=this.worldLayerInvalidationVersion;if(this.canvas.width<=0||this.canvas.height<=0){this.emitDebugEvent({type:"frame-skipped-zero-size-canvas",canvasWidth:this.canvas.width,canvasHeight:this.canvas.height,baseCanvasWidth:this.baseCanvas.width,baseCanvasHeight:this.baseCanvas.height}),this.renderNextFrame=!0;return}let a=Y3(t,{target:n,zoneWindow:this.zoneWindow});this.hasRegionChanged(a)&&(this.worldLayerDirty=!0);let r=this.hasViewportChanged(n);if(this.renderNextFrame||this.worldLayerDirty||r){if((this.baseCanvas.width!==this.canvas.width||this.baseCanvas.height!==this.canvas.height)&&(this.syncBaseLayerCanvas(),this.worldLayerDirty=!0),this.baseCanvas.width<=0||this.baseCanvas.height<=0){this.emitDebugEvent({type:"frame-skipped-zero-size-canvas",canvasWidth:this.canvas.width,canvasHeight:this.canvas.height,baseCanvasWidth:this.baseCanvas.width,baseCanvasHeight:this.baseCanvas.height}),this.renderNextFrame=!0;return}if(this.worldLayerDirty){let l=this.worldLayerInvalidationVersion;this.sharedCanvasResourcesPending=!1,this.emitDebugEvent({type:"world-layer-render-start",region:a});try{this.renderWorldLayer(t,a)}finally{this.emitDebugEvent({type:"world-layer-render-end",region:a})}this.worldLayerDirty=this.sharedCanvasResourcesPending||l!==this.worldLayerInvalidationVersion}this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.context.drawImage(this.baseCanvas,0,0),this.renderViewportBox(n,a),this.lastTargetX=n[1],this.lastTargetY=n[2],this.lastTargetX2=n[3],this.lastTargetY2=n[4],this.lastRegionX=a.x,this.lastRegionY=a.y,this.lastRegionWidth=a.width,this.lastRegionHeight=a.height,this.renderNextFrame=this.sharedCanvasResourcesPending||i!==this.worldLayerInvalidationVersion}}hasViewportChanged(t){return this.lastTargetX!==t[1]||this.lastTargetY!==t[2]||this.lastTargetX2!==t[3]||this.lastTargetY2!==t[4]}hasRegionChanged(t){return this.lastRegionX!==t.x||this.lastRegionY!==t.y||this.lastRegionWidth!==t.width||this.lastRegionHeight!==t.height}syncBaseLayerCanvas(){this.baseCanvas.width=this.canvas.width,this.baseCanvas.height=this.canvas.height}shouldClipImagePaintToBounds(t){return t instanceof gi||t instanceof Ri?!!t.__parent?.renderOptions?.clipToBounds:!1}getBoundsFromPoints(t){let e=1/0,n=1/0,i=-1/0,a=-1/0;for(let r=0;r<t.length;r+=5)t[r]&&(e=Math.min(e,t[r+1]),n=Math.min(n,t[r+2]),i=Math.max(i,t[r+3]),a=Math.max(a,t[r+4]));if(!(!Number.isFinite(e)||!Number.isFinite(n)||!Number.isFinite(i)||!Number.isFinite(a))&&!(i<=e||a<=n))return{x:e,y:n,width:i-e,height:a-n}}getLayerClipBounds(t,e,n){if(!this.shouldClipImagePaintToBounds(t))return;let i=t.__parent,a=i?.crop||i?.points;if(!a)return;let r=e?Xi(a,e):a,l=this.getBoundsFromPoints(r);if(l)return{x:l.x+n.offsetX,y:l.y+n.offsetY,width:l.width,height:l.height}}renderWorldLayer(t,e){let n=this.baseContext;n.clearRect(0,0,this.baseCanvas.width,this.baseCanvas.height),n.fillStyle=this.style.background,n.fillRect(0,0,this.baseCanvas.width,this.baseCanvas.height);let i=t.getActiveZone(),a=eR(e.width,e.height,this.baseCanvas.width,this.baseCanvas.height,e.x,e.y);this.worldTarget[1]=e.x,this.worldTarget[2]=e.y,this.worldTarget[3]=e.x+e.width,this.worldTarget[4]=e.y+e.height;let r=t.getPointsAt(this.worldTarget,this.aggregate,a.scale),l=0;for(let u=0;u<r.length&&!(l>=this.maxRects);u++){let f=r[u][0],h=r[u][1],d=r[u][2],m=d?Xi(h,d):h,y=m.length/5,g=this.getLayerClipBounds(f,d,a);g&&(n.save(),n.beginPath(),n.rect(g.x,g.y,g.width,g.height),n.clip());try{for(let b=0;b<y&&!(l>=this.maxRects);b++){let w=b*5;if(m[w]===0)continue;if(i){let A=f?.__owner?.value;if(!A||i.objects.indexOf(A)===-1)continue}let E=m[w+1]+a.offsetX,T=m[w+2]+a.offsetY,S=Math.max(this.minVisibleRectSize,m[w+3]-m[w+1]),R=Math.max(this.minVisibleRectSize,m[w+4]-m[w+2]);f instanceof cR?this.renderGeometry(n,f,E,T,a.scale):f instanceof Td?this.renderBox(n,f,E,T,S,R,a.scale):this.renderImagePaint(n,f,b,E,T,S,R)||this.drawFallbackBoxes&&this.renderFallbackBox(n,E,T,S,R),l++}}finally{g&&n.restore()}}}renderFallbackBox(t,e,n,i,a){let r=Math.round(e),l=Math.round(n),u=Math.max(1,Math.round(i)),f=Math.max(1,Math.round(a));t.fillStyle=this.style.objectFill,t.strokeStyle=this.style.objectStroke,t.lineWidth=1,t.fillRect(r,l,u,f),u>2&&f>2&&t.strokeRect(r+.5,l+.5,u-1,f-1)}renderImagePaint(t,e,n,i,a,r,l){if(r<=0||l<=0)return!1;let u;if(e instanceof Lv)u=e.getTexture()?.source;else if(e instanceof gi||e instanceof Ri){let d=this.renderSharedCanvasImage(t,e,n,i,a,r,l);if(d!==null)return d;if(typeof e.getImageUrl!="function")return!1;let m=e.getImageUrl(n);u=this.getLoadedPreviewImage(m)}if(!u)return!1;let f=Math.max(1,Math.round(r)),h=Math.max(1,Math.round(l));return t.drawImage(u,Math.round(i),Math.round(a),f,h),!0}ensureSharedCanvasImageBuffer(t){return t.__host?.canvas||this.sharedCanvasRenderer?.createImageHost?.(t),t.__host||(t.__host={}),t.__host.canvas||(t.__host.canvas={canvases:[],tiles:{}}),t.__host.canvas.canvases||(t.__host.canvas.canvases=[]),t.__host.canvas.tiles||(t.__host.canvas.tiles={}),t.__host.canvas}drawSharedCanvasTile(t,e,n,i,a,r,l,u){let f=Math.max(1,Math.round(l)),h=Math.max(1,Math.round(u));if(e.crop&&e.cropData){let g=n*5;if(!e.crop[g])return!1;let b=e.crop[g+1]/e.display.scale-e.display.points[g+1]+e.cropData.x/e.display.scale,w=e.crop[g+2]/e.display.scale-e.display.points[g+2]+e.cropData.y/e.display.scale,E=1+(e.crop[g+3]-e.crop[g+1])/e.display.scale,T=1+(e.crop[g+4]-e.crop[g+2])/e.display.scale;return t.drawImage(i,b,w,E,T,Math.round(a),Math.round(r),f,h),!0}let d=n*5,m=e.display.points[d+3]-e.display.points[d+1],y=e.display.points[d+4]-e.display.points[d+2];return t.drawImage(i,0,0,m,y,Math.round(a),Math.round(r),f,h),!0}renderSharedCanvasImage(t,e,n,i,a,r,l){let u=this.sharedCanvasRenderer;if(!u?.hostCache)return null;let f=this.ensureSharedCanvasImageBuffer(e),h=f.canvases?.[n],d=!!h&&!!u.invalidated?.includes(h),m=h&&!d?u.hostCache.get(h):void 0;if(m)return this.drawSharedCanvasTile(t,e,n,m,i,a,r,l);let y=f.tiles?.[n],g=Math.hypot(i+r/2-this.baseCanvas.width/2,a+l/2-this.baseCanvas.height/2);return(u.schedulePaintToCanvas?.(f,e,n,g,!1)||y?.state==="queued"||y?.state==="loading"||y?.state==="decoded")&&(this.sharedCanvasResourcesPending=!0),!1}getLoadedPreviewImage(t){let e=this.previewImageCache.get(t);if(e){if(e.status==="loading"&&e.image.complete){if(e.image.naturalWidth>0&&e.image.naturalHeight>0)return e.status="loaded",this.emitDebugEvent({type:"preview-image-loaded",imageUrl:t,cached:!0}),this.invalidateWorldLayer("preview-image-loaded"),e.image;e.status="error",this.emitDebugEvent({type:"preview-image-error",imageUrl:t});return}return e.status==="loaded"?e.image:void 0}let n=new Image,i={image:n,status:"loading"};return this.previewImageCache.set(t,i),this.emitDebugEvent({type:"preview-image-requested",imageUrl:t}),n.onload=()=>{i.status==="loading"&&(i.status="loaded",this.emitDebugEvent({type:"preview-image-loaded",imageUrl:t,cached:!1}),this.invalidateWorldLayer("preview-image-loaded"))},n.onerror=()=>{i.status==="loading"&&(i.status="error",this.emitDebugEvent({type:"preview-image-error",imageUrl:t}))},n.src=t,n.complete&&(n.naturalWidth>0&&n.naturalHeight>0?(i.status="loaded",this.emitDebugEvent({type:"preview-image-loaded",imageUrl:t,cached:!0}),this.invalidateWorldLayer("preview-image-loaded")):(i.status="error",this.emitDebugEvent({type:"preview-image-error",imageUrl:t}))),i.status==="loaded"?n:void 0}renderBox(t,e,n,i,a,r,l){let u=e.props?.style;if(!u){this.renderFallbackBox(t,n,i,a,r);return}let f=u.backgroundColor||this.style.objectFill,h=u.borderColor||this.style.objectStroke,d=u.borderWidth?parseInt(u.borderWidth,10):0,m=Math.max(0,d*(e.props?.relativeStyle?1:l));t.globalAlpha=typeof u.opacity=="number"?u.opacity:1,t.fillStyle=f,t.fillRect(Math.round(n),Math.round(i),Math.max(1,Math.round(a)),Math.max(1,Math.round(r))),m>0&&(t.strokeStyle=h,t.lineWidth=Math.max(1,m),t.strokeRect(Math.round(n)+t.lineWidth/2,Math.round(i)+t.lineWidth/2,Math.max(1,Math.round(a))-t.lineWidth,Math.max(1,Math.round(r))-t.lineWidth)),t.globalAlpha=1}renderGeometry(t,e,n,i,a){let r=e.shape;if(r.type!=="polygon"||r.points.length===0)return;let l=e.props?.style||{},u=l.backgroundColor||this.style.objectFill,f=l.borderColor||this.style.objectStroke,h=l.borderWidth?parseInt(l.borderWidth,10):0,d=Math.max(0,h*(e.props?.relativeStyle?1:a));t.globalAlpha=typeof l.opacity=="number"?l.opacity:1,t.beginPath();for(let m=0;m<r.points.length;m++){let y=n+r.points[m][0]*a,g=i+r.points[m][1]*a;m===0?t.moveTo(y,g):t.lineTo(y,g)}r.open||(t.closePath(),t.fillStyle=u,t.fill()),(d>0||r.open)&&(t.strokeStyle=f,t.lineWidth=Math.max(1,d||1),t.stroke()),t.globalAlpha=1}renderViewportBox(t,e){let n=eR(e.width,e.height,this.canvas.width,this.canvas.height,e.x,e.y),i=(t[1]-n.worldX)*n.scale+n.offsetX,a=(t[2]-n.worldY)*n.scale+n.offsetY,r=(t[3]-t[1])*n.scale,l=(t[4]-t[2])*n.scale,u=Math.round(i),f=Math.round(a),h=Math.max(1,Math.round(r)),d=Math.max(1,Math.round(l));this.context.fillStyle=this.style.viewportFill,this.context.fillRect(u,f,h,d),this.context.strokeStyle=this.style.viewportStroke,this.context.lineWidth=Math.max(1,this.style.viewportLineWidth),this.context.strokeRect(u+.5,f+.5,Math.max(1,h-1),Math.max(1,d-1))}},Yh=class extends Yr{constructor(){super(),C(this,"type","spacial-content"),C(this,"id",void 0),C(this,"points",void 0),C(this,"color","#000"),C(this,"backgroundColor",void 0),C(this,"hovering",void 0),C(this,"pressing",void 0),C(this,"text",""),C(this,"display",{x:0,y:0,scale:1,width:100,height:100,points:It(5)}),C(this,"className",void 0),C(this,"html",void 0),C(this,"interactive",!1),C(this,"props",{font:"18px Arial, sans-serif",lineHeight:1,textAlign:"left",verticalAlign:"top",paddingX:0,paddingY:0,fitParent:!1,lineBreak:"auto",strokeText:!1,sizeToFill:!1,maxFontSizeToFill:void 0,allowNewLine:!0,justifyLines:!1,renderHDPI:!1,textDecoration:"none",interactive:!1,relativeSize:!1}),this.id="",this.points=It(5)}getAllPointsAt(t,e){return[[this,this.points,e]]}applyProps({id:t,target:e,text:n,color:i,backgroundColor:a,fontSize:r=18,interactive:l,fontFamily:u="Arial, sans-serif",...f}){f.font=`${r}px ${u}`,this.interactive=l||!1,n!==void 0&&(this.text=n||""),i&&(this.color=i),a&&(this.backgroundColor=a),t&&(this.id=t),e&&(this.points=de.singleBox(e.width,e.height,e.x,e.y),this.display.points=this.points,this.display.width=e.width,this.display.height=e.height),this.props={...this.props,...f},this.__revision++}};function nR(t,e){let n=e?t:JSON.stringify(t),i=5381,a=n.length;for(;a;)i=i*33^n.charCodeAt(--a);let r=(i>>>0).toString(16);return r.length%2?"0"+r:r}var X3=class{constructor(t){C(this,"$element",void 0),C(this,"stylesheetClasses",void 0),C(this,"activeStylesheetClasses",void 0),C(this,"sheetsDidUpdate",void 0),C(this,"sheetPrefix",void 0),C(this,"stylesheetEntries",void 0),this.sheetPrefix=t?.sheetPrefix||"a-",this.$element=document.createElement("style"),this.stylesheetClasses=[],this.activeStylesheetClasses=[],this.sheetsDidUpdate=!1,this.stylesheetEntries={}}getElement(){return this.$element}addStylesheet(t){let e=t.replace(/\s\s+/g," ").replace(/: /g,":").replace(/; /g,";").trim(),n=this.sheetPrefix+nR(e,!0);return this.stylesheetClasses.indexOf(n)===-1&&(this.stylesheetClasses.push(n),this.activeStylesheetClasses.push(n),this.stylesheetEntries[n]=e,this.sheetsDidUpdate=!0),n}removeStylesheet(t){let e=this.sheetPrefix+nR(t,!0);this.stylesheetClasses.indexOf(e)&&(this.stylesheetClasses=this.stylesheetClasses.filter(n=>n!==e)),this.sheetsDidUpdate=!0}clearClasses(){this.activeStylesheetClasses=[]}didUpdateActive(){if(this.activeStylesheetClasses.length){for(let t of this.activeStylesheetClasses)if(this.stylesheetClasses.indexOf(t)===-1)return!0;for(let t of this.stylesheetClasses)if(this.activeStylesheetClasses.indexOf(t)===-1)return!0}return!1}updateSheet(){(this.sheetsDidUpdate||this.didUpdateActive())&&(this.$element.innerText=this.activeStylesheetClasses.map(t=>`.${t}{${this.stylesheetEntries[t]}}`).join(""),this.sheetsDidUpdate=!1,this.stylesheetClasses=[...this.activeStylesheetClasses])}},Q3=class{constructor(t,e){C(this,"htmlContainer",void 0),C(this,"visible",[]),C(this,"previousVisible",[]),C(this,"htmlIds",[]),C(this,"firstMeaningfulPaint",!1),C(this,"rendererPosition",void 0),C(this,"stylesheet",void 0),C(this,"options",void 0),C(this,"paintTx",1),C(this,"zIndex",0),C(this,"classes",void 0),this.htmlContainer=t,this.htmlContainer.innerHTML="",this.rendererPosition=this.htmlContainer.getBoundingClientRect(),this.options={triggerResize:()=>{},box:!1,text:!1,sheetPrefix:"",inlineStyles:!1,background:"",...e||{}},this.stylesheet=new X3({sheetPrefix:this.options.sheetPrefix}),this.options.inlineStyles||this.htmlContainer.appendChild(this.stylesheet.getElement()),this.options.background&&this.htmlContainer.classList.add(this.stylesheet.addStylesheet(`
24
+ `);let T=E.state[u];if(T==null)return;JSON.stringify(a.getState())!==JSON.stringify(T)&&g(T);return}a.dispatchFromDevtools&&typeof a.dispatch=="function"&&a.dispatch(E)});case"DISPATCH":switch(w.payload.type){case"RESET":return g(b),u===void 0?d?.init(a.getState()):d?.init(wg(f.name));case"COMMIT":if(u===void 0){d?.init(a.getState());return}return d?.init(wg(f.name));case"ROLLBACK":return P1(w.state,E=>{if(u===void 0){g(E),d?.init(a.getState());return}g(E[u]),d?.init(wg(f.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return P1(w.state,E=>{if(u===void 0){g(E);return}JSON.stringify(a.getState())!==JSON.stringify(E[u])&&g(E[u])});case"IMPORT_STATE":{let{nextLiftedState:E}=w.payload,T=E.computedStates.slice(-1)[0]?.state;if(!T)return;g(u===void 0?T:T[u]),d?.send(null,E);return}case"PAUSE_RECORDING":return y=!y}return}}),b},P1=(t,e)=>{let n;try{n=JSON.parse(t)}catch(i){console.error("[zustand devtools middleware] Could not parse the received json",i)}n!==void 0&&e(n)},nF=t=>(e,n,i)=>{let a=i.subscribe;return i.subscribe=(r,l,u)=>{let f=r;if(l){let h=u?.equalityFn||Object.is,d=r(i.getState());f=m=>{let y=r(m);if(!h(d,y)){let g=d;l(d=y,g)}},u?.fireImmediately&&l(d,d)}return a(f)},t(e,n,i)},iF=(t={},e)=>{switch(e.type){case pg:return{...t,[e.payload.id]:e.payload.type};case mg:return{...t,...e.payload.mapping};default:return t}};function Nf(t,e,n,i){return!(!t[n]||!t[n][e]||!t[n][e][i]||!Array.isArray(t[n][e][i]))}function aF(t,e){let n={},i=[];for(let[a,r]of Object.entries(t||{})){i.push(a);let l=(e||{})[a];if(!l||l.length===0){n[a]=r;continue}n[a]=l}for(let[a,r]of Object.entries(e||{}))i.indexOf(a)===-1&&(n[a]=r);return n}function Dt(t){return t.payload||{}}function rF(t,e,n){if(!t[e]||!Array.isArray(t[e]))return null;let i=n.index===void 0?t[e].findIndex(a=>a?mc(a)?.id===n.id:!1):n.index;return i===-1?null:{entity:t[e][i],index:i}}function FM(t,e){if(!(!e?.id||!e?.type))return t[e.type]?.[e.id]}function Tg(t,e){return t===void 0?e:t}var qM=(t=D1(),e)=>{let n=(i,a)=>({...t,[Dt(e).type]:{...t[Dt(e).type],[Dt(e).id]:{...i,...a}}});switch(e.type){case ag:{if(!t[Dt(e).type]||!t[Dt(e).type][Dt(e).id])return t;let i=t[Dt(e).type][Dt(e).id];return typeof i=="string"?t:n(i,{[Dt(e).key]:Dt(e).value})}case rg:{if(!Nf(t,Dt(e).id,Dt(e).type,Dt(e).key))return t;let i=t[Dt(e).type][Dt(e).id];if(typeof i=="string")return t;let a=Array.from(i[Dt(e).key]),[r]=a.splice(Dt(e).startIndex,1);return a.splice(Dt(e).endIndex,0,r),n(i,{[Dt(e).key]:a})}case Mf:{let i=Dt(e).subjects,a=Dt(e).from,r=Dt(e).to||a,l=FM(t,a),u=r?.key||a.key;if(!Nf(t,a.id,a.type,a.key)||!Nf(t,r.id,r.type,r.key))return t;let f=[],h=[];if(i.type==="slice"){let E=i.startIndex,T=i.length;f=Array.from(l[a.key]),h=f.splice(E,T)}else{let E=Array.from(l[a.key]);for(let T of i.items){let S=rF(l,a.key,T);S&&(h.push(S.entity),E[S.index]=null),f=E.filter(R=>R!==null)}}let d={...l,[a.key]:f},m={...t,[a.type]:{...t[a.type],[a.id]:d}},y=FM(m,r);if(!y)return t;let g=r?.index===void 0?y[u].length:r.index,b=Array.from(y[r.key]);b.splice(g,0,...h);let w={...y,[u]:b};return{...m,[r.type]:{...m[r.type],[r.id]:w}}}case og:return qM(t,{type:Mf,payload:{subjects:{type:"list",items:[Dt(e).subject]},from:Dt(e).from,to:Dt(e).to}});case lg:{let{id:i,index:a,key:r,newIdentifier:l,reference:u,type:f}=Dt(e),h=t[f][i],d=mc(u);if(!h||!h[r]||!d||a<0)return t;let m=h[r],y=m[a],g=t[d.type]?.[d.id];if(!g||!y)return t;let b=EM(y,l),w=Array.from(m);w.splice(Tg(a,w.length+1),1,b);let E=n(h,{[r]:w}),T={...g,id:l};T["iiif-parser:hasPart"]&&(T["iiif-parser:hasPart"]=T["iiif-parser:hasPart"].filter(R=>R["iiif-parser:partOf"]===i).map(R=>({...R,id:l})));let S={...E[d.type],[l]:T};return E[d.type]=S,E}case ig:{let i=Object.keys(Dt(e).entities),a={...t};for(let r of i){let l=Dt(e).entities[r],u={...t[r]||{}},f=!1,h=Object.keys(l||{})||[];if(l&&h){for(let d of h)f=!0,u[d]=t[r][d]?aF(t[r][d],l[d]):l[d];f&&(a[r]=u)}}return a}case sg:{if(!Nf(t,Dt(e).id,Dt(e).type,Dt(e).key))return t;let i=t[Dt(e).type][Dt(e).id],a=Array.from(i[Dt(e).key]);return a.splice(Tg(Dt(e).index,a.length+1),0,Dt(e).reference),n(i,{[Dt(e).key]:a})}case Of:case ug:{if(!Nf(t,Dt(e).id,Dt(e).type,Dt(e).key))return t;let i=t[Dt(e).type][Dt(e).id],a=Array.from(i[Dt(e).key]),r=Tg(Dt(e).index,a.findIndex(l=>l&&l.id===Dt(e).reference.id));return r===-1||a[r]?.id!==Dt(e).reference.id?t:(e.type===Of?a.splice(r,1,Dt(e).reference):a.splice(r,1),n(i,{[Dt(e).key]:a}))}case cg:{let i=t[Dt(e).type][Dt(e).id];if(!i)return t;let a=Array.from(i.metadata||[]),r=Dt(e);return a.splice(Tg(e.payload.beforeIndex,a.length+1),0,{label:r.label,value:r.label}),n(i,{metadata:a})}case fg:{let i=t[Dt(e).type][Dt(e).id];if(typeof i=="string"||!i)return t;let a=Array.from(i.metadata||[]),[r]=a.splice(Dt(e).startIndex,1);return a.splice(Dt(e).endIndex,0,r),n(i,{metadata:a})}case _f:case dg:{let i=t[Dt(e).type][Dt(e).id],a=Array.from(i.metadata||[]),r=Dt(e).atIndex;return r===void 0||r===-1||!a[r]?t:(e.type===_f?a.splice(r,1,{label:Dt(e).label,value:Dt(e).value}):a.splice(r,1),n(i,{metadata:a}))}default:return t}},oF=(t={},e)=>{switch(e.type){case gg:case Sg:return{...t,[e.payload.id]:{requestUri:e.payload.id,loadingState:zf,uriMismatch:!1,resourceUri:e.payload.id}};case vg:return{...t,[e.payload.requestId]:{...t[e.payload.requestId]||{},uriMismatch:!0,resourceUri:e.payload.actualId},[e.payload.actualId]:{requestUri:e.payload.requestId,loadingState:t[e.payload.requestId].loadingState,uriMismatch:!0,resourceUri:e.payload.actualId}};case yg:return{...t,[e.payload.id]:{...t[e.payload.id]||{},loadingState:yc,error:e.payload.message}};case bg:return{...t,[e.payload.id]:{...t[e.payload.id]||{},loadingState:vc,error:void 0}}}return t},sF=(t={},e)=>{let{id:n,updateValue:i,value:a,meta:r,key:l}=e&&e.payload||{};switch(e.type){case M1:return{...t,[n]:{...t[n]||{},[r]:{...t[n]&&t[n][r]||{},[l]:a}}};case O1:return{...t,[n]:{...t[n]||{},[r]:{...t[n]&&t[n][r]||{},[l]:t[n]&&t[n][r]?i(t[n][r][l]):i(void 0)}}};case _1:return t[n]&&t[n][r]&&t[n][r][l]?{...t,[n]:{...t[n]||{},[r]:{...t[n]&&t[n][r]||{},[l]:void 0}}}:t;default:return t}};function VM(t={}){let e=Object.keys(t);return function(n={},i){let a=!1,r={};for(let l=0;l<e.length;l++){let u=e[l];r[u]=t[u](n[u],i),a=a||r[u]!==n[u]}return a?r:n}}function lF(t){return(e,n)=>n&&n.type===bc?n.payload.actions.reduce(t,e):n&&n.type===xg?{...e,iiif:{...e.iiif,...n.payload.state}}:t(e,n)}var uF=VM({mapping:iF,entities:qM,requests:oF,meta:sF});function cF(){return{iiif:{entities:D1(),meta:{},mapping:{},requests:{}}}}function UM(t={}){let{enableDevtools:e=!1,iiifStoreName:n="iiif",defaultState:i=cF(),customReducers:a={}}=t,r=lF(VM({[n]:uF,...a}));return Qm(nF((typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION__?eF:(l,u)=>l)($H(r,i),{enabled:e})))}function Pi(t,e,n,i=!0){e[wc]=e[wc]||[],e[wc].push(t);let a=new Map;Object.defineProperty(e,t,{enumerable:i,get(){if(e[Hl][t]===void 0)return;let r=e[Hl][t];if(!r)return r;let l=n.get(e[Hl][t],{parent:this.id?{id:this.id,type:this.type}:void 0});return a.has(l)||(a.clear(),a.set(l,Fl(l,n))),a.get(l)},set(r){e[Hl][t]!==r&&(this[Bl]?n.modifyEntityField({id:this.id,type:this.type},t,GM(r)):this[Hl][t]=r)}})}var Hl=Symbol.for("_refs_"),Bl=Symbol.for("_reactive_"),wc=Symbol.for("_defined_"),jM=Symbol.for("_parent_");function dF(t,e=!1,n){let i={id:"",type:"unknown",[wc]:[],[Hl]:{},[jM]:n||null,[Bl]:null,is(a){return typeof a=="string"?this.id===a:a.id?a.id===this.id:!1},reactive(){if(!this[Bl])return this[Bl]=this.subscribe(()=>this.refresh(),!0),()=>{this.unreactive()}},refresh(){if(this.id){let a=this.unwrap();for(let r of Object.keys(a||{}))this[wc].includes(r)?this[Hl][r]=a[r]:this[r]=a[r]}},unreactive(){this[Bl]&&(this[Bl](),this[Bl]=null)},unwrap(){if(!this.id)throw Error("Invalid object");let a=this[jM];return t.get(this.id,{parent:a?{id:a,type:"unknown"}:void 0})},toPresentation3(){return t.toPresentation3(this.unwrap())},toPresentation2(){return t.toPresentation2(this.unwrap())},valueOf(){return this.unwrap()},toJSON(){let a=this;return{...a,items:a.items,annotations:a.annotations,structures:a.structures,seeAlso:a.seeAlso,service:a.service,services:a.services,rendering:a.rendering,partOf:a.partOf,start:a.start,supplementary:a.supplementary,homepage:a.homepage,thumbnail:a.thumbnail,placeholderCanvas:a.placeholderCanvas,accompanyingCanvas:a.accompanyingCanvas,provider:a.provider}},subscribe(a,r=!0){return t.subscribe(()=>this.id?t.get(this.id):null,a,r)}};return Pi("items",i,t),Pi("annotations",i,t),Pi("structures",i,t),Pi("seeAlso",i,t),Pi("rendering",i,t),Pi("partOf",i,t),Pi("start",i,t,!1),Pi("supplementary",i,t),Pi("homepage",i,t),Pi("thumbnail",i,t),Pi("placeholderCanvas",i,t,!1),Pi("accompanyingCanvas",i,t,!1),Pi("provider",i,t),Pi("body",i,t),Pi("logo",i,t),i}function fF(t){return!!t[wc]}function GM(t){return Array.isArray(t)?t.map(e=>GM(e)):!t||!t.type?t:{id:t.id,type:t.type}}function Fl(t,e,n=!1,i){if(Array.isArray(t))return t.map(u=>Fl(u,e,n));if(!t||!t.type||!t.id)return t;let a=dF(e,n),r=Object.create(a),l=Object.assign(r,t);return n&&l.reactive(),l}function kM(t){switch(t){case"Image":case"Video":case"Sound":case"Dataset":case"Text":case"Composite":case"List":case"Independents":case"Audience":return"ContentResource";case"ImageService1":case"ImageService2":case"ImageService3":return"Service"}return t}var Tc=class{constructor(t,e){kn(this,"options",void 0),kn(this,"store",void 0),kn(this,"emitter",void 0),kn(this,"isBatching",!1),kn(this,"batchQueue",[]),kn(this,"remoteFetcher",void 0),kn(this,"staticFetcher",void 0),kn(this,"defaultFetcher",n=>fetch(n).then(i=>{if(i.status===200)return i.json();{let a=Error(`${i.status} ${i.statusText}`);throw a.name="HTTPError",a}})),this.options=Object.assign({reducers:{},customFetcher:this.defaultFetcher,enableDevtools:!0},t||{}),this.store=e||UM({customReducers:this.options.reducers,defaultState:this.options.defaultState,enableDevtools:this.options.enableDevtools}),this.emitter=Km(),this.remoteFetcher=L1(this,this.options.customFetcher),this.staticFetcher=L1(this,(n,i)=>i)}batch(t){this.isBatching=!0;try{t(this),this.isBatching=!1,this.dispatch(Sc({actions:this.batchQueue}))}catch(e){throw this.batchQueue=[],this.isBatching=!1,e}this.batchQueue=[]}async asyncBatch(t){this.isBatching=!0;try{await t(this),this.isBatching=!1,this.dispatch(Sc({actions:this.batchQueue}))}catch(e){throw this.batchQueue=[],this.isBatching=!1,e}this.batchQueue=[]}modifyEntityField(t,e,n){this.dispatch(Pl.modifyEntityField({id:t.id,type:t.type,key:e,value:n}))}dispatch(t){if(this.isBatching)this.batchQueue.push(t);else{if(t.type===bc){for(let i of t.payload.actions)this.emitter.emit(i.type,{action:i,state:this.store.getState()});this.store.dispatch(t);let n=this.getState();for(let i of t.payload.actions)this.emitter.emit(`after:${i.type}`,{action:i,state:n});return}this.emitter.emit(t.type,{action:t,state:this.store.getState()}),this.store.dispatch(t);let e=this.store.getState();this.emitter.emit(`after:${t.type}`,{action:t,state:e});return}}on(t,e){return this.emitter.on(t,e),()=>{this.emitter.off(t,e)}}serialize(t,e){return S1(this.getState().iiif,t,e)}toPresentation2(t){return this.serialize(t,x1)}toPresentation3(t){return this.serialize(t,w1)}hydrate(t,e,n={}){return this.get(t,e,{...n,skipSelfReturn:!1})}get(t,e,n={}){typeof e!="string"&&(n=e||{},e=void 0);let{skipSelfReturn:i=!0}=n||{},a=n.parent?typeof n.parent=="string"?n.parent:n.parent.id:void 0;if(Array.isArray(t))return t.map(d=>this.get(d,n));let r=this.getState();if(ga(t)&&!n.preserveSpecificResources&&(t=t.source),typeof t=="string"){let d=kM(e||r.iiif.mapping[t]);if(!d)return i?null:{id:t,type:"unknown"};t={id:t,type:d}}if(t&&t.partOf&&!a&&!n.skipPartOfCheck){let d=Array.isArray(t.partOf)?t.partOf[0]:t.partOf;d&&(typeof d=="string"&&(a=d),typeof d.id=="string"&&(a=d.id))}let l=kM(e||t?.type),u=t?.id,f=r.iiif.entities[l];if(!f){let d=r.iiif.requests[u];return d&&d.resourceUri!==u?this.get(d.resourceUri,n):i?null:t}let h=f[t.id];return h&&h[mn]?gc(h,h[mn].find(d=>a?d[ya]===a:d[ya]===h.id)):f[t.id]||(i?null:t)}select(t){return t(this.getState())}getStore(){return this.store}getState(){return this.store.getState()}deep(t,e){if(t===void 0)return this.get(e,{skipSelfReturn:!1});if(typeof t=="function")try{let i=t(this.get(e,{skipSelfReturn:!1})),a=r=>this.deep(r,i);return a.size=Array.isArray(i)?i.length:1,a}catch{let i=a=>this.deep(a,void 0);return i.size=0,i}let n=i=>this.deep(i,t);return n.size=Array.isArray(t)?t.length:1,n}loadManifest(t,e,n){let i=typeof t=="string"?t:t.id;return this.load(i,e,n)}loadCollection(t,e,n){let i=typeof t=="string"?t:t.id;return this.load(i,e,n)}load(t,e,n){let i=typeof t=="string"?t:t.id;return e?Promise.resolve(this.staticFetcher(i,e,n)):Promise.resolve(this.remoteFetcher(i,{},n))}loadSync(t,e,n){let i=typeof t=="string"?t:t.id;return this.staticFetcher(i,e,n)}loadManifestSync(t,e,n){let i=typeof t=="string"?t:t.id;return this.loadSync(i,e,n)}loadCollectionSync(t,e,n){let i=typeof t=="string"?t:t.id;return this.loadSync(i,e,n)}areInputsEqual(t,e){return N1(t,e)}subscribe(t,e,n){return n===void 0&&(e===void 0||e===!1||e===!0)&&(n=e,e=t,t=i=>i),this.store.subscribe(t,i=>e(i,this),{equalityFn:N1,fireImmediately:!n})}async ensureLoaded(t){let e=typeof t=="string"?t:t.id;this.requestStatus(e)||await this.load(e)}requestStatus(t){return this.select(e=>e.iiif.requests[t])}getPaginationState(t){let e=typeof t=="string"?t:t.id;if(!e)return null;let n=this.getResourceMeta(e,"@vault/pagination");if(n?.state)return n.state;let i=this.get(t);if(i.first){let a={currentPage:null,currentPageIndex:null,isFetching:!1,isFullyLoaded:!1,next:i.first,page:1,pages:[],previous:null,totalItems:i.total,currentLength:0};return this.setMetaValue([e,"@vault/pagination","state"],a),a}return null}async loadNextPage(t,e){let n=typeof t=="string"?t:t.id;if(!n)return[null,null];let i=this.getPaginationState(t);if(!i||i.isFullyLoaded||!i.next)return[null,null];if(i.isFetching)return[i,null];let a=typeof i.next=="string"?i.next:i.next.id,r=i.currentPage,l={...i,isFetching:!0};this.setMetaValue([n,"@vault/pagination","state"],l);let u;try{u=await this.loadCollection(a,e,y=>{let{id:g,"@id":b,...w}=y||{};return b?{"@id":a,...w}:{id:a,...w}})}catch(y){let g={...i,isFetching:!1,error:y};return this.setMetaValue([n,"@vault/pagination","state"],g),[g,null]}if(!u){let y={...i,isFetching:!1,error:Error("Collection not found")};return this.setMetaValue([n,"@vault/pagination","state"],y),[y,null]}let f=this.get(n),h=[...f.items||[],...u.items||[]].map(y=>({id:y.id,type:y.type}));this.modifyEntityField({id:n,type:"Collection"},"items",h);let d=this.getPaginationState(t);if(!d)throw Error("Pagination state not found");let m={...d,isFetching:!1,error:null,currentPage:u.id,next:u.next?.id||null,currentPageIndex:d.pages.length,currentLength:h.length,pages:[...d.pages,{id:u.id,type:"Collection",startIndex:f.items.length,pageLength:u.items.length,order:typeof d.currentPageIndex=="number"?d.currentPageIndex+1:0}],isFullyLoaded:!u.next,previous:r,page:d.pages.length+1};return this.setMetaValue([n,"@vault/pagination","state"],m),[m,u]}getResourceMeta(t,e){let n=this.getState().iiif.meta[t];if(n)return e?n[e]:n}getObject(t,e,n={}){let{reactive:i,...a}=n;return Fl(this.get(t,e,a),this,i)}async loadObject(t,e){return Fl(await this.load(t,e),this)}async loadManifestObject(t,e){return Fl(await this.loadManifest(t,e),this)}async loadCollectionObject(t,e){return Fl(await this.loadCollection(t,e),this)}wrapObject(t){return Fl(this.get(t,{skipSelfReturn:!1}),this)}isWrapped(t){return fF(t)}setMetaValue([t,e,n],i){this.dispatch(typeof i=="function"?z1.setMetaValueDynamic({id:t,meta:e,key:n,updateValue:i}):z1.setMetaValue({id:t,meta:e,key:n,value:i}))}};function YM(){return typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}function Lf(t){let e=YM();try{let i=e.IIIF_VAULT;if(i)return i}catch{}let n=new Tc(t);try{e.IIIF_VAULT=n}catch{}return n}var H1=I(Z(),1),ms=Rg.default.createContext({vault:null,setVaultInstance:t=>{}});function ho({vault:t,vaultOptions:e,useGlobal:n,resources:i,children:a}){let[r,l]=(0,Rg.useState)(()=>t||(n?Lf(e):e?new Tc(e):new Tc));return(0,H1.jsx)(ms.Provider,{value:{vault:r,setVaultInstance:l},children:(0,H1.jsx)(Di,{value:i||{},children:a})})}var QM=I(ut(),1),KM=I(ut(),1);var XM=I(ut(),1),ce=()=>{let{vault:t}=(0,XM.useContext)(ms);if(t===null)throw new Error("Vault not found. Ensure you have your provider set up correctly.");return t};var Eg=I(ut(),1);function _e(t,e=[]){let n=ce(),[i,a]=(0,Eg.useState)(()=>t(n.getState(),n));return(0,Eg.useEffect)(()=>n.subscribe(r=>t(r,n),r=>{a(r)},!1),e),i}var ql=KM.default.createContext([]);function Vl(){let t=(0,QM.useContext)(ql);return _e(e=>t.map(n=>e.iiif.entities.Canvas[n]).filter(Boolean),[t])}var ZM=I(ut(),1);function po(t){let e=(0,ZM.useContext)(ms);return t||(e&&e.vault?e.vault:Lf())}var WM=I(ut(),1);function Tn(t={},e=[]){let{id:n,selector:i}=t,a=wi(),r=ce(),l=n||a.manifest,u=_e(f=>l?f.iiif.entities.Manifest[l]:void 0,[l]);return(0,WM.useMemo)(()=>{if(u)return i?i(u):u},[u,i,...e])}var RO=I(ut(),1),Ng=I(ut(),1);var gs=I(ut(),1);function Df(t,{noCache:e=!1}={}){let n=typeof t=="string"?t:t.id,i=po(),[a,r]=(0,gs.useState)(n),[l,u]=(0,gs.useState)(void 0),f=(0,gs.useMemo)(()=>i.get(n,{skipSelfReturn:!0})||void 0,[n,i]),[h,d]=(0,gs.useState)(f);return(0,gs.useEffect)(()=>{(async()=>{try{let m=f&&!e?f:await i.load(n),y=m?m.id||m["@id"]:null;m&&a!==y&&r(y),d(m)}catch(m){u(m)}})()},[n,e]),{isLoaded:!!h,id:a,requestId:n,error:l,resource:h,cached:!!(h&&h===f)}}function F1(t,e){let{id:n,isLoaded:i,error:a,resource:r,requestId:l,cached:u}=Df(t,e);return{id:n,isLoaded:i,error:a,manifest:r,requestId:l,cached:u}}var JM=I(Z(),1);function q1({manifest:t,children:e}){return(0,JM.jsx)(Di,{value:{manifest:t},children:e})}var $M=I(Z(),1);function V1({range:t,children:e}){return(0,$M.jsx)(Di,{value:{range:t},children:e})}function tO(t,e){for(let n of e.items){if(n.type==="Canvas")return n;if(n.type==="SpecificResource")return n.source;if(n.type==="Range"){let i=tO(t,t.get(n));if(i)return i}}return null}function Ag(t,e){let n=[];for(let i of e.items)if(i.type==="SpecificResource"&&i.source?.type==="Canvas"&&(i.source.id.indexOf("#")!==-1?n.push({id:i.source.id.split("#")[0],type:"Canvas"}):n.push(i.source)),i.type==="Range"&&n.push(...Ag(t,t.get(i))),i.type==="SpecificResource"){let a=typeof i.source=="string"?i.source:i.source.id;n.push({id:a,type:"Canvas"})}return n}function hF(t,e,n){for(let i of e.structures){let a=U1(t,t.get(i),n);if(a)return a}return null}function U1(t,e,n){for(let i of e.items){let a=i?.source?.id?.split("#")[0];if(i.type==="SpecificResource"&&i.source===n||i.type==="SpecificResource"&&i.source?.type==="Canvas"&&n===a)return e;if(i.type==="Range"){let r=U1(t,t.get(i),n);if(r)return r}}return null}function pF(t,e,n,i=!1){let a=e.behavior,r=n?t.get(n):null;if(!r)return[];let l=r.behavior,u=i?!1:a.includes("paged"),f=u?!1:a.includes("continuous"),h=u||f?!1:a.includes("individuals"),d=l.includes("facing-pages"),m=l.includes("non-paged");if(d||m||h||i)return[{id:r.id,type:"Canvas"}];let[y,g]=Cg(t,e);if(f)return y;let b=y.findIndex(w=>w.id===n);if(b===-1)return[];for(let w of g)if(w.includes(b))return w.map(E=>y[E]);return[{id:r.id,type:"Canvas"}]}function Cg(t,e,{disablePaging:n,skipNonPaged:i}={}){let a=e.behavior,r=a.includes("paged"),l=r?!1:a.includes("continuous"),u=r||l?!1:a.includes("individuals"),f=e.type==="Manifest"?e.items:Ag(t,e);if(l)return[f,[f.map((b,w)=>w)]];if(u||!r||n)return[f,f.map((b,w)=>[w])];let h=[],d=[],m=()=>{d.length&&(h.push([...d]),d=[])},y=0,g=!1;for(let b=0;b<f.length;b++){let w=t.get(f[b]);if(w.behavior.includes("non-paged")){b===y&&y++,i||(m(),h.push([b]),m());continue}if(b===y||w.behavior.includes("facing-pages")){d.length&&(g=!0),m(),h.push([b]),m();continue}if(d.push(b),g){m(),g=!1;continue}d.length>1&&m()}return d.length&&m(),[f,h]}var cr=I(ut(),1);var eO=I(ut(),1);function Pf(t={},e=[]){let{id:n,selector:i}=t,a=wi(),r=n||a.range,l=_e(u=>r?u.iiif.entities.Range[r]:void 0,[r]);return(0,eO.useMemo)(()=>{if(l)return i?i(l):l},[l,i,...e])}function j1({startCanvas:t,disablePaging:e}){let n=ce(),i=Tn(),a=Pf(),[r,l]=(0,cr.useState)(void 0),u=a||i;if(!u)throw new Error("Nothing selected");let[f,h]=(0,cr.useMemo)(()=>Cg(n,u,{disablePaging:e}),[n,u,e]),d=(0,cr.useRef)(h);if(d.current!==h){let E=d.current[r][0],T=h.findIndex(S=>S.includes(E));d.current=h,l(T)}let m=(0,cr.useCallback)(w=>{let E=h.findIndex(T=>T.includes(w));l(E===-1?0:E)},[f,h]),y=(0,cr.useCallback)(w=>{let E=f.findIndex(T=>T.id===w);E!==-1?m(E):l(0)},[f,h]),g=(0,cr.useCallback)(()=>{l(w=>w>=h.length-1?w:w+1)},[h]),b=(0,cr.useCallback)(()=>{l(w=>w<=0?0:w-1)},[h]);return typeof r>"u"&&(t?y(t):l(0)),{visibleItems:h[r]?.map(w=>f[w].id)||[],cursor:r,items:f,sequence:h,hasPrevious:r>0,hasNext:r<h.length-1,setSequenceIndex:l,setCanvasIndex:m,setCanvasId:y,next:g,previous:b}}var fr=I(ut(),1);var iO={},nO=t=>{let e,n=new Set,i=(d,m)=>{let y=typeof d=="function"?d(e):d;if(!Object.is(y,e)){let g=e;e=m??(typeof y!="object"||y===null)?y:Object.assign({},e,y),n.forEach(b=>b(e,g))}},a=()=>e,f={setState:i,getState:a,getInitialState:()=>h,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(iO.env?iO.env.MODE:void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},h=e=t(i,a,f);return f},va=t=>t?nO(t):nO;var pO=I(ut(),1),mO=I(dO(),1),Og={},{useDebugValue:IF}=pO.default,{useSyncExternalStoreWithSelector:NF}=mO.default,fO=!1,LF=t=>t;function zt(t,e=LF,n){(Og.env?Og.env.MODE:void 0)!=="production"&&n&&!fO&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),fO=!0);let i=NF(t.subscribe,t.getState,t.getServerState||t.getInitialState,e,n);return IF(i),i}var hO=t=>{(Og.env?Og.env.MODE:void 0)!=="production"&&typeof t!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");let e=typeof t=="function"?va(t):t,n=(i,a)=>zt(e,i,a);return Object.assign(n,e),n},_g=t=>t?hO(t):hO;function DF(t){let e=t.service||t.services||[];for(let n of e)if(n.type==="AuthProbeService2")return!0;return!1}function dr(t,e,n){let i=e.findIndex(l=>l.service.id===t);if(i===-1)return e;let a=[...e],r=n(a[i]);return r===a[i]?e:(a[i]=r,a)}var Y1=()=>va((t,e)=>({currentAuth:-1,authItems:[],login:()=>{let n=e().authItems[e().currentAuth];if(!n||n.isPending||n.isLoggedIn)return;if(n.type!=="active")throw new Error("Cannot login to non-active service");let i=n.service.service.find(a=>a.type==="AuthAccessTokenService2");if(!i)throw new Error("Token service not found");t(()=>({authItems:dr(n.id,e().authItems,a=>({...a,isPending:!0}))})),G1(n.service).then(()=>{zg(i).then(a=>{let r=a.expiresIn,l=Date.now()+r*1e3;t(()=>({authItems:dr(n.id,e().authItems,u=>({...u,isLoggedIn:!0,isPending:!1,session:{token:a.accessToken,expires:l}}))}))}).catch(a=>{t(()=>({authItems:dr(n.id,e().authItems,r=>({...r,isLoggedIn:!1,isPending:!1,error:a.message}))}))})})},logout:()=>{let n=e().authItems[e().currentAuth];if(!n||n.isPending||!n.isLoggedIn)return;if(n.type!=="active")throw new Error("Cannot logout of non-active service");let i=n.service.service.find(l=>l.type==="AuthLogoutService2");if(!i)return;let a=`${i.id}?origin=${gO()}`,r=window.open(a);t(()=>({authItems:dr(n.id,e().authItems,l=>({...l,isLoggedIn:!1,session:null,isPending:!1}))}))},nextAuth:()=>{let n=e().authItems.length,i=e().currentAuth+1;i>=n||t(()=>({currentAuth:i}))},previousAuth:()=>{let n=e().currentAuth-1;n<0||t(()=>({currentAuth:n}))},setAuth:n=>{n!==-1&&(n<0||n>=e().authItems.length)||t(()=>({currentAuth:n}))},addService:(n,i)=>{if(!n.service)return;let a=n.service.find(u=>u.type==="AuthAccessTokenService2"),r=n;if(e().authItems.find(u=>u.service.id===n.id)){t(()=>({authItems:dr(n.id,e().authItems,u=>({...u,instances:u.instances+1}))}));return}if(t(()=>({currentAuth:r.profile==="active"?0:e().currentAuth,authItems:[{id:n.id,type:n.profile,service:n,probeId:i,canAuthenticate:!0,instances:1,isPending:!1,isLoggedIn:!1,session:null},...e().authItems]})),n.profile==="external"){if(!a)throw new Error("Token service not found");zg(a).then(u=>{t(()=>({authItems:dr(n.id,e().authItems,f=>({...f,isLoggedIn:!0,isPending:!1,session:{token:u.accessToken,expires:u.expiresIn}}))}))}).catch(u=>{t(()=>({authItems:dr(n.id,e().authItems,f=>({...f,isLoggedIn:!1,isPending:!1,canAuthenticate:!1,error:u.message}))}))})}if(n.profile==="kiosk"){if(!a)throw new Error("Token service not found");t(()=>({authItems:dr(n.id,e().authItems,u=>({...u,isPending:!0}))})),G1(r).then(()=>{zg(a).then(u=>{t(()=>({authItems:dr(n.id,e().authItems,f=>({...f,isLoggedIn:!0,isPending:!1,session:{token:u.accessToken,expires:u.expiresIn}}))}))}).catch(u=>{t(()=>({authItems:dr(n.id,e().authItems,f=>({...f,isLoggedIn:!1,isPending:!1,error:u.message}))}))})})}n.profile},removeService:(n,i)=>{let a=e().currentAuth===e().authItems.findIndex(l=>l.service.id===n.id),r=e().currentAuth;if(a){let l=e().authItems.find(f=>f.service.id===n.id);l&&l.instances>1||(r=e().authItems.findIndex(h=>h.service.id!==n.id&&h.instances>0))}t(()=>({authItems:dr(n.id,e().authItems,l=>({...l,instances:l.instances-1})),currentAuth:r}))}})),X1=(t,e)=>va((n,i)=>({service:t,status:t?"unknown":"success",shouldRedirect:!1,redirectResource:null,shouldSubstitute:!1,substituteResource:null,error:null,errorHeading:null,errorNote:null,shouldDisplayResource:!1,token:e||null,async probe(){if(!i().service)return;let a=i().service?.id;if(!a){n({status:"error",error:"Service ID not found",errorHeading:{en:["Service ID not found"]}});return}n({status:"probing"});let r=i().token;try{let l=await fetch(a,{headers:r?{Authorization:`Bearer ${i().token}`,Accept:"application/json"}:{Accept:"application/json"}}).then(u=>u.json());if(l.status===200)n({status:"success",shouldDisplayResource:!0,error:null,errorHeading:null,errorNote:null,shouldSubstitute:!1,shouldRedirect:!1});else if(l.status<400&&l.status>=300){if(!l.location)throw new Error("Redirect location not found");n({status:"error",shouldDisplayResource:!1,shouldRedirect:!0,redirectResource:l.location||null})}else if(l.status===401)n({status:"error",shouldDisplayResource:!1,shouldRedirect:!1,shouldSubstitute:!!l.substitute,substituteResource:l.substitute||null,error:"Unauthorized",errorHeading:l.heading||{en:["Unauthorized"]},errorNote:l.note||null});else throw new Error("Unknown error")}catch(l){n({status:"error",error:l.message,errorHeading:{en:["Unknown error"]}})}},setToken(a){n({token:a})}}));function Q1(t){let e=t.service||t.services||[],n={hasAuth:!1,services:{}};for(let i of e)if(i.type==="AuthProbeService2"){n.services.probe=i,n.hasAuth=!0;let a=i.service.filter(r=>r.type==="AuthAccessService2");a[0]&&(n.services.access=a[0])}return n}async function zg(t,{strict:e=!0}={}){return new Promise((n,i)=>{let a=Math.random().toString(36).substring(7),r=`${t.id}?messageId=${a}&origin=${window.location.origin}`,l=h=>{let d=h.data;if(d.messageId===a){if(e&&d.type!=="AuthAccessToken2"){u(),i("Invalid response, expected type=AuthAccessToken2");return}if(!d.accessToken){u(),i("Invalid response, expected accessToken");return}u(),n(d)}},u=()=>window.removeEventListener("message",l),f=document.createElement("iframe");f.src=r,f.style.display="none",document.body.appendChild(f),window.addEventListener("message",l)})}function gO(t){let e=window.location;if(t){let n=document.createElement("a");return n.href=t,n.protocol+"//"+n.hostname+(n.port?":"+n.port:"")}return e.protocol+"//"+e.hostname+(e.port?":"+e.port:"")}async function G1(t){let e=`${t.id}?origin=${gO()}`,n=window.open(e);if(!n)throw new Error("Failed to open window");return new Promise((i,a)=>{let r=setInterval(()=>{n.closed&&(clearInterval(r),i())},500)})}var Ec=I(ut(),1);function yO(t){let e=(0,Ec.useMemo)(()=>Q1(t),[t]),n=K1(e.services.access?.id),i=(0,Ec.useMemo)(()=>X1(e.services.probe,n),[e.services.probe]),a=zt(i);return(0,Ec.useEffect)(()=>{a.status==="unknown"&&!n&&a.probe()},[e.services.probe,a.status]),(0,Ec.useEffect)(()=>{n&&(a.setToken(n),a.probe())},[n]),[t,a,e.hasAuth]}var Bf=I(Z(),1),Ul=(0,fr.createContext)(null),vO=(0,fr.createContext)(null);vO.displayName="CurrentAuth";var bO=(0,fr.createContext)(null);bO.displayName="AuthActions";function W1({children:t}){let e=(0,fr.useMemo)(()=>Y1(),[]);return(0,Bf.jsx)(Ul.Provider,{value:e,children:t})}function J1(){return!!(0,fr.useContext)(Ul)}function Ac(){let t=(0,fr.useContext)(Ul);if(!t)throw new Error("useAuthActions must be used within a AuthProvider");return t}function SO(){let t=Ac();return zt(t,n=>({login:n.login,logout:n.logout,nextAuth:n.nextAuth,previousAuth:n.previousAuth,setAuth:n.setAuth,addService:n.addService,removeService:n.removeService}))}function PF(){let t=Ac();return zt(t,e=>e)}function xO(t){let e=Ac();return zt(e,i=>i.authItems.find(a=>a.service.id===t))}function K1(t){let e=Ac();return zt(e,i=>i.authItems.find(a=>a.id===t)?.session?.token)}function BF(t){let e=Ac();return zt(e,i=>{let a=i.authItems.find(r=>r.service.id===t);return!a||!a.isLoggedIn||!a.session?null:a.session?.token||null})}function HF(t){let e=SO(),n=xO(t.service.id);return(0,fr.useEffect)(()=>(e?.addService(t.service,t.probeId),()=>{e?.removeService(t.service,t.probeId)}),[t.service]),n?(n.error||!n.isLoggedIn,t.children):null}function Z1(){return null}function $1(t){let[e,n,i]=yO(t.resource),a=t.fallbackComponent||Z1,r=t.loadingComponent||Z1,l=t.errorComponent||Z1,u=n.service,f=null;if(!i||!u)return t.children(e);let h=u.service.filter(d=>d.type==="AuthAccessService2");n.status==="error"&&(f=(0,Bf.jsx)(l,{resource:t.resource,error:n.error||"",heading:n.errorHeading,note:n.errorNote,extra:t.extra})),(n.status==="unknown"||n.status==="probing")&&(f=(0,Bf.jsx)(r,{})),n.status==="success"&&(f=t.children(e));for(let d of h)f=(0,Bf.jsx)(HF,{service:d,probeId:u.id,children:f},d.id);return f}var Hf=I(ut(),1);var FF=t=>t.id||t["@id"];function qF(t){return(Array.isArray(t.service)?t.service:[t.service]).find(n=>n?.profile==="http://iiif.io/api/search/0/autocomplete"||n?.profile==="http://iiif.io/api/search/1/autocomplete"||n?.profile==="AutoCompleteService1")}var wO=t=>{let e;typeof t=="string"?e={"@context":"http://iiif.io/api/search/1/context.json",profile:"http://iiif.io/api/search/1/search","@id":t,id:t,service:[]}:e=t;let n=e?FF(e):void 0,i=null;return va((a,r)=>({service:e,resources:[],lastQuery:{},loading:!1,error:!1,highlight:null,hasSearch:!!e,hasAutocomplete:e?!!qF(e):!1,errorMessage:"",search(l,u={}){if(!n)throw new Error("No search service found.");i&&!i.signal.aborted&&i.abort(),i=new AbortController;let f=new URLSearchParams;l.q&&f.set("q",l.q),l.motivation&&f.set("motivation",l.motivation),l.date&&f.set("date",l.date),l.user&&f.set("user",l.user),a({loading:!0}),fetch(`${n}?${f.toString()}`,{signal:i.signal,headers:{"Content-Type":"application/json",Accept:"application/json",...u.headers||{}}}).then(async h=>{if(!i?.signal.aborted)if(h.ok){let d=await h.json();a({resources:d.resources,error:!1,errorMessage:""})}else a({resources:[],error:!0,errorMessage:h.statusText})})},clearSearch(){a({resources:[],error:!1,errorMessage:""})},highlightResult(l){let u=r().resources.find(f=>f["@id"]===l);a({highlight:u})},nextResult(){let l=r().resources,u=r().highlight;if(!u){a({highlight:l[0]||null});return}let f=l.findIndex(h=>h["@id"]===u["@id"]);if(f===-1){a({highlight:l[0]||null});return}a({highlight:l[f+1]||l[0]||null})},previousResult(){let l=r().resources,u=r().highlight;if(!u){a({highlight:l[l.length-1]||null});return}let f=l.findIndex(h=>h["@id"]===u["@id"]);if(f===-1){a({highlight:l[l.length-1]||null});return}if(f===0){a({highlight:l[l.length-1]||null});return}a({highlight:l[f-1]||l[l.length-1]||null})}}))};function tx(){let t=Tn();return t?t.service.find(e=>e.profile==="SearchService1"||e.profile==="http://iiif.io/api/search/1/search"):void 0}var Ig=I(Z(),1),Cc=(0,Hf.createContext)(null);Cc.displayName="Search";function TO(t){let e=tx();return t.store?(0,Ig.jsx)(Cc.Provider,{value:t.store,children:t.children}):(0,Ig.jsx)(VF,{service:e,children:t.children})}function VF({service:t,children:e}){let n=(0,Hf.useMemo)(()=>wO(t),[t]);return(0,Ig.jsx)(Cc.Provider,{value:n,children:e})}var Yi=I(Z(),1),Ff=()=>{},Mc=(0,Ng.createContext)({setCurrentCanvasId:Ff,setCurrentCanvasIndex:Ff,nextCanvas:Ff,previousCanvas:Ff,items:[],sequence:[],setSequenceIndex:Ff,currentSequenceIndex:0,hasNext:!1,hasPrevious:!1});function EO(t){let e=Tn(),{cursor:n,visibleItems:i,next:a,sequence:r,items:l,setCanvasIndex:u,setCanvasId:f,previous:h,setSequenceIndex:d,hasNext:m,hasPrevious:y}=j1({startCanvas:t.startCanvas,disablePaging:t.pagingEnabled===!1}),g=(0,Ng.useMemo)(()=>({sequence:r,items:l,setCurrentCanvasId:f,nextCanvas:a,previousCanvas:h,totalCanvases:l.length,setCurrentCanvasIndex:u,setSequenceIndex:d,currentSequenceIndex:n,hasNext:m,hasPrevious:y}),[r,l,f,a,h,l,u,d,n]);return e?i.length===0?null:(0,Yi.jsx)(Mc.Provider,{value:g,children:(0,Yi.jsx)(ql.Provider,{value:i,children:(0,Yi.jsx)(qa,{canvas:i[0],children:t.children})})}):(console.warn("The manifest passed to the provider is not a valid IIIF manifest."),(0,Yi.jsx)("div",{children:"Sorry, something went wrong."}))}function ex(t){let e=po(t.vault),n=F1(t.manifest);if(!n)return console.warn("The manifest passed to the provider is not a valid IIIF manifest."),(0,Yi.jsx)("div",{children:"Sorry, something went wrong."});if(n.error)return(0,Yi.jsx)("div",{children:n.error.toString()});if(!n.isLoaded)return(0,Yi.jsx)("div",{children:"Loading..."});let i=(0,Yi.jsx)(EO,{...t,children:t.children});return(0,Yi.jsx)(ho,{vault:e,children:(0,Yi.jsx)(q1,{manifest:n.id,children:(0,Yi.jsx)(W1,{children:(0,Yi.jsx)(TO,{children:t.rangeId?(0,Yi.jsx)(V1,{range:t.rangeId,children:i}):i})})})})}function jl(){return(0,RO.useContext)(Mc)}var Oc=(t,e,n)=>{let i=t.length,a=n||It(i);for(let r=0;r<i;r++)a[r]=r%5===0?t[r+1]<e[3]&&t[r+3]>e[1]&&t[r+2]<e[4]&&t[r+4]>e[2]?1:0:t[r];return a};function It(t,e,n){return new Float32Array(t,e,n)}var AO=(t,e,n)=>{let i=t[1]<=e[3]&&t[3]>=e[1]&&t[2]<=e[4]&&t[4]>=e[2],a=n||It(5);return i?(a[0]=1,a[1]=Math.max(t[1],e[1]),a[2]=Math.max(t[2],e[2]),a[3]=Math.min(t[3],e[3]),a[4]=Math.min(t[4],e[4]),a):(a[0]=0,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a)},CO=t=>t.length/5;var Dr=(t,e,n)=>{let i=n||It(9);return i[0]=t[0]*e[0]+t[1]*e[3]+t[2]*e[6],i[1]=t[0]*e[1]+t[1]*e[4]+t[2]*e[7],i[2]=t[0]*e[2]+t[1]*e[5]+t[2]*e[8],i[3]=t[3]*e[0]+t[4]*e[3]+t[5]*e[6],i[4]=t[3]*e[1]+t[4]*e[4]+t[5]*e[7],i[5]=t[3]*e[2]+t[4]*e[5]+t[5]*e[8],i[6]=t[6]*e[0]+t[7]*e[3]+t[8]*e[6],i[7]=t[6]*e[1]+t[7]*e[4]+t[8]*e[7],i[8]=t[6]*e[2]+t[7]*e[5]+t[8]*e[8],i},de=class t{constructor(e){this.index=0,this.length=e,this.points=It(this.length)}static grid(e=1,n=1){return new t(5*e*n)}static point(e,n){let i=It(5);return i[0]=1,i[1]=e,i[2]=n,i[3]=e,i[4]=n,i}static positionPair(e){let n=It(5);return n[0]=1,n[1]=e.x1,n[2]=e.y1,n[3]=e.x2,n[4]=e.y2,n}static projection(e){return t.singleBox(e.width,e.height,e.x,e.y)}static singleBox(e,n,i=0,a=0){let r=It(5);return r[0]=1,r[1]=i,r[2]=a,r[3]=e+i,r[4]=n+a,r}row(e){return e(this)}addPoints(e,n,i,a){return this.points[this.index]=1,this.points[1+this.index]=e,this.points[2+this.index]=n,this.points[3+this.index]=i,this.points[4+this.index]=a,this.index+=5,this}addBox(e,n,i,a){return this.addPoints(e,n,e+i,n+a),this}build(){return this.points}};var hr=(t,e)=>{let n=t.length;for(let i=0;i<n;i++)t[i]=i%5===0?e[6]*t[i+1]+e[7]*t[i+2]+e[8]*t[i]:i%5%2===1?e[0]*t[i]+e[1]*t[i+1]+e[2]:e[3]*t[i-1]+e[4]*t[i]+e[5];return t},mo=t=>{let e=It(9);return e[0]=t,e[4]=t,e[8]=1,e},ci=(t,e)=>{let n=It(9);return n[0]=1,n[2]=t,n[4]=1,n[5]=e,n[8]=1,n},kl=(t,e,n)=>Dr(ci((1-t)*e,(1-t)*n),mo(t)),Xi=(t,e,n)=>{let i=t.length,a=n&&n.length>=i?n.slice(0,i):It(i);for(let r=0;r<i;r++)a[r]=r%5===0?e[6]*t[r+1]+e[7]*t[r+2]+e[8]*t[r]:r%5%2===1?e[0]*t[r]+e[1]*t[r+1]+e[2]:e[3]*t[r-1]+e[4]*t[r]+e[5];return a};var UF=Object.defineProperty,jF=(t,e,n)=>e in t?UF(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Lg=(t,e,n)=>(jF(t,typeof e!="symbol"?e+"":e,n),n);function Gl(t){return t.endsWith("info.json")?t:t.endsWith("/")?`${t}info.json`:`${t}/info.json`}var kF="http://library.stanford.edu/iiif/image-api/compliance.html#level0",zO="http://library.stanford.edu/iiif/image-api/compliance.html#level1",IO="http://library.stanford.edu/iiif/image-api/compliance.html#level2",GF="http://library.stanford.edu/iiif/image-api/conformance.html#level0",NO="http://library.stanford.edu/iiif/image-api/conformance.html#level1",LO="http://library.stanford.edu/iiif/image-api/conformance.html#level2",YF="http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level0",DO="http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level1",PO="http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level2",XF="http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level0",BO="http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level1",HO="http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level2",QF="http://iiif.io/api/image/1/level0.json",KF="http://iiif.io/api/image/1/profiles/level0.json",FO="http://iiif.io/api/image/1/level1.json",qO="http://iiif.io/api/image/1/profiles/level1.json",VO="http://iiif.io/api/image/1/level2.json",UO="http://iiif.io/api/image/1/profiles/level2.json",ZF="http://iiif.io/api/image/2/level0.json",WF="http://iiif.io/api/image/2/profiles/level0.json",jO="http://iiif.io/api/image/2/level1.json",kO="http://iiif.io/api/image/2/profiles/level1.json",GO="http://iiif.io/api/image/2/level2.json",YO="http://iiif.io/api/image/2/profiles/level2.json",JF="level0",XO="level1",QO="level2",$F="http://iiif.io/api/image/2/level0",KO="http://iiif.io/api/image/2/level1",ZO="http://iiif.io/api/image/2/level2",tq="https://iiif.io/api/image/1.1/compliance/#level0",WO="https://iiif.io/api/image/1.1/compliance/#level1",JO="https://iiif.io/api/image/1.1/compliance/#level2",$O=[ZO,IO,LO,PO,HO,VO,UO,GO,YO,QO,JO],t_=[...$O,KO,zO,NO,DO,BO,FO,qO,jO,kO,XO,WO],eq=[$F,KO,ZO,kF,zO,IO,GF,NO,LO,YF,DO,PO,XF,BO,HO,QF,KF,FO,qO,VO,UO,ZF,WF,jO,kO,GO,YO,JF,XO,QO,tq,WO,JO];var nq={extraFormats:["jpg"],extraQualities:["default"],extraFeatures:["sizeByWhListed"]},iq={extraFormats:["jpg"],extraQualities:["default"],extraFeatures:["baseUriRedirect","cors","jsonldMediaType","regionByPx","regionSquare","sizeByWhListed","sizeByH","sizeByW","sizeByWh"]},aq={extraFormats:["jpg","png"],extraQualities:["default"],extraFeatures:["baseUriRedirect","cors","jsonldMediaType","regionByPct","regionByPx","regionSquare","rotationBy90s","sizeByWhListed","sizeByConfinedWh","sizeByH","sizeByPct","sizeByW","sizeByWh"]};function rq(t){return $O.indexOf(t)!==-1?aq:t_.indexOf(t)!==-1?iq:nq}function oq(t){let e=t?Array.isArray(t.profile)?t.profile:[t.profile]:[],n={extraQualities:[],extraFormats:[],extraFeatures:[]};for(let i of e)if(typeof i=="string"&&(i=rq(i)),!!i){if(i.formats)for(let a of i.formats)n.extraFormats.indexOf(a)===-1&&n.extraFormats.push(a);if(i.qualities)for(let a of i.qualities)n.extraQualities.indexOf(a)===-1&&n.extraQualities.push(a);if(i.supports)for(let a of i.supports)n.extraFeatures.indexOf(a)===-1&&n.extraFeatures.push(a);if(i.maxHeight&&(n.maxHeight=i.maxHeight),i.maxWidth&&(n.maxWidth=i.maxWidth),i.maxArea&&(n.maxArea=i.maxArea),i.extraFormats)for(let a of i.extraFormats)n.extraFormats.indexOf(a)===-1&&n.extraFormats.push(a);if(i.extraQualities)for(let a of i.extraQualities)n.extraQualities.indexOf(a)===-1&&n.extraQualities.push(a);if(i.extraFeatures)for(let a of i.extraFeatures)n.extraFeatures.indexOf(a)===-1&&n.extraFeatures.push(a);i.maxHeight&&(n.maxHeight=i.maxHeight),i.maxWidth&&(n.maxWidth=i.maxWidth),i.maxArea&&(n.maxArea=i.maxArea)}if(t.extraFormats)for(let i of t.extraFormats)n.extraFormats.indexOf(i)===-1&&n.extraFormats.push(i);if(t.extraFeatures)for(let i of t.extraFeatures)n.extraFeatures.indexOf(i)===-1&&n.extraFeatures.push(i);if(t.extraQualities)for(let i of t.extraQualities)n.extraQualities.indexOf(i)===-1&&n.extraQualities.push(i);return n}function sq(t){try{if(t==="full")return{full:!0};if(t==="square")return{square:!0};let e=t.startsWith("pct:"),n=t.substr(e?4:0).split(",").map(i=>parseFloat(i));return{x:n[0],y:n[1],w:n[2],h:n[3],percent:e}}catch{throw new Error("Expected 'full', 'square' or 'x,y,w,h'. Found "+t)}}function lq(t){let e={upscaled:!1,max:!1,confined:!1};if(t[0]==="^"&&(e.upscaled=!0,t=t.slice(1)),t==="max"||t==="full")return e.max=!0,e.serialiseAsFull=t==="full",e;if(t[0]==="!"&&(e.confined=!0,t=t.slice(1)),t[0]==="p")return e.percentScale=parseFloat(t.slice(4)),e;let n=t.split(",").map(i=>i.trim());return n.length&&typeof n[0]<"u"&&(n[0]!==""&&(e.width=parseInt(n[0],10)),typeof n[1]<"u"&&n[1]!==""?(e.height=parseInt(n[1],10),e.version=2):e.version=3),e}function uq(t){let e={angle:0};if(t[0]==="!"&&(e.mirror=!0,t=t.substr(1)),e.angle=parseFloat(t)%360,Number.isNaN(e.angle))throw new Error(`Invalid rotation ${t}`);return e}function cq(t,e=""){let n=t.match(/^(([a-zA-Z]+):\/\/([^/]+))?((.*)+)/);if(!n)throw new Error(`Invalid or unknown input ${t}`);let i=n[2],a=n[3],r=n[4];if(r[0]==="/"&&(r=r.substring(1)),e.length>0){if(e[0]==="/"&&(e=e.substring(1)),e!==r.substring(0,e.length))throw new Error(`Path does not start with prefix (path: ${r}, prefix: ${e})`);r=r.substring(e.length)}return{scheme:i,server:a,path:r,prefix:e}}function dq(t,e=""){let{path:n,scheme:i,server:a,prefix:r}=cq(t,e),l=(n||"").split("/").reverse(),[u,f,h,d,...m]=l,y=m.reverse().filter(Boolean).join("/");if(l.length===1||u==="")return{type:"base",scheme:i,server:a,prefix:r,identifier:y};if(u==="info.json"){let[,...b]=l;return{type:"info",scheme:i,server:a,prefix:r,identifier:b.reverse().filter(Boolean).join("/")}}let g=(u||"").split(".");if(typeof g[1]>"u"||typeof g[0]>"u"||typeof d>"u"||typeof h>"u"||typeof f>"u")throw new Error("Invalid image request");return{type:"image",scheme:i,server:a,prefix:r,identifier:y,originalPath:n,region:sq(d),size:lq(h),rotation:uq(f),quality:g[0],format:g[1]}}function fq(t){let e=dq(Gl(t.id));if(e.type!=="info")throw new Error("Invalid service URL");let n=oq(t);return{identifier:e.identifier,originalPath:"",server:e.server,prefix:e.prefix,scheme:e.scheme,type:"image",quality:n.extraQualities.indexOf("default")===-1?n.extraQualities[0]:"default",region:{full:!0},size:{max:!0,upscaled:!1,confined:!1},format:"jpg",rotation:{angle:0}}}function hq(t,e,n){let i=n.length,a=[];for(let r=0;r<i;r++){let l=n[r];if(l){let u=l.width;a.push(t/u)}}return a}function pq(t,e,n){let i=n.length,a=[];for(let r=0;r<i;r++){let l=n[r];l&&a.push({width:Math.floor(t/l),height:Math.floor(e/l)})}return a}function gn(t){if(t["@id"])return t["@id"];if(t.id)return t.id}function Pg(t){if(!t||!t.profile||!gn(t))return!1;let e=Array.isArray(t.profile)?t.profile:[t.profile];for(let n of e)if(typeof n=="string"&&eq.indexOf(n)!==-1)return!0;return!1}function mq(t){if(!Pg(t))return!1;let e=Array.isArray(t.profile)?t.profile:[t.profile];for(let n of e)if(typeof n=="string"){if(t_.indexOf(n)!==-1)return!0}else{let i=[...n.supports||[],...n.extraFeatures||[]];if(i.indexOf("regionByPx")!==-1&&(i.indexOf("sizeByW")!==-1||i.indexOf("sizeByWh")!==-1))return!0}return!1}function Dg(t,e){if(e&&e.profile){let n=e.profile;if(n){let i=Array.isArray(n)?n:[n];return i.includes(`level${t}`)||i.includes(`http://iiif.io/api/image/2/level${t}.json`)||i.includes(`http://iiif.io/api/image/1/level${t}.json`)||i.includes(`http://iiif.io/api/image/1/profiles/level${t}.json`)}}return!1}function ix(t){return Pg(t)?Dg(0,t)?0:Dg(1,t)?1:Dg(2,t)?2:null:null}function e_(t){return(t["@context"]?Array.isArray(t["@context"])?t["@context"]:[t["@context"]]:[]).indexOf("http://iiif.io/api/image/3/context.json")!==-1}function gq(t){if(!mq(t))return[];let e=[],n=Array.isArray(t.profile)?t.profile:[t.profile],i=n.length;for(let a=0;a<i;a++){let r=n[a];if(r&&typeof r!="string"&&(r.maxHeight||r.maxWidth))return[{id:gn(t),type:"variable",minWidth:0,minHeight:0,maxHeight:r.maxHeight||r.maxWidth,maxWidth:r.maxWidth||r.maxHeight,level:ix(t),version:t["@context"]==="http://iiif.io/api/image/3/context.json"?3:2}]}if(t.tiles){let a=t.tiles.length;for(let r=0;r<a;r++){let l=t.tiles[r];l&&(l.height||l.width)&&e.push({id:gn(t),type:"variable",minHeight:0,minWidth:0,maxHeight:l.height||l.width,maxWidth:l.width,level:ix(t),version:e_(t)?3:2})}}return e}function MO(t){let e=/^.*\/(full)\/(((\d+),(\d+)?)|max)\/(\d+)\/default\.(jpg|png|jpeg)$/,n=t.match(e);if(n&&n[4]&&n[5]){let i=n[1],a=parseInt(n[4],10),r=parseInt(n[5],10),l=n[7];if((i==="max"||i==="full")&&a&&r&&l)return{type:"fixed",id:t,height:r,width:a}}return{type:"unknown",id:t}}function yq(t){if(t["@type"])return t["@type"];if(t.type)return t.type}function vq(t){if(typeof t=="string")return MO(t);let e=yq(t);if(e!=="Image"&&e!=="sc:Image")return null;let n=t,i=gn(n);return i?i&&n.width&&n.height?{id:i,type:"fixed",width:n.width,height:n.height,unsafe:!0}:MO(i):null}function bq(t){return Pg(t)?(t&&t.sizes?t.sizes:[]).map(e=>({id:gn(t),type:"fixed-service",height:e.height,width:e.width,level:ix(t),version:e_(t)?3:2})):[]}function OO(t){let e=[],n=t.length;for(let i=0;i<n;i++){let a=t[i];if(!a)continue;let r=bq(a);r.length&&e.push(...r);let l=gq(a);l.length&&e.push(...l)}return e}function n_(t){let e=t.service?Array.isArray(t.service)?t.service:[t.service]:[],n=e.length,i=[];for(let a=0;a<n;a++)Pg(e[a])&&i.push(e[a]);return i}function Sq(t,e=!0,n){let i=[],a=vq(t);if(a===null)return i;let r=t;if(i.push(a),e&&r&&r.width&&r.height){let l=[],u=n_(r);for(let f of u){let h={id:gn(f),width:r.width,height:r.height};if(n.canLoadSync(h)){let d=n.loadServiceSync(h);d&&(d.height||(d.height=r.height),d.width||(d.width=r.width),l.push(...OO([d])))}}if(l.length)return i.push(...l),i}return r.service&&i.push(...OO(r.service)),i}function xq({x:t=0,y:e=0,w:n,h:i,full:a,square:r,percent:l}){if(a)return"full";if(r)return"square";if(typeof n>"u"||typeof i>"u")throw new Error("RegionParameter: invalid region");let u=`${t},${e},${n},${i}`;return l?`pct:${u}`:u}function wq({max:t,percentScale:e,upscaled:n,confined:i,width:a,height:r,serialiseAsFull:l,version:u}){let f=[];return n&&f.push("^"),t?(f.push(l?"full":"max"),f.join("")):(i&&f.push("!"),e&&f.push(`pct:${e}`),a&&f.push(`${a}`),f.push(","),r&&u===3&&f.push(`${r}`),f.join(""))}function Tq(t){return`${t.mirror?"!":""}${(t.angle||0)%360}`}function Rq(t,e){let n=t.prefix.startsWith("/")?t.prefix.substr(1):t.prefix,i=`${t.scheme}://${t.server}/${n?`${n}/`:""}${t.identifier}`;if(t.type==="base")return i;if(t.type==="info")return`${i}/info.json`;let{size:a}=t,{region:r,rotation:l,format:u,quality:f}=t;if(e){let h=e["@context"]?Array.isArray(e["@context"])?e["@context"]:[e["@context"]]:[],d=e.profile,m=h.indexOf("http://iiif.io/api/image/2/context.json")!==-1||d==="level2",y=h.indexOf("http://iiif.io/api/image/3/context.json")!==-1;if((a.width===e.width&&!a.height||a.height===e.height&&!a.width||a.width===e.width&&a.height===e.height)&&(a={...a,max:!0}),m&&(a.max&&!a.serialiseAsFull&&(a={...a,serialiseAsFull:!0}),!a.max&&a.width&&a.height&&(a={...a,height:void 0}),a={...a,version:2}),y){if(a.max&&a.serialiseAsFull&&(a={...a,serialiseAsFull:!1}),a.width&&!a.height&&e.width&&e.height){let g=e.height/e.width;a={...a,height:Math.ceil(a.width*g)}}a={...a,version:3}}}return[i,xq(r),wq(a),Tq(l),`${f}.${u}`].filter(Boolean).join("/")}function nx(t,e,n){let i=fq({"@context":t.version===3?"http://iiif.io/api/image/3/context.json":"http://iiif.io/api/image/2/context.json",id:Gl(gn(t)),profile:t.level===null||typeof t.level>"u"?"level0":`level${t.level}`,type:t.version===3?"ImageService3":"ImageService2"});if(i.type!=="image")throw new Error("Invalid service");return i.size.max=!1,i.size.width=e,i.size.height=n,{id:Rq(i),type:"fixed",width:e,height:n||t.height/(t.width||1)*e,unsafe:t.width>e}}function _c(t){let e=t.replace(/(https?:\/\/)?(www.)?/i,"");return e.indexOf("/")!==-1?e.split("/")[0]:e}function Eq(t,e,n){let i=t.width?t.width:t.maxWidth;return n.height<=t.maxHeight&&n.width<=t.maxWidth&&n.height>=t.minHeight&&n.width>=t.minWidth&&(!e||Math.abs(n.width-i)<Math.abs(e.width-i))}function Aq(t,e){let n=[],i=Object.assign({unsafeImageService:!1,atAnyCost:!0,fallback:!0,minHeight:64,minWidth:64,maxHeight:1/0,maxWidth:1/0,returnAllOptions:!1,preferFixedSize:!1,allowUnsafe:!1,explain:!1,height:0,width:0},t),a=(d,m=0)=>i.explain?n.push(new Array(m).fill(0).map(y=>" ").join("")+d().trim()):void 0,r=[],l=[],u=null;a(()=>`Using configuration: ${JSON.stringify(i,null,2)}`);let f=(d,m)=>{if(a(()=>"Swapping choice",3),Eq(i,m,d)){if(i.preferFixedSize&&d.unsafe){a(()=>`We found an image that was marked as unsafe, but it was the best size. (${d.id})`,4),l.push(d);return}i.returnAllOptions&&m&&l.push(m),a(()=>`We found a new image that was the best size. (${d.id})`,4),u=d}else i.returnAllOptions&&l.push(d)};a(()=>`The input shows we have ${e.length} list(s) of candidates to choose from.`);let h=e.length;for(let d=0;d<h;d++){let m=e[d]();a(()=>`Candidate group ${d}: ${JSON.stringify(m,null,2)}`,1);let y=m.length;a(()=>`Checking candidate list number ${d} and found ${y} potential ways of creating image(s)`,1);for(let g=0;g<y;g++){let b=m[g];if(a(()=>`-> Checking candidate ${g}`,1),b.type==="unknown"&&i.atAnyCost&&(a(()=>`We've found an unknown image type, adding this to the "last resort" list`,2),r.push(b)),b.type==="fixed"&&(b.unsafe?(a(()=>`We've found an unsafe fixed image type, adding this to the "last resort" list`,2),r.push(b)):(a(()=>"We've found a fixed size image, checking if it matches the request",2),f(b,u))),b.type==="fixed-service")if(i.unsafeImageService){a(()=>"Checking for an image from the tile source, without calculating the right height and width (unsafeImageService)",2);let w=nx(b,i.width,i.height);f(w,u)}else{a(()=>"Checking for an image from the tile source 3",2);let w=nx(b,b.width,b.height);f(w,u)}if(b.type==="variable"&&b.maxWidth){let w=nx({id:b.id,type:"fixed-service",width:b.maxWidth,height:b.maxWidth,level:b.level,version:b.version},b.maxWidth);f(w,u)}}if(u&&!i.returnAllOptions){if(u.unsafe||i.allowUnsafe)continue;a(()=>`We found a match in choice list number ${d}, no searching any more`);break}}return i.atAnyCost&&l.length===0?(a(()=>u?`We found an image! ${u.id} of type ${u.type}`:'We found no images, but "atAnyCost" is set, so returning that'),{best:u||r[0]||null,fallback:r.slice(1),log:n}):i.returnAllOptions?(a(()=>"Returning all options that we have found"),{best:(i.atAnyCost?u||l[0]||r[0]:u||l[0])||null,fallback:[...l,...r],log:n}):(a(()=>"Returning the best image that we found, and a fallback"),{best:u||l[0]||null,fallback:u?l:l.slice(1),log:n})}function Cq(t,e,n){let i=t>e?t:e,a=n.length,r=[];for(let l=0;l<a;l++){let u=n[l];if(!u||u.scaleFactors.length===0)continue;let f=u.scaleFactors[0];if(!f)continue;let h=i/f,d=[f];for(;h>=u.width;)f=f*2,d.push(f),h=h/2;r.push({...u,scaleFactors:d})}return r}function Mq(t,e){if(t.length!==e.length)return!1;if(t.length===0&&e.length===0)return!0;let n=t.length,i=!0;for(let r=0;r<n;r++){let l=t[r],u=e[r];if(l.width!==u.width||l.height!==u.height){i=!1;break}}if(i)return!0;let a=0;for(let r=0;r<n;r++)for(let l=0;l<n;l++)if(t[r].width===e[l].width&&t[r].height===e[l].height){a++;break}return a===n}function _O(t){return Dg(0,t)}var i_=class{constructor(t={}){Lg(this,"config",{verificationsRequired:1,approximateServices:!1,enableFetching:!0,disableThrottling:!1}),Lg(this,"fetchingCount",0),Lg(this,"imageServices",{}),Lg(this,"knownImageServers",{}),this.config=Object.assign(this.config,t)}setConfig(t){Object.assign(this.config,t)}sample(t,e,n=!0){let i=_c(gn(t)),a=Gl(gn(t)),r=this.knownImageServers[i];return this.imageServices[a]=Object.assign(t,{real:!0}),!r&&t.tiles&&!_O(t)?(this.knownImageServers[i]={verifications:0,malformed:!1,root:i,preLoaded:n,sampledId:gn(t),verified:!1,server:null,result:{context:t["@context"]||[],sampledProfile:t.profile,resourceServiceRatio:e&&t.height?e.height/t.height:1,sampledSizes:t.sizes||[],sizeRatios:hq(t.width,t.height,t.sizes||[]),sampledTiles:t.tiles||[]}},!0):this.verify(t)}preLoad(t,e=!0){this.knownImageServers[t.root]=t,e&&(this.knownImageServers[t.root].malformed=!1,this.knownImageServers[t.root].verifications=this.config.verificationsRequired)}predict(t,e=!1,n=!1){let i=t?.source,a=_c(gn(t)),r=this.knownImageServers[a],l=Gl(gn(t));return this.imageServices[l]?this.imageServices[l]||null:!this.config.approximateServices||!r||!r.result||!(i?.height||t.height)||!(i?.width||t.width)||!n&&(r.malformed||r.verifications<this.config.verificationsRequired)||_O(t.source)?null:(this.imageServices[l]||(this.imageServices[l]={"@context":r.result.context,"@id":gn(t),id:gn(t),protocol:"http://iiif.io/api/image",tiles:i?.tiles||Cq(t.width,t.height,r.result.sampledTiles),sizes:i?.sizes||pq(Math.round(t.width/r.result.resourceServiceRatio),Math.round(t.height/r.result.resourceServiceRatio),r.result.sizeRatios),profile:i?.profile||r.result.sampledProfile,height:i?.height||t.height,width:i?.width||t.width,real:!1}),this.imageServices[l]||null)}async getThumbnailFromResource(t,e,n=!0,i=[]){let a=t?await this.getImageCandidates(t,n):[];return Aq(e,[()=>i,()=>a])}async getImageCandidates(t,e=!0){let n=t;if(e&&n&&n.height&&n.width){let i=n_(n);for(let a of i){let r={id:gn(a),width:a.width?a.width:n.width,height:a.height?a.height:n.height,source:a};await this.loadService(r)}}return Sq(t,e,this)}async verify(t){let e=this.predict(t,!1,!0),n=await this.fetchService(gn(t));if(!e)return!1;let i=e.height===n.height&&e.width===n.width&&e["@context"]===n["@context"]&&Mq(e.sizes||[],n.sizes||[]);if(i){let a=_c(gn(t)),r=this.knownImageServers[a];r&&(r.verifications+=1,r.verifications>=this.config.verificationsRequired&&(r.verified=!0))}return i}canLoadSync(t){let e=typeof t=="string"?t:gn(t),n=Gl(e);if(this.imageServices[n])return!0;let i=this.knownImageServers[_c(e)];return!!(i&&!i.malformed&&i.verifications>=this.config.verificationsRequired)}async markAsMalformed(t){return this.knownImageServers[_c(gn(t))].malformed=!0,this.loadService(t,!0)}async fetchService(t,e=!1){let n=Gl(t),i=this.imageServices[n];if(i&&(!e||i.real))return i;if(!this.config.enableFetching)throw new Error("Fetching is not enabled");let a=await this.fetch(n).then(r=>r.json());return!a.id&&a["@id"]&&(a.id=a["@id"]),a.id!==t&&(a.id=t,a["@id"]&&(a["@id"]=t)),this.imageServices[n]=Object.assign(a,{real:!0}),this.imageServices[n]}async fetch(t,e){return fetch(t,e)}async loadService(t,e=!1){if(!this.config.disableThrottling){let a=!0;for(;a;)if(this.fetchingCount>=this.config.verificationsRequired)await new Promise(r=>setTimeout(r,500));else{a=!1;break}}let n=this.knownImageServers[_c(gn(t))];if(n&&!n.malformed&&!e){await n.result;let a=this.loadServiceSync(t);if(a)return a}this.fetchingCount++;let i=await this.fetchService(gn(t),e);return this.fetchingCount--,i.real&&this.sample(i,t),i}loadServiceSync(t){let e=Gl(gn(t));return this.imageServices[e]?this.imageServices[e]:this.config.approximateServices?this.predict(t):null}},uQ=new i_;var Bg={},go={get(t){return t},setMetaValue([t,e,n],i){let a=go.getResourceMeta(t,e),r=a?a[n]:void 0,l=typeof i=="function"?i(r):i;Bg[t]={...Bg[t]||{},[e]:{...(Bg[t]||{})[e]||{},[n]:l}}},getResourceMeta:(t,e)=>{let n=Bg[t];if(n)return e?n[e]:n},async load(t){let e=typeof t=="string"?t:t.id;return fetch(e).then(n=>n.json())},subscribe(t){return()=>{}},requestStatus(t){}};function Oq(t){try{if(t==="full")return{full:!0};if(t==="square")return{square:!0};let e=t.startsWith("pct:"),n=t.substr(e?4:0).split(","),i=n.map(a=>parseFloat(a));return{x:i[0],y:i[1],w:i[2],h:i[3],percent:e}}catch{throw Error("Expected 'full', 'square' or 'x,y,w,h'. Found "+t)}}function _q(t){let e={upscaled:!1,max:!1,confined:!1};if(t[0]==="^"&&(e.upscaled=!0,t=t.slice(1)),t==="max"||t==="full")return e.max=!0,e.serialiseAsFull=t==="full",e;if(t[0]==="!"&&(e.confined=!0,t=t.slice(1)),t[0]==="p")return e.percentScale=parseFloat(t.slice(4)),e;let n=t.split(",").map(i=>i.trim());return n.length&&(n[0]!==""&&(e.width=parseInt(n[0],10)),n[1]!==""&&(e.height=parseInt(n[1],10))),e}function zq(t){let e={angle:0};if(t[0]==="!"&&(e.mirror=!0,t=t.substr(1)),e.angle=parseFloat(t)%360,Number.isNaN(e.angle))throw Error(`Invalid rotation ${t}`);return e}function Iq(t,e=""){let n=t.match(/^(([a-zA-Z]+):\/\/([^/]+))?((.*)+)/);if(!n)throw Error(`Invalid or unknown input ${t}`);let i=n[2],a=n[3],r=n[4];if(r[0]==="/"&&(r=r.substring(1)),e.length>0){if(e[0]==="/"&&(e=e.substring(1)),e!==r.substring(0,e.length))throw Error(`Path does not start with prefix (path: ${r}, prefix: ${e})`);r=r.substring(e.length)}return{scheme:i,server:a,path:r,prefix:e}}function Nq(t,e=""){let{path:n,scheme:i,server:a,prefix:r}=Iq(t,e),l=n.split("/").reverse(),[u,f,h,d,...m]=l,y=m.reverse().filter(Boolean).join("/");if(l.length===1||u==="")return{type:"base",scheme:i,server:a,prefix:r,identifier:y};if(u==="info.json"){let[,...w]=l;return{type:"info",scheme:i,server:a,prefix:r,identifier:w.reverse().filter(Boolean).join("/")}}if(i===void 0||a===void 0||n===void 0||d===void 0||h===void 0||f===void 0||u===void 0)throw Error("Invalid image service URL");let[g="",b=""]=u.split(".");return{type:"image",scheme:i,server:a,prefix:r,identifier:y,originalPath:n,region:Oq(d),size:_q(h),rotation:zq(f),quality:g,format:b}}function Lq(t){return cc.indexOf(t)!==-1?J2:Wm.indexOf(t)!==-1?W2:Z2}function Dq(t){let e=t?Array.isArray(t.profile)?t.profile:[t.profile]:[],n={extraQualities:[],extraFormats:[],extraFeatures:[]};for(let i of e)if(typeof i=="string"&&(i=Lq(i)),!!i){if(i.formats)for(let a of i.formats)n.extraFormats.indexOf(a)===-1&&n.extraFormats.push(a);if(i.qualities)for(let a of i.qualities)n.extraQualities.indexOf(a)===-1&&n.extraQualities.push(a);if(i.supports)for(let a of i.supports)n.extraFeatures.indexOf(a)===-1&&n.extraFeatures.push(a);if(i.maxHeight&&(n.maxHeight=i.maxHeight),i.maxWidth&&(n.maxWidth=i.maxWidth),i.maxArea&&(n.maxArea=i.maxArea),i.extraFormats)for(let a of i.extraFormats)n.extraFormats.indexOf(a)===-1&&n.extraFormats.push(a);if(i.extraQualities)for(let a of i.extraQualities)n.extraQualities.indexOf(a)===-1&&n.extraQualities.push(a);if(i.extraFeatures)for(let a of i.extraFeatures)n.extraFeatures.indexOf(a)===-1&&n.extraFeatures.push(a);i.maxHeight&&(n.maxHeight=i.maxHeight),i.maxWidth&&(n.maxWidth=i.maxWidth),i.maxArea&&(n.maxArea=i.maxArea)}if(t.extraFormats)for(let i of t.extraFormats)n.extraFormats.indexOf(i)===-1&&n.extraFormats.push(i);if(t.extraFeatures)for(let i of t.extraFeatures)n.extraFeatures.indexOf(i)===-1&&n.extraFeatures.push(i);if(t.extraQualities)for(let i of t.extraQualities)n.extraQualities.indexOf(i)===-1&&n.extraQualities.push(i);return n}function ax(t){let e=Array.isArray(t.profile)?t.profile:[t.profile];for(let n of e)if(typeof n=="string"&&d1.indexOf(n)!==-1)return!0;return!1}function ke(t){if(t["@id"])return t["@id"];if(t.id)return t.id}function qf(t){if(!t||!t.profile||!ke(t))return!1;let e=Array.isArray(t.profile)?t.profile:[t.profile];for(let n of e)if(typeof n=="string"&&u1.indexOf(n)!==-1)return!0;return!1}function a_(t){if(!qf(t))return!1;let e=Array.isArray(t.profile)?t.profile:[t.profile];for(let n of e)if(typeof n=="string"){if(Wm.indexOf(n)!==-1)return!0}else{let i=[...n.supports||[],...n.extraFeatures||[]];if(i.indexOf("regionByPx")!==-1&&(i.indexOf("sizeByW")!==-1||i.indexOf("sizeByWh")!==-1))return!0}return!1}function Pq({x:t=0,y:e=0,w:n,h:i,full:a,square:r,percent:l}){if(a)return"full";if(r)return"square";if(n===void 0||i===void 0)throw Error("RegionParameter: invalid region");let u=`${t},${e},${n},${i}`;return l?`pct:${u}`:u}function Bq({max:t,percentScale:e,upscaled:n,confined:i,width:a,height:r,serialiseAsFull:l,version:u}){let f=[];return n&&f.push("^"),t?(f.push(l?"full":"max"),f.join("")):(i&&f.push("!"),e&&f.push(`pct:${e}`),a&&f.push(`${a}`),f.push(","),r&&u===3&&f.push(`${r}`),f.join(""))}function Hq(t){return`${t.mirror?"!":""}${(t.angle||0)%360}`}function Hg(t,e){let n=t.prefix.startsWith("/")?t.prefix.substring(1):t.prefix,i=`${t.scheme}://${t.server}/${n?`${n}/`:""}${t.identifier}`;if(t.type==="base")return i;if(t.type==="info")return`${i}/info.json`;let{size:a}=t,{region:r,rotation:l,format:u,quality:f}=t;if(e){let h=e["@context"]?Array.isArray(e["@context"])?e["@context"]:[e["@context"]]:[],d=h.indexOf("http://iiif.io/api/image/2/context.json")!==-1,m=h.indexOf("http://iiif.io/api/image/3/context.json")!==-1;if((a.width===e.width&&!a.height||a.height===e.height&&!a.width||a.width===e.width&&a.height===e.height)&&(a={...a,max:!0}),d&&(a.max&&!a.serialiseAsFull&&(a={...a,serialiseAsFull:!0}),!a.max&&a.width&&a.height&&(a={...a,height:void 0}),a={...a,version:2}),m){if(a.max&&a.serialiseAsFull&&(a={...a,serialiseAsFull:!1}),a.width&&!a.height&&e.width&&e.height){let y=e.height/e.width;a={...a,height:Math.ceil(a.width*y)}}a={...a,version:3}}}return[i,Pq(r),Bq(a),Hq(l),`${f}.${u}`].filter(Boolean).join("/")}function ys(t){return t.endsWith("info.json")?t:t.endsWith("/")?`${t}info.json`:`${t}/info.json`}function Fg(t){let e=Nq(ys(t.id));if(e.type!=="info")throw Error("Invalid service URL");let n=Dq(t);return{identifier:e.identifier,originalPath:"",server:e.server,prefix:e.prefix,scheme:e.scheme,type:"image",quality:n.extraQualities.indexOf("default")===-1?n.extraQualities[0]:"default",region:{full:!0},size:{max:!0,upscaled:!1,confined:!1},format:"jpg",rotation:{angle:0}}}function r_(t,e,n){let i=n.length,a=[];for(let r=0;r<i;r++){let l=n[r];if(!l)continue;let u=l.width;a.push(t/u)}return a}function o_(t,e,n){let i=n.length,a=[];for(let r=0;r<i;r++){let l=n[r];l&&a.push({width:Math.floor(t/l),height:Math.floor(e/l)})}return a}function zc(t,e){if(e&&e.profile){let n=e.profile;if(n){let i=Array.isArray(n)?n:[n];if(i.includes(`level${t}`)||i.includes(`http://iiif.io/api/image/2/level${t}.json`)||i.includes(`http://iiif.io/api/image/1/level${t}.json`)||i.includes(`http://iiif.io/api/image/1/profiles/level${t}.json`))return!0;if(t===2){for(let a of i)if(cc.includes(a))return!0}if(t===1){for(let a of i)if(Wm.includes(a))return!0}if(t===0){for(let a of i)if(d1.includes(a))return!0}}}return!1}function qg(t){return qf(t)?zc(2,t)?2:zc(1,t)?1:zc(0,t)?0:null:null}function vs(t){let e=t.service?Array.isArray(t.service)?t.service:[t.service]:[],n=e.length,i=[];for(let a=0;a<n;a++)qf(e[a])&&i.push(e[a]);return i}function s_(t){if(t["@type"])return t["@type"];if(t.type)return t.type}function Yl(t){let e=t.replace(/(https?:\/\/)?(www.)?/i,"");return e.indexOf("/")===-1?e:e.split("/")[0]}function l_(t,e,n){let i=t>e?t:e,a=n.length,r=[];for(let l=0;l<a;l++){let u=n[l];if(!u||u.scaleFactors.length===0)continue;let f=u.scaleFactors[0];if(!f)continue;let h=i/f,d=[f];for(;h>=u.width;)f*=2,d.push(f),h/=2;r.push({...u,scaleFactors:d})}return r}function Vg(t,e,n){let i=Fg({"@context":t.version===3?"http://iiif.io/api/image/3/context.json":"http://iiif.io/api/image/2/context.json",id:ys(ke(t)),profile:t.level===null||t.level===void 0?"level0":`level${t.level}`,type:t.version===3?"ImageService3":"ImageService2"});if(i.type!=="image")throw Error("Invalid service");return i.size.max=!1,i.size.width=e,i.size.height=n,{id:Hg(i),type:"fixed",width:e,height:n||t.height/(t.width||1)*e,unsafe:t.width>e}}function u_(t,e,n){let i=t.width?t.width:t.maxWidth;return n.height<=t.maxHeight&&n.width<=t.maxWidth&&n.height>=t.minHeight&&n.width>=t.minWidth&&(!e||Math.abs(n.width-i)<Math.abs(e.width-i))}function c_(t,e){let n=[],i=Object.assign({unsafeImageService:!1,atAnyCost:!0,fallback:!0,minHeight:64,minWidth:64,maxHeight:1/0,maxWidth:1/0,returnAllOptions:!1,preferFixedSize:!1,allowUnsafe:!1,explain:!1,height:0,width:0},t),a=(d,m=0)=>i.explain?n.push(Array(m).fill(0).map(y=>" ").join("")+d().trim()):void 0,r=[],l=[],u=null;a(()=>`Using configuration: ${JSON.stringify(i,null,2)}`);let f=(d,m)=>{if(a(()=>"Swapping choice",3),u_(i,m,d)){if(i.preferFixedSize&&d.unsafe){a(()=>`We found an image that was marked as unsafe, but it was the best size. (${d.id})`,4),l.push(d);return}i.returnAllOptions&&m&&l.push(m),a(()=>`We found a new image that was the best size. (${d.id})`,4),u=d}else i.returnAllOptions&&l.push(d)};a(()=>`The input shows we have ${e.length} list(s) of candidates to choose from.`);let h=e.length;for(let d=0;d<h;d++){let m=e[d]();a(()=>`Candidate group ${d}: ${JSON.stringify(m,null,2)}`,1);let y=m.length;a(()=>`Checking candidate list number ${d} and found ${y} potential ways of creating image(s)`,1);for(let g=0;g<y;g++){let b=m[g];a(()=>`-> Checking candidate ${g}`,1),b.type==="unknown"&&i.atAnyCost&&(a(()=>`We've found an unknown image type, adding this to the "last resort" list`,2),r.push(b)),b.type==="fixed"&&(b.unsafe?(a(()=>`We've found an unsafe fixed image type, adding this to the "last resort" list`,2),r.push(b)):(a(()=>"We've found a fixed size image, checking if it matches the request",2),f(b,u))),b.type==="fixed-service"&&(i.unsafeImageService?(a(()=>"Checking for an image from the tile source, without calculating the right height and width (unsafeImageService)",2),f(Vg(b,i.width,i.height),u)):(a(()=>"Checking for an image from the tile source 3",2),f(Vg(b,b.width,b.height),u))),b.type==="variable"&&b.maxWidth&&f(Vg({id:b.id,type:"fixed-service",width:b.maxWidth,height:b.maxWidth,level:b.level,version:b.version},b.maxWidth),u)}if(u&&!i.returnAllOptions){if(u.unsafe||i.allowUnsafe)continue;a(()=>`We found a match in choice list number ${d}, no searching any more`);break}}return i.atAnyCost&&l.length===0?(a(()=>u?`We found an image! ${u.id} of type ${u.type}`:'We found no images, but "atAnyCost" is set, so returning that'),{best:u||r[0]||null,fallback:r.slice(1),log:n}):i.returnAllOptions?(a(()=>"Returning all options that we have found"),{best:(i.atAnyCost?u||l[0]||r[0]:u||l[0])||null,fallback:[...l,...r],log:n}):(a(()=>"Returning the best image that we found, and a fallback"),{best:u||l[0]||null,fallback:u?l:l.slice(1),log:n})}function sx(t){return(t["@context"]?Array.isArray(t["@context"])?t["@context"]:[t["@context"]]:[]).indexOf("http://iiif.io/api/image/3/context.json")!==-1}function d_(t){return qf(t)?(t&&t.sizes?t.sizes:[]).map(e=>({id:ke(t),type:"fixed-service",height:e.height,width:e.width,level:qg(t),version:sx(t)?3:2})):[]}function f_(t){if(!a_(t))return[];let e=[],n=Array.isArray(t.profile)?t.profile:[t.profile],i=n.length;for(let a=0;a<i;a++){let r=n[a];if(r&&typeof r!="string"&&(r.maxHeight||r.maxWidth))return[{id:ke(t),type:"variable",minWidth:0,minHeight:0,maxHeight:r.maxHeight||r.maxWidth,maxWidth:r.maxWidth||r.maxHeight,level:qg(t),version:t["@context"]==="http://iiif.io/api/image/3/context.json"?3:2}]}if(t.tiles){let a=t.tiles.length;for(let r=0;r<a;r++){let l=t.tiles[r];l&&(l.height||l.width)&&e.push({id:ke(t),type:"variable",minHeight:0,minWidth:0,maxHeight:l.height||l.width,maxWidth:l.width,level:qg(t),version:sx(t)?3:2})}}return e}function rx(t){let e=[],n=t.length;for(let i=0;i<n;i++){let a=t[i];if(!a)continue;let r=d_(a);r.length&&e.push(...r);let l=f_(a);l.length&&e.push(...l)}return e}function ox(t){let e=t.match(/^.*\/(full)\/(((\d+),(\d+)?)|max)\/(\d+)\/default\.(jpg|png|jpeg)$/);if(e&&e[4]&&e[5]){let n=e[1],i=parseInt(e[4],10),a=parseInt(e[5],10),r=e[7];if((n==="max"||n==="full")&&i&&a&&r)return{type:"fixed",id:t,height:a,width:i}}return{type:"unknown",id:t}}function Vf(t){if(typeof t=="string")return ox(t);let e=s_(t);if(e!=="Image"&&e!=="sc:Image")return null;let n=t,i=ke(n);return i?i&&n.width&&n.height?{id:i,type:"fixed",width:n.width,height:n.height,unsafe:!0}:ox(i):null}function h_(t,e=!0,n){let i=[],a=Vf(t);if(a===null)return i;let r=t;if(i.push(a),e&&r&&r.width&&r.height){let l=[],u=vs(r);for(let f of u){let h={id:ke(f),width:r.width,height:r.height};if(n.canLoadSync(h)){let d=n.loadServiceSync(h);d&&(d.height||(d.height=r.height),d.width||(d.width=r.width),l.push(...rx([d])))}}if(l.length)return i.push(...l),i}return r.service&&i.push(...rx(r.service)),i}function p_(t,e){if(t.length!==e.length)return!1;if(t.length===0&&e.length===0)return!0;let n=t.length,i=!0;for(let r=0;r<n;r++){let l=t[r],u=e[r];if(l.width!==u.width||l.height!==u.height){i=!1;break}}if(i)return!0;let a=0;for(let r=0;r<n;r++)for(let l=0;l<n;l++)if(t[r].width===e[l].width&&t[r].height===e[l].height){a++;break}return a===n}var Ic=class{constructor(t={}){kn(this,"config",{verificationsRequired:1,approximateServices:!1,enableFetching:!0,disableThrottling:!1}),kn(this,"fetchingCount",0),kn(this,"imageServices",{}),kn(this,"knownImageServers",{}),this.config=Object.assign(this.config,t)}setConfig(t){Object.assign(this.config,t)}sample(t,e,n=!0){let i=Yl(ke(t)),a=ys(ke(t)),r=this.knownImageServers[i];return this.imageServices[a]=Object.assign(t,{real:!0}),!r&&t.tiles&&!ax(t)?(this.knownImageServers[i]={verifications:0,malformed:!1,root:i,preLoaded:n,sampledId:ke(t),verified:!1,server:null,result:{context:t["@context"]||[],sampledProfile:t.profile,resourceServiceRatio:e&&t.height?e.height/t.height:1,sampledSizes:t.sizes||[],sizeRatios:r_(t.width,t.height,t.sizes||[]),sampledTiles:t.tiles||[]}},!0):this.verify(t)}preLoad(t,e=!0){this.knownImageServers[t.root]=t,e&&(this.knownImageServers[t.root].malformed=!1,this.knownImageServers[t.root].verifications=this.config.verificationsRequired)}predict(t,e=!1,n=!1){let i=t?.source,a=Yl(ke(t)),r=this.knownImageServers[a],l=ys(ke(t));return this.imageServices[l]?this.imageServices[l]||null:!this.config.approximateServices||!r||!r.result||!(i?.height||t.height)||!(i?.width||t.width)||!n&&(r.malformed||r.verifications<this.config.verificationsRequired)||t.source&&ax(t.source)?null:(this.imageServices[l]||(this.imageServices[l]={"@context":r.result.context,"@id":ke(t),id:ke(t),protocol:"http://iiif.io/api/image",tiles:i?.tiles||l_(t.width,t.height,r.result.sampledTiles),sizes:i?.sizes||o_(Math.round(t.width/r.result.resourceServiceRatio),Math.round(t.height/r.result.resourceServiceRatio),r.result.sizeRatios),profile:i?.profile||r.result.sampledProfile,height:i?.height||t.height,width:i?.width||t.width,real:!1}),this.imageServices[l]||null)}async getThumbnailFromResource(t,e,n=!0,i=[]){let a=t?await this.getImageCandidates(t,n):[];return c_(e,[()=>i,()=>a])}async getImageCandidates(t,e=!0){let n=t;if(e&&n&&n.height&&n.width){let i=vs(n);for(let a of i){let r={id:ke(a),width:a.width?a.width:n.width,height:a.height?a.height:n.height,source:a};await this.loadService(r)}}return h_(t,e,this)}async verify(t){let e=this.predict(t,!1,!0),n=await this.fetchService(ke(t));if(!e)return!1;let i=e.height===n.height&&e.width===n.width&&e["@context"]===n["@context"]&&p_(e.sizes||[],n.sizes||[]);if(i){let a=Yl(ke(t)),r=this.knownImageServers[a];r&&(r.verifications+=1,r.verifications>=this.config.verificationsRequired&&(r.verified=!0))}return i}canLoadSync(t){let e=typeof t=="string"?t:ke(t),n=ys(e);if(this.imageServices[n])return!0;let i=this.knownImageServers[Yl(e)];return!!(i&&!i.malformed&&i.verifications>=this.config.verificationsRequired)}async markAsMalformed(t){return this.knownImageServers[Yl(ke(t))].malformed=!0,this.loadService(t,!0)}async fetchService(t,e=!1){let n=ys(t),i=this.imageServices[n];if(i&&(!e||i.real))return i;if(!this.config.enableFetching)throw Error("Fetching is not enabled");let a=await this.fetch(n).then(r=>r.json());return!a.id&&a["@id"]&&(a.id=a["@id"]),a.id!==t&&(a.id=t,a["@id"]&&(a["@id"]=t)),this.imageServices[n]=Object.assign(a,{real:!0}),this.imageServices[n]}async fetch(t,e){return fetch(t,e)}async loadService(t,e=!1){if(!this.config.disableThrottling){let a=!0;for(;a;)if(this.fetchingCount>=this.config.verificationsRequired)await new Promise(r=>setTimeout(r,500));else{a=!1;break}}let n=this.knownImageServers[Yl(ke(t))];if(n&&!n.malformed&&!e){await n.result;let a=this.loadServiceSync(t);if(a)return a}this.fetchingCount++;let i=await this.fetchService(ke(t),e);return this.fetchingCount--,i.real&&this.sample(i,t),i}loadServiceSync(t){let e=ys(ke(t));return this.imageServices[e]?this.imageServices[e]:this.config.approximateServices?this.predict(t):null}};function m_(t={}){let e=t.events||Km(),n=t.loader||new Ic;return{store:Qm((i,a)=>({loaded:{},loadServiceSync:(r,l,u)=>{let f=r.id||r["@id"],h=a().loaded[f];if(h&&h.status==="done")return h.service;if(h&&h.status==="loading")return null;if(h&&h.status==="error")throw Error("Failed to load image service");let d={id:ke(r),width:r.width||l?.width||0,height:r.height||l?.height||0,source:r},m=n.loadServiceSync(d);return m?(i(y=>({loaded:{...y.loaded,[f]:{status:"done",service:m,real:!0}}})),e.emit("image-service.loaded",{id:f,service:m})):u&&a().loadService(r,l).then(()=>{}),m},loadService:async(r,l)=>{let u=r.id||r["@id"],f=a().loaded[u];if(f&&f.status==="done")return f.service;if(f&&f.status==="loading")return new Promise((h,d)=>{let m=y=>{y.id===u&&(e.off("image-service.loaded",m),h(y.service||r))};e.on("image-service.loaded",m)});if(f&&f.status==="error"&&!l?.force)throw Error("Failed to load image service");e.emit("image-service.loading",{id:u});try{let h={id:ke(r),width:r.width||0,height:r.height||0,source:r},d=await n.loadService(h,l?.force);return i(m=>({loaded:{...m.loaded,[u]:{status:"done",service:d,real:d.real}}})),e.emit("image-service.loaded",{id:u,service:d}),d}catch(h){throw e.emit("image-service.error",{id:u,error:h}),h}}})),events:e}}var lx=m_();var g_=new Ic;function ux(t=go,e={}){let n=e.imageServiceLoader||g_;async function i(a,r,l=!1,u=[],f){let h=()=>n.getThumbnailFromResource(void 0,r,l,u);if(!a)return await n.getThumbnailFromResource(void 0,r,l,u);if(typeof a=="string"){let m=Vf(a);return m&&u.push(m),await n.getThumbnailFromResource(void 0,r,l,u)}let d=t.get(a,{skipSelfReturn:!1});if(typeof d=="string")return{best:Vf(d),fallback:[],log:[]};if(!d)return await h();switch(await(async m=>{if(m&&m.thumbnail&&m.thumbnail.length){let y=t.get(m.thumbnail[0]),g=await n.getImageCandidates(y,l);g&&g.length&&u.push(...g)}})(d),d.type){case"Annotation":{let m=Array.isArray(d.body)?d.body:[d.body],y=t.get(m[0]);return f&&!y.width&&(y.width=f.width,y.height=f.height),await n.getThumbnailFromResource(y,r,l,u)}case"Canvas":{let m=d;return i(m.items[0],r,l,u,{width:m.width,height:m.height})}case"AnnotationPage":return i(d.items[0],r,l,u,f);case"Choice":{let m=d;return!m.items||m.items[0]?await h():i(m.items[0],r,l,u,f)}case"Collection":{let m=d.items[0];return m?i(m,r,l,u,f):await h()}case"Manifest":{let m=d.items[0];return m?i(m,r,l,u,f):await h()}case"SpecificResource":case"Image":case"Dataset":case"Sound":case"Text":case"TextualBody":case"Video":return f&&!d.width&&(d.width=f.width,d.height=f.height),n.getThumbnailFromResource(d,r,l,u)}return await h()}return{getBestThumbnailAtSize:i}}var Fv=I(ut(),1),k=I(ut(),1);var ba=I(ut(),1);function y_(t,e){let n;return(...i)=>{window.clearTimeout(n),n=window.setTimeout(()=>t(...i),e)}}function cx({debounce:t,scroll:e,polyfill:n,offsetSize:i}={debounce:0,scroll:!1,offsetSize:!1}){let a=n||(typeof window>"u"?class{}:window.ResizeObserver);if(!a)throw new Error("This browser does not support ResizeObserver out of the box. See: https://github.com/react-spring/react-use-measure/#resize-observer-polyfills");let[r,l]=(0,ba.useState)({left:0,top:0,width:0,height:0,bottom:0,right:0,x:0,y:0}),u=(0,ba.useRef)({element:null,scrollContainers:null,resizeObserver:null,lastBounds:r,orientationHandler:null}),f=t?typeof t=="number"?t:t.scroll:null,h=t?typeof t=="number"?t:t.resize:null,d=(0,ba.useRef)(!1);(0,ba.useEffect)(()=>(d.current=!0,()=>void(d.current=!1)));let[m,y,g]=(0,ba.useMemo)(()=>{let T=()=>{if(!u.current.element)return;let{left:S,top:R,width:A,height:M,bottom:z,right:N,x:L,y:H}=u.current.element.getBoundingClientRect(),U={left:S,top:R,width:A,height:M,bottom:z,right:N,x:L,y:H};u.current.element instanceof HTMLElement&&i&&(U.height=u.current.element.offsetHeight,U.width=u.current.element.offsetWidth),Object.freeze(U),d.current&&!Uq(u.current.lastBounds,U)&&l(u.current.lastBounds=U)};return[T,h?y_(T,h):T,f?y_(T,f):T]},[l,i,f,h]);function b(){u.current.scrollContainers&&(u.current.scrollContainers.forEach(T=>T.removeEventListener("scroll",g,!0)),u.current.scrollContainers=null),u.current.resizeObserver&&(u.current.resizeObserver.disconnect(),u.current.resizeObserver=null),u.current.orientationHandler&&("orientation"in screen&&"removeEventListener"in screen.orientation?screen.orientation.removeEventListener("change",u.current.orientationHandler):"onorientationchange"in window&&window.removeEventListener("orientationchange",u.current.orientationHandler))}function w(){u.current.element&&(u.current.resizeObserver=new a(g),u.current.resizeObserver.observe(u.current.element),e&&u.current.scrollContainers&&u.current.scrollContainers.forEach(T=>T.addEventListener("scroll",g,{capture:!0,passive:!0})),u.current.orientationHandler=()=>{g()},"orientation"in screen&&"addEventListener"in screen.orientation?screen.orientation.addEventListener("change",u.current.orientationHandler):"onorientationchange"in window&&window.addEventListener("orientationchange",u.current.orientationHandler))}let E=T=>{!T||T===u.current.element||(b(),u.current.element=T,u.current.scrollContainers=v_(T),w())};return qq(g,!!e),Fq(y),(0,ba.useEffect)(()=>{b(),w()},[e,g,y]),(0,ba.useEffect)(()=>b,[]),[E,r,m]}function Fq(t){(0,ba.useEffect)(()=>{let e=t;return window.addEventListener("resize",e),()=>void window.removeEventListener("resize",e)},[t])}function qq(t,e){(0,ba.useEffect)(()=>{if(e){let n=t;return window.addEventListener("scroll",n,{capture:!0,passive:!0}),()=>void window.removeEventListener("scroll",n,!0)}},[t,e])}function v_(t){let e=[];if(!t||t===document.body)return e;let{overflow:n,overflowX:i,overflowY:a}=window.getComputedStyle(t);return[n,i,a].some(r=>r==="auto"||r==="scroll")&&e.push(t),[...e,...v_(t.parentElement)]}var Vq=["x","y","top","bottom","left","right","width","height"],Uq=(t,e)=>Vq.every(n=>t[n]===e[n]);var W=I(Z(),1),Gh=I(I_(),1),m8=Object.create,R3=Object.defineProperty,g8=Object.getOwnPropertyDescriptor,y8=Object.getOwnPropertyNames,v8=Object.getPrototypeOf,b8=Object.prototype.hasOwnProperty,tp=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),S8=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(var a=y8(e),r=0,l=a.length,u;r<l;r++)u=a[r],!b8.call(t,u)&&u!==n&&R3(t,u,{get:(f=>e[f]).bind(null,u),enumerable:!(i=g8(e,u))||i.enumerable});return t},E3=(t,e,n)=>(n=t==null?{}:m8(v8(t)),S8(e||!t||!t.__esModule?R3(n,"default",{value:t,enumerable:!0}):n,t)),qv="onMouseDown.onMouseEnter.onMouseLeave.onMouseMove.onMouseOut.onMouseOver.onMouseUp.onTouchCancel.onTouchEnd.onTouchMove.onTouchStart.onPointerDown.onPointerMove.onPointerUp.onPointerCancel.onPointerEnter.onPointerLeave.onPointerOver.onPointerOut.onScroll.onWheel.onClick.onDragStart.onDragEnd.onDragEnter.onDragExit.onDrag.onDragOver.onContextMenu".split(".");function x8(){return qv.reduce((t,e)=>(t[e]=[],t),{})}var Rd=qv.reduce((t,e)=>(t[e.slice(2).toLowerCase()]=e,t[e]=e,t),{});function w8(t,e,n=1){let i=e.length;if(i===0)throw Error("No resources passed in.");let a=0,r=1/0;for(let l=0;l<i&&!(!e[l]||!e[l].display);l++){let u=JT(e[l].display.scale,t/(n||1));u<r&&(r=u,a=l)}return a}function JT(t,e){return Math.abs(t-e)}function Qh(t,e){let n=JT(t.x,e.x),i=JT(t.y,e.y);return Math.sqrt(n**2+i**2)}function T8(t){let e=t.length;return t.indexOf("/info.json")===e-10?t.slice(0,-10):t}function Wh(t){"@babel/helpers - typeof";return Wh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Wh(t)}function R8(t,e){if(Wh(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var i=n.call(t,e||"default");if(Wh(i)!="object")return i;throw TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function E8(t){var e=R8(t,"string");return Wh(e)=="symbol"?e:e+""}function C(t,e,n){return(e=E8(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var sR=class Mv{constructor(e,n,i){C(this,"element",void 0),C(this,"runtime",void 0),C(this,"unsubscribe",void 0),C(this,"activatedEvents",[]),C(this,"eventHandlers",[]),C(this,"bounds",void 0),C(this,"listening",void 0),C(this,"pointerMoveEvent",void 0),C(this,"pointerEventState",{isClicking:!1,isDragging:!1,isPressed:!1,mousedOver:[],itemsBeingDragged:[],mouseDownStart:{x:0,y:0},lastTouches:[]}),C(this,"options",void 0),C(this,"_realPointerMove",r=>{this.pointerMoveEvent=r}),C(this,"onWheelEvent",r=>{r.preventDefault(),this.onPointerEvent(r)}),C(this,"onContextMenu",r=>{r.preventDefault();let l="onContextMenu";if(this.runtime.world.activatedEvents.indexOf(l)!==-1){let{x:u,y:f}=this.runtime.viewerToWorld(r.clientX-this.bounds.left,r.clientY-this.bounds.top);this.assignToEvent(r,u,f),this.runtime.world.propagatePointerEvent(l,r,u,f)}}),C(this,"onTouchEvent",r=>{let l=Rd[r.type],u=[],f=r.touches.length;for(let h=0;h<f;h++){let d=r.touches.item(h);if(!d)continue;let{x:m,y}=this.runtime.viewerToWorld(d.clientX-this.bounds.left,d.clientY-this.bounds.top),g={id:d.identifier,x:m,y};u.push(g)}u.length&&this.assignToEvent(r,u[0].x,u[0].y),l!=="onTouchEnd"&&l!=="onTouchCancel"?(this.pointerEventState.lastTouches=u,r.atlasTouches=u,this.runtime.world.propagateTouchEvent(l,r,u)):(r.atlasTouches=[],this.runtime.world.propagateTouchEvent(l,r,this.pointerEventState.lastTouches),this.pointerEventState.lastTouches=[])}),C(this,"onPointerEvent",r=>{if(r.button===2)return;let l=Rd[r.type];if(l&&this.runtime.world.activatedEvents.indexOf(l)!==-1){let{x:u,y:f}=this.runtime.viewerToWorld(r.clientX-this.bounds.left,r.clientY-this.bounds.top);this.assignToEvent(r,u,f),this.runtime.world.propagatePointerEvent(l,r,u,f)}}),C(this,"onPointerDown",r=>{r.button!==2&&(this.pointerEventState.isPressed=!0,this.pointerEventState.isClicking=!0,this.pointerEventState.mouseDownStart.x=r.clientX,this.pointerEventState.mouseDownStart.y=r.clientY,setTimeout(()=>{this.runtime&&(this.pointerEventState.isClicking=!1)},250),setTimeout(()=>{if(this.runtime&&this.pointerEventState.isPressed&&!this.pointerEventState.isDragging){let l=this.runtime.viewerToWorld(this.pointerEventState.mouseDownStart.x-this.bounds.left,this.pointerEventState.mouseDownStart.y-this.bounds.top);this.pointerEventState.isDragging=!0,this.pointerEventState.itemsBeingDragged=this.runtime.world.propagatePointerEvent("onDragStart",r,l.x,l.y)}},800),this.onPointerEvent(r))}),C(this,"onPointerUp",r=>{if(r.button!==2){if(this.pointerEventState.isClicking){let{x:l,y:u}=this.runtime.viewerToWorld(r.clientX-this.bounds.left,r.clientY-this.bounds.top);this.assignToEvent(r,l,u),this.runtime.world.propagatePointerEvent("onClick",r,l,u)}if(this.pointerEventState.isDragging){for(let l of this.pointerEventState.itemsBeingDragged)l.dispatchEvent("onDragEnd",r);this.pointerEventState.isDragging=!1}this.pointerEventState.isClicking=!1,this.pointerEventState.isPressed=!1,this.pointerEventState.itemsBeingDragged=[],this.onPointerEvent(r)}}),C(this,"onPointerMove",r=>{this.pointerMoveEvent=void 0;let{x:l,y:u}=this.runtime.viewerToWorld(r.clientX-this.bounds.left,r.clientY-this.bounds.top);if(Number.isNaN(l)||Number.isNaN(u))return;this.assignToEvent(r,l,u),this.runtime.world.propagatePointerEvent("onPointerMove",r,l,u);let f=this.runtime.world.propagatePointerEvent("onMouseMove",r,l,u),h=[],d=[];for(let m of f)h.push(m.id),d.push(m),this.pointerEventState.mousedOver.indexOf(m)===-1&&(m.dispatchEvent("onMouseEnter",r),m.dispatchEvent("onPointerEnter",r),m.dispatchEvent("onMouseOver",r),m.dispatchEvent("onPointerOver",r));for(let m of this.pointerEventState.mousedOver)h.indexOf(m.id)===-1&&(m.dispatchEvent("onMouseLeave",r),m.dispatchEvent("onPointerLeave",r),m.dispatchEvent("onMouseOut",r),m.dispatchEvent("onPointerOut",r));if(this.pointerEventState.isDragging)for(let m of this.pointerEventState.itemsBeingDragged)m.dispatchEvent("onDrag",r);if(this.pointerEventState.isPressed&&!this.pointerEventState.isDragging&&Qh(this.pointerEventState.mouseDownStart,{x:r.clientX,y:r.clientY})>50){let m=this.runtime.viewerToWorld(this.pointerEventState.mouseDownStart.x-this.bounds.left,this.pointerEventState.mouseDownStart.y-this.bounds.top);this.pointerEventState.isDragging=!0,this.pointerEventState.itemsBeingDragged=this.runtime.world.propagatePointerEvent("onDragStart",{...r,atlas:{x:m.x,y:m.y}},m.x,m.y)}this.pointerEventState.mousedOver=d}),this.element=e,this.runtime=n,this.unsubscribe=n.world.addLayoutSubscriber(this.layoutSubscriber.bind(this)),this.bounds=e.getBoundingClientRect(),this.listening=!1,this.options={simulationRate:0,...i||{}};let a=0;n.registerHook("useFrame",r=>{a+=r,a>this.options.simulationRate&&this.pointerMoveEvent&&(a=0,n.updateNextFrame())}),n.registerHook("useBeforeFrame",()=>{this.pointerMoveEvent&&this.onPointerMove(this.pointerMoveEvent)}),this.activateEvents()}updateBounds(){this.bounds=this.element.getBoundingClientRect(),this.runtime.updateRendererScreenPosition()}layoutSubscriber(e){e==="event-activation"&&this.listening==0&&this.activateEvents()}assignToEvent(e,n,i){Mv.eventPool.atlas.x=n,Mv.eventPool.atlas.y=i,e.atlas=Mv.eventPool.atlas}activateEvents(){this.listening=!0,this.element.addEventListener("pointermove",this._realPointerMove),this.element.addEventListener("pointerup",this.onPointerUp),this.element.addEventListener("pointerdown",this.onPointerDown),this.element.addEventListener("mousedown",this.onPointerEvent),this.element.addEventListener("mouseup",this.onPointerEvent),this.element.addEventListener("pointercancel",this.onPointerEvent),this.element.addEventListener("wheel",this.onWheelEvent),this.element.addEventListener("contextmenu",this.onContextMenu),this.element.addEventListener("touchstart",this.onTouchEvent),this.element.addEventListener("touchcancel",this.onTouchEvent),this.element.addEventListener("touchend",this.onTouchEvent),this.element.addEventListener("touchmove",this.onTouchEvent)}normalizeEventName(e){return e.startsWith("on")?e.slice(2).toLowerCase():e.toLowerCase()}stop(){this.listening=!1,this.element.removeEventListener("pointermove",this._realPointerMove),this.element.removeEventListener("pointerup",this.onPointerUp),this.element.removeEventListener("pointerdown",this.onPointerDown),this.element.removeEventListener("mousedown",this.onPointerEvent),this.element.removeEventListener("mouseup",this.onPointerEvent),this.element.removeEventListener("pointercancel",this.onPointerEvent),this.element.removeEventListener("wheel",this.onWheelEvent),this.element.removeEventListener("touchstart",this.onTouchEvent),this.element.removeEventListener("touchcancel",this.onTouchEvent),this.element.removeEventListener("touchend",this.onTouchEvent),this.element.removeEventListener("touchmove",this.onTouchEvent),this.unsubscribe();for(let[e,n]of this.eventHandlers)this.element.removeEventListener(this.normalizeEventName(e),n)}};C(sR,"eventPool",{atlas:{x:0,y:0}});var jh=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Nv=typeof AbortController=="function"?AbortController:class{constructor(){this.signal=new A3}abort(t=Error("This operation was aborted")){this.signal.reason=this.signal.reason||t,this.signal.aborted=!0,this.signal.dispatchEvent({type:"abort",target:this.signal})}},A8=typeof AbortSignal=="function",C8=typeof Nv.AbortSignal=="function",A3=A8?AbortSignal:C8?Nv.AbortController:class{constructor(){this.reason=void 0,this.aborted=!1,this._listeners=[]}dispatchEvent(t){t.type==="abort"&&(this.aborted=!0,this.onabort(t),this._listeners.forEach(e=>e(t),this))}onabort(){}addEventListener(t,e){t==="abort"&&this._listeners.push(e)}removeEventListener(t,e){t==="abort"&&(this._listeners=this._listeners.filter(n=>n!==e))}},lR=new Set,kT=(t,e)=>{let n=`LRU_CACHE_OPTION_${t}`;Vv(n)&&uR(n,`${t} option`,`options.${e}`,Uv)},GT=(t,e)=>{let n=`LRU_CACHE_METHOD_${t}`;if(Vv(n)){let{prototype:i}=Uv,{get:a}=Object.getOwnPropertyDescriptor(i,t);uR(n,`${t} method`,`cache.${e}()`,a)}},M8=(t,e)=>{let n=`LRU_CACHE_PROPERTY_${t}`;if(Vv(n)){let{prototype:i}=Uv,{get:a}=Object.getOwnPropertyDescriptor(i,t);uR(n,`${t} property`,`cache.${e}`,a)}},C3=(...t)=>{typeof process=="object"&&process&&typeof process.emitWarning=="function"?process.emitWarning(...t):console.error(...t)},Vv=t=>!lR.has(t),uR=(t,e,n,i)=>{lR.add(t),C3(`The ${e} is deprecated. Please use ${n} instead.`,"DeprecationWarning",t,i)},Qs=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),M3=t=>Qs(t)?t<=2**8?Uint8Array:t<=2**16?Uint16Array:t<=2**32?Uint32Array:t<=2**53-1?Ov:null:null,Ov=class extends Array{constructor(t){super(t),this.fill(0)}},O8=class{constructor(t){if(t===0)return[];this.heap=new(M3(t))(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},Uv=class $T{constructor(e={}){let{max:n=0,ttl:i,ttlResolution:a=1,ttlAutopurge:r,updateAgeOnGet:l,updateAgeOnHas:u,allowStale:f,dispose:h,disposeAfter:d,noDisposeOnSet:m,noUpdateTTL:y,maxSize:g=0,maxEntrySize:b=0,sizeCalculation:w,fetchMethod:E,fetchContext:T,noDeleteOnFetchRejection:S,noDeleteOnStaleGet:R,allowStaleOnFetchRejection:A,allowStaleOnFetchAbort:M,ignoreFetchAbort:z}=e,{length:N,maxAge:L,stale:H}=e instanceof $T?{}:e;if(n!==0&&!Qs(n))throw TypeError("max option must be a nonnegative integer");let U=n?M3(n):Array;if(!U)throw Error("invalid max value: "+n);if(this.max=n,this.maxSize=g,this.maxEntrySize=b||this.maxSize,this.sizeCalculation=w||N,this.sizeCalculation){if(!this.maxSize&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw TypeError("sizeCalculation set to non-function")}if(this.fetchMethod=E||null,this.fetchMethod&&typeof this.fetchMethod!="function")throw TypeError("fetchMethod must be a function if specified");if(this.fetchContext=T,!this.fetchMethod&&T!==void 0)throw TypeError("cannot set fetchContext without fetchMethod");if(this.keyMap=new Map,this.keyList=Array(n).fill(null),this.valList=Array(n).fill(null),this.next=new U(n),this.prev=new U(n),this.head=0,this.tail=0,this.free=new O8(n),this.initialFill=1,this.size=0,typeof h=="function"&&(this.dispose=h),typeof d=="function"?(this.disposeAfter=d,this.disposed=[]):(this.disposeAfter=null,this.disposed=null),this.noDisposeOnSet=!!m,this.noUpdateTTL=!!y,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!A,this.allowStaleOnFetchAbort=!!M,this.ignoreFetchAbort=!!z,this.maxEntrySize!==0){if(this.maxSize!==0&&!Qs(this.maxSize))throw TypeError("maxSize must be a positive integer if specified");if(!Qs(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.initializeSizeTracking()}if(this.allowStale=!!f||!!H,this.noDeleteOnStaleGet=!!R,this.updateAgeOnGet=!!l,this.updateAgeOnHas=!!u,this.ttlResolution=Qs(a)||a===0?a:1,this.ttlAutopurge=!!r,this.ttl=i||L||0,this.ttl){if(!Qs(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.initializeTTLTracking()}if(this.max===0&&this.ttl===0&&this.maxSize===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.max&&!this.maxSize){let nt="LRU_CACHE_UNBOUNDED";Vv(nt)&&(lR.add(nt),C3("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",nt,$T))}H&&kT("stale","allowStale"),L&&kT("maxAge","ttl"),N&&kT("length","sizeCalculation")}getRemainingTTL(e){return this.has(e,{updateAgeOnHas:!1})?1/0:0}initializeTTLTracking(){this.ttls=new Ov(this.max),this.starts=new Ov(this.max),this.setItemTTL=(i,a,r=jh.now())=>{if(this.starts[i]=a===0?0:r,this.ttls[i]=a,a!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.isStale(i)&&this.delete(this.keyList[i])},a+1);l.unref&&l.unref()}},this.updateItemAge=i=>{this.starts[i]=this.ttls[i]===0?0:jh.now()},this.statusTTL=(i,a)=>{i&&(i.ttl=this.ttls[a],i.start=this.starts[a],i.now=e||n(),i.remainingTTL=i.now+i.ttl-i.start)};let e=0,n=()=>{let i=jh.now();if(this.ttlResolution>0){e=i;let a=setTimeout(()=>e=0,this.ttlResolution);a.unref&&a.unref()}return i};this.getRemainingTTL=i=>{let a=this.keyMap.get(i);return a===void 0?0:this.ttls[a]===0||this.starts[a]===0?1/0:this.starts[a]+this.ttls[a]-(e||n())},this.isStale=i=>this.ttls[i]!==0&&this.starts[i]!==0&&(e||n())-this.starts[i]>this.ttls[i]}updateItemAge(e){}statusTTL(e,n){}setItemTTL(e,n,i){}isStale(e){return!1}initializeSizeTracking(){this.calculatedSize=0,this.sizes=new Ov(this.max),this.removeItemSize=e=>{this.calculatedSize-=this.sizes[e],this.sizes[e]=0},this.requireSize=(e,n,i,a)=>{if(this.isBackgroundFetch(n))return 0;if(!Qs(i))if(a){if(typeof a!="function")throw TypeError("sizeCalculation must be a function");if(i=a(n,e),!Qs(i))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.addItemSize=(e,n,i)=>{if(this.sizes[e]=n,this.maxSize){let a=this.maxSize-this.sizes[e];for(;this.calculatedSize>a;)this.evict(!0)}this.calculatedSize+=this.sizes[e],i&&(i.entrySize=n,i.totalCalculatedSize=this.calculatedSize)}}removeItemSize(e){}addItemSize(e,n){}requireSize(e,n,i,a){if(i||a)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache")}*indexes({allowStale:e=this.allowStale}={}){if(this.size)for(let n=this.tail;!(!this.isValidIndex(n)||((e||!this.isStale(n))&&(yield n),n===this.head));)n=this.prev[n]}*rindexes({allowStale:e=this.allowStale}={}){if(this.size)for(let n=this.head;!(!this.isValidIndex(n)||((e||!this.isStale(n))&&(yield n),n===this.tail));)n=this.next[n]}isValidIndex(e){return e!==void 0&&this.keyMap.get(this.keyList[e])===e}*entries(){for(let e of this.indexes())this.valList[e]!==void 0&&this.keyList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield[this.keyList[e],this.valList[e]])}*rentries(){for(let e of this.rindexes())this.valList[e]!==void 0&&this.keyList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield[this.keyList[e],this.valList[e]])}*keys(){for(let e of this.indexes())this.keyList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield this.keyList[e])}*rkeys(){for(let e of this.rindexes())this.keyList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield this.keyList[e])}*values(){for(let e of this.indexes())this.valList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield this.valList[e])}*rvalues(){for(let e of this.rindexes())this.valList[e]!==void 0&&!this.isBackgroundFetch(this.valList[e])&&(yield this.valList[e])}[Symbol.iterator](){return this.entries()}find(e,n){for(let i of this.indexes()){let a=this.valList[i],r=this.isBackgroundFetch(a)?a.__staleWhileFetching:a;if(r!==void 0&&e(r,this.keyList[i],this))return this.get(this.keyList[i],n)}}forEach(e,n=this){for(let i of this.indexes()){let a=this.valList[i],r=this.isBackgroundFetch(a)?a.__staleWhileFetching:a;r!==void 0&&e.call(n,r,this.keyList[i],this)}}rforEach(e,n=this){for(let i of this.rindexes()){let a=this.valList[i],r=this.isBackgroundFetch(a)?a.__staleWhileFetching:a;r!==void 0&&e.call(n,r,this.keyList[i],this)}}get prune(){return GT("prune","purgeStale"),this.purgeStale}purgeStale(){let e=!1;for(let n of this.rindexes({allowStale:!0}))this.isStale(n)&&(this.delete(this.keyList[n]),e=!0);return e}dump(){let e=[];for(let n of this.indexes({allowStale:!0})){let i=this.keyList[n],a=this.valList[n],r=this.isBackgroundFetch(a)?a.__staleWhileFetching:a;if(r===void 0)continue;let l={value:r};if(this.ttls){l.ttl=this.ttls[n];let u=jh.now()-this.starts[n];l.start=Math.floor(Date.now()-u)}this.sizes&&(l.size=this.sizes[n]),e.unshift([i,l])}return e}load(e){this.clear();for(let[n,i]of e){if(i.start){let a=Date.now()-i.start;i.start=jh.now()-a}this.set(n,i.value,i)}}dispose(e,n,i){}set(e,n,{ttl:i=this.ttl,start:a,noDisposeOnSet:r=this.noDisposeOnSet,size:l=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:f=this.noUpdateTTL,status:h}={}){if(l=this.requireSize(e,n,l,u),this.maxEntrySize&&l>this.maxEntrySize)return h&&(h.set="miss",h.maxEntrySizeExceeded=!0),this.delete(e),this;let d=this.size===0?void 0:this.keyMap.get(e);if(d===void 0)d=this.newIndex(),this.keyList[d]=e,this.valList[d]=n,this.keyMap.set(e,d),this.next[this.tail]=d,this.prev[d]=this.tail,this.tail=d,this.size++,this.addItemSize(d,l,h),h&&(h.set="add"),f=!1;else{this.moveToTail(d);let m=this.valList[d];if(n!==m){if(this.isBackgroundFetch(m)?m.__abortController.abort(Error("replaced")):r||(this.dispose(m,e,"set"),this.disposeAfter&&this.disposed.push([m,e,"set"])),this.removeItemSize(d),this.valList[d]=n,this.addItemSize(d,l,h),h){h.set="replace";let y=m&&this.isBackgroundFetch(m)?m.__staleWhileFetching:m;y!==void 0&&(h.oldValue=y)}}else h&&(h.set="update")}if(i!==0&&this.ttl===0&&!this.ttls&&this.initializeTTLTracking(),f||this.setItemTTL(d,i,a),this.statusTTL(h,d),this.disposeAfter)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift());return this}newIndex(){return this.size===0?this.tail:this.size===this.max&&this.max!==0?this.evict(!1):this.free.length===0?this.initialFill++:this.free.pop()}pop(){if(this.size){let e=this.valList[this.head];return this.evict(!0),e}}evict(e){let n=this.head,i=this.keyList[n],a=this.valList[n];return this.isBackgroundFetch(a)?a.__abortController.abort(Error("evicted")):(this.dispose(a,i,"evict"),this.disposeAfter&&this.disposed.push([a,i,"evict"])),this.removeItemSize(n),e&&(this.keyList[n]=null,this.valList[n]=null,this.free.push(n)),this.head=this.next[n],this.keyMap.delete(i),this.size--,n}has(e,{updateAgeOnHas:n=this.updateAgeOnHas,status:i}={}){let a=this.keyMap.get(e);if(a!==void 0)if(this.isStale(a))i&&(i.has="stale",this.statusTTL(i,a));else return n&&this.updateItemAge(a),i&&(i.has="hit"),this.statusTTL(i,a),!0;else i&&(i.has="miss");return!1}peek(e,{allowStale:n=this.allowStale}={}){let i=this.keyMap.get(e);if(i!==void 0&&(n||!this.isStale(i))){let a=this.valList[i];return this.isBackgroundFetch(a)?a.__staleWhileFetching:a}}backgroundFetch(e,n,i,a){let r=n===void 0?void 0:this.valList[n];if(this.isBackgroundFetch(r))return r;let l=new Nv;i.signal&&i.signal.addEventListener("abort",()=>l.abort(i.signal.reason));let u={signal:l.signal,options:i,context:a},f=(g,b=!1)=>{let{aborted:w}=l.signal,E=i.ignoreFetchAbort&&g!==void 0;return i.status&&(w&&!b?(i.status.fetchAborted=!0,i.status.fetchError=l.signal.reason,E&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),w&&!E&&!b?d(l.signal.reason):(this.valList[n]===y&&(g===void 0?y.__staleWhileFetching?this.valList[n]=y.__staleWhileFetching:this.delete(e):(i.status&&(i.status.fetchUpdated=!0),this.set(e,g,u.options))),g)},h=g=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=g),d(g)),d=g=>{let{aborted:b}=l.signal,w=b&&i.allowStaleOnFetchAbort,E=w||i.allowStaleOnFetchRejection,T=E||i.noDeleteOnFetchRejection;if(this.valList[n]===y&&(!T||y.__staleWhileFetching===void 0?this.delete(e):w||(this.valList[n]=y.__staleWhileFetching)),E)return i.status&&y.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),y.__staleWhileFetching;if(y.__returned===y)throw g},m=(g,b)=>{this.fetchMethod(e,r,u).then(w=>g(w),b),l.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(g(),i.allowStaleOnFetchAbort&&(g=w=>f(w,!0)))})};i.status&&(i.status.fetchDispatched=!0);let y=new Promise(m).then(f,h);return y.__abortController=l,y.__staleWhileFetching=r,y.__returned=null,n===void 0?(this.set(e,y,{...u.options,status:void 0}),n=this.keyMap.get(e)):this.valList[n]=y,y}isBackgroundFetch(e){return e&&typeof e=="object"&&typeof e.then=="function"&&Object.prototype.hasOwnProperty.call(e,"__staleWhileFetching")&&Object.prototype.hasOwnProperty.call(e,"__returned")&&(e.__returned===e||e.__returned===null)}async fetch(e,{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,ttl:r=this.ttl,noDisposeOnSet:l=this.noDisposeOnSet,size:u=0,sizeCalculation:f=this.sizeCalculation,noUpdateTTL:h=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:m=this.allowStaleOnFetchRejection,ignoreFetchAbort:y=this.ignoreFetchAbort,allowStaleOnFetchAbort:g=this.allowStaleOnFetchAbort,fetchContext:b=this.fetchContext,forceRefresh:w=!1,status:E,signal:T}={}){if(!this.fetchMethod)return E&&(E.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:a,status:E});let S={allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:a,ttl:r,noDisposeOnSet:l,size:u,sizeCalculation:f,noUpdateTTL:h,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:m,allowStaleOnFetchAbort:g,ignoreFetchAbort:y,status:E,signal:T},R=this.keyMap.get(e);if(R===void 0){E&&(E.fetch="miss");let A=this.backgroundFetch(e,R,S,b);return A.__returned=A}else{let A=this.valList[R];if(this.isBackgroundFetch(A)){let H=n&&A.__staleWhileFetching!==void 0;return E&&(E.fetch="inflight",H&&(E.returnedStale=!0)),H?A.__staleWhileFetching:A.__returned=A}let M=this.isStale(R);if(!w&&!M)return E&&(E.fetch="hit"),this.moveToTail(R),i&&this.updateItemAge(R),this.statusTTL(E,R),A;let z=this.backgroundFetch(e,R,S,b),N=z.__staleWhileFetching!==void 0,L=N&&n;return E&&(E.fetch=N&&M?"stale":"refresh",L&&M&&(E.returnedStale=!0)),L?z.__staleWhileFetching:z.__returned=z}}get(e,{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,status:r}={}){let l=this.keyMap.get(e);if(l!==void 0){let u=this.valList[l],f=this.isBackgroundFetch(u);return this.statusTTL(r,l),this.isStale(l)?(r&&(r.get="stale"),f?(r&&(r.returnedStale=n&&u.__staleWhileFetching!==void 0),n?u.__staleWhileFetching:void 0):(a||this.delete(e),r&&(r.returnedStale=n),n?u:void 0)):(r&&(r.get="hit"),f?u.__staleWhileFetching:(this.moveToTail(l),i&&this.updateItemAge(l),u))}else r&&(r.get="miss")}connect(e,n){this.prev[n]=e,this.next[e]=n}moveToTail(e){e!==this.tail&&(e===this.head?this.head=this.next[e]:this.connect(this.prev[e],this.next[e]),this.connect(this.tail,e),this.tail=e)}get del(){return GT("del","delete"),this.delete}delete(e){let n=!1;if(this.size!==0){let i=this.keyMap.get(e);if(i!==void 0)if(n=!0,this.size===1)this.clear();else{this.removeItemSize(i);let a=this.valList[i];this.isBackgroundFetch(a)?a.__abortController.abort(Error("deleted")):(this.dispose(a,e,"delete"),this.disposeAfter&&this.disposed.push([a,e,"delete"])),this.keyMap.delete(e),this.keyList[i]=null,this.valList[i]=null,i===this.tail?this.tail=this.prev[i]:i===this.head?this.head=this.next[i]:(this.next[this.prev[i]]=this.next[i],this.prev[this.next[i]]=this.prev[i]),this.size--,this.free.push(i)}}if(this.disposed)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift());return n}clear(){for(let e of this.rindexes({allowStale:!0})){let n=this.valList[e];if(this.isBackgroundFetch(n))n.__abortController.abort(Error("deleted"));else{let i=this.keyList[e];this.dispose(n,i,"delete"),this.disposeAfter&&this.disposed.push([n,i,"delete"])}}if(this.keyMap.clear(),this.valList.fill(null),this.keyList.fill(null),this.ttls&&(this.ttls.fill(0),this.starts.fill(0)),this.sizes&&this.sizes.fill(0),this.head=0,this.tail=0,this.initialFill=1,this.free.length=0,this.calculatedSize=0,this.size=0,this.disposed)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift())}get reset(){return GT("reset","clear"),this.clear}get length(){return M8("length","size"),this.size}static get AbortController(){return Nv}static get AbortSignal(){return A3}},_8=Uv,jv=(t=21)=>{let e="",n=crypto.getRandomValues(new Uint8Array(t));for(;t--;)e+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[n[t]&63];return e},Yr=class{get crop(){return this._crop}set crop(t){this._crop=t}getObjectsAt(t){return[]}getAllPointsAt(t,e,n){return[]}getScheduledUpdates(t,e){return[]}constructor(){C(this,"__id",void 0),C(this,"__revision",0),C(this,"__host",void 0),C(this,"__onCreate",void 0),C(this,"__parent",void 0),C(this,"__owner",{value:void 0}),C(this,"__state",{}),C(this,"eventHandlers",void 0),C(this,"scale",1),C(this,"layers",[]),C(this,"time",[]),C(this,"_crop",void 0),C(this,"cropData",void 0),C(this,"id",void 0),C(this,"addEventListener",(t,e,n)=>{let i=Rd[t];if(!this.eventHandlers[i])throw Error(`Unknown event ${i}`);this.eventHandlers[i].indexOf(e)===-1&&this.eventHandlers[i].push(e)}),C(this,"removeEventListener",(t,e)=>{let n=Rd[t];if(!this.eventHandlers[n]){console.warn(`Unknown event ${n}`);return}this.eventHandlers[n].indexOf(e)!==-1&&(this.eventHandlers[n]=this.eventHandlers[n].filter(i=>i!==e))}),this.id=this.__id=jv(),this.eventHandlers=x8()}dispatchEvent(t,e){let n=this.eventHandlers[t],i=n?n.length:0,a=!1;if(i)for(let r=0;r<i;r++)try{n[r]?.(e),a=!0}catch(l){console.error(t,l)}return a}get x(){return this.points[1]}get y(){return this.points[2]}get width(){return this.points[3]-this.points[1]}get height(){return this.points[4]-this.points[2]}translate(t,e){hr(this.points,ci(t,e))}atScale(t){hr(this.points,kl(t,this.x,this.y)),this.scale*=t}transform(t){hr(this.points,t)}applyProps(t){this.__revision++}appendChild(t){}removeChild(t){}insertBefore(t,e){}hideInstance(){}},gv=/([0-9]+(px|em)\s+)+(solid)\s+(.*)/g,yv={},z8=["backgroundColor","opacity","boxShadow","borderColor","borderWidth","borderStyle","outlineColor","outlineWidth","outlineOffset","outlineStyle"],Td=class extends Yr{constructor(){super(),C(this,"id",void 0),C(this,"type","spacial-content"),C(this,"points",void 0),C(this,"hoverEvents",!1),C(this,"activeEvents",!1),C(this,"display",{x:0,y:0,scale:1,width:-1,height:-1,points:It(5)}),C(this,"_parsed",{border:{id:null,match:[]},outline:{id:null,match:[]}}),C(this,"hovering",void 0),C(this,"pressing",void 0),C(this,"props",{}),C(this,"addHover",()=>{this.hovering=!0,this.__revision++}),C(this,"removeHover",()=>{this.hovering=!1,this.pressing=!1,this.__revision++}),C(this,"addPress",()=>{this.pressing=!0,this.__revision++}),C(this,"removePress",()=>{this.pressing=!1,this.__revision++}),this.id=jv(12),this.points=It(5)}getAllPointsAt(t,e){return[[this,this.points,e]]}applyProps(t={}){let e=!1;if(t.interactive!==this.props.interactive&&(e=!0,this.props.interactive=t.interactive),t.style){let n=t.border||t.style.border;if(n!==this._parsed.border.id)if(!n)this._parsed.border.id=null,this._parsed.border.match=[];else{let i=yv[n]||gv.exec(n)||gv.exec(n);i&&(this._parsed.border.id=n,this._parsed.border.match=yv[n]=i)}if(this._parsed.border.id&&(t.style.borderWidth=this._parsed.border.match[1],t.style.borderStyle="solid",t.style.borderColor=this._parsed.border.match[4]),t.style.outline!==this._parsed.outline.id)if(!t.style.outline)this._parsed.outline.id=null,this._parsed.outline.match=[];else{let i=yv[t.style.outline]||gv.exec(t.style.outline)||gv.exec(t.style.outline);i&&(this._parsed.outline.id=t.style.outline,this._parsed.outline.match=yv[t.style.outline]=i)}this._parsed.outline.id&&(t.style.outlineWidth=this._parsed.outline.match[1],t.style.outlineStyle="solid",t.style.outlineColor=this._parsed.outline.match[4]),this.props.style=t.style,t.backgroundColor&&!this.props.style.backgroundColor&&(this.props.style.backgroundColor=t.backgroundColor,e=!0),t.style.background&&!this.props.style.backgroundColor&&(this.props.style.backgroundColor=t.style.background,e=!0);for(let i of z8)if(this.props.style[i]!==t.style[i]){e=!0;break}t.style[":hover"]!==this.props.hoverStyles&&(this.props.hoverStyles=t.style[":hover"],this.hoverEvents||(this.hoverEvents=!0,this.addEventListener("pointerenter",this.addHover),this.addEventListener("pointerleave",this.removeHover)),e=!0),t.style[":active"]!==this.props.pressStyles&&(this.props.pressStyles=t.style[":active"],this.activeEvents||(this.activeEvents=!0,this.addEventListener("mousedown",this.addPress),this.addEventListener("mouseup",this.removePress)),e=!0)}t.href!==this.props.href&&(this.props.href=t.href,e=!0),t.hrefTarget!==this.props.hrefTarget&&(this.props.hrefTarget=t.hrefTarget,e=!0),t.title!==this.props.title&&(this.props.title=t.title,e=!0),t.className!==this.props.className&&(this.props.className=t.className,t.className&&!this.hoverEvents&&(this.hoverEvents=!0,this.addEventListener("pointerenter",this.addHover),this.addEventListener("pointerleave",this.removeHover)),t.className&&!this.activeEvents&&(this.activeEvents=!0,this.addEventListener("mousedown",this.addPress),this.addEventListener("mouseup",this.removePress)),e=!0),t.relativeSize!==this.props.relativeSize&&(this.props.relativeSize=t.relativeSize,e=!0),t.relativeStyle!==this.props.relativeStyle&&(this.props.relativeStyle=t.relativeStyle,e=!0),t.html!==this.props.html&&(this.props.html=t.html,e=!0),t.target&&(t.target.width!==this.display.width||t.target.height!==this.display.height||t.target.x!==this.points[1]||t.target.y!==this.points[2])&&(e=!0,this.points=de.singleBox(t.target.width,t.target.height,t.target.x,t.target.y),this.display.points=de.singleBox(t.target.width,t.target.height,t.target.x,t.target.y),this.display.width=t.target.width,this.display.height=t.target.height),e&&this.__revision++}},vv=/([0-9]+(px|em)\s+)+(solid)\s+(.*)/g,bv={},I8=["backgroundColor","opacity","boxShadow","borderColor","borderWidth","borderStyle","outlineColor","outlineWidth","outlineOffset","outlineStyle"],cR=class extends Yr{constructor(){super(),C(this,"id",void 0),C(this,"type","spacial-content"),C(this,"isShape",!0),C(this,"points",void 0),C(this,"hoverEvents",!1),C(this,"activeEvents",!1),C(this,"display",{x:0,y:0,scale:1,width:-1,height:-1,points:It(5)}),C(this,"boundingBox",null),C(this,"_parsed",{border:{id:null,match:[]},outline:{id:null,match:[]}}),C(this,"hovering",void 0),C(this,"pressing",void 0),C(this,"props",{}),C(this,"shape",{type:"none"}),C(this,"addHover",()=>{this.hovering=!0,this.__revision++}),C(this,"removeHover",()=>{this.hovering=!1,this.pressing=!1,this.__revision++}),C(this,"addPress",()=>{this.pressing=!0,this.__revision++}),C(this,"removePress",()=>{this.pressing=!1,this.__revision++}),this.id=jv(12),this.points=It(5),this.shape={type:"none"}}updateBoundingBox(){if(this.shape.type==="none")return;let t=this.shape.points;if(this.shape.points.length>2){let e=Math.min(...t.map(r=>r[0])),n=Math.min(...t.map(r=>r[1])),i=Math.max(0,...t.map(r=>r[0])),a=Math.max(0,...t.map(r=>r[1]));this.boundingBox={x:e,y:n,width:i-e,height:a-n};return}this.boundingBox=null}intersects(t){if(!t||this.shape.type==="none")return!1;let[e,n]=t,i=this.shape.points,a=this.boundingBox;if(a||(this.updateBoundingBox(),a=this.boundingBox),!a||e<a.x||e>a.x+a.width||n<a.y||n>a.height+a.y)return!1;let r=!1;for(let l=0,u=i.length-1;l<i.length;u=l++)i[l][1]>n!=i[u][1]>n&&e<(i[u][0]-i[l][0])*(n-i[l][1])/(i[u][1]-i[l][1])+i[l][0]&&(r=!r);return r}getAllPointsAt(t,e){return t[3]-t[1]===1&&t[4]-t[2]===1?this.intersects([t[1],t[2]])?[[this,this.points,e]]:[]:[[this,this.points,e]]}applyProps(t={}){let e=!1;if(t.points)if(this.shape.type!=="polygon"||this.shape.points.length!==t.points.length)this.shape={type:"polygon",points:t.points,open:t.open},this.updateBoundingBox();else{let n=!1,i=t.points.length;for(let a=0;a<i;a++)if(t.points[a][0]!==this.shape.points[a][0]||t.points[a][1]!==this.shape.points[a][1]){n=!0;break}n&&(this.shape={type:"polygon",points:t.points,open:t.open},this.updateBoundingBox())}if(t.interactive!==this.props.interactive&&(e=!0,this.props.interactive=t.interactive),(t.open||t.open===!1)&&(e=!0,this.shape.open=t.open),t.style){let n=t.border||t.style.border;if(n!==this._parsed.border.id)if(!n)this._parsed.border.id=null,this._parsed.border.match=[];else{let i=bv[n]||vv.exec(n)||vv.exec(n);i&&(this._parsed.border.id=n,this._parsed.border.match=bv[n]=i)}if(this._parsed.border.id&&(t.style.borderWidth=this._parsed.border.match[1],t.style.borderStyle="solid",t.style.borderColor=this._parsed.border.match[4]),t.style.outline!==this._parsed.outline.id)if(!t.style.outline)this._parsed.outline.id=null,this._parsed.outline.match=[];else{let i=bv[t.style.outline]||vv.exec(t.style.outline)||vv.exec(t.style.outline);i&&(this._parsed.outline.id=t.style.outline,this._parsed.outline.match=bv[t.style.outline]=i)}this._parsed.outline.id&&(t.style.outlineWidth=this._parsed.outline.match[1],t.style.outlineStyle="solid",t.style.outlineColor=this._parsed.outline.match[4]),this.props.style=t.style,t.backgroundColor&&!this.props.style.backgroundColor&&(this.props.style.backgroundColor=t.backgroundColor,e=!0),t.style.background&&!this.props.style.backgroundColor&&(this.props.style.backgroundColor=t.style.background,e=!0);for(let i of I8)if(this.props.style[i]!==t.style[i]){e=!0;break}t.style[":hover"]!==this.props.hoverStyles&&(this.props.hoverStyles=t.style[":hover"],this.hoverEvents||(this.hoverEvents=!0,this.addEventListener("pointerenter",this.addHover),this.addEventListener("pointerleave",this.removeHover)),e=!0),t.style[":active"]!==this.props.pressStyles&&(this.props.pressStyles=t.style[":active"],this.activeEvents||(this.activeEvents=!0,this.addEventListener("mousedown",this.addPress),this.addEventListener("mouseup",this.removePress)),e=!0)}t.href!==this.props.href&&(this.props.href=t.href,e=!0),t.hrefTarget!==this.props.hrefTarget&&(this.props.hrefTarget=t.hrefTarget,e=!0),t.title!==this.props.title&&(this.props.title=t.title,e=!0),t.className!==this.props.className&&(this.props.className=t.className,t.className&&!this.hoverEvents&&(this.hoverEvents=!0,this.addEventListener("pointerenter",this.addHover),this.addEventListener("pointerleave",this.removeHover)),t.className&&!this.activeEvents&&(this.activeEvents=!0,this.addEventListener("mousedown",this.addPress),this.addEventListener("mouseup",this.removePress)),e=!0),t.relativeSize!==this.props.relativeSize&&(this.props.relativeSize=t.relativeSize,e=!0),t.relativeStyle!==this.props.relativeStyle&&(this.props.relativeStyle=t.relativeStyle,e=!0),t.html!==this.props.html&&(this.props.html=t.html,e=!0),t.target&&(t.target.width!==this.display.width||t.target.height!==this.display.height||t.target.x!==this.points[1]||t.target.y!==this.points[2])&&(e=!0,this.points=de.singleBox(t.target.width,t.target.height,t.target.x,t.target.y),this.display.points=de.singleBox(t.target.width,t.target.height,t.target.x,t.target.y),this.display.width=t.target.width,this.display.height=t.target.height),e&&this.__revision++}},gi=class tR extends Yr{constructor(e){if(super(),C(this,"type","spacial-content"),C(this,"id",void 0),C(this,"uri",void 0),C(this,"display",void 0),C(this,"points",void 0),C(this,"priority",void 0),C(this,"style",{opacity:1}),!e)this.id="",this.uri="",this.display={x:0,y:0,scale:1,width:0,height:0,points:It(5)},this.points=It(5);else{let n=e.scale||1;this.id=e.id||e.uri,this.uri=e.uri,this.points=de.singleBox(e.width,e.height,e.x,e.y),this.display={x:0,y:0,scale:n,width:e.width/n,height:e.height/n,points:de.singleBox(e.width/n,e.height/n),rotation:e?.rotation}}}applyProps(e){let n=e.display?e.display.width:e.target.width,i=e.target.width/n;if(this.id=e.id||e.uri,this.uri=e.uri,this.points.set(de.singleBox(e.target.width,e.target.height,e.target.x,e.target.y)),e.style&&e.style.opacity!==void 0&&(this.style.opacity=e.style.opacity),e.crop){this.cropData=e.crop;let a=de.singleBox(e.crop.width,e.crop.height,e.crop.x,e.crop.y);hr(a,ci(-e.crop.x,-e.crop.y)),this.crop?this.crop.set(a):this.crop=It(a)}e.display?(this.display.scale=i,this.display.width=e.display.width,this.display.height=e.display.height,this.display.rotation=e.display.rotation,this.display.points=de.singleBox(e.display.width,e.display.height)):(this.display.scale=i,this.display.width=e.target.width/i,this.display.height=e.target.height/i,this.display.points=de.singleBox(e.target.width/i,e.target.height/i))}getAllPointsAt(e,n,i){return[[this,this.crop||this.points,n]]}static fromSvg(e,n,i,a){return tR.fromImage("data:image/svg+xml;base64,"+btoa(e),n,i,a)}static fromImage(e,n,i,a){let r=new tR;return r.applyProps({uri:e,id:a,display:i,target:n}),r}getImageUrl(){return this.uri}};function Sv(t,e,n){return Math.min(Math.max(t,e),n)}var Ri=class O3 extends Yr{constructor(e){super(),C(this,"id",void 0),C(this,"type","spacial-content"),C(this,"display",void 0),C(this,"tileWidth",void 0),C(this,"tileHeight",void 0),C(this,"columns",void 0),C(this,"rows",void 0),C(this,"style",{opacity:1}),C(this,"points",void 0),C(this,"service",void 0),C(this,"format","jpg"),C(this,"crop2",void 0),C(this,"version3",void 0),C(this,"tileUrl",void 0),this.tileUrl=T8(e.url),this.id=e.id||`${this.tileUrl}--${e.scaleFactor}--${e.tileWidth}x${e.tileHeight}`,this.points=e.displayPoints?e.displayPoints:Xi(e.points,mo(e.scaleFactor)),this.tileWidth=e.tileWidth,this.tileHeight=e.tileHeight,this.columns=e.columns,this.rows=e.rows,this.version3=e.version3,this.display={x:0,y:0,width:e.width/e.scaleFactor,height:e.height/e.scaleFactor,points:e.points,scale:e.scaleFactor},e.format&&(this.format=e.format)}applyProps(e){if(e.style&&e.style.opacity!==void 0&&(this.style.opacity=e.style.opacity),e.service!==this.service&&(this.service=e.service),e.format?this.format=e.format:this.format="jpg",e.version3!==void 0&&(this.version3=e.version3),e.crop){this.cropData=e.crop;let n=It([...this.points]),i=n.length/5,a=e.crop.x||0,r=e.crop.y||0,l=e.crop.x+e.crop.width,u=e.crop.y+e.crop.height;for(let f=0;f<i;f++){let h=f*5;n[h+1]<l&&n[h+3]>a&&n[h+2]<u&&n[h+4]>r?(n[h+1]=Sv(n[h+1],a,l),n[h+3]=Sv(n[h+3],a,l),n[h+2]=Sv(n[h+2],r,u),n[h+4]=Sv(n[h+4],r,u)):n[h]=0}hr(n,ci(-e.crop.x,-e.crop.y)),this.crop?this.crop.set(n):this.crop=n}}static fromTile(e,n,i,a,r,l,u,f){let h=i.height?i.height:i.width,d=u?Math.floor(n.width/a):Math.ceil(n.width/a),m=u?Math.floor(n.height/a):Math.ceil(n.height/a),y=Math.ceil(d/i.width),g=Math.ceil(m/h),b=de.grid(y,g),w=de.grid(y,g),E=r&&r["@context"]?Array.isArray(r["@context"])?r["@context"]:[r["@context"]]:[],T=f===void 0?E.indexOf("http://iiif.io/api/image/3/context.json")!==-1:f;for(let R=0;R<g;R++)for(let A=0;A<y;A++){let M=A*i.width,z=R*h;w.addPoints(M*a,z*a,A===y-1?n.width:(M+i.width)*a,R===g-1?n.height:(z+h)*a),b.addPoints(M,z,A===y-1?d:M+i.width,R===g-1?m:z+h)}let S=new O3({url:e,scaleFactor:a,points:b.build(),displayPoints:w.build(),width:n.width,height:n.height,tileWidth:i.width,tileHeight:h,columns:y,rows:g,format:l,version3:T});return S.applyProps({service:r}),S}getImageUrl(e){let n=this.points.slice(e*5,e*5+5),i=n[3]-n[1],a=n[4]-n[2],r=Math.ceil(i/this.display.scale),l=Math.ceil(a/this.display.scale),u=`${r>this.tileWidth?this.tileWidth:r},`;return this.version3&&(u+=`${l>this.tileHeight?this.tileHeight:l}`),`${this.tileUrl}/${n[1]},${n[2]},${i},${a}/${u}/0/default.${this.format||"jpg"}`}getAllPointsAt(e,n,i){let a=Oc(this.crop||this.points,e);return[[this,a,n]]}transform(e){hr(this.points,e)}getScheduledUpdates(e,n){return[]}};function _3(t,e,n){if(!e||e[0]===0)return null;let i=t[3]-t[1],a=t[4]-t[2],r=e[3]-e[1],l=e[4]-e[2],u=i<r,f=a<l,h=e[1]+r/2-i/2,d=e[2]+l/2-a/2;return{minX:u?e[1]-n:h,maxX:u?e[3]-i+n:h,minY:f?e[2]-n:d,maxY:f?e[4]-a+n:d}}function z3(t){if(!t.enableFilters||!t.filters.brightness&&!t.filters.contrast&&!t.filters.grayscale&&!t.filters.invert&&!t.filters.sepia&&!t.filters.saturate&&!t.filters.hueRotate&&!t.filters.blur)return"none";let e="";return t.filters.brightness&&(e+=`brightness(${~~(100+t.filters.brightness*100)}%) `),t.filters.contrast&&(e+=`contrast(${~~(100+t.filters.contrast*100)}%) `),t.filters.grayscale&&(e+=`grayscale(${~~(t.filters.grayscale*100)}%) `),t.filters.invert&&(e+=`invert(${~~(t.filters.invert*100)}%) `),t.filters.sepia&&(e+=`sepia(${~~(t.filters.sepia*100)}%) `),t.filters.saturate&&(e+=`saturate(${~~(100+t.filters.saturate*100)}%) `),t.filters.hueRotate&&(e+=`hue-rotate(${t.filters.hueRotate}deg) `),t.filters.blur&&(e+=`blur(${t.filters.blur}px) `),e.trim()}function I3(t,e,n){return Math.max(e,Math.min(n,t))}function N8(){if(typeof navigator>"u")return;let t=navigator;return t.connection||t.mozConnection||t.webkitConnection}function L8(t){let e=10;return typeof navigator<"u"&&typeof navigator.hardwareConcurrency=="number"&&(e=I3(Math.round(navigator.hardwareConcurrency*.75),4,10)),t?.saveData?3:t?.effectiveType==="slow-2g"||t?.effectiveType==="2g"?2:t?.effectiveType==="3g"?Math.min(e,4):e}function D8(t,e){return e?.saveData||e?.effectiveType==="slow-2g"||e?.effectiveType==="2g"?0:e?.effectiveType==="3g"?2:Math.min(t+2,12)}function N3(t={}){let e=N8(),n=L8(e),i=typeof t.maxConcurrentRequests=="number"?Math.max(1,Math.floor(t.maxConcurrentRequests)):n;return{maxConcurrentRequests:i,maxPrefetchPerFrame:typeof t.maxPrefetchPerFrame=="number"?Math.max(0,Math.floor(t.maxPrefetchPerFrame)):D8(i,e),timeoutMs:typeof t.timeoutMs=="number"?Math.max(250,Math.floor(t.timeoutMs)):8e3,maxAttempts:typeof t.maxAttempts=="number"?Math.max(1,Math.floor(t.maxAttempts)):3,baseDelayMs:typeof t.baseDelayMs=="number"?Math.max(0,Math.floor(t.baseDelayMs)):250,maxDelayMs:typeof t.maxDelayMs=="number"?Math.max(0,Math.floor(t.maxDelayMs)):3e3,jitterRatio:typeof t.jitterRatio=="number"?I3(t.jitterRatio,0,1):.2,errorRetryIntervalMs:typeof t.errorRetryIntervalMs=="number"?Math.max(0,Math.floor(t.errorRetryIntervalMs)):3e4,revealDelayFrames:typeof t.revealDelayFrames=="number"?Math.max(0,Math.floor(t.revealDelayFrames)):1,revealBatchWindowFrames:typeof t.revealBatchWindowFrames=="number"?Math.max(0,Math.floor(t.revealBatchWindowFrames)):1,skipFadeIfLoadedWithinMs:typeof t.skipFadeIfLoadedWithinMs=="number"?Math.max(0,Math.floor(t.skipFadeIfLoadedWithinMs)):120}}function L3(t,e,n=Math.random){let i=Math.max(1,Math.floor(e)),a=t.baseDelayMs*2**(i-1),r=Math.min(t.maxDelayMs,a),l=r*t.jitterRatio;return l?Math.max(0,Math.floor(r+(n()*2-1)*l)):r}var D3=class extends Error{constructor(t="Image request cancelled",e=!0){super(t),C(this,"silent",void 0),this.name="ImageRequestCancelledError",this.silent=e}};function P3(t){return t instanceof D3}var KL=0;function P8(t){return KL+=1,`${KL}:${t}`}function B3(t){return Error(`Image load timeout: ${t}`)}function ZL(t,e){let n,i=document.createElement("img");i.decoding="async",e.crossOrigin&&(i.crossOrigin=e.crossOrigin);let a=!1;return{promise:new Promise((r,l)=>{let u=()=>{n&&clearTimeout(n),i.onload=null,i.onerror=null};i.onload=()=>{a||(a=!0,u(),r(i))},i.onerror=f=>{a||(a=!0,u(),l(f))},n=setTimeout(()=>{a||(a=!0,u(),l(B3(t)))},e.timeoutMs),i.src=t,i.complete&&i.naturalWidth>0&&(a=!0,u(),r(i))}),abort:()=>{a||(a=!0,n&&clearTimeout(n),i.onload=null,i.onerror=null,i.src="")}}}var H3=class{constructor(t){C(this,"timeoutMs",void 0),C(this,"crossOrigin",void 0),C(this,"useFetch",void 0),C(this,"cache",void 0),C(this,"inFlight",new Map),C(this,"knownConsumers",new Map),this.timeoutMs=t.timeoutMs,this.crossOrigin=t.crossOrigin,this.useFetch=!!t.useFetch&&typeof fetch<"u"&&typeof AbortController<"u",this.cache=t.cache||new Map}acquire(t,e){let n=this.cache.get(t);if(n&&n.naturalWidth>0)return{requestKey:`cached:${t}`,promise:Promise.resolve(n),release:()=>{}};let i=this.inFlight.get(t);i||(i={url:t,requestKey:P8(t),consumers:new Set,promise:Promise.resolve(document.createElement("img")),settled:!1,cancelled:!1,silentCancellation:!0},i.promise=this.createRequest(i).then(r=>(i.settled=!0,this.cache.set(t,r),r)).catch(r=>{throw i.settled=!0,i.cancelled?new D3("Image request cancelled",i.silentCancellation):r}).finally(()=>{i&&i.consumers.size===0&&this.inFlight.delete(t)}),this.inFlight.set(t,i)),i.consumers.add(e);let a=this.knownConsumers.get(e)||new Set;return a.add(t),this.knownConsumers.set(e,a),{requestKey:i.requestKey,promise:i.promise,release:r=>{this.release(t,e,r)}}}release(t,e,n={}){let i=this.knownConsumers.get(e);i&&(i.delete(t),i.size===0&&this.knownConsumers.delete(e));let a=this.inFlight.get(t);if(a&&(a.consumers.delete(e),n.silent===!1&&(a.silentCancellation=!1),!(a.consumers.size>0))){if(!a.settled){a.cancelled=!0,a.abortController&&a.abortController.abort(),a.abortDomImage&&a.abortDomImage();return}this.inFlight.delete(t)}}releaseConsumer(t,e={}){let n=this.knownConsumers.get(t);if(n)for(let i of[...n])this.release(i,t,e)}cancelAll(t={}){let e=[...this.knownConsumers.keys()];for(let n of e)this.releaseConsumer(n,t)}async createRequest(t){if(this.useFetch){let i=new AbortController;t.abortController=i;let a=setTimeout(()=>{i.abort(B3(t.url))},this.timeoutMs);try{let r=this.crossOrigin==="use-credentials"?"include":"same-origin",l=await fetch(t.url,{signal:i.signal,credentials:r});if(!l.ok)throw Error(`Image request failed (${l.status}): ${t.url}`);let u=await l.blob(),f=URL.createObjectURL(u);try{let{promise:h,abort:d}=ZL(f,{timeoutMs:this.timeoutMs,crossOrigin:void 0});return t.abortDomImage=d,await h}finally{URL.revokeObjectURL(f)}}finally{clearTimeout(a)}}let{promise:e,abort:n}=ZL(t.url,{timeoutMs:this.timeoutMs,crossOrigin:this.crossOrigin});return t.abortDomImage=n,e}},WL=/(-?[0-9]+(px|em)\s+|0\s+)(-?[0-9]+(px|em)\s+|0\s+)(-?[0-9]+(px|em)\s+|0\s+)?(-?[0-9]+(px|em)\s+|0\s+)?(.*)/g,JL={},B8=typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes("firefox"),H8=new Map,xv=class{constructor(t,e){C(this,"canvas",void 0),C(this,"ctx",void 0),C(this,"options",void 0),C(this,"imagesPending",0),C(this,"imagesLoaded",0),C(this,"imageIdsLoaded",[]),C(this,"frameIsRendering",!1),C(this,"pendingDrawCall",!1),C(this,"firstMeaningfulPaint",!1),C(this,"parallelTasks",6),C(this,"maxPrefetchPerFrame",8),C(this,"imageLoadingConfig",void 0),C(this,"imageRequestPool",void 0),C(this,"frameTasks",0),C(this,"loadingQueueOrdered",!0),C(this,"loadingQueue",[]),C(this,"currentTask",Promise.resolve()),C(this,"tasksRunning",0),C(this,"inFlightImageLoads",new Map),C(this,"requiredTileKeys",new Set),C(this,"requiredPrefetchTileKeys",new Set),C(this,"requestGeneration",0),C(this,"frameCounter",0),C(this,"pendingTileReveals",new Map),C(this,"stats",void 0),C(this,"averageJobTime",64),C(this,"lastKnownScale",1),C(this,"visible",[]),C(this,"previousVisible",[]),C(this,"rendererPosition",void 0),C(this,"dpi",void 0),C(this,"drawCalls",[]),C(this,"lastPaintedObject",void 0),C(this,"hostCache",void 0),C(this,"invalidated",[]),C(this,"fallbackRevealTimeout",null),C(this,"framePrefetchCount",0),C(this,"hasTilesFading",!1),C(this,"hasActiveLayerClip",!1),C(this,"_worker",()=>{if(this.loadingQueue.length&&this.tasksRunning<this.parallelTasks&&this.frameTasks<this.parallelTasks){let n=this.loadingQueue.pop();n&&(this.tasksRunning++,this.frameTasks++,this.currentTask=n.task().then(()=>{this.tasksRunning--}).catch(()=>{this.tasksRunning--}))}}),C(this,"_scheduled",0),C(this,"_doWork",()=>{this.loadingQueue.length===0&&this.tasksRunning===0&&this._scheduled&&(clearInterval(this._scheduled),this._scheduled=0);let n=this.parallelTasks||1;!this.firstMeaningfulPaint&&this.loadingQueue.length&&(n=this.loadingQueue.length);for(let i=0;i<n;i++)this._worker()}),this.canvas=t,this.rendererPosition=t.getBoundingClientRect(),this.ctx=t.getContext("2d",{alpha:!0}),this.ctx.imageSmoothingEnabled=!0,this.options=e||{},this.imageLoadingConfig=N3(this.options.imageLoading),this.parallelTasks=this.imageLoadingConfig.maxConcurrentRequests,this.maxPrefetchPerFrame=this.imageLoadingConfig.maxPrefetchPerFrame,this.imageRequestPool=new H3({timeoutMs:this.imageLoadingConfig.timeoutMs,crossOrigin:this.options.crossOrigin?"anonymous":void 0,useFetch:!!this.options.crossOrigin,cache:H8}),this.canvas.style.transition="opacity .3s",this.dpi=e?.dpi||1,this.options.readiness==="immediate"&&(this.firstMeaningfulPaint=!0,this.canvas.style.opacity="1"),this.hostCache=e?.lruCache?new _8({maxSize:1024*512*512,dispose:(n,i,a)=>{this.invalidated.push(i),n.width=0,n.height=0},sizeCalculation:(n,i)=>n.width*n.height}):{store:{},get(n){return this.store[n]},set(n,i){this.store[n]=i}}}getCanvasDims(){return{width:this.canvas.width/this.dpi,height:this.canvas.height/this.dpi}}resize(){this.rendererPosition=this.canvas.getBoundingClientRect()}getCompositeOwner(t){let e=t?.__parent;return e&&e.renderOptions?e:void 0}compareCompositeLoadPriority(t,e){let n=this.getCompositeOwner(t),i=this.getCompositeOwner(e);return!n||n!==i?0:(t?.display.scale||0)-(e?.display.scale||0)}isReady(){return this.firstMeaningfulPaint}afterFrame(t){if(this.clearTransform(),this.lastPaintedObject=void 0,this.frameIsRendering=!1,this.imagesPending=this.loadingQueue.length+this.tasksRunning+this.inFlightImageLoads.size+this.pendingTileReveals.size,this.imagesLoaded=0,this.loadingQueueOrdered||(this.loadingQueue=this.loadingQueue.sort((e,n)=>{let i=this.compareCompositeLoadPriority(e.paint,n.paint);return i===0?e.network&&n.network&&e.scale===n.scale?n.distance-e.distance:e.scale-n.scale:i}),this.loadingQueueOrdered=!0),this.scheduleSingleImageLookahead(t),this.previousVisible=this.visible,this.pruneStaleTileWork(),this.pendingDrawCall=!!this.drawCalls.length,this.pendingDrawCall)for(let e=0;e<this.drawCalls.length;e++){let n=this.drawCalls.shift();n&&n()}this.doOffscreenWork(),this.options.debug&&this.stats&&this.stats.end()}doOffscreenWork(){this.frameTasks=0,this.loadingQueue.length&&(this._worker(),this.loadingQueue.length&&this.tasksRunning<this.parallelTasks&&(this._scheduled||(this._scheduled=setInterval(this._doWork,0))))}getScale(t,e,n){if(Number.isNaN(t)||Number.isNaN(e))return this.lastKnownScale;let i=this.getCanvasDims(),a=i.width/t,r=i.height/e,l=(a<r?r:a)*(n&&this.dpi||1);return Number.isNaN(l)||(this.lastKnownScale=l),this.lastKnownScale}beforeFrame(t,e,n,i){this.options.debug&&this.stats&&this.stats.begin(),this.frameIsRendering=!0,this.frameCounter+=1,this.visible=[],this.framePrefetchCount=0,this.hasTilesFading=!1,this.requiredTileKeys.clear(),this.requiredPrefetchTileKeys.clear(),this.flushTileRevealBatch(),this.options.beforeFrame&&this.options.beforeFrame(e);let a=this.getCanvasDims();this.ctx.globalAlpha=1,this.canvas.dataset.background==="transparent"?this.ctx.clearRect(0,0,a.width,a.height):(this.ctx.fillStyle=this.canvas.dataset.background??"rgb(0, 0, 0)",this.ctx.fillRect(0,0,a.width,a.height));let r=z3(i);this.ctx.filter!==r&&(this.ctx.filter=r)}applyTransform(t,e,n,i,a){let r=t.__owner.value;if(r&&r.rotation){this.ctx.save();let l=e+i/2,u=n+a/2;this.ctx.translate(l,u),this.ctx.rotate(r.rotation*Math.PI/180),this.ctx.translate(-l,-u),this.lastPaintedObject=r}}clearTransform(){this.lastPaintedObject&&(this.lastPaintedObject.rotation&&this.ctx.restore(),this.lastPaintedObject=void 0)}getTileKey(t,e){return`${t.id}::${t.display.scale}::${e}`}nextRequestKey(t){return this.requestGeneration+=1,`${t}::${this.requestGeneration}`}markTileRequired(t,e){if(e){this.requiredPrefetchTileKeys.add(t);return}this.requiredTileKeys.add(t)}isTileRequired(t){return this.requiredTileKeys.has(t)||this.requiredPrefetchTileKeys.has(t)}shouldSkipFade(t,e=performance.now()){return t?.requestedAt?e-t.requestedAt<=this.imageLoadingConfig.skipFadeIfLoadedWithinMs:!1}enqueueTileReveal(t,e,n){let i=performance.now();if(this.imageLoadingConfig.revealDelayFrames===0&&this.imageLoadingConfig.revealBatchWindowFrames===0){let a=this.getTileState(e,n);this.setTileState(e,n,{...a,loadedAt:i,skipFade:this.shouldSkipFade(a,i)});return}this.pendingTileReveals.set(t,{imageBuffer:e,index:n,queuedFrame:this.frameCounter})}flushTileRevealBatch(){if(this.pendingTileReveals.size===0)return;let t=this.imageLoadingConfig.revealDelayFrames,e=this.imageLoadingConfig.revealBatchWindowFrames,n=performance.now(),i=[...this.pendingTileReveals.entries()].sort((r,l)=>r[1].queuedFrame-l[1].queuedFrame),a=0;for(;a<i.length;){let r=i[a];if(this.frameCounter-r[1].queuedFrame<t)break;let l=r[1].queuedFrame+e;for(;a<i.length&&i[a][1].queuedFrame<=l;){let[u,f]=i[a],h=this.getTileState(f.imageBuffer,f.index);h.state==="decoded"&&!h.loadedAt&&this.setTileState(f.imageBuffer,f.index,{...h,loadedAt:n,skipFade:this.shouldSkipFade(h,n)}),this.pendingTileReveals.delete(u),a+=1}}}emitImageError(t){this.options.onImageError&&this.options.onImageError({renderer:"canvas",...t})}releaseInFlightTileLoad(t,e={}){let n=this.inFlightImageLoads.get(t);n&&(n.release(e),this.inFlightImageLoads.delete(t))}pruneStaleTileWork(){let t=[];for(let n of this.loadingQueue){if(!n.tileKey||this.isTileRequired(n.tileKey)){t.push(n);continue}if(n.paint&&typeof n.index=="number"){let i=this.ensureImageBuffer(n.paint),a=this.getTileState(i,n.index);a.lastRequestKey===n.requestKey&&(a.state==="queued"||a.state==="loading")&&this.setTileState(i,n.index,{...a,state:"idle",cancelledAt:performance.now()})}n.tileKey&&this.pendingTileReveals.delete(n.tileKey)}this.loadingQueue=t;let e=[];for(let[n,i]of this.inFlightImageLoads.entries()){if(this.isTileRequired(n))continue;e.push(n);let a=this.getTileState(i.imageBuffer,i.index);a.lastRequestKey===i.requestKey&&a.state==="loading"&&this.setTileState(i.imageBuffer,i.index,{...a,state:"idle",cancelledAt:performance.now()}),this.pendingTileReveals.delete(n)}for(let n of e)this.releaseInFlightTileLoad(n,{silent:!0})}ensureImageBuffer(t){(!t.__host||!t.__host.canvas)&&this.createImageHost(t);let e=t.__host.canvas;return e.tiles||(e.tiles={}),e.indices||(e.indices=[]),e.loaded||(e.loaded=[]),e.canvases||(e.canvases=[]),e}getTileState(t,e){return t.tiles||(t.tiles={}),t.tiles[e]||(t.tiles[e]={state:"idle"},this.syncBufferState(t)),t.tiles[e]}setTileState(t,e,n){t.tiles||(t.tiles={}),t.tiles[e]=n,this.syncBufferState(t)}syncBufferState(t){let e=[],n=[],i=t.tiles||{},a=Object.keys(i);for(let r=0;r<a.length;r++){let l=parseInt(a[r],10),u=i[l].state;(u==="queued"||u==="loading")&&e.push(l),u==="decoded"&&n.push(l)}t.indices=e,t.loaded=n,t.loading=e.length>0}getCompositeRenderOptions(t){return t.__parent?.renderOptions}shouldClipLayerToBounds(t){return t instanceof gi||t instanceof Ri?!!this.getCompositeRenderOptions(t)?.clipToBounds:!1}getBoundsFromPoints(t){let e=1/0,n=1/0,i=-1/0,a=-1/0;for(let r=0;r<t.length;r+=5)t[r]&&(e=Math.min(e,t[r+1]),n=Math.min(n,t[r+2]),i=Math.max(i,t[r+3]),a=Math.max(a,t[r+4]));if(!(!Number.isFinite(e)||!Number.isFinite(n)||!Number.isFinite(i)||!Number.isFinite(a))&&!(i<=e||a<=n))return{x:e,y:n,width:i-e,height:a-n}}getLayerPolicy(t){return this.getCompositeRenderOptions(t)?.layerPolicy||"fallback-only"}isLayerActive(t){let e=t.__parent;return!e||this.getLayerPolicy(t)==="always-blend"?!0:typeof e.isImageActive=="function"?!!e.isImageActive(t):!0}getPrefetchRadius(t){let e=this.getCompositeRenderOptions(t);return e?typeof e.prefetchRadius=="number"?Math.max(0,e.prefetchRadius):e.loadingBias==="speed"?2:e.loadingBias==="data"?0:1:0}getFadeAlpha(t,e,n){if(e?.skipFade)return 1;if(e?.state==="decoded"&&!e.loadedAt&&(this.imageLoadingConfig.revealDelayFrames>0||this.imageLoadingConfig.revealBatchWindowFrames>0))return 0;let i=this.getCompositeRenderOptions(t);if(!i||!i.fadeInMs||i.fadeInMs<=0)return 1;let a=performance.now(),r=1;if(n&&i.fadeOnLayerChange&&i.layerPolicy!=="active-only"){let l=t.__parent;if(l&&typeof l.getImageActivatedAt=="function"){let u=l.getImageActivatedAt(t);typeof u=="number"&&(r=Math.min(r,Math.max(0,Math.min(1,(a-u)/i.fadeInMs))))}}return e?.loadedAt&&(n||i.fadeFallbackTiles)&&(r=Math.min(r,Math.max(0,Math.min(1,(a-e.loadedAt)/i.fadeInMs)))),r}schedulePrefetchNeighbours(t,e,n,i){if(!(e instanceof Ri)||this.framePrefetchCount>=this.maxPrefetchPerFrame||this.getCompositeRenderOptions(e)?.loadingBias==="data")return;let a=this.getPrefetchRadius(e);if(a<=0)return;let r=e.columns,l=e.rows;if(!r||!l)return;let u=n%r,f=Math.floor(n/r);for(let h=1;h<=a;h++)for(let d=-h;d<=h;d++)for(let m=-h;m<=h;m++){if(Math.max(Math.abs(m),Math.abs(d))!==h)continue;let y=u+m,g=f+d;if(y<0||g<0||y>=r||g>=l)continue;let b=g*r+y,w=this.getTileKey(e,b);if(this.markTileRequired(w,!0),this.schedulePaintToCanvas(t,e,b,i+h*1e3,!0)&&(this.framePrefetchCount++,this.framePrefetchCount>=this.maxPrefetchPerFrame))return}}scheduleSingleImageLookahead(t){if(this.maxPrefetchPerFrame<=0||this.framePrefetchCount>=this.maxPrefetchPerFrame||t.hasActiveZone())return;let e=1/0,n=-1/0,i=new Set;for(let y=0;y<this.visible.length;y++){let g=this.visible[y].__owner?.value;!g||g.type!=="world-object"||g.points[0]===0||(i.add(g),e=Math.min(e,g.points[2]),n=Math.max(n,g.points[4]))}if(!Number.isFinite(e)||!Number.isFinite(n))return;let a=n-e;if(a<=0)return;let r=a*1.5,l=n+r,u=e-r,f,h,d=t.getObjects();for(let y=0;y<d.length;y++){let g=d[y];if(!g||g.type!=="world-object"||g.points[0]===0||i.has(g))continue;let b=g.points[2],w=g.points[4],E=b>=n&&b<=l,T=w<=e&&w>=u;if(!E&&!T)continue;let S;for(let R=0;R<g.layers.length;R++){let A=g.layers[R];if(A instanceof gi){S=A;break}}if(S){if(E){let R=b-n;(!f||R<f.distance)&&(f={image:S,distance:R})}if(T){let R=e-w;(!h||R<h.distance)&&(h={image:S,distance:R})}}}let m=[f,h].filter(Boolean);for(let y of m){if(this.framePrefetchCount>=this.maxPrefetchPerFrame)break;let g=this.ensureImageBuffer(y.image);this.schedulePaintToCanvas(g,y.image,0,1e4+y.distance,!0)&&this.framePrefetchCount++}}paint(t,e,n,i,a,r){let l=this.ctx.globalAlpha,u=typeof t.__zoneVisibilityAlpha=="number"?t.__zoneVisibilityAlpha:1;if(t instanceof gi||t instanceof Ri){let d=t.display.rotation||0,m=d!==0;try{if(m){this.ctx.save();let L=n+a/2,H=i+r/2;t.crop&&(L-=t.crop[e*5+1],H-=t.crop[e*5+2]),this.ctx.translate(L,H),this.ctx.rotate(d*Math.PI/180),this.ctx.translate(-L,-H)}let y=this.options.paintImages!==!1,g=this.options.shouldPaintImage?this.options.shouldPaintImage(t,e):!0;if(!y||!g)return;this.visible.push(t);let b=(t.style?.opacity===void 0?1:t.style.opacity)*u;if(!b)return;this.ctx.globalAlpha=l*b;let w=this.ensureImageBuffer(t),E=this.getTileState(w,e);E.lastUsedAt=performance.now(),this.setTileState(w,e,E);let T=this.getTileKey(t,e);this.markTileRequired(T,!1);let S=this.isLayerActive(t),R=this.getCanvasDims(),A=Qh({x:n+a/2,y:i+r/2},{x:R.width/2,y:R.height/2}),M=this.invalidated.indexOf(w.canvases[e])!==-1,z=this.hostCache.get(w.canvases[e]),N=!!z&&!M;if(M&&this.setTileState(w,e,{...E,state:"idle"}),(M||!N||E.state==="idle"||E.state==="error")&&S&&(this.schedulePaintToCanvas(w,t,e,A,!1),this.schedulePrefetchNeighbours(w,t,e,A)),!this.firstMeaningfulPaint)return;if(z&&!M){let L=this.getFadeAlpha(t,E,S);if(L<1&&(this.hasTilesFading=!0),this.ctx.globalAlpha=l*b*L,t.crop&&t.cropData){if(t.crop[e*5]){let H=[t.crop[e*5+1]/t.display.scale-t.display.points[e*5+1],t.crop[e*5+2]/t.display.scale-t.display.points[e*5+2],1+(t.crop[e*5+3]-t.crop[e*5+1])/t.display.scale,1+(t.crop[e*5+4]-t.crop[e*5+2])/t.display.scale];H[0]+=t.cropData.x/t.display.scale,H[1]+=t.cropData.y/t.display.scale;let U=t.x*this.lastKnownScale,nt=t.y*this.lastKnownScale,Q=[n+U,i+nt,a,r];Q[0]+=U,Q[1]+=nt,this.ctx.drawImage(z,H[0],H[1],H[2],H[3],Q[0],Q[1],Q[2]+1,Q[3]+1)}}else B8?this.ctx.drawImage(z,0,0,t.display.points[e*5+3]-t.display.points[e*5+1],t.display.points[e*5+4]-t.display.points[e*5+2],n,i,a+1,r+1):this.ctx.drawImage(z,0,0,t.display.points[e*5+3]-t.display.points[e*5+1],t.display.points[e*5+4]-t.display.points[e*5+2],n,i,a+Number.MIN_VALUE+.5,r+Number.MIN_VALUE+.5)}}catch{}finally{m&&this.ctx.restore(),this.ctx.globalAlpha=l}}let f=t instanceof Td&&this.options.box,h=t instanceof cR&&this.options.polygon;if((f||h)&&!t.props.className&&!t.props.html&&!t.props.href){if(this.visible.push(t),t.props.style){let d=Object.assign({},t.props.style||{},t.hovering?t.props.hoverStyles:{},t.pressing?t.props.pressStyles:{}),m=t.props.relativeStyle?1:a/t.width,y=d.opacity===void 0?1:d.opacity;this.ctx.globalAlpha=l*y*u;let g=0;d.borderWidth!==void 0&&(g=parseInt(d.borderWidth,10)*m);let b=0;d.outlineWidth!==void 0&&(b=parseInt(d.outlineWidth,10)*m);let w=0;if(d.outlineOffset!==void 0&&(w=parseInt(d.outlineOffset,10)*m),d.borderColor&&(this.ctx.strokeStyle=d.borderColor),d.boxShadow){let E=d.boxShadow.split(/,(?![^(]*\))/);for(let T of E){let S=JL[T]||WL.exec(T)||WL.exec(T);JL[T]=S,S&&(this.ctx.save(),this.ctx.shadowOffsetX=parseInt(S[1])*this.dpi*m,this.ctx.shadowOffsetY=parseInt(S[3])*this.dpi*m,this.ctx.shadowBlur=parseInt(S[5])*this.dpi*m,this.ctx.shadowColor=S[9],this.ctx.fillStyle="rgba(0,0,0,1)",this.ctx.fillRect(n+g,i+g,a,r),this.ctx.restore())}}if(this.ctx.fillStyle=d.backgroundColor||"transparent",this.ctx.lineWidth=g,h){let E=t.shape,T=E.points||[],S=T.length;this.ctx.beginPath();for(let R=0;R<S;R++)this.ctx.lineTo(n+T[R][0]*this.lastKnownScale,i+T[R][1]*this.lastKnownScale);E.open||this.ctx.closePath(),g&&this.ctx.stroke(),E.open||this.ctx.fill()}else g&&this.ctx.strokeRect(n+g/2,i+g/2,a+g,r+g),this.ctx.fillRect(n+g,i+g,a,r);b&&(d.outlineColor&&(this.ctx.strokeStyle=d.outlineColor),this.ctx.lineWidth=b,this.ctx.strokeRect(n-b/2-w,i-b/2-w,a+g*2+b+w*2,r+g*2+b+w*2))}this.ctx.globalAlpha=l}}schedulePaintToCanvas(t,e,n,i,a=!1){let r=this.getTileState(t,n),l=performance.now(),u=this.getTileKey(e,n);if(this.markTileRequired(u,a),this.pendingTileReveals.delete(u),r.nextRetryAt&&r.nextRetryAt>l||r.state==="queued"||r.state==="loading"||r.state==="decoded")return!1;let f=`${e.id}--${e.display.scale}-${n}`,h=this.nextRequestKey(u);t.canvases[n]=f;let d=this.invalidated.indexOf(f);return d!==-1&&this.invalidated.splice(d,1),this.setTileState(t,n,{...r,state:"queued",requestedAt:l,error:void 0,lastRequestKey:h,cancelledAt:void 0,skipFade:!1}),this.loadingQueueOrdered=!1,this.loadingQueue.push({id:f,scale:e.display.scale,kind:"network",tileKey:u,requestKey:h,network:!0,distance:i,paint:e,index:n,prefetch:a,task:async()=>{let m=this.getTileState(t,n);if(m.lastRequestKey!==h||m.state!=="queued"&&m.state!=="loading")return;let y=this.visible.indexOf(e)!==-1,g=this.previousVisible.indexOf(e)!==-1;if(!a&&!y&&!g){this.setTileState(t,n,{...m,state:"idle",cancelledAt:performance.now()}),this.pendingTileReveals.delete(u);return}let b=e.getImageUrl(n);this.setTileState(t,n,{...m,state:"loading",url:b,requestedAt:m.requestedAt||performance.now(),error:void 0});try{let w=`${u}::${h}`,E=this.imageRequestPool.acquire(b,w);this.inFlightImageLoads.set(u,{tileKey:u,requestKey:h,url:b,consumerId:w,paint:e,imageBuffer:t,index:n,release:E.release});let T=await E.promise;this.releaseInFlightTileLoad(u,{silent:!0});let S=this.getTileState(t,n);if(S.lastRequestKey!==h||S.state!=="loading")return;this.loadingQueueOrdered=!1,this.loadingQueue.push({id:`${f}--decode`,scale:e.display.scale,kind:"decode",tileKey:u,requestKey:h,distance:i,paint:e,index:n,prefetch:a,task:()=>new Promise(R=>{let A=this.getTileState(t,n);if(A.lastRequestKey!==h||A.state!=="loading"){R();return}let M=e.display.points.slice(n*5,n*5+5),z=document.createElement("canvas"),N=z.getContext("2d");z.width=M[3]-M[1],z.height=M[4]-M[2],this.hostCache.set(t.canvases[n],z),this.drawCalls.push(()=>{let L=this.getTileState(t,n);if(L.lastRequestKey!==h||L.state!=="loading"){R();return}N.drawImage(T,0,0,M[3]-M[1],M[4]-M[2]);let H=this.getTileState(t,n);this.setTileState(t,n,{...H,state:"decoded",loadedAt:void 0,error:void 0,attempts:0,nextRetryAt:void 0}),this.enqueueTileReveal(u,t,n),this.imagesLoaded++,R()})})})}catch(w){if(this.releaseInFlightTileLoad(u,{silent:!0}),P3(w)){let A=this.getTileState(t,n);A.lastRequestKey===h&&this.setTileState(t,n,{...A,state:"idle",cancelledAt:performance.now()}),this.pendingTileReveals.delete(u);return}let E=this.getTileState(t,n);if(E.lastRequestKey!==h)return;let T=(E.attempts||0)+1,S=T<this.imageLoadingConfig.maxAttempts,R=S?performance.now()+L3(this.imageLoadingConfig,T):performance.now()+this.imageLoadingConfig.errorRetryIntervalMs;this.setTileState(t,n,{...E,state:S?"idle":"error",error:w,attempts:T,nextRetryAt:R}),this.pendingTileReveals.delete(u),this.emitImageError({severity:"recoverable",imageUrl:b,contentId:e.id,tileIndex:n,attempt:T,maxAttempts:this.imageLoadingConfig.maxAttempts,willRetry:S,nextRetryAt:R,error:w})}}}),!0}afterPaintLayer(t,e){}prepareLayer(t,e){if(this.hasActiveLayerClip=!1,t.__owner.value&&(t.cropData&&this.lastKnownScale*(1/t.display.scale),this.applyTransform(t,e[1],e[2],e[3]-e[1],e[4]-e[2])),this.shouldClipLayerToBounds(t)){let n=this.getBoundsFromPoints(e);n&&(this.ctx.save(),this.ctx.beginPath(),this.ctx.rect(n.x,n.y,n.width,n.height),this.ctx.clip(),this.hasActiveLayerClip=!0)}(!t.__host||!t.__host.canvas)&&(t instanceof gi||t instanceof Ri)&&this.createImageHost(t)}finishLayer(){this.hasActiveLayerClip&&(this.ctx.restore(),this.hasActiveLayerClip=!1),this.lastPaintedObject&&this.clearTransform()}createImageHost(t){t.__host=t.__host?t.__host:{},t.__host.canvas={canvas:void 0,canvases:[],tiles:{},indices:[],loaded:[],loading:!1}}getPointsAt(t,e,n,i){return t.getPointsAt(e,n,i)}getViewportBounds(t,e,n){let i=t.getActiveZone();if(i){i.recalculateBounds();let a=_3(e,i.points,n);if(a){let r=e[3]-e[1],l=e[4]-e[2];return{x1:a.minX,y1:a.minY,x2:a.maxX+r,y2:a.maxY+l}}}return null}pendingUpdate(){this.imagesPending=this.loadingQueue.length+this.tasksRunning+this.inFlightImageLoads.size+this.pendingTileReveals.size;let t=!this.pendingDrawCall&&this.drawCalls.length===0&&this.loadingQueue.length===0&&this.tasksRunning===0&&this.inFlightImageLoads.size===0&&this.pendingTileReveals.size===0;return!t&&this.visible.length===0&&this.options.readiness!=="immediate"&&this.fallbackRevealTimeout===null&&(this.fallbackRevealTimeout=setTimeout(()=>{this.canvas.style.opacity="1",this.firstMeaningfulPaint=!0,this.fallbackRevealTimeout=null},500)),!this.firstMeaningfulPaint&&t&&(this.visible.length||this.options.readiness==="immediate")?(this.canvas.style.opacity="1",this.firstMeaningfulPaint=t,!0):this.options.debug||this.hasTilesFading?!0:!t}getRendererScreenPosition(){return this.rendererPosition}resetReadyState(){this.options.readiness!=="immediate"&&(this.firstMeaningfulPaint=!1,this.fallbackRevealTimeout&&(clearTimeout(this.fallbackRevealTimeout),this.fallbackRevealTimeout=null))}reset(){this.loadingQueue=[],this.drawCalls=[],this._scheduled&&(clearInterval(this._scheduled),this._scheduled=0);for(let t of[...this.inFlightImageLoads.keys()])this.releaseInFlightTileLoad(t,{silent:!0});this.imageRequestPool.cancelAll({silent:!0}),this.inFlightImageLoads.clear(),this.requiredTileKeys.clear(),this.requiredPrefetchTileKeys.clear(),this.pendingTileReveals.clear(),this.requestGeneration+=1,this.frameCounter=0,this.fallbackRevealTimeout&&(clearTimeout(this.fallbackRevealTimeout),this.fallbackRevealTimeout=null),this.imagesPending=0,this.imagesLoaded=0,this.hasTilesFading=!1}},F3=class{constructor(t){C(this,"renderers",[]),C(this,"length",void 0);for(let e of t)e&&this.renderers.push(e);this.length=this.renderers.length}afterFrame(t,e,n,i){for(let a=0;a<this.length;a++)this.renderers[a].afterFrame(t,e,n,i)}afterPaintLayer(t,e){for(let n=0;n<this.length;n++)this.renderers[n].afterPaintLayer(t,e)}beforeFrame(t,e,n,i){for(let a=0;a<this.length;a++)this.renderers[a].beforeFrame(t,e,n,i)}triggerResize(){for(let t=0;t<this.length;t++){let e=this.renderers[t];e.triggerResize&&e.triggerResize()}}getPointsAt(t,e,n,i){return this.renderers[0].getPointsAt(t,e,n,i)}getScale(t,e){return this.renderers[0].getScale(t,e)}getViewportBounds(t,e,n){return this.renderers[0].getViewportBounds(t,e,n)}getRendererScreenPosition(){return this.renderers[0].getRendererScreenPosition()}isReady(){for(let t=0;t<this.length;t++)if(!this.renderers[t].isReady())return!1;return!0}paint(t,e,n,i,a,r){for(let l=0;l<this.length;l++)this.renderers[l].paint(t,e,n,i,a,r)}pendingUpdate(){for(let t=0;t<this.length;t++)if(this.renderers[t].pendingUpdate())return!0;return!1}prepareLayer(t,e){for(let n=0;n<this.length;n++)this.renderers[n].prepareLayer(t,e)}finishLayer(t,e){for(let n=0;n<this.length;n++)this.renderers[n].finishLayer(t,e)}resize(t,e){for(let n=0;n<this.length;n++)this.renderers[n].resize(t,e)}reset(){for(let t=0;t<this.length;t++)this.renderers[t].reset()}resetReadyState(){for(let t=0;t<this.length;t++)this.renderers[t].resetReadyState&&this.renderers[t].resetReadyState()}},F8=class extends Yr{constructor(...t){super(...t),C(this,"type","spacial-content")}getAllPointsAt(t,e,n){return[[this,this.points,e]]}},dR=class extends F8{constructor(t){super(),C(this,"id",void 0),C(this,"display",void 0),C(this,"points",void 0),C(this,"images",[]),C(this,"allImages",[]),C(this,"scaleFactors",[]),C(this,"aggregateBuffer",It(9)),C(this,"lazyLoader",void 0),C(this,"isFullyLoaded",!1),C(this,"isLoadingFullResource",!1),C(this,"maxScaleFactor",0),C(this,"layerSelection",new WeakMap),C(this,"layerSelectionFrame",0),C(this,"renderOptions",void 0),C(this,"_scheduleSortByScales",!1),C(this,"_sortByScales",()=>{this._scheduleSortByScales=!1,this.allImages.sort((n,i)=>i.display.width-n.display.width),this.images=[];let e=.1;for(let n of this.allImages)if(!(n.display.width<this.renderOptions.minSize&&n.display.height<this.renderOptions.minSize&&!n.priority)&&!(n instanceof gi&&(n.display.width>this.renderOptions.maxImageSize||n.display.height>this.renderOptions.maxImageSize)&&!n.priority)){if(Math.abs(n.display.scale-e)<.25||n.priority){let i=this.images.pop();i&&(i instanceof gi||i.priority)?(n.priority&&this.images.push(n),this.images.push(i)):n&&this.images.push(n)}else n&&this.images.push(n);e=n.display.scale}this.images.length===0&&(this.images=[...this.allImages]),this.scaleFactors=this.images.map(n=>n.display.scale),this.maxScaleFactor=this.scaleFactors.length?Math.max(...this.scaleFactors):0}),C(this,"loadFullResource",async()=>{if(!(this.isFullyLoaded||this.isLoadingFullResource)&&this.lazyLoader){this.isLoadingFullResource=!0;try{let e=await this.lazyLoader();this.addImages(e||[]),this.isFullyLoaded=!0}finally{this.isLoadingFullResource=!1}}}),C(this,"fallback",[this.loadFullResource]),this.id=t.id,this.points=de.singleBox(t.width,t.height),this.lazyLoader=t.loadFullImages,t.loadFullImages||(this.isFullyLoaded=!0),this.display={x:0,y:0,points:de.singleBox(t.width,t.height),height:t.height,width:t.width,scale:1},this.renderOptions={renderSmallestFallback:!0,renderLayers:2,minSize:255,maxImageSize:2048,quality:1.3,useDevicePixelRatio:!0,layerPolicy:"always-blend",loadingBias:"balanced",prefetchRadius:1,fadeInMs:300,fadeFallbackTiles:!1,fadeOnLayerChange:!1,clipToBounds:!1,...t.renderOptions||{}},this.addImages(t.images)}applyProps(t){let e=!1;t.renderSmallestFallback!==void 0&&t.renderSmallestFallback!==this.renderOptions.renderSmallestFallback&&(this.renderOptions.renderSmallestFallback=t.renderSmallestFallback),t.renderLayers!==void 0&&t.renderLayers!==this.renderOptions.renderLayers&&(this.renderOptions.renderLayers=t.renderLayers),t.minSize!==void 0&&t.minSize!==this.renderOptions.minSize&&(this.renderOptions.minSize=t.minSize,e=!0),t.maxImageSize!==void 0&&t.maxImageSize!==this.renderOptions.maxImageSize&&(this.renderOptions.maxImageSize=t.maxImageSize,e=!0),t.quality!==void 0&&t.quality!==this.renderOptions.quality&&(this.renderOptions.quality=t.quality),t.useDevicePixelRatio!==void 0&&t.useDevicePixelRatio!==this.renderOptions.useDevicePixelRatio&&(this.renderOptions.useDevicePixelRatio=t.useDevicePixelRatio),t.layerPolicy!==void 0&&t.layerPolicy!==this.renderOptions.layerPolicy&&(this.renderOptions.layerPolicy=t.layerPolicy),t.loadingBias!==void 0&&t.loadingBias!==this.renderOptions.loadingBias&&(this.renderOptions.loadingBias=t.loadingBias),t.prefetchRadius!==void 0&&t.prefetchRadius!==this.renderOptions.prefetchRadius&&(this.renderOptions.prefetchRadius=t.prefetchRadius),t.fadeInMs!==void 0&&t.fadeInMs!==this.renderOptions.fadeInMs&&(this.renderOptions.fadeInMs=t.fadeInMs),t.fadeFallbackTiles!==void 0&&t.fadeFallbackTiles!==this.renderOptions.fadeFallbackTiles&&(this.renderOptions.fadeFallbackTiles=t.fadeFallbackTiles),t.fadeOnLayerChange!==void 0&&t.fadeOnLayerChange!==this.renderOptions.fadeOnLayerChange&&(this.renderOptions.fadeOnLayerChange=t.fadeOnLayerChange),t.clipToBounds!==void 0&&t.clipToBounds!==this.renderOptions.clipToBounds&&(this.renderOptions.clipToBounds=t.clipToBounds),e&&this.sortByScales()}appendChild(t){this.addImages([t])}removeChild(t){if(this.images.indexOf(t)===-1&&this.allImages.indexOf(t)===-1)return;let e=this.getImageDedupeKey(t);this.images=this.images.filter(n=>n!==t&&this.getImageDedupeKey(n)!==e),this.allImages=this.allImages.filter(n=>n!==t&&this.getImageDedupeKey(n)!==e),this.sortByScales()}insertBefore(t,e){this.addImages([t])}hideInstance(){}addImages(t){let e=new Set(this.allImages),n=new Set(this.allImages.map(i=>this.getImageDedupeKey(i)));for(let i of t){if(!i||e.has(i))continue;let a=this.getImageDedupeKey(i);n.has(a)||(i.__parent=this,i.__owner=this.__owner,this.allImages.push(i),e.add(i),n.add(a))}this.sortByScales()}getImageDedupeKey(t){return`${t.id}::${t.display.scale}`}sortByScales(){this._scheduleSortByScales=!0}getScheduledUpdates(t,e){return this._scheduleSortByScales?[this._sortByScales]:this.isFullyLoaded?[]:e>1/this.maxScaleFactor?this.fallback:[]}getAllPointsAt(t,e,n){if(this.images.length===0)return[];let i=this.renderOptions.useDevicePixelRatio&&typeof window<"u"&&window.devicePixelRatio||1,a=w8(1/(n||1)/i,this.images,this.renderOptions.quality),r=this.images.length,l=e?Dr(e,ci(this.x,this.y)):ci(this.x,this.y),u=[a];if(a!==this.images.length-1&&this.images[a+1]){u=[];for(let b=r-1;b>=a;b--)u.push(b);let g=u[0];this.renderOptions.renderLayers&&(u=u.slice(-Math.min(u.length,this.renderOptions.renderLayers))),this.renderOptions.renderSmallestFallback&&u.indexOf(g)===-1&&u.unshift(g)}u.sort((g,b)=>{let w=this.images[g],E=this.images[b],T=w?w.display.scale:0;return(E?E.display.scale:0)-T});let f=new Set;switch(this.renderOptions.layerPolicy){case"always-blend":for(let g of u)f.add(g);break;case"active-only":f.add(a),u=[a];break;case"fallback-only":default:f.add(a),this.renderOptions.renderSmallestFallback&&u.length&&f.add(u[0]);break}let h=new Set;for(let g of f){let b=this.images[g];b&&h.add(b)}this.layerSelectionFrame+=1;let d=this.getNow(),m=d-Math.max(0,this.renderOptions.fadeInMs);for(let g of this.allImages){let b=this.layerSelection.get(g);if(!h.has(g)){this.layerSelection.set(g,{active:!1,frame:this.layerSelectionFrame});continue}let w=!!b&&b.frame===this.layerSelectionFrame-1,E=w&&b.active;this.layerSelection.set(g,{active:!0,frame:this.layerSelectionFrame,activatedAt:E&&typeof b.activatedAt=="number"?b.activatedAt:w?d:m})}let y=[];for(let g=0;g<u.length;g++){let b=u[g],w=this.images[b];y.push(...w.getAllPointsAt(t,l,n))}return y}isImageActive(t){let e=this.layerSelection.get(t);return!!e&&e.frame===this.layerSelectionFrame&&e.active}getImageActivatedAt(t){let e=this.layerSelection.get(t);if(!(!e||e.frame!==this.layerSelectionFrame||!e.active))return e.activatedAt}getNow(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}},Lv=class extends Yr{constructor(t){if(super(),C(this,"type","spacial-content"),C(this,"id",void 0),C(this,"uri",void 0),C(this,"display",void 0),C(this,"points",void 0),C(this,"getTexture",void 0),this.getTexture=()=>({source:void 0,hash:-1}),!t)this.id="",this.uri="",this.display={x:0,y:0,scale:1,width:0,height:0,points:It(5)},this.points=It(5);else{let e=t.scale||1;this.id=t.id||t.uri,this.uri=t.uri,this.points=de.singleBox(t.width,t.height),this.display={x:0,y:0,scale:e,width:t.width/e,height:t.height/e,points:e===1?this.points:de.singleBox(t.width/e,t.height/e)}}}applyProps(t){let e=t.display?t.display.width:t.target.width,n=t.target.width/e;this.id=t.id,this.points.set(de.singleBox(t.target.width,t.target.height)),this.display.scale=n,this.display.width=t.target.width/n,this.display.height=t.target.height/n,this.getTexture=t.getTexture,this.display.points=n===1?this.points:de.singleBox(t.target.width/n,t.target.height/n)}getAllPointsAt(t,e,n){return[[this,this.points,e]]}},wv=85.05112878;function yr(t,e){if(!Number.isFinite(t))throw Error(`${e} must be a finite number`)}function $L(t,e){if(yr(t,e),t<=0)throw Error(`${e} must be greater than 0`)}function q8(t){if(!Number.isFinite(t))throw Error("Latitude must be a finite number");return t>wv?wv:t<-wv?-wv:t}function Dv(t){if(yr(t.west,"Map bounds west"),yr(t.south,"Map bounds south"),yr(t.east,"Map bounds east"),yr(t.north,"Map bounds north"),t.west<-180||t.west>180)throw Error("Map bounds west must be within [-180, 180]");if(t.east<-180||t.east>180)throw Error("Map bounds east must be within [-180, 180]");if(t.south<-90||t.south>90)throw Error("Map bounds south must be within [-90, 90]");if(t.north<-90||t.north>90)throw Error("Map bounds north must be within [-90, 90]");if(t.west>=t.east)throw Error("Map bounds must satisfy west < east (antimeridian crossing is not supported)");if(t.south>=t.north)throw Error("Map bounds must satisfy south < north");return t}function _v(t){if(!Number.isFinite(t))throw Error("Longitude must be a finite number");return(t+180)/360}function zv(t){let e=q8(t)*Math.PI/180;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}function q3(t){if(!Number.isFinite(t))throw Error("Mercator X must be a finite number");return t*360-180}function V3(t){if(!Number.isFinite(t))throw Error("Mercator Y must be a finite number");let e=Math.PI*(1-2*t);return 180/Math.PI*Math.atan(Math.sinh(e))}function t3(t,e){return _v(t)*2**e}function e3(t,e){return zv(t)*2**e}function n3(t,e){return q3(t/2**e)}function i3(t,e){return V3(t/2**e)}function V8(t){let e=Dv(t.bounds);$L(t.width,"Map world width"),$L(t.height,"Map world height");let n=_v(e.west),i=_v(e.east),a=zv(e.north),r=zv(e.south),l=i-n,u=r-a;if(!(l>0))throw Error("Map bounds produce an invalid mercator X span");if(!(u>0))throw Error("Map bounds produce an invalid mercator Y span");let f=(d,m)=>{let y=_v(d),g=zv(m);return{x:(y-n)/l*t.width,y:(g-a)/u*t.height}},h=(d,m)=>{yr(d,"World x"),yr(m,"World y");let y=n+d/t.width*l,g=a+m/t.height*u;return{lng:q3(y),lat:V3(g)}};return{lngLatToWorld:f,worldToLngLat:h,lngLatBoundsToWorldRect:d=>{Dv(d);let m=f(d.west,d.north),y=f(d.east,d.south);return{x:m.x,y:m.y,width:y.x-m.x,height:y.y-m.y}},worldRectToLngLatBounds:d=>{yr(d.x,"World rect x"),yr(d.y,"World rect y"),yr(d.width,"World rect width"),yr(d.height,"World rect height");let m=h(d.x,d.y),y=h(d.x+d.width,d.y+d.height);return{west:m.lng,south:y.lat,east:y.lng,north:m.lat}},projectRing:d=>{let m=[];for(let[y,g]of d){let b=f(y,g);m.push([b.x,b.y])}return m}}}var U3="https://tile.openstreetmap.org/{z}/{x}/{y}.png";function U8(t){if(t.s)return t.s;let e=t.subdomains||[];if(e.length!==0)return e[Math.abs(t.x+t.y+t.z)%e.length]}function j8(t,e){let n=U8(e)||"";return t.replace(/\{z\}/g,`${e.z}`).replace(/\{x\}/g,`${e.x}`).replace(/\{y\}/g,`${e.y}`).replace(/\{s\}/g,n)}function k8(t,e){let n=t||U3;return typeof n=="function"?n(e):j8(n,e)}function Ys(t,e,n){return Math.min(n,Math.max(e,t))}function G8(t){Dv(t.bounds);let e=Math.max(0,Math.floor(t.zoom)),n=2**e,i=n-1,a=t3(t.bounds.west,e),r=t3(t.bounds.east,e),l=e3(t.bounds.north,e),u=e3(t.bounds.south,e),f=Ys(a,0,n),h=Ys(r,0,n),d=Ys(l,0,n),m=Ys(u,0,n),y=Math.max(1e-9,h-f),g=Math.max(1e-9,m-d),b=Ys(Math.floor(a),0,i),w=Ys(Math.ceil(r)-1,0,i),E=Ys(Math.floor(l),0,i),T=Ys(Math.ceil(u)-1,0,i),S=Math.max(1,w-b+1),R=Math.max(1,T-E+1);return{columns:S,rows:R,count:S*R,minTileX:b,maxTileX:w,minTileY:E,maxTileY:T,westTile:f,eastTile:h,northTile:d,southTile:m,tileSpanX:y,tileSpanY:g}}function Y8(t){Dv(t.bounds);let e=Math.max(0,Math.floor(t.zoom)),n=V8({bounds:t.bounds,width:t.worldWidth,height:t.worldHeight}),i=G8({bounds:t.bounds,zoom:e}),a=typeof t.maxTiles=="number"?t.maxTiles:1/0;if(i.count>a)throw Error(`Map tile grid too large at zoom ${e}: ${i.count} tiles exceeds the configured max (${a})`);let r=[],l=[];for(let u=i.minTileY;u<=i.maxTileY;u++)for(let f=i.minTileX;f<=i.maxTileX;f++){let h=n3(f,e),d=n3(f+1,e),m=i3(u,e),y=i3(u+1,e),g=n.lngLatToWorld(h,m),b=n.lngLatToWorld(d,y);r.push(1,g.x,g.y,b.x,b.y),l.push({x:f,y:u,z:e})}return{points:It(r.length?r:[0]),tiles:l,columns:i.columns,rows:i.rows,count:i.count,minTileX:i.minTileX,maxTileX:i.maxTileX,minTileY:i.minTileY,maxTileY:i.maxTileY}}var X8=class extends Ri{constructor(t){let e=t.scaleFactor||1,n=t.tileSize||256,i=t.tileSource||t.tileUrlTemplate||U3,a=Y8({bounds:t.bounds,zoom:t.zoom,worldWidth:t.worldWidth,worldHeight:t.worldHeight}),r=t.id||`map-tiled-image-z${t.zoom}-${t.worldWidth}x${t.worldHeight}-${a.minTileX}:${a.maxTileX}-${a.minTileY}:${a.maxTileY}`;super({id:r,url:"map://tile-source",scaleFactor:e,points:a.points,displayPoints:a.points,tileWidth:n,tileHeight:n,width:t.worldWidth,height:t.worldHeight,columns:a.columns,rows:a.rows,format:"png",version3:!1}),C(this,"zoom",void 0),C(this,"bounds",void 0),C(this,"worldWidth",void 0),C(this,"worldHeight",void 0),C(this,"tileSize",void 0),C(this,"tileSource",void 0),C(this,"subdomains",void 0),C(this,"tileCoordinates",void 0),C(this,"minTileX",void 0),C(this,"maxTileX",void 0),C(this,"minTileY",void 0),C(this,"maxTileY",void 0),this.zoom=Math.max(0,Math.floor(t.zoom)),this.bounds={...t.bounds},this.worldWidth=t.worldWidth,this.worldHeight=t.worldHeight,this.tileSize=n,this.tileSource=i,this.subdomains=[...t.subdomains||[]],this.tileCoordinates=a.tiles,this.minTileX=a.minTileX,this.maxTileX=a.maxTileX,this.minTileY=a.minTileY,this.maxTileY=a.maxTileY}getImageUrl(t){let e=this.tileCoordinates[t];return e?k8(this.tileSource,{z:e.z,x:e.x,y:e.y,tileSize:this.tileSize,subdomains:this.subdomains}):""}},Q8=class{constructor(t){C(this,"canvas",void 0),C(this,"context",void 0),C(this,"heightRatio",1),C(this,"widthRatio",1),C(this,"target",new Float32Array(5)),C(this,"initialWidth",void 0),C(this,"initialHeight",void 0),C(this,"bounds",void 0),C(this,"aggregate",void 0),C(this,"delta",0),C(this,"renderNextFrame",!0),this.canvas=t,this.initialWidth=t.width,this.initialHeight=t.height,this.context=t.getContext("2d"),this.context.globalAlpha=.5,this.aggregate=mo(1)}isReady(){return!0}resize(){this.initialWidth=this.canvas.width,this.initialHeight=this.canvas.height,this.renderNextFrame=!0}afterFrame(t,e,n){if(this.renderNextFrame){this.context.clearRect(0,0,this.canvas.width,this.canvas.height);let i=this.initialWidth/t.width,a=this.initialHeight/t.height,r=this.widthRatio>this.heightRatio?i:a;if(this.target=n,this.bounds){let l=t.getPointsAt(this.bounds,this.aggregate,r);for(let[u,f]of l)if(u instanceof gi&&u.__host.canvas){let h=f.length/5;for(let d=0;d<h;d++)u.__host.canvas.canvases[d]&&(f[d+1]*r,f[d+2]*r,(f[d+3]-f[d+1])*r,(f[d+4]-f[d+2])*r)}}t.getPoints().forEach((l,u,f)=>{if(u%5==0&&l){let h={x1:f[u+1]*r,y1:f[u+2]*r,x2:f[u+3]*r,y2:f[u+4]*r,width:(f[u+3]-f[u+1])*r,height:(f[u+4]-f[u+2])*r};this.context.strokeStyle="red",this.context.strokeRect(h.x1,h.y1,h.width,h.height)}}),n&&(this.context.strokeStyle="red",this.context.lineWidth=window.devicePixelRatio||1,this.context.strokeRect(n[1]*r,n[2]*r,(n[3]-n[1])*r,(n[4]-n[2])*r))}}getActiveZone(t){return null}getPointsAt(t,e,n,i){return t.getPointsAt(e,n,i)}getScale(t,e){return 1}beforeFrame(t,e){this.bounds=de.singleBox(t.width,t.height)}drawImage(){}afterPaintLayer(t,e){}paint(t,e,n,i,a,r){this.renderNextFrame=!0}prepareLayer(t){}pendingUpdate(){return!1}hasActiveZone(){return!1}getViewportBounds(t,e,n){return null}getRendererScreenPosition(){return this.canvas.getBoundingClientRect()}finishLayer(){}reset(){}};function Tv(t,e,n,i,a){let r=Math.PI/180*a,l=Math.cos(r),u=Math.sin(r);return[l*(n-t)+u*(i-e)+t,l*(i-e)-u*(n-t)+e]}var Bo=class j3 extends Yr{constructor(e,n){super(),C(this,"id",void 0),C(this,"type","world-object"),C(this,"scale",void 0),C(this,"layers",void 0),C(this,"points",void 0),C(this,"worldPoints",void 0),C(this,"intersectionBuffer",It(5)),C(this,"aggregateBuffer",It(9)),C(this,"invertedBuffer",It(9)),C(this,"rotation",0),C(this,"filteredPointsBuffer",void 0),C(this,"_updatedList",[]),C(this,"geometry",void 0);let{x:i=0,y:a=0}=n||{};e?(this.id=e.id||"",this.scale=1,this.layers=e.layers,this.points=It([1,i,a,i+e.width,a+e.height]),this.worldPoints=It([1,i,a,i+e.width,a+e.height]),this.filteredPointsBuffer=It(e.layers.length*5)):(this.id="",this.scale=1,this.layers=[],this.points=It(5),this.worldPoints=It(5),this.filteredPointsBuffer=It(5))}static createWithProps(e){let n=new j3;return n.applyProps(e),n}applyProps(e){let n=e.x||0,i=e.y||0;e.id!==void 0&&(this.id=e.id);let a=e.scale===void 0?this.scale:e.scale;this.points[0]=1,this.points[1]=n,this.points[2]=i,this.points[3]=n+e.width,this.points[4]=i+e.height,this.rotation=e.rotation||0,this.worldPoints[3]=this.worldPoints[1]+e.width,this.worldPoints[4]=this.worldPoints[2]+e.height,e.scale&&e.scale!==1&&this.atScale(a),this.scale=a}appendChild(e){e.points[0]===0&&e.points.set(this.points),e.__owner.value=this,this.addLayers([e])}removeChild(e){this.layers=this.layers.filter(n=>n!==e),this.filteredPointsBuffer=It(this.layers.length*5)}insertBefore(e,n){let i=this.layers.indexOf(n);if(i===-1||this.layers.indexOf(e)!==-1)return;let a=this.layers.slice(0,i),r=this.layers.slice(i);this.layers=[...a,e,...r]}hideInstance(){console.warn("hideInstance: not yet implemented")}getObjectsAt(e,n){if(this.rotation&&(e=this.applyRotation(e)),Oc(this.points,e,this.filteredPointsBuffer)[0]===0)return[];let i=this.layers.length,a=[];for(let r=0;r<i;r++){let l=this.layers[r];if(n&&l.isShape){let u=Xi(l.points,ci(this.x,this.y));if(!l.intersects([e[1]-u[1],e[2]-u[2]]))continue}if(Oc(Xi(l.points,ci(this.x,this.y)),e,this.filteredPointsBuffer)[0]!==0&&a.push(l),n){let u=l;a.push(...u.getObjectsAt(e,n))}}return a}applyRotation(e){if(this.rotation){let n={x:e[1],y:e[2]},i={x:e[1],y:e[4]},a={x:e[3],y:e[2]},r={x:e[3],y:e[4]},l=this.points[1]+(this.points[3]-this.points[1])/2,u=this.points[2]+(this.points[4]-this.points[2])/2,[f,h]=Tv(l,u,n.x,n.y,this.rotation),[d,m]=Tv(l,u,i.x,i.y,this.rotation),[y,g]=Tv(l,u,a.x,a.y,this.rotation),[b,w]=Tv(l,u,r.x,r.y,this.rotation),E=Math.min(f,d,y,b),T=Math.max(f,d,y,b),S=Math.min(h,m,g,w),R=Math.max(h,m,g,w);return It([e[0],E,S,T,R])}return e}getAllPointsAt(e,n,i){let a=Dr(ci(this.x,this.y),mo(this.scale),this.aggregateBuffer);this.rotation&&(e=this.applyRotation(e));let r=AO(e,this.points,this.intersectionBuffer),l=this.layers.length,u=[],f=Xi(r,Dr(mo(1/this.scale),ci(-this.x,-this.y),this.invertedBuffer)),h=n?Dr(n,a,this.aggregateBuffer):a,d=i*this.scale;for(let m=0;m<l;m++)u.push(...this.layers[m].getAllPointsAt(f,h,d));return u}addLayers(e){let n=[];for(let i of e)this.layers.indexOf(i)===-1&&(n.push(i),i.points.length===5&&(i.points[1]<this.worldPoints[1]/this.scale||i.points[2]<this.worldPoints[2]/this.scale||i.points[3]>this.worldPoints[3]/this.scale||i.points[4]>this.worldPoints[4]/this.scale)&&(i.crop=i.crop||It([1,Math.max(this.worldPoints[1]/this.scale,i.points[1]),Math.max(this.worldPoints[2]/this.scale,i.points[2]),Math.min(this.worldPoints[3]/this.scale,i.points[3]),Math.min(this.worldPoints[4]/this.scale,i.points[4])])));this.layers=this.layers.concat(n),this.filteredPointsBuffer=It(this.layers.length*5)}getScheduledUpdates(e,n){let i=this.layers.length;this._updatedList=[];let a=n*this.scale;for(let r=0;r<i;r++){let l=this.layers[r].getScheduledUpdates(e,a);l&&this._updatedList.push(...l)}return this._updatedList}},mu=class k3 extends Yr{get x(){return 0}get y(){return 0}get width(){return this._width}get height(){return this._height}constructor(e=0,n=0,i=100,a="left-to-right"){super(),C(this,"id","world"),C(this,"_width",void 0),C(this,"_height",void 0),C(this,"aspectRatio",void 0),C(this,"viewingDirection",void 0),C(this,"aggregateBuffer",It(9)),C(this,"isDirty",!1),C(this,"zones",[]),C(this,"filteredPointsBuffer",void 0),C(this,"selectedZone",void 0),C(this,"triggerQueue",[]),C(this,"activatedEvents",[]),C(this,"_updatedList",[]),C(this,"translationBuffer",It(9)),C(this,"needsRecalculate",!0),C(this,"emptyPaintables",[]),C(this,"renderOrder",[]),C(this,"debugSubscribers",new Set),C(this,"zoneVisibilityFadeDurationMs",220),C(this,"zoneOutsideOpacity",.2),C(this,"zoneVisibilityFade",void 0),C(this,"points",void 0),C(this,"objects",[]),C(this,"subscriptions",[]),C(this,"_propagateEventTargets",[]),C(this,"_alreadyFlushed",[]),this._width=e,this._height=n,this.aspectRatio=Number.isNaN(e/n)?1:e/n,this.viewingDirection=a,this.points=It(i*5),this.filteredPointsBuffer=It(i*5)}static withProps(e){let n=new k3;return n.applyProps(e),n}applyProps(e){e.width!==void 0&&e.height!==void 0&&(e.width!==this._width||e.height!==this._height)&&this.resize(e.width,e.height),e.viewingDirection!==this.viewingDirection&&(this.viewingDirection=e.viewingDirection,this.triggerRepaint())}propagateTouchEvent(e,n,i){let a=[];for(let r of i)if(r.x&&r.y){let l=de.singleBox(1,1,r.x,r.y);a.push(this.getObjectsAt(l,!0).reverse())}return this.emitDebug({type:"touch",at:performance.now(),event:e,touches:i.length}),a.map(r=>this.propagateEvent(e,n,r,{bubbles:!0,cancelable:!0}))}propagatePointerEvent(e,n,i,a,r={}){let l=de.singleBox(1,1,i,a),u=this.getObjectsAt(l,!0).reverse(),f=this.propagateEvent(e,n,u,r);return this.emitDebug({type:"pointer",at:performance.now(),event:e,x:i,y:a,targets:f.length}),f}propagateEvent(e,n,i,{bubbles:a=!1,cancelable:r=!1}={}){n.atlasTarget=this,this._propagateEventTargets.length=1,this._propagateEventTargets[0]=this;let l=!1;n.stopPropagation=()=>{l=!0};let u=i.length;for(let d=u-1;d>=0;d--){this._propagateEventTargets.unshift(i[d][0]);let m=i[d][1].length;if(m)for(let y=0;y<m;y++)this._propagateEventTargets.unshift(i[d][1][y])}let f=this._propagateEventTargets.length,h=!1;for(let d=0;d<f&&(n.atlasTarget=this._propagateEventTargets[d],n.atlasWorld=this,h=this._propagateEventTargets[d].dispatchEvent(e,n)||h,!l);d++);return h&&this.triggerRepaint(),this._propagateEventTargets}appendChild(e){let n=this.appendWorldObject(e);this.renderOrder.push(n/5)}removeChild(e){let n=this.objects.indexOf(e);if(n===-1){for(let i of this.objects)if(i&&i.id===e.id){this.removeChild(i);return}return}this.objects[n]=null,this.renderOrder=this.renderOrder.filter(i=>i!==n),this.points[n*5]=0;for(let i of this.zones){let a=i.objects.indexOf(e);a!==-1&&(i.objects.splice(a,1),i.recalculateBounds())}this.triggerRepaint(),this.needsRecalculate=!0}insertBefore(e,n){let i=this.objects.indexOf(n);if(i===-1)return;let a=this.appendWorldObject(e);this.renderOrder.splice(i-1,0,a/5)}hideInstance(){}asWorldObject(){return null}addZone(e){this.zones.push(e)}removeZone(e){let n=this.zones.indexOf(e);if(n!==-1&&(this.zones.splice(n,1),this.selectedZone!==void 0)){if(this.selectedZone===n){this.selectedZone=void 0,this.trigger("zone-changed");return}this.selectedZone>n&&--this.selectedZone}}getZoneById(e){for(let n of this.zones)if(n.id===e)return n}hasZone(e){return this.getZoneById(e)!==void 0}selectZone(e){if(typeof e=="string"){let n=this.getZoneById(e);n&&(this.selectedZone=this.zones.indexOf(n),this.zoneVisibilityFade={zoneId:n.id,startedAt:performance.now()},this.trigger("zone-changed"))}else this.zones[e]&&(this.selectedZone=e,this.zoneVisibilityFade={zoneId:this.zones[e].id,startedAt:performance.now()},this.trigger("zone-changed"))}deselectZone(){this.selectedZone=void 0,this.zoneVisibilityFade=void 0,this.trigger("zone-changed")}getActiveZone(){if(this.selectedZone!==void 0)return this.zones[this.selectedZone]}hasActiveZone(){return this.selectedZone!==void 0}checkResizeInternalBuffer(){if(CO(this.points)===this.objects.length){let e=this.points,n=It(this.points.length*2);n.set(e,0),this.points=n}}appendWorldObject(e){this.checkResizeInternalBuffer();let n=this.objects.length*5,i=e.points;return e.points=this.points.subarray(this.objects.length*5,this.objects.length*5+5),e.points[1]=i[1],e.points[2]=i[2],e.points[3]=i[3],e.points[4]=i[4],this.objects.push(e),this.filteredPointsBuffer=It(this.objects.length*5),this.needsRecalculate=!0,this.triggerRepaint(),n}recalculateWorldSize(){let e=!1;if(this.needsRecalculate){let n=new Int32Array(this.objects.length),i=new Int32Array(this.objects.length),a=this.renderOrder.length;for(let u=0;u<a;u++){let f=this.renderOrder[u];this.objects[f]&&(n[u]=this.points[f*5+3],i[u]=this.points[f*5+4])}let r=Math.max(...n);r!==this._width&&(this._width=r,e=!0);let l=Math.max(...i);l!==this._height&&(this._height=l,e=!0),e&&this.trigger("recalculate-world-size",{width:r,height:l}),this.needsRecalculate=!1}return e}addObjectAt(e,n){n.width&&!n.height?n.height=n.width/e.width*e.height:n.height&&!n.width&&(n.width=n.height/e.height*e.width),(!n||!n.width||!n.height)&&(n.width=e.width,n.height=e.height);let{width:i,x:a,y:r}=n,l=i/e.width;this.checkResizeInternalBuffer(),this.points.set(de.singleBox(e.width,e.height,0,0),this.objects.length*5);let u=new Bo(e);return u.points=this.points.subarray(this.objects.length*5,this.objects.length*5+5),this.objects.push(u),this.scaleWorldObject(this.objects.length-1,l),this.translateWorldObject(this.objects.length-1,a,r),this.filteredPointsBuffer=It(this.points.length*2),this.triggerRepaint(),this.needsRecalculate=!0,u}scaleWorldObject(e,n){hr(this.points.subarray(e*5,e*5+5),kl(n,this.points[e*5+1],this.points[e*5+2]));let i=this.objects[e];i&&(i.atScale(n),this.triggerRepaint())}translateWorldObject(e,n,i){hr(this.points.subarray(e*5,e*5+5),ci(n,i));let a=this.objects[e];a&&(a.translate(n,i),this.triggerRepaint())}resize(e,n){return this._width=e,this._height=n,this.aspectRatio=e/n,this.triggerRepaint(),this}getObjects(){return this.objects}getPoints(){return this.points}getPointsFromViewer(e,n){let i=de.singleBox(e.width,e.height,e.x,e.y);return this.getPointsAt(i,n,e.scale)}addLayoutSubscriber(e){return this.subscriptions.push(e),()=>{this.subscriptions.splice(this.subscriptions.indexOf(e),1)}}getScheduledUpdates(e,n){let i=Oc(this.points,e,this.filteredPointsBuffer),a=this.objects.length;this._updatedList=[];for(let r=0;r<a;r++)if(i[r*5]!==0){if(!this.objects[r])continue;this._updatedList.push(...this.objects[r].getScheduledUpdates(e,n))}return this._updatedList}isZoneOutsideVisibilityFading(e){return!!(this.zoneVisibilityFade&&this.zoneVisibilityFade.zoneId===e.id&&performance.now()-this.zoneVisibilityFade.startedAt<this.zoneVisibilityFadeDurationMs)}getZoneOutsideVisibility(e){let n=this.zoneOutsideOpacity;if(!this.zoneVisibilityFade||this.zoneVisibilityFade.zoneId!==e.id)return n;let i=performance.now()-this.zoneVisibilityFade.startedAt;return i>=this.zoneVisibilityFadeDurationMs?n:1-Math.max(0,Math.min(1,i/this.zoneVisibilityFadeDurationMs))*(1-n)}getObjectsAt(e,n=!1,i=!1){let a=this.getActiveZone(),r=a&&i?this.getZoneOutsideVisibility(a)>0:!1,l=Oc(this.points,e,this.filteredPointsBuffer),u=this.renderOrder.length,f=[];for(let h=0;h<u;h++){let d=this.renderOrder[h];if(l[d*5]!==0){let m=this.objects[d],y=!a||a.objects.indexOf(m)!==-1;if(!m||!y&&!r)continue;if(m.type!=="world-object"){f.push([m,[m]]);continue}n?f.push([m,m.getObjectsAt(e,n)]):f.push([m,this.emptyPaintables])}}return f}getPointsAt(e,n,i=1){let a=this.getActiveZone(),r=a?this.getZoneOutsideVisibility(a):0,l=this.getObjectsAt(e,!1,!0),u=Dr(mo(i),ci(-e[1],-e[2]),this.translationBuffer),f=n?Dr(n,u,this.aggregateBuffer):u,h=l.length,d=[];for(let m=0;m<h;m++)if(l[m]){let y=l[m][0],g=y.getAllPointsAt(e,f,i),b=!a||a.objects.indexOf(y)!==-1?1:r;for(let w=0;w<g.length;w++)g[w][0].__zoneVisibilityAlpha=b;d.push(...g)}return a&&this.isZoneOutsideVisibilityFading(a)&&this.triggerRepaint(),d}flushSubscriptions(){if(this.triggerQueue.length){this._alreadyFlushed=[];let e=this.triggerQueue.length;for(let n=0;n<e;n++){if(this._alreadyFlushed.indexOf(this.triggerQueue[n][0])!==-1)continue;this.triggerQueue[n][1]===void 0&&this._alreadyFlushed.push(this.triggerQueue[n][0]);let i=this.subscriptions.length;for(let a=0;a<i;a++)this.subscriptions[a].apply(null,this.triggerQueue[n])}this.triggerQueue=[]}}trigger(e,n){this.emitDebug({type:"trigger",at:performance.now(),event:e,data:n}),this.triggerQueue.push([e,n])}triggerEventActivation(){this.trigger("event-activation")}triggerRepaint(){this.trigger("repaint")}gotoRegion(e){this.trigger("goto-region",e)}goHome(e=!1,n){this.trigger("go-home",{immediate:e,paddingPx:n})}zoomTo(e,n,i){this.trigger("zoom-to",{point:n,factor:e,stream:i})}zoomIn(e){this.trigger("zoom-to",{point:e,factor:.5})}zoomOut(e){this.trigger("zoom-to",{point:e,factor:2})}constraintBounds(e){this.trigger("constrain-bounds",{immediate:e})}hasPendingAnimation(){return!!(this.zoneVisibilityFade&&performance.now()-this.zoneVisibilityFade.startedAt<this.zoneVisibilityFadeDurationMs)}addDebugSubscriber(e){return this.debugSubscribers.add(e),()=>{this.removeDebugSubscriber(e)}}removeDebugSubscriber(e){this.debugSubscribers.delete(e)}emitDebug(e){if(this.debugSubscribers.size!==0)for(let n of this.debugSubscribers)n(e)}};var K8={background:"rgba(15, 23, 42, 0.7)",objectFill:"rgba(56, 189, 248, 0.22)",objectStroke:"rgba(56, 189, 248, 0.62)",viewportFill:"rgba(251, 191, 36, 0.22)",viewportStroke:"rgba(250, 204, 21, 1)",viewportLineWidth:2};function YT(t){if(!(typeof t!="number"||!Number.isFinite(t)))return Math.floor(t)}function Z8(t,e){if(!t||e<=1)return null;let n=YT(t.total),i=YT(t.before),a=YT(t.after),r=n===void 0?i!==void 0||a!==void 0?Math.max(1,Math.max(0,i||0)+Math.max(0,a||0)+1):9:Math.max(1,n),l=i===void 0?void 0:Math.max(0,i),u=a===void 0?void 0:Math.max(0,a);l===void 0&&u===void 0?(l=Math.floor((r-1)/2),u=r-l-1):l===void 0?l=Math.max(0,r-(u||0)-1):u===void 0&&(u=Math.max(0,r-l-1));let f=l+u+1;return f!==r&&(r=f),r=Math.max(1,Math.min(e,r)),l=Math.min(l,r-1),u=r-l-1,{total:r,before:l,after:u}}function W8(t){let e=[];for(let n=0;n<t.zones.length;n++){let i=t.zones[n];i.recalculateBounds(),i.points[0]!==0&&e.push({zone:i,minX:i.points[1],minY:i.points[2],maxX:i.points[3],maxY:i.points[4]})}return e.sort((n,i)=>n.minY===i.minY?n.minX===i.minX?(n.zone?.id||"").localeCompare(i.zone?.id||""):n.minX-i.minX:n.minY-i.minY),e}function G3(t,e){let n=Z8(e.zoneWindow,t.zones.length);if(!n)return null;let i=W8(t);if(i.length<=n.total)return i;let a=$8(i,e.target)-n.before,r=a+n.total-1;return a<0&&(a=0,r=n.total-1),r>=i.length&&(r=i.length-1,a=Math.max(0,r-n.total+1)),i.slice(a,r+1)}function J8(t){if(!t)return null;if(Array.isArray(t)||ArrayBuffer.isView(t)){let e=t;return e[0]===0?null:{x:(e[1]+e[3])/2,y:(e[2]+e[4])/2}}return{x:t.x+t.width/2,y:t.y+t.height/2}}function $8(t,e){if(t.length===0)return 0;let n=J8(e);if(!n)return 0;for(let r=0;r<t.length;r++){let l=t[r];if(n.x>=l.minX&&n.x<=l.maxX&&n.y>=l.minY&&n.y<=l.maxY)return r}let i=0,a=1/0;for(let r=0;r<t.length;r++){let l=t[r],u=(l.minY+l.maxY)/2,f=Math.abs(n.y-u);f<a&&(a=f,i=r)}return i}function tj(t){if(t.length===0)return null;let e=t[0].minX,n=t[0].minY,i=t[0].maxX,a=t[0].maxY;for(let r=1;r<t.length;r++){let l=t[r];e=Math.min(e,l.minX),n=Math.min(n,l.minY),i=Math.max(i,l.maxX),a=Math.max(a,l.maxY)}return{x:e,y:n,width:Math.max(1,i-e),height:Math.max(1,a-n)}}function eR(t,e,n,i,a=0,r=0){let l=Math.max(1,t),u=Math.max(1,e),f=Math.min(n/l,i/u),h=l*f,d=u*f;return{scale:f,offsetX:(n-h)/2,offsetY:(i-d)/2,worldX:a,worldY:r,worldWidth:l,worldHeight:u}}function Y3(t,e={}){let n=t.getActiveZone();if(n&&(n.recalculateBounds(),n.points[0]!==0))return{x:n.points[1],y:n.points[2],width:Math.max(1,n.points[3]-n.points[1]),height:Math.max(1,n.points[4]-n.points[2])};let i=G3(t,e);if(i&&i.length>0){let a=tj(i);if(a)return a}return{x:0,y:0,width:Math.max(1,t.width),height:Math.max(1,t.height)}}function ej(t,e={}){let n=t.getActiveZone();if(n)return n.recalculateBounds(),n.points[0]===0?new Set:new Set([n.id]);let i=G3(t,e);if(!i)return null;let a=new Set;for(let r of i)a.add(r.zone.id);return a}function nj(t,e,n){if(!t.scale||!Number.isFinite(t.scale))return{x:t.worldX,y:t.worldY};let i=t.worldX+(e-t.offsetX)/t.scale,a=t.worldY+(n-t.offsetY)/t.scale;return{x:Math.max(t.worldX,Math.min(t.worldX+t.worldWidth,i)),y:Math.max(t.worldY,Math.min(t.worldY+t.worldHeight,a))}}var ij=class extends Q8{constructor(t,e={}){super(t),C(this,"style",void 0),C(this,"maxRects",void 0),C(this,"minVisibleRectSize",void 0),C(this,"drawFallbackBoxes",void 0),C(this,"zoneWindow",void 0),C(this,"sharedCanvasRenderer",void 0),C(this,"onRequestRender",void 0),C(this,"onDebugEvent",void 0),C(this,"baseCanvas",void 0),C(this,"baseContext",void 0),C(this,"worldTarget",de.singleBox(1,1,0,0)),C(this,"previewImageCache",new Map),C(this,"worldLayerDirty",!0),C(this,"lastWorldWidth",0),C(this,"lastWorldHeight",0),C(this,"lastTargetX",NaN),C(this,"lastTargetY",NaN),C(this,"lastTargetX2",NaN),C(this,"lastTargetY2",NaN),C(this,"lastRegionX",NaN),C(this,"lastRegionY",NaN),C(this,"lastRegionWidth",NaN),C(this,"lastRegionHeight",NaN),C(this,"worldLayerInvalidationVersion",0),C(this,"sharedCanvasResourcesPending",!1),this.style={...K8,...e.style||{}},this.maxRects=Math.max(100,e.maxRects||5e3),this.minVisibleRectSize=Math.max(1,e.minVisibleRectSize||1),this.drawFallbackBoxes=e.drawFallbackBoxes!==!1,this.zoneWindow=e.zoneWindow,this.sharedCanvasRenderer=e.sharedCanvasRenderer,this.onRequestRender=e.onRequestRender,this.onDebugEvent=e.onDebugEvent,this.context.globalAlpha=1,this.context.imageSmoothingEnabled=!1,this.baseCanvas=document.createElement("canvas"),this.baseContext=this.baseCanvas.getContext("2d"),this.baseContext.imageSmoothingEnabled=!0,this.syncBaseLayerCanvas()}emitDebugEvent(t){this.onDebugEvent&&this.onDebugEvent(t)}requestRender(t){this.onRequestRender&&(this.emitDebugEvent({type:"render-request-forwarded",reason:t}),this.onRequestRender())}invalidateWorldLayer(t="manual"){this.worldLayerInvalidationVersion++,this.worldLayerDirty=!0,this.renderNextFrame=!0,this.emitDebugEvent({type:"world-layer-invalidated",reason:t}),this.requestRender(t)}resize(){super.resize(),this.syncBaseLayerCanvas(),this.invalidateWorldLayer("resize")}beforeFrame(t){(t.width!==this.lastWorldWidth||t.height!==this.lastWorldHeight)&&(this.lastWorldWidth=t.width,this.lastWorldHeight=t.height,this.invalidateWorldLayer("world-size-changed"))}paint(){this.renderNextFrame=!0}pendingUpdate(){return this.renderNextFrame||this.worldLayerDirty}afterFrame(t,e,n){let i=this.worldLayerInvalidationVersion;if(this.canvas.width<=0||this.canvas.height<=0){this.emitDebugEvent({type:"frame-skipped-zero-size-canvas",canvasWidth:this.canvas.width,canvasHeight:this.canvas.height,baseCanvasWidth:this.baseCanvas.width,baseCanvasHeight:this.baseCanvas.height}),this.renderNextFrame=!0;return}let a=Y3(t,{target:n,zoneWindow:this.zoneWindow});this.hasRegionChanged(a)&&(this.worldLayerDirty=!0);let r=this.hasViewportChanged(n);if(this.renderNextFrame||this.worldLayerDirty||r){if((this.baseCanvas.width!==this.canvas.width||this.baseCanvas.height!==this.canvas.height)&&(this.syncBaseLayerCanvas(),this.worldLayerDirty=!0),this.baseCanvas.width<=0||this.baseCanvas.height<=0){this.emitDebugEvent({type:"frame-skipped-zero-size-canvas",canvasWidth:this.canvas.width,canvasHeight:this.canvas.height,baseCanvasWidth:this.baseCanvas.width,baseCanvasHeight:this.baseCanvas.height}),this.renderNextFrame=!0;return}if(this.worldLayerDirty){let l=this.worldLayerInvalidationVersion;this.sharedCanvasResourcesPending=!1,this.emitDebugEvent({type:"world-layer-render-start",region:a});try{this.renderWorldLayer(t,a)}finally{this.emitDebugEvent({type:"world-layer-render-end",region:a})}this.worldLayerDirty=this.sharedCanvasResourcesPending||l!==this.worldLayerInvalidationVersion}this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.context.drawImage(this.baseCanvas,0,0),this.renderViewportBox(n,a),this.lastTargetX=n[1],this.lastTargetY=n[2],this.lastTargetX2=n[3],this.lastTargetY2=n[4],this.lastRegionX=a.x,this.lastRegionY=a.y,this.lastRegionWidth=a.width,this.lastRegionHeight=a.height,this.renderNextFrame=this.sharedCanvasResourcesPending||i!==this.worldLayerInvalidationVersion}}hasViewportChanged(t){return this.lastTargetX!==t[1]||this.lastTargetY!==t[2]||this.lastTargetX2!==t[3]||this.lastTargetY2!==t[4]}hasRegionChanged(t){return this.lastRegionX!==t.x||this.lastRegionY!==t.y||this.lastRegionWidth!==t.width||this.lastRegionHeight!==t.height}syncBaseLayerCanvas(){this.baseCanvas.width=this.canvas.width,this.baseCanvas.height=this.canvas.height}shouldClipImagePaintToBounds(t){return t instanceof gi||t instanceof Ri?!!t.__parent?.renderOptions?.clipToBounds:!1}getBoundsFromPoints(t){let e=1/0,n=1/0,i=-1/0,a=-1/0;for(let r=0;r<t.length;r+=5)t[r]&&(e=Math.min(e,t[r+1]),n=Math.min(n,t[r+2]),i=Math.max(i,t[r+3]),a=Math.max(a,t[r+4]));if(!(!Number.isFinite(e)||!Number.isFinite(n)||!Number.isFinite(i)||!Number.isFinite(a))&&!(i<=e||a<=n))return{x:e,y:n,width:i-e,height:a-n}}getLayerClipBounds(t,e,n){if(!this.shouldClipImagePaintToBounds(t))return;let i=t.__parent,a=i?.crop||i?.points;if(!a)return;let r=e?Xi(a,e):a,l=this.getBoundsFromPoints(r);if(l)return{x:l.x+n.offsetX,y:l.y+n.offsetY,width:l.width,height:l.height}}renderWorldLayer(t,e){let n=this.baseContext;n.clearRect(0,0,this.baseCanvas.width,this.baseCanvas.height),n.fillStyle=this.style.background,n.fillRect(0,0,this.baseCanvas.width,this.baseCanvas.height);let i=t.getActiveZone(),a=eR(e.width,e.height,this.baseCanvas.width,this.baseCanvas.height,e.x,e.y);this.worldTarget[1]=e.x,this.worldTarget[2]=e.y,this.worldTarget[3]=e.x+e.width,this.worldTarget[4]=e.y+e.height;let r=t.getPointsAt(this.worldTarget,this.aggregate,a.scale),l=0;for(let u=0;u<r.length&&!(l>=this.maxRects);u++){let f=r[u][0],h=r[u][1],d=r[u][2],m=d?Xi(h,d):h,y=m.length/5,g=this.getLayerClipBounds(f,d,a);g&&(n.save(),n.beginPath(),n.rect(g.x,g.y,g.width,g.height),n.clip());try{for(let b=0;b<y&&!(l>=this.maxRects);b++){let w=b*5;if(m[w]===0)continue;if(i){let A=f?.__owner?.value;if(!A||i.objects.indexOf(A)===-1)continue}let E=m[w+1]+a.offsetX,T=m[w+2]+a.offsetY,S=Math.max(this.minVisibleRectSize,m[w+3]-m[w+1]),R=Math.max(this.minVisibleRectSize,m[w+4]-m[w+2]);f instanceof cR?this.renderGeometry(n,f,E,T,a.scale):f instanceof Td?this.renderBox(n,f,E,T,S,R,a.scale):this.renderImagePaint(n,f,b,E,T,S,R)||this.drawFallbackBoxes&&this.renderFallbackBox(n,E,T,S,R),l++}}finally{g&&n.restore()}}}renderFallbackBox(t,e,n,i,a){let r=Math.round(e),l=Math.round(n),u=Math.max(1,Math.round(i)),f=Math.max(1,Math.round(a));t.fillStyle=this.style.objectFill,t.strokeStyle=this.style.objectStroke,t.lineWidth=1,t.fillRect(r,l,u,f),u>2&&f>2&&t.strokeRect(r+.5,l+.5,u-1,f-1)}renderImagePaint(t,e,n,i,a,r,l){if(r<=0||l<=0)return!1;let u;if(e instanceof Lv)u=e.getTexture()?.source;else if(e instanceof gi||e instanceof Ri){let d=this.renderSharedCanvasImage(t,e,n,i,a,r,l);if(d!==null)return d;if(typeof e.getImageUrl!="function")return!1;let m=e.getImageUrl(n);u=this.getLoadedPreviewImage(m)}if(!u)return!1;let f=Math.max(1,Math.round(r)),h=Math.max(1,Math.round(l));return t.drawImage(u,Math.round(i),Math.round(a),f,h),!0}ensureSharedCanvasImageBuffer(t){return t.__host?.canvas||this.sharedCanvasRenderer?.createImageHost?.(t),t.__host||(t.__host={}),t.__host.canvas||(t.__host.canvas={canvases:[],tiles:{}}),t.__host.canvas.canvases||(t.__host.canvas.canvases=[]),t.__host.canvas.tiles||(t.__host.canvas.tiles={}),t.__host.canvas}drawSharedCanvasTile(t,e,n,i,a,r,l,u){let f=Math.max(1,Math.round(l)),h=Math.max(1,Math.round(u));if(e.crop&&e.cropData){let g=n*5;if(!e.crop[g])return!1;let b=e.crop[g+1]/e.display.scale-e.display.points[g+1]+e.cropData.x/e.display.scale,w=e.crop[g+2]/e.display.scale-e.display.points[g+2]+e.cropData.y/e.display.scale,E=1+(e.crop[g+3]-e.crop[g+1])/e.display.scale,T=1+(e.crop[g+4]-e.crop[g+2])/e.display.scale;return t.drawImage(i,b,w,E,T,Math.round(a),Math.round(r),f,h),!0}let d=n*5,m=e.display.points[d+3]-e.display.points[d+1],y=e.display.points[d+4]-e.display.points[d+2];return t.drawImage(i,0,0,m,y,Math.round(a),Math.round(r),f,h),!0}renderSharedCanvasImage(t,e,n,i,a,r,l){let u=this.sharedCanvasRenderer;if(!u?.hostCache)return null;let f=this.ensureSharedCanvasImageBuffer(e),h=f.canvases?.[n],d=!!h&&!!u.invalidated?.includes(h),m=h&&!d?u.hostCache.get(h):void 0;if(m)return this.drawSharedCanvasTile(t,e,n,m,i,a,r,l);let y=f.tiles?.[n],g=Math.hypot(i+r/2-this.baseCanvas.width/2,a+l/2-this.baseCanvas.height/2);return(u.schedulePaintToCanvas?.(f,e,n,g,!1)||y?.state==="queued"||y?.state==="loading"||y?.state==="decoded")&&(this.sharedCanvasResourcesPending=!0),!1}getLoadedPreviewImage(t){let e=this.previewImageCache.get(t);if(e){if(e.status==="loading"&&e.image.complete){if(e.image.naturalWidth>0&&e.image.naturalHeight>0)return e.status="loaded",this.emitDebugEvent({type:"preview-image-loaded",imageUrl:t,cached:!0}),this.invalidateWorldLayer("preview-image-loaded"),e.image;e.status="error",this.emitDebugEvent({type:"preview-image-error",imageUrl:t});return}return e.status==="loaded"?e.image:void 0}let n=new Image,i={image:n,status:"loading"};return this.previewImageCache.set(t,i),this.emitDebugEvent({type:"preview-image-requested",imageUrl:t}),n.onload=()=>{i.status==="loading"&&(i.status="loaded",this.emitDebugEvent({type:"preview-image-loaded",imageUrl:t,cached:!1}),this.invalidateWorldLayer("preview-image-loaded"))},n.onerror=()=>{i.status==="loading"&&(i.status="error",this.emitDebugEvent({type:"preview-image-error",imageUrl:t}))},n.src=t,n.complete&&(n.naturalWidth>0&&n.naturalHeight>0?(i.status="loaded",this.emitDebugEvent({type:"preview-image-loaded",imageUrl:t,cached:!0}),this.invalidateWorldLayer("preview-image-loaded")):(i.status="error",this.emitDebugEvent({type:"preview-image-error",imageUrl:t}))),i.status==="loaded"?n:void 0}renderBox(t,e,n,i,a,r,l){let u=e.props?.style;if(!u){this.renderFallbackBox(t,n,i,a,r);return}let f=u.backgroundColor||this.style.objectFill,h=u.borderColor||this.style.objectStroke,d=u.borderWidth?parseInt(u.borderWidth,10):0,m=Math.max(0,d*(e.props?.relativeStyle?1:l));t.globalAlpha=typeof u.opacity=="number"?u.opacity:1,t.fillStyle=f,t.fillRect(Math.round(n),Math.round(i),Math.max(1,Math.round(a)),Math.max(1,Math.round(r))),m>0&&(t.strokeStyle=h,t.lineWidth=Math.max(1,m),t.strokeRect(Math.round(n)+t.lineWidth/2,Math.round(i)+t.lineWidth/2,Math.max(1,Math.round(a))-t.lineWidth,Math.max(1,Math.round(r))-t.lineWidth)),t.globalAlpha=1}renderGeometry(t,e,n,i,a){let r=e.shape;if(r.type!=="polygon"||r.points.length===0)return;let l=e.props?.style||{},u=l.backgroundColor||this.style.objectFill,f=l.borderColor||this.style.objectStroke,h=l.borderWidth?parseInt(l.borderWidth,10):0,d=Math.max(0,h*(e.props?.relativeStyle?1:a));t.globalAlpha=typeof l.opacity=="number"?l.opacity:1,t.beginPath();for(let m=0;m<r.points.length;m++){let y=n+r.points[m][0]*a,g=i+r.points[m][1]*a;m===0?t.moveTo(y,g):t.lineTo(y,g)}r.open||(t.closePath(),t.fillStyle=u,t.fill()),(d>0||r.open)&&(t.strokeStyle=f,t.lineWidth=Math.max(1,d||1),t.stroke()),t.globalAlpha=1}renderViewportBox(t,e){let n=eR(e.width,e.height,this.canvas.width,this.canvas.height,e.x,e.y),i=(t[1]-n.worldX)*n.scale+n.offsetX,a=(t[2]-n.worldY)*n.scale+n.offsetY,r=(t[3]-t[1])*n.scale,l=(t[4]-t[2])*n.scale,u=Math.round(i),f=Math.round(a),h=Math.max(1,Math.round(r)),d=Math.max(1,Math.round(l));this.context.fillStyle=this.style.viewportFill,this.context.fillRect(u,f,h,d),this.context.strokeStyle=this.style.viewportStroke,this.context.lineWidth=Math.max(1,this.style.viewportLineWidth),this.context.strokeRect(u+.5,f+.5,Math.max(1,h-1),Math.max(1,d-1))}},Yh=class extends Yr{constructor(){super(),C(this,"type","spacial-content"),C(this,"id",void 0),C(this,"points",void 0),C(this,"color","#000"),C(this,"backgroundColor",void 0),C(this,"hovering",void 0),C(this,"pressing",void 0),C(this,"text",""),C(this,"display",{x:0,y:0,scale:1,width:100,height:100,points:It(5)}),C(this,"className",void 0),C(this,"html",void 0),C(this,"interactive",!1),C(this,"props",{font:"18px Arial, sans-serif",lineHeight:1,textAlign:"left",verticalAlign:"top",paddingX:0,paddingY:0,fitParent:!1,lineBreak:"auto",strokeText:!1,sizeToFill:!1,maxFontSizeToFill:void 0,allowNewLine:!0,justifyLines:!1,renderHDPI:!1,textDecoration:"none",interactive:!1,relativeSize:!1}),this.id="",this.points=It(5)}getAllPointsAt(t,e){return[[this,this.points,e]]}applyProps({id:t,target:e,text:n,color:i,backgroundColor:a,fontSize:r=18,interactive:l,fontFamily:u="Arial, sans-serif",...f}){f.font=`${r}px ${u}`,this.interactive=l||!1,n!==void 0&&(this.text=n||""),i&&(this.color=i),a&&(this.backgroundColor=a),t&&(this.id=t),e&&(this.points=de.singleBox(e.width,e.height,e.x,e.y),this.display.points=this.points,this.display.width=e.width,this.display.height=e.height),this.props={...this.props,...f},this.__revision++}};function nR(t,e){let n=e?t:JSON.stringify(t),i=5381,a=n.length;for(;a;)i=i*33^n.charCodeAt(--a);let r=(i>>>0).toString(16);return r.length%2?"0"+r:r}var X3=class{constructor(t){C(this,"$element",void 0),C(this,"stylesheetClasses",void 0),C(this,"activeStylesheetClasses",void 0),C(this,"sheetsDidUpdate",void 0),C(this,"sheetPrefix",void 0),C(this,"stylesheetEntries",void 0),this.sheetPrefix=t?.sheetPrefix||"a-",this.$element=document.createElement("style"),this.stylesheetClasses=[],this.activeStylesheetClasses=[],this.sheetsDidUpdate=!1,this.stylesheetEntries={}}getElement(){return this.$element}addStylesheet(t){let e=t.replace(/\s\s+/g," ").replace(/: /g,":").replace(/; /g,";").trim(),n=this.sheetPrefix+nR(e,!0);return this.stylesheetClasses.indexOf(n)===-1&&(this.stylesheetClasses.push(n),this.activeStylesheetClasses.push(n),this.stylesheetEntries[n]=e,this.sheetsDidUpdate=!0),n}removeStylesheet(t){let e=this.sheetPrefix+nR(t,!0);this.stylesheetClasses.indexOf(e)&&(this.stylesheetClasses=this.stylesheetClasses.filter(n=>n!==e)),this.sheetsDidUpdate=!0}clearClasses(){this.activeStylesheetClasses=[]}didUpdateActive(){if(this.activeStylesheetClasses.length){for(let t of this.activeStylesheetClasses)if(this.stylesheetClasses.indexOf(t)===-1)return!0;for(let t of this.stylesheetClasses)if(this.activeStylesheetClasses.indexOf(t)===-1)return!0}return!1}updateSheet(){(this.sheetsDidUpdate||this.didUpdateActive())&&(this.$element.innerText=this.activeStylesheetClasses.map(t=>`.${t}{${this.stylesheetEntries[t]}}`).join(""),this.sheetsDidUpdate=!1,this.stylesheetClasses=[...this.activeStylesheetClasses])}},Q3=class{constructor(t,e){C(this,"htmlContainer",void 0),C(this,"visible",[]),C(this,"previousVisible",[]),C(this,"htmlIds",[]),C(this,"firstMeaningfulPaint",!1),C(this,"rendererPosition",void 0),C(this,"stylesheet",void 0),C(this,"options",void 0),C(this,"paintTx",1),C(this,"zIndex",0),C(this,"classes",void 0),this.htmlContainer=t,this.htmlContainer.innerHTML="",this.rendererPosition=this.htmlContainer.getBoundingClientRect(),this.options={triggerResize:()=>{},box:!1,text:!1,sheetPrefix:"",inlineStyles:!1,background:"",...e||{}},this.stylesheet=new X3({sheetPrefix:this.options.sheetPrefix}),this.options.inlineStyles||this.htmlContainer.appendChild(this.stylesheet.getElement()),this.options.background&&this.htmlContainer.classList.add(this.stylesheet.addStylesheet(`
25
25
  background: ${this.options.background};
26
26
  `)),this.classes={hostClassName:this.stylesheet.addStylesheet(`
27
27
  position: absolute;