@embedpdf/core 1.5.0 → 2.0.0-next.1

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.
Files changed (55) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.js +680 -113
  4. package/dist/index.js.map +1 -1
  5. package/dist/lib/base/base-plugin.d.ts +52 -0
  6. package/dist/lib/index.d.ts +1 -0
  7. package/dist/lib/registry/plugin-registry.d.ts +6 -2
  8. package/dist/lib/store/actions.d.ts +122 -31
  9. package/dist/lib/store/initial-state.d.ts +22 -6
  10. package/dist/lib/store/reducer-helpers.d.ts +11 -0
  11. package/dist/lib/store/selectors.d.ts +21 -3
  12. package/dist/lib/types/plugin.d.ts +2 -2
  13. package/dist/lib/utils/event-control.d.ts +37 -2
  14. package/dist/lib/utils/eventing.d.ts +1 -1
  15. package/dist/lib/utils/scoped-eventing.d.ts +71 -0
  16. package/dist/preact/index.cjs +1 -1
  17. package/dist/preact/index.cjs.map +1 -1
  18. package/dist/preact/index.js +53 -18
  19. package/dist/preact/index.js.map +1 -1
  20. package/dist/react/index.cjs +1 -1
  21. package/dist/react/index.cjs.map +1 -1
  22. package/dist/react/index.js +53 -18
  23. package/dist/react/index.js.map +1 -1
  24. package/dist/shared/context.d.ts +6 -1
  25. package/dist/shared/hooks/index.d.ts +1 -0
  26. package/dist/shared/hooks/use-core-state.d.ts +4 -2
  27. package/dist/shared/hooks/use-document-state.d.ts +8 -0
  28. package/dist/shared-preact/context.d.ts +6 -1
  29. package/dist/shared-preact/hooks/index.d.ts +1 -0
  30. package/dist/shared-preact/hooks/use-core-state.d.ts +4 -2
  31. package/dist/shared-preact/hooks/use-document-state.d.ts +8 -0
  32. package/dist/shared-react/context.d.ts +6 -1
  33. package/dist/shared-react/hooks/index.d.ts +1 -0
  34. package/dist/shared-react/hooks/use-core-state.d.ts +4 -2
  35. package/dist/shared-react/hooks/use-document-state.d.ts +8 -0
  36. package/dist/svelte/hooks/index.d.ts +1 -0
  37. package/dist/svelte/hooks/use-core-state.svelte.d.ts +5 -4
  38. package/dist/svelte/hooks/use-document-state.svelte.d.ts +9 -0
  39. package/dist/svelte/hooks/use-registry.svelte.d.ts +6 -1
  40. package/dist/svelte/index.cjs +1 -1
  41. package/dist/svelte/index.cjs.map +1 -1
  42. package/dist/svelte/index.js +55 -17
  43. package/dist/svelte/index.js.map +1 -1
  44. package/dist/vue/components/auto-mount.vue.d.ts +3 -2
  45. package/dist/vue/components/embed-pdf.vue.d.ts +13 -2
  46. package/dist/vue/components/nested-wrapper.vue.d.ts +3 -2
  47. package/dist/vue/composables/index.d.ts +1 -0
  48. package/dist/vue/composables/use-core-state.d.ts +8 -1
  49. package/dist/vue/composables/use-document-state.d.ts +8 -0
  50. package/dist/vue/context.d.ts +6 -1
  51. package/dist/vue/index.cjs +1 -1
  52. package/dist/vue/index.cjs.map +1 -1
  53. package/dist/vue/index.js +88 -27
  54. package/dist/vue/index.js.map +1 -1
  55. package/package.json +3 -3
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("@embedpdf/models");class e{constructor(){this.dependencyGraph=new Map}addNode(t,e=[]){this.dependencyGraph.set(t,new Set(e))}hasCircularDependencies(){const t=new Set,e=new Set,i=s=>{t.add(s),e.add(s);const r=this.dependencyGraph.get(s)||new Set;for(const n of r)if(t.has(n)){if(e.has(n))return!0}else if(i(n))return!0;return e.delete(s),!1};for(const s of this.dependencyGraph.keys())if(!t.has(s)&&i(s))return!0;return!1}resolveLoadOrder(){if(this.hasCircularDependencies())throw new Error("Circular dependencies detected");const t=[],e=new Set,i=new Set,s=r=>{if(i.has(r))throw new Error("Circular dependency");if(e.has(r))return;i.add(r);const n=this.dependencyGraph.get(r)||new Set;for(const t of n)s(t);i.delete(r),e.add(r),t.push(r)};for(const r of this.dependencyGraph.keys())e.has(r)||s(r);return t}}class i extends Error{constructor(t){super(t),this.name="PluginRegistrationError"}}class s extends Error{constructor(t){super(t),this.name="PluginNotFoundError"}}class r extends Error{constructor(t){super(t),this.name="CircularDependencyError"}}class n extends Error{constructor(t){super(t),this.name="CapabilityNotFoundError"}}class o extends Error{constructor(t){super(t),this.name="CapabilityConflictError"}}class a extends Error{constructor(t){super(t),this.name="PluginInitializationError"}}class u extends Error{constructor(t){super(t),this.name="PluginConfigurationError"}}class l{constructor(t,e){this.store=t,this.pluginId=e}getState(){return this.store.getState().plugins[this.pluginId]}dispatch(t){return this.store.dispatchToPlugin(this.pluginId,t)}subscribeToState(t){return this.store.subscribeToPlugin(this.pluginId,((e,i,s)=>{t(e,i,s)}))}onAction(t,e){return this.store.onAction(t,((t,i,s)=>{e(t,i.plugins[this.pluginId],s.plugins[this.pluginId])}))}}const h="LOAD_DOCUMENT",c="REFRESH_DOCUMENT",d="REFRESH_PAGES",g="SET_DOCUMENT",p="SET_DOCUMENT_ERROR",f="SET_SCALE",y="SET_ROTATION",m="SET_PAGES",w=[h,c,g,p,f,y,m];class b{constructor(t,e){this.initialCoreState=e,this.pluginReducers={},this.listeners=[],this.pluginListeners={},this.isDispatching=!1,this.state={core:e,plugins:{}},this.coreReducer=t}addPluginReducer(t,e,i){this.state.plugins[t]=i,this.pluginReducers[t]=e}dispatchToCore(t){if(!this.coreReducer)return this.getState();if(this.isDispatching)throw new Error("Reducers may not dispatch actions. To trigger cascading actions, dispatch from a listener callback instead.");const e=this.getState();try{this.isDispatching=!0,this.state.core=this.coreReducer(this.state.core,t)}finally{this.isDispatching=!1}return this.listeners.forEach((i=>{const s=this.getState();i(t,s,e)})),this.getState()}dispatchToPlugin(t,e,i=!0){if(this.isDispatching)throw new Error("Reducers may not dispatch actions. To trigger cascading actions, dispatch from a listener callback instead.");const s=this.getState(),r=this.pluginReducers[t];if(!r)return s.plugins[t];const n=s.plugins[t];try{this.isDispatching=!0;const i=r(n,e);this.state.plugins[t]=i}finally{this.isDispatching=!1}return i&&this.listeners.forEach((t=>{const i=this.getState();t(e,i,s)})),this.pluginListeners[t]&&this.pluginListeners[t].forEach((i=>{const s=this.getState().plugins[t];i(e,s,n)})),this.getState().plugins[t]}dispatch(t){if(this.isDispatching)throw new Error("Reducers may not dispatch actions. To trigger cascading actions, dispatch from a listener callback instead.");const e=this.getState();try{this.isDispatching=!0,this.isCoreAction(t)&&(this.state.core=this.coreReducer(this.state.core,t));for(const i in this.pluginReducers){const s=this.pluginReducers[i],r=e.plugins[i];s&&(this.state.plugins[i]=s(r,t))}}finally{this.isDispatching=!1}return this.listeners.forEach((i=>{const s=this.getState();i(t,s,e)})),this.getState()}getState(){if(this.isDispatching)throw new Error("You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.");return{core:{...this.state.core},plugins:{...this.state.plugins}}}subscribe(t){if(this.isDispatching)throw new Error("You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state.");return this.listeners.push(t),()=>{if(this.isDispatching)throw new Error("You may not unsubscribe from a store listener while the reducer is executing.");this.listeners=this.listeners.filter((e=>e!==t))}}subscribeToPlugin(t,e){if(!(t in this.state.plugins))throw new Error(`Plugin state not found for plugin "${t}". Did you forget to call addPluginReducer?`);if(this.isDispatching)throw new Error("You may not call store.subscribeToPlugin() while the reducer is executing.");return this.pluginListeners[t]||(this.pluginListeners[t]=[]),this.pluginListeners[t].push(e),()=>{if(this.isDispatching)throw new Error("You may not unsubscribe from a store listener while the reducer is executing.");this.pluginListeners[t]=this.pluginListeners[t].filter((t=>t!==e)),0===this.pluginListeners[t].length&&delete this.pluginListeners[t]}}onAction(t,e){return this.subscribe(((i,s,r)=>{i.type===t&&e(i,s,r)}))}getPluginStore(t){if(!(t in this.state.plugins))throw new Error(`Plugin state not found for plugin "${t}". Did you forget to call addPluginReducer?`);return new l(this,t)}isCoreAction(t){return w.includes(t.type)}destroy(){var t,e;this.listeners.length=0;for(const i in this.pluginListeners)null==(e=null==(t=this.pluginListeners[i])?void 0:t.splice)||e.call(t,0);this.pluginListeners={},this.pluginReducers={},this.state.plugins={},this.state.core={...this.initialCoreState}}}const S=e=>({scale:(null==e?void 0:e.scale)??1,rotation:(null==e?void 0:e.rotation)??t.Rotation.Degree0,document:null,pages:[],loading:!1,error:null}),E=(t,e)=>{switch(e.type){case h:return{...t,loading:!0,error:null};case g:case c:return{...t,document:e.payload,pages:e.payload.pages.map((t=>[t])),loading:!1,error:null};case y:return{...t,rotation:e.payload};case m:return{...t,pages:e.payload};case p:return{...t,loading:!1,error:e.payload};case f:return{...t,scale:e.payload};default:return t}};class P{constructor(t,e){this.handler=t,this.options=e,this.lastRun=0,this.handle=t=>{"debounce"===this.options.mode?this.debounce(t):this.throttle(t)}}debounce(t){this.timeoutId&&window.clearTimeout(this.timeoutId),this.timeoutId=window.setTimeout((()=>{this.handler(t),this.timeoutId=void 0}),this.options.wait)}throttle(t){if("debounce"===this.options.mode)return;const e=Date.now(),i=this.options.throttleMode||"leading-trailing";e-this.lastRun>=this.options.wait&&("leading-trailing"===i&&this.handler(t),this.lastRun=e),this.timeoutId&&window.clearTimeout(this.timeoutId),this.timeoutId=window.setTimeout((()=>{this.handler(t),this.lastRun=Date.now(),this.timeoutId=void 0}),this.options.wait-(e-this.lastRun))}destroy(){this.timeoutId&&window.clearTimeout(this.timeoutId)}}function R(t,e,i){if(t===e)return!0;if(null==t||null==e)return t===e;const s=typeof t;if(s!==typeof e)return!1;if("object"===s){i||(i=new Set);const s=function(t,e){return`${T(t)}__${T(e)}`}(t,e);if(i.has(s))return!0;i.add(s);const r=Array.isArray(t),n=Array.isArray(e);return r&&n?function(t,e,i){if(t.length!==e.length)return!1;const s=new Array(e.length).fill(!1);t:for(let r=0;r<t.length;r++){const n=t[r];for(let t=0;t<e.length;t++)if(!s[t]&&R(n,e[t],i)){s[t]=!0;continue t}return!1}return!0}(t,e,i):!r&&!n&&function(t,e,i){const s=Object.keys(t).sort(),r=Object.keys(e).sort();if(s.length!==r.length)return!1;for(let n=0;n<s.length;n++)if(s[n]!==r[n])return!1;for(const n of s){if(!R(t[n],e[n],i))return!1}return!0}(t,e,i)}return!1}let v=0;const C=new WeakMap;function T(t){return C.has(t)||C.set(t,++v),C.get(t)}class x{constructor(t){this.autoMountElements=[],this.package=t}addUtility(t){return this.autoMountElements.push({component:t,type:"utility"}),this}addWrapper(t){return this.autoMountElements.push({component:t,type:"wrapper"}),this}build(){return{...this.package,autoMountElements:()=>this.autoMountElements}}}exports.BasePlugin=class{constructor(t,e){if(this.id=t,this.registry=e,this.cooldownActions={},this.debouncedTimeouts={},this.unsubscribeFromState=null,this.unsubscribeFromCoreStore=null,t!==this.constructor.id)throw new Error(`Plugin ID mismatch: ${t} !== ${this.constructor.id}`);this.engine=this.registry.getEngine(),this.logger=this.registry.getLogger(),this.coreStore=this.registry.getStore(),this.pluginStore=this.coreStore.getPluginStore(this.id),this.unsubscribeFromState=this.pluginStore.subscribeToState(((t,e,i)=>{this.onStoreUpdated(i,e)})),this.unsubscribeFromCoreStore=this.coreStore.subscribe(((t,e,i)=>{this.onCoreStoreUpdated(i,e)})),this.readyPromise=new Promise((t=>{this.readyResolve=t})),this.readyResolve()}provides(){if(!this._capability){const t=this.buildCapability();this._capability=Object.freeze(t)}return this._capability}get state(){return this.pluginStore.getState()}get coreState(){return this.coreStore.getState()}getState(){return this.pluginStore.getState()}getCoreState(){return this.coreStore.getState()}dispatchCoreAction(t){return this.coreStore.dispatchToCore(t)}dispatchToAllPlugins(t){return this.coreStore.dispatch(t)}dispatch(t){return this.pluginStore.dispatch(t)}cooldownDispatch(t,e=100){const i=Date.now();return i-(this.cooldownActions[t.type]||0)>=e&&(this.cooldownActions[t.type]=i,this.dispatch(t),!0)}debouncedDispatch(t,e=100){const i=t.type;this.debouncedTimeouts[i]&&clearTimeout(this.debouncedTimeouts[i]),this.debouncedTimeouts[i]=setTimeout((()=>{this.dispatch(t),delete this.debouncedTimeouts[i]}),e)}cancelDebouncedDispatch(t){this.debouncedTimeouts[t]&&(clearTimeout(this.debouncedTimeouts[t]),delete this.debouncedTimeouts[t])}subscribe(t){return this.pluginStore.subscribeToState(t)}subscribeToCoreStore(t){return this.coreStore.subscribe(t)}onStoreUpdated(t,e){}onCoreStoreUpdated(t,e){}destroy(){Object.values(this.debouncedTimeouts).forEach((t=>{clearTimeout(t)})),this.debouncedTimeouts={},this.unsubscribeFromState&&(this.unsubscribeFromState(),this.unsubscribeFromState=null),this.unsubscribeFromCoreStore&&(this.unsubscribeFromCoreStore(),this.unsubscribeFromCoreStore=null)}ready(){return this.readyPromise}markReady(){this.readyResolve()}resetReady(){this.readyPromise=new Promise((t=>{this.readyResolve=t}))}},exports.CORE_ACTION_TYPES=w,exports.CapabilityConflictError=o,exports.CapabilityNotFoundError=n,exports.CircularDependencyError=r,exports.DependencyResolver=e,exports.EventControl=P,exports.LOAD_DOCUMENT=h,exports.PluginConfigurationError=u,exports.PluginInitializationError=a,exports.PluginNotFoundError=s,exports.PluginPackageBuilder=x,exports.PluginRegistrationError=i,exports.PluginRegistry=class{constructor(i,s){this.plugins=new Map,this.manifests=new Map,this.capabilities=new Map,this.status=new Map,this.configurations=new Map,this.engineInitialized=!1,this.initPromise=null,this.pendingRegistrations=[],this.processingRegistrations=[],this.initialized=!1,this.isInitializing=!1,this.pluginsReadyPromise=null,this.destroyed=!1,this.resolver=new e,this.engine=i,this.initialCoreState=S(s),this.store=new b(E,this.initialCoreState),this.logger=(null==s?void 0:s.logger)??new t.NoopLogger}getLogger(){return this.logger}async ensureEngineInitialized(){if(!this.engineInitialized)if(this.engine.initialize){const t=this.engine.initialize();await t.toPromise(),this.engineInitialized=!0}else this.engineInitialized=!0}registerPlugin(t,e){if(this.initialized&&!this.isInitializing)throw new i("Cannot register plugins after initialization");this.validateManifest(t.manifest),this.store.addPluginReducer(t.manifest.id,t.reducer,"function"==typeof t.initialState?t.initialState(this.initialCoreState,{...t.manifest.defaultConfig,...e}):t.initialState),this.pendingRegistrations.push({package:t,config:e})}getStore(){return this.store}getEngine(){return this.engine}pluginsReady(){return this.pluginsReadyPromise||(this.pluginsReadyPromise=(async()=>{this.initialized||await this.initialize();const t=Array.from(this.plugins.values()).map((t=>"function"==typeof t.ready?t.ready():Promise.resolve()));await Promise.all(t)})()),this.pluginsReadyPromise}async initialize(){if(this.destroyed)throw new i("Registry has been destroyed");return this.initPromise||(this.initPromise=(async()=>{var t;if(this.initialized)throw new i("Registry is already initialized");this.isInitializing=!0;try{if(await this.ensureEngineInitialized(),this.destroyed)return;for(;this.pendingRegistrations.length>0;){if(this.destroyed)return;this.processingRegistrations=[...this.pendingRegistrations],this.pendingRegistrations=[];for(const e of this.processingRegistrations){const t=new Set,i=[...e.package.manifest.requires,...e.package.manifest.optional];for(const e of i){const i=this.processingRegistrations.find((t=>t.package.manifest.provides.includes(e)));i&&t.add(i.package.manifest.id)}this.resolver.addNode(e.package.manifest.id,[...t])}const t=this.resolver.resolveLoadOrder();for(const e of t){const t=this.processingRegistrations.find((t=>t.package.manifest.id===e));await this.initializePlugin(t.package.manifest,t.package.create,t.config)}this.processingRegistrations=[],this.resolver=new e}for(const e of this.plugins.values())await(null==(t=e.postInitialize)?void 0:t.call(e).catch((t=>{console.error(`Error in postInitialize for plugin ${e.id}`,t),this.status.set(e.id,"error")})));this.initialized=!0}catch(s){if(s instanceof Error)throw new r(`Failed to resolve plugin dependencies: ${s.message}`);throw s}finally{this.isInitializing=!1}})()),this.initPromise}async initializePlugin(t,e,s){const r={...t.defaultConfig,...s};this.validateConfig(t.id,r,t.defaultConfig);const n=e(this,r);this.validatePlugin(n);for(const a of t.requires)if(!this.capabilities.has(a))throw new i(`Missing required capability: ${a} for plugin ${t.id}`);for(const i of t.optional)this.capabilities.has(i)&&this.logger.debug("PluginRegistry","OptionalCapability",`Optional capability ${i} is available for plugin ${t.id}`);this.logger.debug("PluginRegistry","InitializePlugin",`Initializing plugin ${t.id}`,{provides:t.provides});for(const a of t.provides){if(this.capabilities.has(a))throw new i(`Capability ${a} is already provided by plugin ${this.capabilities.get(a)}`);this.capabilities.set(a,t.id)}this.plugins.set(t.id,n),this.manifests.set(t.id,t),this.status.set(t.id,"registered"),this.configurations.set(t.id,r);try{n.initialize&&await n.initialize(r),this.status.set(t.id,"active"),this.logger.info("PluginRegistry","PluginInitialized",`Plugin ${t.id} initialized successfully`)}catch(o){throw this.plugins.delete(t.id),this.manifests.delete(t.id),this.logger.error("PluginRegistry","InitializationFailed",`Plugin ${t.id} initialization failed`,{provides:t.provides,error:o}),t.provides.forEach((t=>this.capabilities.delete(t))),o}}getPluginConfig(t){const e=this.configurations.get(t);if(!e)throw new s(`Configuration for plugin ${t} not found`);return e}validateConfig(t,e,i){const s=Object.keys(i).filter((t=>!e.hasOwnProperty(t)));if(s.length>0)throw new u(`Missing required configuration keys for plugin ${t}: ${s.join(", ")}`)}async updatePluginConfig(t,e){const i=this.getPlugin(t);if(!i)throw new s(`Plugin ${t} not found`);const r=this.manifests.get(t),n=this.configurations.get(t);if(!r||!n)throw new s(`Plugin ${t} not found`);const o={...n,...e};this.validateConfig(t,o,r.defaultConfig),this.configurations.set(t,o),i.initialize&&await i.initialize(o)}registerPluginBatch(t){for(const e of t)this.registerPlugin(e.package,e.config)}async unregisterPlugin(t){const e=this.plugins.get(t);if(!e)throw new s(`Plugin ${t} is not registered`);const r=this.manifests.get(t);if(!r)throw new s(`Manifest for plugin ${t} not found`);for(const[s,o]of this.manifests.entries()){if(s===t)continue;if([...o.requires,...o.optional].some((t=>r.provides.includes(t))))throw new i(`Cannot unregister plugin ${t}: plugin ${s} depends on it`)}try{e.destroy&&await e.destroy();for(const t of r.provides)this.capabilities.delete(t);this.plugins.delete(t),this.manifests.delete(t),this.status.delete(t)}catch(n){if(n instanceof Error)throw new Error(`Failed to unregister plugin ${t}: ${n.message}`);throw n}}getPlugin(t){const e=this.plugins.get(t);return e||null}getCapabilityProvider(t){const e=this.capabilities.get(t);return e?this.getPlugin(e):null}hasCapability(t){return this.capabilities.has(t)}getAllPlugins(){return Array.from(this.plugins.values())}getPluginStatus(t){const e=this.status.get(t);if(!e)throw new s(`Plugin ${t} not found`);return e}validatePlugin(t){if(!t.id)throw new i("Plugin must have an id")}validateManifest(t){if(!t.id)throw new i("Manifest must have an id");if(!t.name)throw new i("Manifest must have a name");if(!t.version)throw new i("Manifest must have a version");if(!Array.isArray(t.provides))throw new i("Manifest must have a provides array");if(!Array.isArray(t.requires))throw new i("Manifest must have a requires array");if(!Array.isArray(t.optional))throw new i("Manifest must have an optional array")}isDestroyed(){return this.destroyed}async destroy(){var t;if(this.destroyed)throw new i("Registry has already been destroyed");this.destroyed=!0;try{await this.initPromise}catch{}for(const e of Array.from(this.plugins.values()).reverse())await(null==(t=e.destroy)?void 0:t.call(e));this.store.destroy(),this.plugins.clear(),this.manifests.clear(),this.capabilities.clear(),this.status.clear(),this.pendingRegistrations.length=0,this.processingRegistrations.length=0}},exports.REFRESH_DOCUMENT=c,exports.REFRESH_PAGES=d,exports.SET_DOCUMENT=g,exports.SET_DOCUMENT_ERROR=p,exports.SET_PAGES=m,exports.SET_ROTATION=y,exports.SET_SCALE=f,exports.arePropsEqual=R,exports.clamp=function(t,e,i){return t<e?e:t>i?i:t},exports.createBehaviorEmitter=function(t,e=R){const i=new Set,s=new Map;let r=t;const n=(t,e)=>{let n=t,o=()=>{};if(e){const i=new P(t,e);n=i.handle,o=()=>i.destroy(),s.set(t,{wrapped:n,destroy:o})}return void 0!==r&&n(r),i.add(n),()=>{i.delete(n),o(),s.delete(t)}};return{get value(){return r},emit(t=void 0){void 0!==r&&e(r,t)||(r=t,(t=>{i.forEach((e=>e(t)))})(t))},on:n,off(t){const e=s.get(t);e?(i.delete(e.wrapped),e.destroy(),s.delete(t)):i.delete(t)},clear(){i.clear(),s.forEach((t=>t.destroy())),s.clear()},select:(t,e=R)=>(i,s)=>{let o;if(void 0!==r){const e=t(r);o=e,i(e)}return n((s=>{const r=t(s);void 0!==o&&e(o,r)||(o=r,i(r))}),s)}}},exports.createEmitter=function(){const t=new Set;return{emit:(e=void 0)=>t.forEach((t=>t(e))),on:e=>(t.add(e),()=>t.delete(e)),off:e=>t.delete(e),clear:()=>t.clear()}},exports.createPluginPackage=function(t){return new x(t)},exports.createPluginRegistration=function(t,e){return{package:t,config:e}},exports.enumEntries=function(t){return Object.entries(t).map((([t,e])=>{const i=Number(t);return[Number.isFinite(i)&&""!==t.trim()?i:t,e]}))},exports.getPagesWithRotatedSize=e=>e.pages.map((i=>i.map((i=>({...i,rotatedSize:t.transformSize(i.size,e.rotation,1)}))))),exports.hasAutoMountElements=function(t){return"autoMountElements"in t&&"function"==typeof t.autoMountElements},exports.initialCoreState=S,exports.loadDocument=()=>({type:h}),exports.refreshDocument=t=>({type:c,payload:t}),exports.refreshPages=t=>({type:d,payload:t}),exports.setDocument=t=>({type:g,payload:t}),exports.setDocumentError=t=>({type:p,payload:t}),exports.setPages=t=>({type:m,payload:t}),exports.setRotation=t=>({type:y,payload:t}),exports.setScale=t=>({type:f,payload:t});
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("@embedpdf/models");class e{constructor(){this.dependencyGraph=new Map}addNode(t,e=[]){this.dependencyGraph.set(t,new Set(e))}hasCircularDependencies(){const t=new Set,e=new Set,i=s=>{t.add(s),e.add(s);const n=this.dependencyGraph.get(s)||new Set;for(const o of n)if(t.has(o)){if(e.has(o))return!0}else if(i(o))return!0;return e.delete(s),!1};for(const s of this.dependencyGraph.keys())if(!t.has(s)&&i(s))return!0;return!1}resolveLoadOrder(){if(this.hasCircularDependencies())throw new Error("Circular dependencies detected");const t=[],e=new Set,i=new Set,s=n=>{if(i.has(n))throw new Error("Circular dependency");if(e.has(n))return;i.add(n);const o=this.dependencyGraph.get(n)||new Set;for(const t of o)s(t);i.delete(n),e.add(n),t.push(n)};for(const n of this.dependencyGraph.keys())e.has(n)||s(n);return t}}class i extends Error{constructor(t){super(t),this.name="PluginRegistrationError"}}class s extends Error{constructor(t){super(t),this.name="PluginNotFoundError"}}class n extends Error{constructor(t){super(t),this.name="CircularDependencyError"}}class o extends Error{constructor(t){super(t),this.name="CapabilityNotFoundError"}}class r extends Error{constructor(t){super(t),this.name="CapabilityConflictError"}}class a extends Error{constructor(t){super(t),this.name="PluginInitializationError"}}class c extends Error{constructor(t){super(t),this.name="PluginConfigurationError"}}class u{constructor(t,e){this.store=t,this.pluginId=e}getState(){return this.store.getState().plugins[this.pluginId]}dispatch(t){return this.store.dispatchToPlugin(this.pluginId,t)}subscribeToState(t){return this.store.subscribeToPlugin(this.pluginId,(e,i,s)=>{t(e,i,s)})}onAction(t,e){return this.store.onAction(t,(t,i,s)=>{e(t,i.plugins[this.pluginId],s.plugins[this.pluginId])})}}const d="START_LOADING_DOCUMENT",l="UPDATE_DOCUMENT_LOADING_PROGRESS",h="SET_DOCUMENT_LOADED",g="SET_DOCUMENT_ERROR",p="RETRY_LOADING_DOCUMENT",m="CLOSE_DOCUMENT",f="SET_ACTIVE_DOCUMENT",y="REORDER_DOCUMENTS",w="MOVE_DOCUMENT",S="REFRESH_DOCUMENT",b="REFRESH_PAGES",E="SET_PAGES",D="SET_SCALE",v="SET_ROTATION",R="SET_DEFAULT_SCALE",I="SET_DEFAULT_ROTATION",C=[d,l,h,m,f,g,p,S,b,E,D,v,R,I,y,w];class P{constructor(t,e){this.initialCoreState=e,this.pluginReducers={},this.listeners=[],this.pluginListeners={},this.isDispatching=!1,this.state={core:e,plugins:{}},this.coreReducer=t}addPluginReducer(t,e,i){this.state.plugins[t]=i,this.pluginReducers[t]=e}dispatchToCore(t){if(!this.coreReducer)return this.getState();if(this.isDispatching)throw new Error("Reducers may not dispatch actions. To trigger cascading actions, dispatch from a listener callback instead.");const e=this.getState();try{this.isDispatching=!0,this.state.core=this.coreReducer(this.state.core,t)}finally{this.isDispatching=!1}return this.listeners.forEach(i=>{const s=this.getState();i(t,s,e)}),this.getState()}dispatchToPlugin(t,e,i=!0){if(this.isDispatching)throw new Error("Reducers may not dispatch actions. To trigger cascading actions, dispatch from a listener callback instead.");const s=this.getState(),n=this.pluginReducers[t];if(!n)return s.plugins[t];const o=s.plugins[t];try{this.isDispatching=!0;const i=n(o,e);this.state.plugins[t]=i}finally{this.isDispatching=!1}return i&&this.listeners.forEach(t=>{const i=this.getState();t(e,i,s)}),this.pluginListeners[t]&&this.pluginListeners[t].forEach(i=>{const s=this.getState().plugins[t];i(e,s,o)}),this.getState().plugins[t]}dispatch(t){if(this.isDispatching)throw new Error("Reducers may not dispatch actions. To trigger cascading actions, dispatch from a listener callback instead.");const e=this.getState();try{this.isDispatching=!0,this.isCoreAction(t)&&(this.state.core=this.coreReducer(this.state.core,t));for(const i in this.pluginReducers){const s=this.pluginReducers[i],n=e.plugins[i];s&&(this.state.plugins[i]=s(n,t))}}finally{this.isDispatching=!1}return this.listeners.forEach(i=>{const s=this.getState();i(t,s,e)}),this.getState()}getState(){if(this.isDispatching)throw new Error("You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.");return{core:{...this.state.core},plugins:{...this.state.plugins}}}subscribe(t){if(this.isDispatching)throw new Error("You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state.");return this.listeners.push(t),()=>{if(this.isDispatching)throw new Error("You may not unsubscribe from a store listener while the reducer is executing.");this.listeners=this.listeners.filter(e=>e!==t)}}subscribeToPlugin(t,e){if(!(t in this.state.plugins))throw new Error(`Plugin state not found for plugin "${t}". Did you forget to call addPluginReducer?`);if(this.isDispatching)throw new Error("You may not call store.subscribeToPlugin() while the reducer is executing.");return this.pluginListeners[t]||(this.pluginListeners[t]=[]),this.pluginListeners[t].push(e),()=>{if(this.isDispatching)throw new Error("You may not unsubscribe from a store listener while the reducer is executing.");this.pluginListeners[t]=this.pluginListeners[t].filter(t=>t!==e),0===this.pluginListeners[t].length&&delete this.pluginListeners[t]}}onAction(t,e){return this.subscribe((i,s,n)=>{i.type===t&&e(i,s,n)})}getPluginStore(t){if(!(t in this.state.plugins))throw new Error(`Plugin state not found for plugin "${t}". Did you forget to call addPluginReducer?`);return new u(this,t)}isCoreAction(t){return C.includes(t.type)}destroy(){var t,e;this.listeners.length=0;for(const i in this.pluginListeners)null==(e=null==(t=this.pluginListeners[i])?void 0:t.splice)||e.call(t,0);this.pluginListeners={},this.pluginReducers={},this.state.plugins={},this.state.core={...this.initialCoreState}}}const T=e=>({documents:{},documentOrder:[],activeDocumentId:null,defaultScale:(null==e?void 0:e.defaultScale)??1,defaultRotation:(null==e?void 0:e.defaultRotation)??t.Rotation.Degree0});function x(t,e,i){const s=t.activeDocumentId;if(s!==e)return s;if(void 0!==i)return i&&t.documents[i]?i:null;const n=t.documentOrder.indexOf(e);return-1===n?null:n>0?t.documentOrder[n-1]:n<t.documentOrder.length-1?t.documentOrder[n+1]:null}const O=(t,e)=>{switch(e.type){case d:{const{documentId:i,name:s,scale:n,rotation:o,passwordProvided:r,autoActivate:a=!0}=e.payload,c={id:i,name:s,status:"loading",loadingProgress:0,error:null,document:null,scale:n??t.defaultScale,rotation:o??t.defaultRotation,passwordProvided:r??!1,pageRefreshVersions:{},loadStartedAt:Date.now()};return{...t,documents:{...t.documents,[i]:c},documentOrder:[...t.documentOrder,i],activeDocumentId:a||!t.activeDocumentId?i:t.activeDocumentId}}case l:{const{documentId:i,progress:s}=e.payload,n=t.documents[i];return n&&"loading"===n.status?{...t,documents:{...t.documents,[i]:{...n,loadingProgress:s}}}:t}case h:{const{documentId:i,document:s}=e.payload,n=t.documents[i];return n?{...t,documents:{...t.documents,[i]:{...n,status:"loaded",document:s,error:null,errorCode:void 0,errorDetails:void 0,passwordProvided:void 0,loadedAt:Date.now()}}}:t}case g:{const{documentId:i,error:s,errorCode:n,errorDetails:o}=e.payload,r=t.documents[i];return r?{...t,documents:{...t.documents,[i]:{...r,status:"error",error:s,errorCode:n,errorDetails:o}}}:t}case p:{const{documentId:i,passwordProvided:s}=e.payload,n=t.documents[i];return n&&"error"===n.status?{...t,documents:{...t.documents,[i]:{...n,status:"loading",loadingProgress:0,error:null,errorCode:void 0,errorDetails:void 0,passwordProvided:s??!1,loadStartedAt:Date.now()}}}:t}case m:{const{documentId:i,nextActiveDocumentId:s}=e.payload,{[i]:n,...o}=t.documents;return{...t,documents:o,documentOrder:t.documentOrder.filter(t=>t!==i),activeDocumentId:x(t,i,s)}}case w:{const{documentId:i,toIndex:s}=e.payload,n=function(t,e,i){const s=t.indexOf(e);if(-1===s)return null;if(i<0||i>=t.length)return null;if(s===i)return null;const n=[...t];return n.splice(s,1),n.splice(i,0,e),n}(t.documentOrder,i,s);return n?{...t,documentOrder:n}:t}case y:return{...t,documentOrder:e.payload};case f:return{...t,activeDocumentId:e.payload};case D:{const{scale:i,documentId:s}=e.payload,n=s??t.activeDocumentId;if(!n)return t;const o=t.documents[n];return o?{...t,documents:{...t.documents,[n]:{...o,scale:i}}}:t}case v:{const{rotation:i,documentId:s}=e.payload,n=s??t.activeDocumentId;if(!n)return t;const o=t.documents[n];return o?{...t,documents:{...t.documents,[n]:{...o,rotation:i}}}:t}case b:{const{documentId:i,pageIndexes:s}=e.payload,n=t.documents[i];if(!n)return t;const o={...n.pageRefreshVersions};for(const t of s)o[t]=(o[t]||0)+1;return{...t,documents:{...t.documents,[i]:{...n,pageRefreshVersions:o}}}}default:return t}};class A{constructor(t,e){this.handler=t,this.options=e,this.lastRun=0,this.handle=t=>{"debounce"===this.options.mode?this.debounce(t):this.throttle(t)}}debounce(t){this.timeoutId&&window.clearTimeout(this.timeoutId),this.timeoutId=window.setTimeout(()=>{this.handler(t),this.timeoutId=void 0},this.options.wait)}throttle(t){if("debounce"===this.options.mode)return;const e=Date.now(),i=this.options.throttleMode||"leading-trailing";e-this.lastRun>=this.options.wait&&("leading-trailing"===i&&this.handler(t),this.lastRun=e),this.timeoutId&&window.clearTimeout(this.timeoutId),this.timeoutId=window.setTimeout(()=>{this.handler(t),this.lastRun=Date.now(),this.timeoutId=void 0},this.options.wait-(e-this.lastRun))}destroy(){this.timeoutId&&window.clearTimeout(this.timeoutId)}}class M{constructor(t,e){this.handler=t,this.options=e,this.controls=new Map,this.handle=t=>{const e=String(this.options.keyExtractor(t));let i=this.controls.get(e);i||(i=new A(this.handler,this.baseOptions),this.controls.set(e,i)),i.handle(t)},this.baseOptions={mode:e.mode,wait:e.wait,..."throttle"===e.mode&&"throttleMode"in e?{throttleMode:e.throttleMode}:{}}}destroy(){for(const t of this.controls.values())t.destroy();this.controls.clear()}}function _(t){return"keyExtractor"in t}function L(t,e,i){if(t===e)return!0;if(null==t||null==e)return t===e;const s=typeof t;if(s!==typeof e)return!1;if("object"===s){i||(i=new Set);const s=function(t,e){return`${z(t)}__${z(e)}`}(t,e);if(i.has(s))return!0;i.add(s);const n=Array.isArray(t),o=Array.isArray(e);return n&&o?function(t,e,i){if(t.length!==e.length)return!1;const s=new Array(e.length).fill(!1);t:for(let n=0;n<t.length;n++){const o=t[n];for(let t=0;t<e.length;t++)if(!s[t]&&L(o,e[t],i)){s[t]=!0;continue t}return!1}return!0}(t,e,i):!n&&!o&&function(t,e,i){const s=Object.keys(t).sort(),n=Object.keys(e).sort();if(s.length!==n.length)return!1;for(let o=0;o<s.length;o++)if(s[o]!==n[o])return!1;for(const o of s){if(!L(t[o],e[o],i))return!1}return!0}(t,e,i)}return!1}let F=0;const N=new WeakMap;function z(t){return N.has(t)||N.set(t,++F),N.get(t)}class k{constructor(t){this.autoMountElements=[],this.package=t}addUtility(t){return this.autoMountElements.push({component:t,type:"utility"}),this}addWrapper(t){return this.autoMountElements.push({component:t,type:"wrapper"}),this}build(){return{...this.package,autoMountElements:()=>this.autoMountElements}}}exports.BasePlugin=class{constructor(t,e){if(this.id=t,this.registry=e,this.cooldownActions={},this.debouncedTimeouts={},this.unsubscribeFromState=null,this.unsubscribeFromCoreStore=null,this.unsubscribeFromStartLoadingDocument=null,this.unsubscribeFromSetDocumentLoaded=null,this.unsubscribeFromCloseDocument=null,this.unsubscribeFromSetScale=null,this.unsubscribeFromSetRotation=null,t!==this.constructor.id)throw new Error(`Plugin ID mismatch: ${t} !== ${this.constructor.id}`);this.engine=this.registry.getEngine(),this.logger=this.registry.getLogger(),this.coreStore=this.registry.getStore(),this.pluginStore=this.coreStore.getPluginStore(this.id),this.unsubscribeFromState=this.pluginStore.subscribeToState((t,e,i)=>{this.onStoreUpdated(i,e)}),this.unsubscribeFromCoreStore=this.coreStore.subscribe((t,e,i)=>{this.onCoreStoreUpdated(i,e),e.core.activeDocumentId!==i.core.activeDocumentId&&this.onActiveDocumentChanged(i.core.activeDocumentId,e.core.activeDocumentId)}),this.unsubscribeFromStartLoadingDocument=this.coreStore.onAction(d,t=>{this.onDocumentLoadingStarted(t.payload.documentId)}),this.unsubscribeFromSetDocumentLoaded=this.coreStore.onAction(h,t=>{this.onDocumentLoaded(t.payload.documentId)}),this.unsubscribeFromCloseDocument=this.coreStore.onAction(m,t=>{this.onDocumentClosed(t.payload.documentId)}),this.unsubscribeFromSetScale=this.coreStore.onAction(D,(t,e)=>{const i=t.payload.documentId??e.core.activeDocumentId;i&&this.onScaleChanged(i,t.payload.scale)}),this.unsubscribeFromSetRotation=this.coreStore.onAction(v,(t,e)=>{const i=t.payload.documentId??e.core.activeDocumentId;i&&this.onRotationChanged(i,t.payload.rotation)}),this.readyPromise=new Promise(t=>{this.readyResolve=t}),this.readyResolve()}provides(){if(!this._capability){const t=this.buildCapability();this._capability=Object.freeze(t)}return this._capability}get state(){return this.pluginStore.getState()}get coreState(){return this.coreStore.getState()}getState(){return this.pluginStore.getState()}getCoreState(){return this.coreStore.getState()}dispatchCoreAction(t){return this.coreStore.dispatchToCore(t)}dispatchToAllPlugins(t){return this.coreStore.dispatch(t)}dispatch(t){return this.pluginStore.dispatch(t)}cooldownDispatch(t,e=100){const i=Date.now();return i-(this.cooldownActions[t.type]||0)>=e&&(this.cooldownActions[t.type]=i,this.dispatch(t),!0)}debouncedDispatch(t,e=100){const i=t.type;this.debouncedTimeouts[i]&&clearTimeout(this.debouncedTimeouts[i]),this.debouncedTimeouts[i]=setTimeout(()=>{this.dispatch(t),delete this.debouncedTimeouts[i]},e)}cancelDebouncedDispatch(t){this.debouncedTimeouts[t]&&(clearTimeout(this.debouncedTimeouts[t]),delete this.debouncedTimeouts[t])}subscribe(t){return this.pluginStore.subscribeToState(t)}subscribeToCoreStore(t){return this.coreStore.subscribe(t)}onStoreUpdated(t,e){}onCoreStoreUpdated(t,e){}onDocumentLoadingStarted(t){}onDocumentLoaded(t){}onDocumentClosed(t){}onActiveDocumentChanged(t,e){}onScaleChanged(t,e){}onRotationChanged(t,e){}destroy(){Object.values(this.debouncedTimeouts).forEach(t=>{clearTimeout(t)}),this.debouncedTimeouts={},this.unsubscribeFromState&&(this.unsubscribeFromState(),this.unsubscribeFromState=null),this.unsubscribeFromCoreStore&&(this.unsubscribeFromCoreStore(),this.unsubscribeFromCoreStore=null),this.unsubscribeFromStartLoadingDocument&&(this.unsubscribeFromStartLoadingDocument(),this.unsubscribeFromStartLoadingDocument=null),this.unsubscribeFromSetDocumentLoaded&&(this.unsubscribeFromSetDocumentLoaded(),this.unsubscribeFromSetDocumentLoaded=null),this.unsubscribeFromCloseDocument&&(this.unsubscribeFromCloseDocument(),this.unsubscribeFromCloseDocument=null),this.unsubscribeFromSetScale&&(this.unsubscribeFromSetScale(),this.unsubscribeFromSetScale=null),this.unsubscribeFromSetRotation&&(this.unsubscribeFromSetRotation(),this.unsubscribeFromSetRotation=null)}ready(){return this.readyPromise}markReady(){this.readyResolve()}resetReady(){this.readyPromise=new Promise(t=>{this.readyResolve=t})}getActiveDocumentId(){const t=this.coreState.core.activeDocumentId;if(!t)throw new Error("No active document");return t}getActiveDocumentIdOrNull(){return this.coreState.core.activeDocumentId}getCoreDocument(t){const e=t??this.getActiveDocumentIdOrNull();return e?this.coreState.core.documents[e]??null:null}getCoreDocumentOrThrow(t){const e=this.getCoreDocument(t);if(!e)throw new Error(`Document not found: ${t??"active"}`);return e}},exports.CLOSE_DOCUMENT=m,exports.CORE_ACTION_TYPES=C,exports.CapabilityConflictError=r,exports.CapabilityNotFoundError=o,exports.CircularDependencyError=n,exports.DependencyResolver=e,exports.EventControl=A,exports.KeyedEventControl=M,exports.MOVE_DOCUMENT=w,exports.PluginConfigurationError=c,exports.PluginInitializationError=a,exports.PluginNotFoundError=s,exports.PluginPackageBuilder=k,exports.PluginRegistrationError=i,exports.PluginRegistry=class{constructor(i,s){this.plugins=new Map,this.manifests=new Map,this.capabilities=new Map,this.status=new Map,this.configurations=new Map,this.engineInitialized=!1,this.initPromise=null,this.pendingRegistrations=[],this.processingRegistrations=[],this.initialized=!1,this.isInitializing=!1,this.pluginsReadyPromise=null,this.destroyed=!1,this.resolver=new e,this.engine=i,this.initialCoreState=T(s),this.store=new P(O,this.initialCoreState),this.logger=(null==s?void 0:s.logger)??new t.NoopLogger}getLogger(){return this.logger}async ensureEngineInitialized(){if(!this.engineInitialized)if(this.engine.initialize){const t=this.engine.initialize();await t.toPromise(),this.engineInitialized=!0}else this.engineInitialized=!0}registerPlugin(t,e){if(this.initialized&&!this.isInitializing)throw new i("Cannot register plugins after initialization");this.validateManifest(t.manifest),this.store.addPluginReducer(t.manifest.id,t.reducer,"function"==typeof t.initialState?t.initialState(this.initialCoreState,{...t.manifest.defaultConfig,...e}):t.initialState),this.pendingRegistrations.push({package:t,config:e})}getStore(){return this.store}getEngine(){return this.engine}pluginsReady(){return this.pluginsReadyPromise||(this.pluginsReadyPromise=(async()=>{this.initialized||await this.initialize();const t=Array.from(this.plugins.values()).map(t=>"function"==typeof t.ready?t.ready():Promise.resolve());await Promise.all(t)})()),this.pluginsReadyPromise}async initialize(){if(this.destroyed)throw new i("Registry has been destroyed");return this.initPromise||(this.initPromise=(async()=>{if(this.initialized)throw new i("Registry is already initialized");this.isInitializing=!0;try{if(await this.ensureEngineInitialized(),this.destroyed)return;for(;this.pendingRegistrations.length>0;){if(this.destroyed)return;this.processingRegistrations=[...this.pendingRegistrations],this.pendingRegistrations=[];for(const e of this.processingRegistrations){const t=new Set,i=[...e.package.manifest.requires,...e.package.manifest.optional];for(const e of i){const i=this.processingRegistrations.find(t=>t.package.manifest.provides.includes(e));i&&t.add(i.package.manifest.id)}this.resolver.addNode(e.package.manifest.id,[...t])}const t=this.resolver.resolveLoadOrder();for(const e of t){const t=this.processingRegistrations.find(t=>t.package.manifest.id===e);this.instantiatePlugin(t.package.manifest,t.package.create,t.config)}for(const e of t)await this.runPluginInitialization(e);this.processingRegistrations=[],this.resolver=new e}this.initialized=!0}catch(t){if(t instanceof Error)throw new n(`Failed to resolve plugin dependencies: ${t.message}`);throw t}finally{this.isInitializing=!1}})()),this.initPromise}instantiatePlugin(t,e,s){const n={...t.defaultConfig,...s};this.validateConfig(t.id,n,t.defaultConfig);const o=e(this,n);this.validatePlugin(o);for(const r of t.provides){if(this.capabilities.has(r))throw new i(`Capability ${r} is already provided by plugin ${this.capabilities.get(r)}`);this.capabilities.set(r,t.id)}this.plugins.set(t.id,o),this.manifests.set(t.id,t),this.status.set(t.id,"registered"),this.configurations.set(t.id,n)}async runPluginInitialization(t){const e=this.plugins.get(t);if(!e)return;const s=this.manifests.get(t),n=this.configurations.get(t);for(const r of s.requires)if(!this.capabilities.has(r))throw new i(`Missing required capability: ${r} for plugin ${t}`);this.logger.debug("PluginRegistry","InitializePlugin",`Initializing plugin ${t}`);try{e.initialize&&await e.initialize(n),this.status.set(t,"active"),this.logger.info("PluginRegistry","PluginInitialized",`Plugin ${t} initialized successfully`)}catch(o){throw this.status.set(t,"error"),this.logger.error("PluginRegistry","InitializationFailed",`Plugin ${t} initialization failed`,{error:o}),o}}getPluginConfig(t){const e=this.configurations.get(t);if(!e)throw new s(`Configuration for plugin ${t} not found`);return e}validateConfig(t,e,i){const s=Object.keys(i).filter(t=>!e.hasOwnProperty(t));if(s.length>0)throw new c(`Missing required configuration keys for plugin ${t}: ${s.join(", ")}`)}async updatePluginConfig(t,e){const i=this.getPlugin(t);if(!i)throw new s(`Plugin ${t} not found`);const n=this.manifests.get(t),o=this.configurations.get(t);if(!n||!o)throw new s(`Plugin ${t} not found`);const r={...o,...e};this.validateConfig(t,r,n.defaultConfig),this.configurations.set(t,r),i.initialize&&await i.initialize(r)}registerPluginBatch(t){for(const e of t)this.registerPlugin(e.package,e.config)}async unregisterPlugin(t){const e=this.plugins.get(t);if(!e)throw new s(`Plugin ${t} is not registered`);const n=this.manifests.get(t);if(!n)throw new s(`Manifest for plugin ${t} not found`);for(const[s,r]of this.manifests.entries()){if(s===t)continue;if([...r.requires,...r.optional].some(t=>n.provides.includes(t)))throw new i(`Cannot unregister plugin ${t}: plugin ${s} depends on it`)}try{e.destroy&&await e.destroy();for(const t of n.provides)this.capabilities.delete(t);this.plugins.delete(t),this.manifests.delete(t),this.status.delete(t)}catch(o){if(o instanceof Error)throw new Error(`Failed to unregister plugin ${t}: ${o.message}`);throw o}}getPlugin(t){const e=this.plugins.get(t);return e||null}getCapabilityProvider(t){const e=this.capabilities.get(t);return e?this.getPlugin(e):null}hasCapability(t){return this.capabilities.has(t)}getAllPlugins(){return Array.from(this.plugins.values())}getPluginStatus(t){const e=this.status.get(t);if(!e)throw new s(`Plugin ${t} not found`);return e}validatePlugin(t){if(!t.id)throw new i("Plugin must have an id")}validateManifest(t){if(!t.id)throw new i("Manifest must have an id");if(!t.name)throw new i("Manifest must have a name");if(!t.version)throw new i("Manifest must have a version");if(!Array.isArray(t.provides))throw new i("Manifest must have a provides array");if(!Array.isArray(t.requires))throw new i("Manifest must have a requires array");if(!Array.isArray(t.optional))throw new i("Manifest must have an optional array")}isDestroyed(){return this.destroyed}async destroy(){var t;if(this.destroyed)throw new i("Registry has already been destroyed");this.destroyed=!0;try{await this.initPromise}catch{}for(const e of Array.from(this.plugins.values()).reverse())await(null==(t=e.destroy)?void 0:t.call(e));this.store.destroy(),this.plugins.clear(),this.manifests.clear(),this.capabilities.clear(),this.status.clear(),this.pendingRegistrations.length=0,this.processingRegistrations.length=0}},exports.REFRESH_DOCUMENT=S,exports.REFRESH_PAGES=b,exports.REORDER_DOCUMENTS=y,exports.RETRY_LOADING_DOCUMENT=p,exports.SET_ACTIVE_DOCUMENT=f,exports.SET_DEFAULT_ROTATION=I,exports.SET_DEFAULT_SCALE=R,exports.SET_DOCUMENT_ERROR=g,exports.SET_DOCUMENT_LOADED=h,exports.SET_PAGES=E,exports.SET_ROTATION=v,exports.SET_SCALE=D,exports.START_LOADING_DOCUMENT=d,exports.UPDATE_DOCUMENT_LOADING_PROGRESS=l,exports.arePropsEqual=L,exports.clamp=function(t,e,i){return t<e?e:t>i?i:t},exports.closeDocument=(t,e)=>({type:m,payload:{documentId:t,nextActiveDocumentId:e}}),exports.createBehaviorEmitter=function(t,e=L){const i=new Set,s=new Map;let n=t;const o=(t,e)=>{let o=t,r=()=>{};if(e){if(_(e)){const i=new M(t,e);o=i.handle,r=()=>i.destroy()}else{const i=new A(t,e);o=i.handle,r=()=>i.destroy()}s.set(t,{wrapped:o,destroy:r})}return void 0!==n&&o(n),i.add(o),()=>{i.delete(o),r(),s.delete(t)}};return{get value(){return n},emit(t=void 0){void 0!==n&&e(n,t)||(n=t,(t=>{i.forEach(e=>e(t))})(t))},on:o,off(t){const e=s.get(t);e?(i.delete(e.wrapped),e.destroy(),s.delete(t)):i.delete(t)},clear(){i.clear(),s.forEach(t=>t.destroy()),s.clear()},select:(t,e=L)=>(i,s)=>{let r;if(void 0!==n){const e=t(n);r=e,i(e)}return o(s=>{const n=t(s);void 0!==r&&e(r,n)||(r=n,i(n))},s)}}},exports.createEmitter=function(){const t=new Set;return{emit:(e=void 0)=>t.forEach(t=>t(e)),on:e=>(t.add(e),()=>t.delete(e)),off:e=>t.delete(e),clear:()=>t.clear()}},exports.createPluginPackage=function(t){return new k(t)},exports.createPluginRegistration=function(t,e){return{package:t,config:e}},exports.createScopedEmitter=function(t,e){const i=(null==e?void 0:e.cache)??!0,s=(null==e?void 0:e.equality)??L,n=new Map,o=new Map,r=new Map,a=new Set,c=new Map,u=t=>String(t);return{emit(e,r){const c=u(e);if(i){const t=n.get(c);if(void 0!==t&&s(t,r))return;n.set(c,r)}const d=o.get(c);d&&d.forEach(t=>t(r));const l=t(e,r);a.forEach(t=>t(l))},forScope(t){const e=u(t);return(t,s)=>{const a=(t=>{let e=o.get(t);return e||(e=new Set,o.set(t,e)),e})(e),c=(t=>{let e=r.get(t);return e||(e=new Map,r.set(t,e)),e})(e);let u=t,d=()=>{};if(s){if(_(s)){const e=new M(t,s);u=e.handle,d=()=>e.destroy()}else{const e=new A(t,s);u=e.handle,d=()=>e.destroy()}c.set(t,{wrapped:u,destroy:d})}if(i){const t=n.get(e);void 0!==t&&u(t)}return a.add(u),()=>{a.delete(u),d(),c.delete(t),0===a.size&&o.delete(e),0===c.size&&r.delete(e)}}},onGlobal:(t,e)=>{let i=t,s=()=>{};if(e){if(_(e)){const n=new M(t,e);i=n.handle,s=()=>n.destroy()}else{const n=new A(t,e);i=n.handle,s=()=>n.destroy()}c.set(t,{wrapped:i,destroy:s})}return a.add(i),()=>{a.delete(i),s(),c.delete(t)}},getValue:t=>i?n.get(u(t)):void 0,getScopes:()=>i?Array.from(n.keys()):Array.from(o.keys()),clearScope(t){const e=u(t);i&&n.delete(e);const s=o.get(e);s&&(s.clear(),o.delete(e));const a=r.get(e);a&&(a.forEach(t=>t.destroy()),a.clear(),r.delete(e))},clear(){i&&n.clear(),o.forEach(t=>t.clear()),o.clear(),r.forEach(t=>{t.forEach(t=>t.destroy()),t.clear()}),r.clear(),a.clear(),c.forEach(t=>t.destroy()),c.clear()}}},exports.enumEntries=function(t){return Object.entries(t).map(([t,e])=>{const i=Number(t);return[Number.isFinite(i)&&""!==t.trim()?i:t,e]})},exports.getActiveDocumentState=t=>t.activeDocumentId?t.documents[t.activeDocumentId]??null:null,exports.getDocumentCount=t=>Object.keys(t.documents).length,exports.getDocumentIds=t=>Object.keys(t.documents),exports.getDocumentState=(t,e)=>t.documents[e]??null,exports.hasAutoMountElements=function(t){return"autoMountElements"in t&&"function"==typeof t.autoMountElements},exports.initialCoreState=T,exports.isDocumentLoaded=(t,e)=>!!t.documents[e],exports.isKeyedOptions=_,exports.moveDocument=(t,e)=>({type:w,payload:{documentId:t,toIndex:e}}),exports.refreshDocument=(t,e)=>({type:S,payload:{documentId:t,document:e}}),exports.refreshPages=(t,e)=>({type:b,payload:{documentId:t,pageIndexes:e}}),exports.reorderDocuments=t=>({type:y,payload:t}),exports.retryLoadingDocument=(t,e)=>({type:p,payload:{documentId:t,passwordProvided:e}}),exports.setActiveDocument=t=>({type:f,payload:t}),exports.setDefaultRotation=t=>({type:I,payload:t}),exports.setDefaultScale=t=>({type:R,payload:t}),exports.setDocumentError=(t,e,i,s)=>({type:g,payload:{documentId:t,error:e,errorCode:i,errorDetails:s}}),exports.setDocumentLoaded=(t,e)=>({type:h,payload:{documentId:t,document:e}}),exports.setPages=(t,e)=>({type:E,payload:{documentId:t,pages:e}}),exports.setRotation=(t,e)=>({type:v,payload:{rotation:t,documentId:e}}),exports.setScale=(t,e)=>({type:D,payload:{scale:t,documentId:e}}),exports.startLoadingDocument=(t,e,i,s,n,o)=>({type:d,payload:{documentId:t,name:e,scale:i,rotation:s,passwordProvided:n,autoActivate:o}}),exports.updateDocumentLoadingProgress=(t,e)=>({type:l,payload:{documentId:t,progress:e}});
2
2
  //# sourceMappingURL=index.cjs.map