@embedpdf/core 2.1.2 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +165 -7
- package/dist/index.js.map +1 -1
- package/dist/lib/base/base-plugin.d.ts +24 -1
- package/dist/lib/index.d.ts +1 -0
- package/dist/lib/store/actions.d.ts +15 -3
- package/dist/lib/store/initial-state.d.ts +4 -0
- package/dist/lib/store/selectors.d.ts +20 -0
- package/dist/lib/types/permissions.d.ts +55 -0
- package/dist/lib/types/plugin.d.ts +6 -0
- package/dist/preact/index.cjs +1 -1
- package/dist/preact/index.cjs.map +1 -1
- package/dist/preact/index.js +113 -1
- package/dist/preact/index.js.map +1 -1
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.js +113 -1
- package/dist/react/index.js.map +1 -1
- package/dist/shared/components/embed-pdf.d.ts +7 -3
- package/dist/shared/hooks/index.d.ts +1 -0
- package/dist/shared/hooks/use-document-permissions.d.ts +35 -0
- package/dist/shared-preact/components/embed-pdf.d.ts +7 -3
- package/dist/shared-preact/hooks/index.d.ts +1 -0
- package/dist/shared-preact/hooks/use-document-permissions.d.ts +35 -0
- package/dist/shared-react/components/embed-pdf.d.ts +7 -3
- package/dist/shared-react/hooks/index.d.ts +1 -0
- package/dist/shared-react/hooks/use-document-permissions.d.ts +35 -0
- package/dist/svelte/components/EmbedPDF.svelte.d.ts +6 -2
- package/dist/svelte/hooks/index.d.ts +1 -0
- package/dist/svelte/hooks/use-document-permissions.svelte.d.ts +35 -0
- package/dist/svelte/index.cjs +1 -1
- package/dist/svelte/index.cjs.map +1 -1
- package/dist/svelte/index.js +118 -1
- package/dist/svelte/index.js.map +1 -1
- package/dist/vue/components/embed-pdf.vue.d.ts +48 -1
- package/dist/vue/composables/index.d.ts +1 -0
- package/dist/vue/composables/use-document-permissions.d.ts +36 -0
- package/dist/vue/index.cjs +1 -1
- package/dist/vue/index.cjs.map +1 -1
- package/dist/vue/index.js +116 -3
- package/dist/vue/index.js.map +1 -1
- package/package.json +3 -3
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { IPlugin } from '../types/plugin';
|
|
2
2
|
import { PluginRegistry } from '../registry/plugin-registry';
|
|
3
3
|
import { Action, CoreAction, CoreState, PluginStore, Store, StoreState } from '../store';
|
|
4
|
-
import { Logger, PdfEngine } from '@embedpdf/models';
|
|
4
|
+
import { Logger, PdfEngine, PdfPermissionFlag } from '@embedpdf/models';
|
|
5
5
|
import { DocumentState } from '../store/initial-state';
|
|
6
6
|
export interface StateChangeHandler<TState> {
|
|
7
7
|
(state: TState): void;
|
|
@@ -164,4 +164,27 @@ export declare abstract class BasePlugin<TConfig = unknown, TCapability = unknow
|
|
|
164
164
|
* @throws Error if document not found
|
|
165
165
|
*/
|
|
166
166
|
protected getCoreDocumentOrThrow(documentId?: string): DocumentState;
|
|
167
|
+
/**
|
|
168
|
+
* Get the effective permission flags for a document.
|
|
169
|
+
* Applies layered resolution: per-document override → global override → PDF permission.
|
|
170
|
+
* Returns AllowAll if document not found.
|
|
171
|
+
* @param documentId Document ID (optional, defaults to active document)
|
|
172
|
+
*/
|
|
173
|
+
protected getDocumentPermissions(documentId?: string): number;
|
|
174
|
+
/**
|
|
175
|
+
* Check if a document has the required permissions (returns boolean).
|
|
176
|
+
* Applies layered resolution: per-document override → global override → PDF permission.
|
|
177
|
+
* Useful for conditional UI logic.
|
|
178
|
+
* @param documentId Document ID (optional, defaults to active document)
|
|
179
|
+
* @param flags Permission flags to check
|
|
180
|
+
*/
|
|
181
|
+
protected checkPermission(documentId: string | undefined, ...flags: PdfPermissionFlag[]): boolean;
|
|
182
|
+
/**
|
|
183
|
+
* Assert that a document has the required permissions.
|
|
184
|
+
* Applies layered resolution: per-document override → global override → PDF permission.
|
|
185
|
+
* Throws PermissionDeniedError if any flag is missing.
|
|
186
|
+
* @param documentId Document ID (optional, defaults to active document)
|
|
187
|
+
* @param flags Permission flags to require
|
|
188
|
+
*/
|
|
189
|
+
protected requirePermission(documentId: string | undefined, ...flags: PdfPermissionFlag[]): void;
|
|
167
190
|
}
|
package/dist/lib/index.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ export * from './utils/dependency-resolver';
|
|
|
3
3
|
export * from './utils/plugin-helpers';
|
|
4
4
|
export * from './types/plugin';
|
|
5
5
|
export * from './types/errors';
|
|
6
|
+
export * from './types/permissions';
|
|
6
7
|
export * from './base/base-plugin';
|
|
7
8
|
export * from './store/types';
|
|
8
9
|
export * from './store/actions';
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { PdfDocumentObject, PdfErrorCode, PdfPageObject, Rotation } from '@embedpdf/models';
|
|
2
|
+
import { PermissionConfig } from '../types/permissions';
|
|
2
3
|
export declare const START_LOADING_DOCUMENT = "START_LOADING_DOCUMENT";
|
|
3
4
|
export declare const UPDATE_DOCUMENT_LOADING_PROGRESS = "UPDATE_DOCUMENT_LOADING_PROGRESS";
|
|
4
5
|
export declare const SET_DOCUMENT_LOADED = "SET_DOCUMENT_LOADED";
|
|
@@ -8,6 +9,7 @@ export declare const CLOSE_DOCUMENT = "CLOSE_DOCUMENT";
|
|
|
8
9
|
export declare const SET_ACTIVE_DOCUMENT = "SET_ACTIVE_DOCUMENT";
|
|
9
10
|
export declare const REORDER_DOCUMENTS = "REORDER_DOCUMENTS";
|
|
10
11
|
export declare const MOVE_DOCUMENT = "MOVE_DOCUMENT";
|
|
12
|
+
export declare const UPDATE_DOCUMENT_SECURITY = "UPDATE_DOCUMENT_SECURITY";
|
|
11
13
|
export declare const REFRESH_DOCUMENT = "REFRESH_DOCUMENT";
|
|
12
14
|
export declare const REFRESH_PAGES = "REFRESH_PAGES";
|
|
13
15
|
export declare const SET_PAGES = "SET_PAGES";
|
|
@@ -15,7 +17,7 @@ export declare const SET_SCALE = "SET_SCALE";
|
|
|
15
17
|
export declare const SET_ROTATION = "SET_ROTATION";
|
|
16
18
|
export declare const SET_DEFAULT_SCALE = "SET_DEFAULT_SCALE";
|
|
17
19
|
export declare const SET_DEFAULT_ROTATION = "SET_DEFAULT_ROTATION";
|
|
18
|
-
export declare const CORE_ACTION_TYPES: readonly ["START_LOADING_DOCUMENT", "UPDATE_DOCUMENT_LOADING_PROGRESS", "SET_DOCUMENT_LOADED", "CLOSE_DOCUMENT", "SET_ACTIVE_DOCUMENT", "SET_DOCUMENT_ERROR", "RETRY_LOADING_DOCUMENT", "REFRESH_DOCUMENT", "REFRESH_PAGES", "SET_PAGES", "SET_SCALE", "SET_ROTATION", "SET_DEFAULT_SCALE", "SET_DEFAULT_ROTATION", "REORDER_DOCUMENTS", "MOVE_DOCUMENT"];
|
|
20
|
+
export declare const CORE_ACTION_TYPES: readonly ["START_LOADING_DOCUMENT", "UPDATE_DOCUMENT_LOADING_PROGRESS", "SET_DOCUMENT_LOADED", "CLOSE_DOCUMENT", "SET_ACTIVE_DOCUMENT", "SET_DOCUMENT_ERROR", "RETRY_LOADING_DOCUMENT", "REFRESH_DOCUMENT", "REFRESH_PAGES", "SET_PAGES", "SET_SCALE", "SET_ROTATION", "SET_DEFAULT_SCALE", "SET_DEFAULT_ROTATION", "REORDER_DOCUMENTS", "MOVE_DOCUMENT", "UPDATE_DOCUMENT_SECURITY"];
|
|
19
21
|
export interface StartLoadingDocumentAction {
|
|
20
22
|
type: typeof START_LOADING_DOCUMENT;
|
|
21
23
|
payload: {
|
|
@@ -25,6 +27,7 @@ export interface StartLoadingDocumentAction {
|
|
|
25
27
|
rotation?: Rotation;
|
|
26
28
|
passwordProvided?: boolean;
|
|
27
29
|
autoActivate?: boolean;
|
|
30
|
+
permissions?: PermissionConfig;
|
|
28
31
|
};
|
|
29
32
|
}
|
|
30
33
|
export interface UpdateDocumentLoadingProgressAction {
|
|
@@ -79,6 +82,14 @@ export interface MoveDocumentAction {
|
|
|
79
82
|
toIndex: number;
|
|
80
83
|
};
|
|
81
84
|
}
|
|
85
|
+
export interface UpdateDocumentSecurityAction {
|
|
86
|
+
type: typeof UPDATE_DOCUMENT_SECURITY;
|
|
87
|
+
payload: {
|
|
88
|
+
documentId: string;
|
|
89
|
+
permissions: number;
|
|
90
|
+
isOwnerUnlocked: boolean;
|
|
91
|
+
};
|
|
92
|
+
}
|
|
82
93
|
export interface RefreshDocumentAction {
|
|
83
94
|
type: typeof REFRESH_DOCUMENT;
|
|
84
95
|
payload: {
|
|
@@ -122,9 +133,9 @@ export interface SetDefaultRotationAction {
|
|
|
122
133
|
type: typeof SET_DEFAULT_ROTATION;
|
|
123
134
|
payload: Rotation;
|
|
124
135
|
}
|
|
125
|
-
export type DocumentAction = StartLoadingDocumentAction | UpdateDocumentLoadingProgressAction | SetDocumentLoadedAction | SetDocumentErrorAction | RetryLoadingDocumentAction | CloseDocumentAction | SetActiveDocumentAction | RefreshDocumentAction | RefreshPagesAction | SetPagesAction | SetScaleAction | SetRotationAction | SetDefaultScaleAction | SetDefaultRotationAction | ReorderDocumentsAction | MoveDocumentAction;
|
|
136
|
+
export type DocumentAction = StartLoadingDocumentAction | UpdateDocumentLoadingProgressAction | SetDocumentLoadedAction | SetDocumentErrorAction | RetryLoadingDocumentAction | CloseDocumentAction | SetActiveDocumentAction | RefreshDocumentAction | RefreshPagesAction | SetPagesAction | SetScaleAction | SetRotationAction | SetDefaultScaleAction | SetDefaultRotationAction | ReorderDocumentsAction | MoveDocumentAction | UpdateDocumentSecurityAction;
|
|
126
137
|
export type CoreAction = DocumentAction;
|
|
127
|
-
export declare const startLoadingDocument: (documentId: string, name?: string, scale?: number, rotation?: Rotation, passwordProvided?: boolean, autoActivate?: boolean) => CoreAction;
|
|
138
|
+
export declare const startLoadingDocument: (documentId: string, name?: string, scale?: number, rotation?: Rotation, passwordProvided?: boolean, autoActivate?: boolean, permissions?: PermissionConfig) => CoreAction;
|
|
128
139
|
export declare const updateDocumentLoadingProgress: (documentId: string, progress: number) => CoreAction;
|
|
129
140
|
export declare const setDocumentLoaded: (documentId: string, document: PdfDocumentObject) => CoreAction;
|
|
130
141
|
export declare const setDocumentError: (documentId: string, error: string, errorCode?: PdfErrorCode, errorDetails?: any) => CoreAction;
|
|
@@ -140,3 +151,4 @@ export declare const setDefaultScale: (scale: number) => CoreAction;
|
|
|
140
151
|
export declare const setDefaultRotation: (rotation: Rotation) => CoreAction;
|
|
141
152
|
export declare const reorderDocuments: (order: string[]) => CoreAction;
|
|
142
153
|
export declare const moveDocument: (documentId: string, toIndex: number) => CoreAction;
|
|
154
|
+
export declare const updateDocumentSecurity: (documentId: string, permissions: number, isOwnerUnlocked: boolean) => CoreAction;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { PdfDocumentObject, PdfErrorCode, Rotation } from '@embedpdf/models';
|
|
2
2
|
import { PluginRegistryConfig } from '../types/plugin';
|
|
3
|
+
import { PermissionConfig } from '../types/permissions';
|
|
3
4
|
export type DocumentStatus = 'loading' | 'loaded' | 'error';
|
|
4
5
|
export interface DocumentState {
|
|
5
6
|
id: string;
|
|
@@ -14,6 +15,7 @@ export interface DocumentState {
|
|
|
14
15
|
scale: number;
|
|
15
16
|
rotation: Rotation;
|
|
16
17
|
pageRefreshVersions: Record<number, number>;
|
|
18
|
+
permissions?: PermissionConfig;
|
|
17
19
|
loadStartedAt: number;
|
|
18
20
|
loadedAt?: number;
|
|
19
21
|
}
|
|
@@ -23,5 +25,7 @@ export interface CoreState {
|
|
|
23
25
|
activeDocumentId: string | null;
|
|
24
26
|
defaultScale: number;
|
|
25
27
|
defaultRotation: Rotation;
|
|
28
|
+
/** Global permission configuration applied to all documents unless overridden per-document */
|
|
29
|
+
globalPermissions?: PermissionConfig;
|
|
26
30
|
}
|
|
27
31
|
export declare const initialCoreState: (config?: PluginRegistryConfig) => CoreState;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { PdfPermissionFlag } from '@embedpdf/models';
|
|
1
2
|
import { CoreState, DocumentState } from './initial-state';
|
|
2
3
|
/**
|
|
3
4
|
* Get the active document state
|
|
@@ -19,3 +20,22 @@ export declare const isDocumentLoaded: (state: CoreState, documentId: string) =>
|
|
|
19
20
|
* Get the number of open documents
|
|
20
21
|
*/
|
|
21
22
|
export declare const getDocumentCount: (state: CoreState) => number;
|
|
23
|
+
/**
|
|
24
|
+
* Check if a specific permission flag is effectively allowed for a document.
|
|
25
|
+
* Applies layered resolution: per-document override → global override → enforceDocumentPermissions → PDF permission.
|
|
26
|
+
*
|
|
27
|
+
* @param state - The core state
|
|
28
|
+
* @param documentId - The document ID to check permissions for
|
|
29
|
+
* @param flag - The permission flag to check
|
|
30
|
+
* @returns true if the permission is allowed, false otherwise
|
|
31
|
+
*/
|
|
32
|
+
export declare function getEffectivePermission(state: CoreState, documentId: string, flag: PdfPermissionFlag): boolean;
|
|
33
|
+
/**
|
|
34
|
+
* Get all effective permissions as a bitmask for a document.
|
|
35
|
+
* Combines all individual permission checks into a single bitmask.
|
|
36
|
+
*
|
|
37
|
+
* @param state - The core state
|
|
38
|
+
* @param documentId - The document ID to get permissions for
|
|
39
|
+
* @returns A bitmask of all effective permissions
|
|
40
|
+
*/
|
|
41
|
+
export declare function getEffectivePermissions(state: CoreState, documentId: string): number;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { PdfPermissionFlag } from '@embedpdf/models';
|
|
2
|
+
/**
|
|
3
|
+
* Human-readable permission names for use in configuration.
|
|
4
|
+
*/
|
|
5
|
+
export type PermissionName = 'print' | 'modifyContents' | 'copyContents' | 'modifyAnnotations' | 'fillForms' | 'extractForAccessibility' | 'assembleDocument' | 'printHighQuality';
|
|
6
|
+
/**
|
|
7
|
+
* Map from human-readable names to PdfPermissionFlag values.
|
|
8
|
+
*/
|
|
9
|
+
export declare const PERMISSION_NAME_TO_FLAG: Record<PermissionName, PdfPermissionFlag>;
|
|
10
|
+
/**
|
|
11
|
+
* Permission overrides can use either numeric flags or human-readable string names.
|
|
12
|
+
*/
|
|
13
|
+
export type PermissionOverrides = Partial<Record<PdfPermissionFlag, boolean> & Record<PermissionName, boolean>>;
|
|
14
|
+
/**
|
|
15
|
+
* Configuration for overriding document permissions.
|
|
16
|
+
* Can be applied globally (at PluginRegistry level) or per-document (when opening).
|
|
17
|
+
*/
|
|
18
|
+
export interface PermissionConfig {
|
|
19
|
+
/**
|
|
20
|
+
* When true (default): use PDF's permissions as the base, then apply overrides.
|
|
21
|
+
* When false: treat document as having all permissions allowed, then apply overrides.
|
|
22
|
+
*/
|
|
23
|
+
enforceDocumentPermissions?: boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Explicit per-flag overrides. Supports both numeric flags and string names.
|
|
26
|
+
* - true = force allow (even if PDF denies)
|
|
27
|
+
* - false = force deny (even if PDF allows)
|
|
28
|
+
* - undefined = use base permissions
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* // Using string names (recommended)
|
|
32
|
+
* overrides: { print: false, modifyAnnotations: true }
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* // Using numeric flags
|
|
36
|
+
* overrides: { [PdfPermissionFlag.Print]: false }
|
|
37
|
+
*/
|
|
38
|
+
overrides?: PermissionOverrides;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* All permission flags for iteration when computing effective permissions.
|
|
42
|
+
*/
|
|
43
|
+
export declare const ALL_PERMISSION_FLAGS: PdfPermissionFlag[];
|
|
44
|
+
/**
|
|
45
|
+
* All permission names for iteration.
|
|
46
|
+
*/
|
|
47
|
+
export declare const ALL_PERMISSION_NAMES: PermissionName[];
|
|
48
|
+
/**
|
|
49
|
+
* Map from PdfPermissionFlag to human-readable name.
|
|
50
|
+
*/
|
|
51
|
+
export declare const PERMISSION_FLAG_TO_NAME: Record<PdfPermissionFlag, PermissionName>;
|
|
52
|
+
/**
|
|
53
|
+
* Helper to get the override value for a permission flag, checking both numeric and string keys.
|
|
54
|
+
*/
|
|
55
|
+
export declare function getPermissionOverride(overrides: PermissionOverrides | undefined, flag: PdfPermissionFlag): boolean | undefined;
|
|
@@ -2,6 +2,7 @@ import { PluginRegistry } from '../registry/plugin-registry';
|
|
|
2
2
|
import { Logger, Rotation } from '@embedpdf/models';
|
|
3
3
|
import { Action, Reducer } from '../store/types';
|
|
4
4
|
import { CoreState } from '../store';
|
|
5
|
+
import { PermissionConfig } from './permissions';
|
|
5
6
|
export interface IPlugin<TConfig = unknown> {
|
|
6
7
|
id: string;
|
|
7
8
|
initialize?(config: TConfig): Promise<void>;
|
|
@@ -16,6 +17,11 @@ export interface PluginRegistryConfig {
|
|
|
16
17
|
defaultRotation?: Rotation;
|
|
17
18
|
defaultScale?: number;
|
|
18
19
|
logger?: Logger;
|
|
20
|
+
/**
|
|
21
|
+
* Global permission configuration.
|
|
22
|
+
* Applied to all documents unless overridden per-document.
|
|
23
|
+
*/
|
|
24
|
+
permissions?: PermissionConfig;
|
|
19
25
|
}
|
|
20
26
|
export interface PluginManifest<TConfig = unknown> {
|
|
21
27
|
id: string;
|
package/dist/preact/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("preact"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("preact"),n=require("preact/hooks"),i=require("preact/jsx-runtime"),t=require("@embedpdf/core"),s=require("@embedpdf/models"),o=e.createContext({registry:null,coreState:null,isInitializing:!0,pluginsReady:!1,activeDocumentId:null,activeDocument:null,documents:{},documentStates:[]});function r({plugins:s,children:o}){const{utilities:r,wrappers:l}=n.useMemo(()=>{const e=[],n=[];for(const i of s){const s=i.package;if(t.hasAutoMountElements(s)){const i=s.autoMountElements()||[];for(const t of i)"utility"===t.type?e.push(t.component):"wrapper"===t.type&&n.push(t.component)}}return{utilities:e,wrappers:n}},[s]),u=l.reduce((e,n)=>i.jsx(n,{children:e}),o);return i.jsxs(e.Fragment,{children:[u,r.map((e,n)=>i.jsx(e,{},`utility-${n}`))]})}function l(){const e=n.useContext(o);if(void 0===e)throw new Error("useCapability must be used within a PDFContext.Provider");const{registry:i,isInitializing:t}=e;if(t)return e;if(null===i)throw new Error("PDF registry failed to initialize properly");return e}function u(e){const{registry:n}=l();if(null===n)return{plugin:null,isLoading:!0,ready:new Promise(()=>{})};const i=n.getPlugin(e);if(!i)throw new Error(`Plugin ${e} not found`);return{plugin:i,isLoading:!1,ready:i.ready()}}function a(){const{coreState:e}=n.useContext(o);return e}s.PdfPermissionFlag.Print,s.PdfPermissionFlag.ModifyContents,s.PdfPermissionFlag.CopyContents,s.PdfPermissionFlag.ModifyAnnotations,s.PdfPermissionFlag.FillForms,s.PdfPermissionFlag.ExtractForAccessibility,s.PdfPermissionFlag.AssembleDocument,s.PdfPermissionFlag.PrintHighQuality;const c=[s.PdfPermissionFlag.Print,s.PdfPermissionFlag.ModifyContents,s.PdfPermissionFlag.CopyContents,s.PdfPermissionFlag.ModifyAnnotations,s.PdfPermissionFlag.FillForms,s.PdfPermissionFlag.ExtractForAccessibility,s.PdfPermissionFlag.AssembleDocument,s.PdfPermissionFlag.PrintHighQuality],d={[s.PdfPermissionFlag.Print]:"print",[s.PdfPermissionFlag.ModifyContents]:"modifyContents",[s.PdfPermissionFlag.CopyContents]:"copyContents",[s.PdfPermissionFlag.ModifyAnnotations]:"modifyAnnotations",[s.PdfPermissionFlag.FillForms]:"fillForms",[s.PdfPermissionFlag.ExtractForAccessibility]:"extractForAccessibility",[s.PdfPermissionFlag.AssembleDocument]:"assembleDocument",[s.PdfPermissionFlag.PrintHighQuality]:"printHighQuality"};function m(e,n){if(!e)return;if(n in e)return e[n];const i=d[n];return i&&i in e?e[i]:void 0}function P(e,n,i){var t;const o=e.documents[n],r=null==o?void 0:o.permissions,l=e.globalPermissions,u=(null==(t=null==o?void 0:o.document)?void 0:t.permissions)??s.PdfPermissionFlag.AllowAll,a=m(null==r?void 0:r.overrides,i);if(void 0!==a)return a;const c=m(null==l?void 0:l.overrides,i);if(void 0!==c)return c;return!((null==r?void 0:r.enforceDocumentPermissions)??(null==l?void 0:l.enforceDocumentPermissions)??!0)||0!==(u&i)}exports.EmbedPDF=function({engine:e,config:s,logger:l,onInitialized:u,plugins:a,children:c,autoMountDomElements:d=!0}){const[m,P]=n.useState(null),[f,g]=n.useState(null),[y,p]=n.useState(!0),[F,v]=n.useState(!1),A=n.useRef(u);n.useEffect(()=>{A.current=u},[u]),n.useEffect(()=>{const n={...s,logger:(null==s?void 0:s.logger)??l},i=new t.PluginRegistry(e,n);i.registerPluginBatch(a);let o;return(async()=>{var e;if(await i.initialize(),i.isDestroyed())return;const n=i.getStore();g(n.getState().core);const t=n.subscribe((e,i,t)=>{n.isCoreAction(e)&&i.core!==t.core&&g(i.core)});if(await(null==(e=A.current)?void 0:e.call(A,i)),!i.isDestroyed())return i.pluginsReady().then(()=>{i.isDestroyed()||v(!0)}),P(i),p(!1),t;t()})().then(e=>{o=e}).catch(console.error),()=>{null==o||o(),i.destroy(),P(null),g(null),p(!0),v(!1)}},[e,a]);const h=n.useMemo(()=>{const e=(null==f?void 0:f.activeDocumentId)??null,n=(null==f?void 0:f.documents)??{},i=(null==f?void 0:f.documentOrder)??[],t=e&&n[e]?n[e]:null,s=i.map(e=>n[e]).filter(e=>null!=e);return{registry:m,coreState:f,isInitializing:y,pluginsReady:F,activeDocumentId:e,activeDocument:t,documents:n,documentStates:s}},[m,f,y,F]),C="function"==typeof c?c(h):c;return i.jsx(o.Provider,{value:h,children:F&&d?i.jsx(r,{plugins:a,children:C}):C})},exports.PDFContext=o,exports.useCapability=function(e){const{plugin:n,isLoading:i,ready:t}=u(e);if(!n)return{provides:null,isLoading:i,ready:t};if(!n.provides)throw new Error(`Plugin ${e} does not provide a capability`);return{provides:n.provides(),isLoading:i,ready:t}},exports.useCoreState=a,exports.useDocumentPermissions=function(e){const i=a();return n.useMemo(()=>{var n,t;if(!i)return{permissions:s.PdfPermissionFlag.AllowAll,pdfPermissions:s.PdfPermissionFlag.AllowAll,hasPermission:()=>!0,hasAllPermissions:()=>!0,canPrint:!0,canModifyContents:!0,canCopyContents:!0,canModifyAnnotations:!0,canFillForms:!0,canExtractForAccessibility:!0,canAssembleDocument:!0,canPrintHighQuality:!0};const o=function(e,n){return c.reduce((i,t)=>P(e,n,t)?i|t:i,0)}(i,e),r=n=>P(i,e,n);return{permissions:o,pdfPermissions:(null==(t=null==(n=i.documents[e])?void 0:n.document)?void 0:t.permissions)??s.PdfPermissionFlag.AllowAll,hasPermission:r,hasAllPermissions:(...n)=>n.every(n=>P(i,e,n)),canPrint:r(s.PdfPermissionFlag.Print),canModifyContents:r(s.PdfPermissionFlag.ModifyContents),canCopyContents:r(s.PdfPermissionFlag.CopyContents),canModifyAnnotations:r(s.PdfPermissionFlag.ModifyAnnotations),canFillForms:r(s.PdfPermissionFlag.FillForms),canExtractForAccessibility:r(s.PdfPermissionFlag.ExtractForAccessibility),canAssembleDocument:r(s.PdfPermissionFlag.AssembleDocument),canPrintHighQuality:r(s.PdfPermissionFlag.PrintHighQuality)}},[i,e])},exports.useDocumentState=function(e){const i=a();return n.useMemo(()=>i&&e?i.documents[e]??null:null,[i,e])},exports.usePlugin=u,exports.useRegistry=l,exports.useStoreState=function(){const{registry:e}=l(),[i,t]=n.useState(null);return n.useEffect(()=>{if(!e)return;t(e.getStore().getState());const n=e.getStore().subscribe((e,n)=>{t(n)});return()=>n()},[e]),i};
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../../src/shared/context.ts","../../src/shared/components/auto-mount.tsx","../../src/shared/hooks/use-registry.ts","../../src/shared/hooks/use-plugin.ts","../../src/shared/hooks/use-core-state.ts","../../src/shared/components/embed-pdf.tsx","../../src/shared/hooks/use-capability.ts","../../src/shared/hooks/use-document-state.ts","../../src/shared/hooks/use-store-state.ts"],"sourcesContent":["import { createContext } from '@framework';\nimport type { CoreState, DocumentState, PluginRegistry } from '@embedpdf/core';\n\nexport interface PDFContextState {\n registry: PluginRegistry | null;\n coreState: CoreState | null;\n isInitializing: boolean;\n pluginsReady: boolean;\n\n // Convenience accessors (always safe to use)\n activeDocumentId: string | null;\n activeDocument: DocumentState | null;\n documents: Record<string, DocumentState>;\n documentStates: DocumentState[];\n}\n\nexport const PDFContext = createContext<PDFContextState>({\n registry: null,\n coreState: null,\n isInitializing: true,\n pluginsReady: false,\n activeDocumentId: null,\n activeDocument: null,\n documents: {},\n documentStates: [],\n});\n","import { Fragment, useMemo, ComponentType, ReactNode } from '@framework';\nimport { hasAutoMountElements } from '@embedpdf/core';\nimport type { PluginBatchRegistration, IPlugin } from '@embedpdf/core';\n\ninterface AutoMountProps {\n plugins: PluginBatchRegistration<IPlugin<any>, any>[];\n children: ReactNode;\n}\n\nexport function AutoMount({ plugins, children }: AutoMountProps) {\n const { utilities, wrappers } = useMemo(() => {\n // React-specific types for internal use\n const utilities: ComponentType[] = [];\n const wrappers: ComponentType<{ children: ReactNode }>[] = [];\n\n for (const reg of plugins) {\n const pkg = reg.package;\n if (hasAutoMountElements(pkg)) {\n const elements = pkg.autoMountElements() || [];\n\n for (const element of elements) {\n if (element.type === 'utility') {\n utilities.push(element.component);\n } else if (element.type === 'wrapper') {\n // In React context, we know wrappers need children\n wrappers.push(element.component);\n }\n }\n }\n }\n return { utilities, wrappers };\n }, [plugins]);\n\n // React-specific wrapping logic\n const wrappedContent = wrappers.reduce(\n (content, Wrapper) => <Wrapper>{content}</Wrapper>,\n children,\n );\n\n return (\n <Fragment>\n {wrappedContent}\n {utilities.map((Utility, i) => (\n <Utility key={`utility-${i}`} />\n ))}\n </Fragment>\n );\n}\n","import { useContext } from '@framework';\nimport { PDFContext, PDFContextState } from '../context';\n\n/**\n * Hook to access the PDF registry.\n * @returns The PDF registry or null during initialization\n */\nexport function useRegistry(): PDFContextState {\n const contextValue = useContext(PDFContext);\n\n // Error if used outside of context\n if (contextValue === undefined) {\n throw new Error('useCapability must be used within a PDFContext.Provider');\n }\n\n const { registry, isInitializing } = contextValue;\n\n // During initialization, return null instead of throwing an error\n if (isInitializing) {\n return contextValue;\n }\n\n // At this point, initialization is complete but registry is still null, which is unexpected\n if (registry === null) {\n throw new Error('PDF registry failed to initialize properly');\n }\n\n return contextValue;\n}\n","import type { BasePlugin } from '@embedpdf/core';\nimport { useRegistry } from './use-registry';\n\ntype PluginState<T extends BasePlugin> = {\n plugin: T | null;\n isLoading: boolean;\n ready: Promise<void>;\n};\n\n/**\n * Hook to access a plugin.\n * @param pluginId The ID of the plugin to access\n * @returns The plugin or null during initialization\n * @example\n * // Get zoom plugin\n * const zoom = usePlugin<ZoomPlugin>(ZoomPlugin.id);\n */\nexport function usePlugin<T extends BasePlugin>(pluginId: T['id']): PluginState<T> {\n const { registry } = useRegistry();\n\n if (registry === null) {\n return {\n plugin: null,\n isLoading: true,\n ready: new Promise(() => {}),\n };\n }\n\n const plugin = registry.getPlugin<T>(pluginId);\n\n if (!plugin) {\n throw new Error(`Plugin ${pluginId} not found`);\n }\n\n return {\n plugin,\n isLoading: false,\n ready: plugin.ready(),\n };\n}\n","import { useContext } from '@framework';\nimport { CoreState } from '@embedpdf/core';\nimport { PDFContext } from '../context';\n\n/**\n * Hook that provides access to the current core state.\n *\n * Note: This reads from the context which is already subscribed to core state changes\n * in the EmbedPDF component, so there's no additional subscription overhead.\n */\nexport function useCoreState(): CoreState | null {\n const { coreState } = useContext(PDFContext);\n return coreState;\n}\n","import { useState, useEffect, useRef, useMemo, ReactNode } from '@framework';\nimport { Logger, PdfEngine } from '@embedpdf/models';\nimport { PluginRegistry, CoreState, DocumentState } from '@embedpdf/core';\nimport type { PluginBatchRegistrations } from '@embedpdf/core';\n\nimport { PDFContext, PDFContextState } from '../context';\nimport { AutoMount } from './auto-mount';\n\nexport type { PluginBatchRegistrations };\n\ninterface EmbedPDFProps {\n /**\n * The PDF engine to use for the PDF viewer.\n */\n engine: PdfEngine;\n /**\n * The logger to use for the PDF viewer.\n */\n logger?: Logger;\n /**\n * The callback to call when the PDF viewer is initialized.\n */\n onInitialized?: (registry: PluginRegistry) => Promise<void>;\n /**\n * The plugins to use for the PDF viewer.\n */\n plugins: PluginBatchRegistrations;\n /**\n * The children to render for the PDF viewer.\n */\n children: ReactNode | ((state: PDFContextState) => ReactNode);\n /**\n * Whether to auto-mount specific non-visual DOM elements from plugins.\n * @default true\n */\n autoMountDomElements?: boolean;\n}\n\nexport function EmbedPDF({\n engine,\n logger,\n onInitialized,\n plugins,\n children,\n autoMountDomElements = true,\n}: EmbedPDFProps) {\n const [registry, setRegistry] = useState<PluginRegistry | null>(null);\n const [coreState, setCoreState] = useState<CoreState | null>(null);\n const [isInitializing, setIsInitializing] = useState<boolean>(true);\n const [pluginsReady, setPluginsReady] = useState<boolean>(false);\n const initRef = useRef<EmbedPDFProps['onInitialized']>(onInitialized);\n\n useEffect(() => {\n initRef.current = onInitialized;\n }, [onInitialized]);\n\n useEffect(() => {\n const pdfViewer = new PluginRegistry(engine, { logger });\n pdfViewer.registerPluginBatch(plugins);\n\n const initialize = async () => {\n await pdfViewer.initialize();\n\n if (pdfViewer.isDestroyed()) {\n return;\n }\n\n const store = pdfViewer.getStore();\n setCoreState(store.getState().core);\n\n const unsubscribe = store.subscribe((action, newState, oldState) => {\n // Only update if it's a core action and the core state changed\n if (store.isCoreAction(action) && newState.core !== oldState.core) {\n setCoreState(newState.core);\n }\n });\n\n /* always call the *latest* callback */\n await initRef.current?.(pdfViewer);\n\n if (pdfViewer.isDestroyed()) {\n unsubscribe();\n return;\n }\n\n pdfViewer.pluginsReady().then(() => {\n if (!pdfViewer.isDestroyed()) {\n setPluginsReady(true);\n }\n });\n\n // Provide the registry to children via context\n setRegistry(pdfViewer);\n setIsInitializing(false);\n\n // Return cleanup function\n return unsubscribe;\n };\n\n let cleanup: (() => void) | undefined;\n initialize()\n .then((unsub) => {\n cleanup = unsub;\n })\n .catch(console.error);\n\n return () => {\n cleanup?.();\n pdfViewer.destroy();\n setRegistry(null);\n setCoreState(null);\n setIsInitializing(true);\n setPluginsReady(false);\n };\n }, [engine, plugins]);\n\n // Compute convenience accessors\n const contextValue: PDFContextState = useMemo(() => {\n const activeDocumentId = coreState?.activeDocumentId ?? null;\n const documents = coreState?.documents ?? {};\n const documentOrder = coreState?.documentOrder ?? [];\n\n // Compute active document\n const activeDocument =\n activeDocumentId && documents[activeDocumentId] ? documents[activeDocumentId] : null;\n\n // Compute open documents in order\n const documentStates = documentOrder\n .map((docId) => documents[docId])\n .filter((doc): doc is DocumentState => doc !== null && doc !== undefined);\n\n return {\n registry,\n coreState,\n isInitializing,\n pluginsReady,\n // Convenience accessors (always safe to use)\n activeDocumentId,\n activeDocument,\n documents,\n documentStates,\n };\n }, [registry, coreState, isInitializing, pluginsReady]);\n\n const content = typeof children === 'function' ? children(contextValue) : children;\n\n return (\n <PDFContext.Provider value={contextValue}>\n {pluginsReady && autoMountDomElements ? (\n <AutoMount plugins={plugins}>{content}</AutoMount>\n ) : (\n content\n )}\n </PDFContext.Provider>\n );\n}\n","import type { BasePlugin } from '@embedpdf/core';\nimport { usePlugin } from './use-plugin';\n\ntype CapabilityState<T extends BasePlugin> = {\n provides: ReturnType<NonNullable<T['provides']>> | null;\n isLoading: boolean;\n ready: Promise<void>;\n};\n\n/**\n * Hook to access a plugin's capability.\n * @param pluginId The ID of the plugin to access\n * @returns The capability provided by the plugin or null during initialization\n * @example\n * // Get zoom capability\n * const zoom = useCapability<ZoomPlugin>(ZoomPlugin.id);\n */\nexport function useCapability<T extends BasePlugin>(pluginId: T['id']): CapabilityState<T> {\n const { plugin, isLoading, ready } = usePlugin<T>(pluginId);\n\n if (!plugin) {\n return {\n provides: null,\n isLoading,\n ready,\n };\n }\n\n if (!plugin.provides) {\n throw new Error(`Plugin ${pluginId} does not provide a capability`);\n }\n\n return {\n provides: plugin.provides() as ReturnType<NonNullable<T['provides']>>,\n isLoading,\n ready,\n };\n}\n","import { useMemo } from '@framework';\nimport { DocumentState } from '@embedpdf/core';\nimport { useCoreState } from './use-core-state';\n\n/**\n * Hook that provides reactive access to a specific document's state from the core store.\n *\n * @param documentId The ID of the document to retrieve.\n * @returns The reactive DocumentState object or null if not found.\n */\nexport function useDocumentState(documentId: string | null): DocumentState | null {\n const coreState = useCoreState();\n\n const documentState = useMemo(() => {\n if (!coreState || !documentId) return null;\n return coreState.documents[documentId] ?? null;\n }, [coreState, documentId]);\n\n return documentState;\n}\n","import { useState, useEffect } from '@framework';\nimport { CoreState, StoreState } from '@embedpdf/core';\nimport { useRegistry } from './use-registry';\n\n/**\n * Hook that provides access to the current global store state\n * and re-renders the component when the state changes\n */\nexport function useStoreState<T = CoreState>(): StoreState<T> | null {\n const { registry } = useRegistry();\n const [state, setState] = useState<StoreState<T> | null>(null);\n\n useEffect(() => {\n if (!registry) return;\n\n // Get initial state\n setState(registry.getStore().getState() as StoreState<T>);\n\n // Subscribe to store changes\n const unsubscribe = registry.getStore().subscribe((_action, newState) => {\n setState(newState as StoreState<T>);\n });\n\n return () => unsubscribe();\n }, [registry]);\n\n return state;\n}\n"],"names":["PDFContext","createContext","registry","coreState","isInitializing","pluginsReady","activeDocumentId","activeDocument","documents","documentStates","AutoMount","plugins","children","utilities","wrappers","useMemo","reg","pkg","package","hasAutoMountElements","elements","autoMountElements","element","type","push","component","wrappedContent","reduce","content","Wrapper","jsx","Fragment","map","Utility","i","useRegistry","contextValue","useContext","Error","usePlugin","pluginId","plugin","isLoading","ready","Promise","getPlugin","useCoreState","engine","logger","onInitialized","autoMountDomElements","setRegistry","useState","setCoreState","setIsInitializing","setPluginsReady","initRef","useRef","useEffect","current","pdfViewer","PluginRegistry","registerPluginBatch","cleanup","async","initialize","isDestroyed","store","getStore","getState","core","unsubscribe","subscribe","action","newState","oldState","isCoreAction","_a","call","then","unsub","catch","console","error","destroy","documentOrder","docId","filter","doc","Provider","value","provides","documentId","state","setState","_action"],"mappings":"gMAgBaA,EAAaC,EAAAA,cAA+B,CACvDC,SAAU,KACVC,UAAW,KACXC,gBAAgB,EAChBC,cAAc,EACdC,iBAAkB,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":["../../src/shared/context.ts","../../src/shared/components/auto-mount.tsx","../../src/shared/hooks/use-registry.ts","../../src/shared/hooks/use-plugin.ts","../../src/shared/hooks/use-core-state.ts","../../src/lib/types/permissions.ts","../../src/lib/store/selectors.ts","../../src/shared/components/embed-pdf.tsx","../../src/shared/hooks/use-capability.ts","../../src/shared/hooks/use-document-permissions.ts","../../src/shared/hooks/use-document-state.ts","../../src/shared/hooks/use-store-state.ts"],"sourcesContent":["import { createContext } from '@framework';\nimport type { CoreState, DocumentState, PluginRegistry } from '@embedpdf/core';\n\nexport interface PDFContextState {\n registry: PluginRegistry | null;\n coreState: CoreState | null;\n isInitializing: boolean;\n pluginsReady: boolean;\n\n // Convenience accessors (always safe to use)\n activeDocumentId: string | null;\n activeDocument: DocumentState | null;\n documents: Record<string, DocumentState>;\n documentStates: DocumentState[];\n}\n\nexport const PDFContext = createContext<PDFContextState>({\n registry: null,\n coreState: null,\n isInitializing: true,\n pluginsReady: false,\n activeDocumentId: null,\n activeDocument: null,\n documents: {},\n documentStates: [],\n});\n","import { Fragment, useMemo, ComponentType, ReactNode } from '@framework';\nimport { hasAutoMountElements } from '@embedpdf/core';\nimport type { PluginBatchRegistration, IPlugin } from '@embedpdf/core';\n\ninterface AutoMountProps {\n plugins: PluginBatchRegistration<IPlugin<any>, any>[];\n children: ReactNode;\n}\n\nexport function AutoMount({ plugins, children }: AutoMountProps) {\n const { utilities, wrappers } = useMemo(() => {\n // React-specific types for internal use\n const utilities: ComponentType[] = [];\n const wrappers: ComponentType<{ children: ReactNode }>[] = [];\n\n for (const reg of plugins) {\n const pkg = reg.package;\n if (hasAutoMountElements(pkg)) {\n const elements = pkg.autoMountElements() || [];\n\n for (const element of elements) {\n if (element.type === 'utility') {\n utilities.push(element.component);\n } else if (element.type === 'wrapper') {\n // In React context, we know wrappers need children\n wrappers.push(element.component);\n }\n }\n }\n }\n return { utilities, wrappers };\n }, [plugins]);\n\n // React-specific wrapping logic\n const wrappedContent = wrappers.reduce(\n (content, Wrapper) => <Wrapper>{content}</Wrapper>,\n children,\n );\n\n return (\n <Fragment>\n {wrappedContent}\n {utilities.map((Utility, i) => (\n <Utility key={`utility-${i}`} />\n ))}\n </Fragment>\n );\n}\n","import { useContext } from '@framework';\nimport { PDFContext, PDFContextState } from '../context';\n\n/**\n * Hook to access the PDF registry.\n * @returns The PDF registry or null during initialization\n */\nexport function useRegistry(): PDFContextState {\n const contextValue = useContext(PDFContext);\n\n // Error if used outside of context\n if (contextValue === undefined) {\n throw new Error('useCapability must be used within a PDFContext.Provider');\n }\n\n const { registry, isInitializing } = contextValue;\n\n // During initialization, return null instead of throwing an error\n if (isInitializing) {\n return contextValue;\n }\n\n // At this point, initialization is complete but registry is still null, which is unexpected\n if (registry === null) {\n throw new Error('PDF registry failed to initialize properly');\n }\n\n return contextValue;\n}\n","import type { BasePlugin } from '@embedpdf/core';\nimport { useRegistry } from './use-registry';\n\ntype PluginState<T extends BasePlugin> = {\n plugin: T | null;\n isLoading: boolean;\n ready: Promise<void>;\n};\n\n/**\n * Hook to access a plugin.\n * @param pluginId The ID of the plugin to access\n * @returns The plugin or null during initialization\n * @example\n * // Get zoom plugin\n * const zoom = usePlugin<ZoomPlugin>(ZoomPlugin.id);\n */\nexport function usePlugin<T extends BasePlugin>(pluginId: T['id']): PluginState<T> {\n const { registry } = useRegistry();\n\n if (registry === null) {\n return {\n plugin: null,\n isLoading: true,\n ready: new Promise(() => {}),\n };\n }\n\n const plugin = registry.getPlugin<T>(pluginId);\n\n if (!plugin) {\n throw new Error(`Plugin ${pluginId} not found`);\n }\n\n return {\n plugin,\n isLoading: false,\n ready: plugin.ready(),\n };\n}\n","import { useContext } from '@framework';\nimport { CoreState } from '@embedpdf/core';\nimport { PDFContext } from '../context';\n\n/**\n * Hook that provides access to the current core state.\n *\n * Note: This reads from the context which is already subscribed to core state changes\n * in the EmbedPDF component, so there's no additional subscription overhead.\n */\nexport function useCoreState(): CoreState | null {\n const { coreState } = useContext(PDFContext);\n return coreState;\n}\n","import { PdfPermissionFlag } from '@embedpdf/models';\n\n/**\n * Human-readable permission names for use in configuration.\n */\nexport type PermissionName =\n | 'print'\n | 'modifyContents'\n | 'copyContents'\n | 'modifyAnnotations'\n | 'fillForms'\n | 'extractForAccessibility'\n | 'assembleDocument'\n | 'printHighQuality';\n\n/**\n * Map from human-readable names to PdfPermissionFlag values.\n */\nexport const PERMISSION_NAME_TO_FLAG: Record<PermissionName, PdfPermissionFlag> = {\n print: PdfPermissionFlag.Print,\n modifyContents: PdfPermissionFlag.ModifyContents,\n copyContents: PdfPermissionFlag.CopyContents,\n modifyAnnotations: PdfPermissionFlag.ModifyAnnotations,\n fillForms: PdfPermissionFlag.FillForms,\n extractForAccessibility: PdfPermissionFlag.ExtractForAccessibility,\n assembleDocument: PdfPermissionFlag.AssembleDocument,\n printHighQuality: PdfPermissionFlag.PrintHighQuality,\n};\n\n/**\n * Permission overrides can use either numeric flags or human-readable string names.\n */\nexport type PermissionOverrides = Partial<\n Record<PdfPermissionFlag, boolean> & Record<PermissionName, boolean>\n>;\n\n/**\n * Configuration for overriding document permissions.\n * Can be applied globally (at PluginRegistry level) or per-document (when opening).\n */\nexport interface PermissionConfig {\n /**\n * When true (default): use PDF's permissions as the base, then apply overrides.\n * When false: treat document as having all permissions allowed, then apply overrides.\n */\n enforceDocumentPermissions?: boolean;\n\n /**\n * Explicit per-flag overrides. Supports both numeric flags and string names.\n * - true = force allow (even if PDF denies)\n * - false = force deny (even if PDF allows)\n * - undefined = use base permissions\n *\n * @example\n * // Using string names (recommended)\n * overrides: { print: false, modifyAnnotations: true }\n *\n * @example\n * // Using numeric flags\n * overrides: { [PdfPermissionFlag.Print]: false }\n */\n overrides?: PermissionOverrides;\n}\n\n/**\n * All permission flags for iteration when computing effective permissions.\n */\nexport const ALL_PERMISSION_FLAGS: PdfPermissionFlag[] = [\n PdfPermissionFlag.Print,\n PdfPermissionFlag.ModifyContents,\n PdfPermissionFlag.CopyContents,\n PdfPermissionFlag.ModifyAnnotations,\n PdfPermissionFlag.FillForms,\n PdfPermissionFlag.ExtractForAccessibility,\n PdfPermissionFlag.AssembleDocument,\n PdfPermissionFlag.PrintHighQuality,\n];\n\n/**\n * All permission names for iteration.\n */\nexport const ALL_PERMISSION_NAMES: PermissionName[] = [\n 'print',\n 'modifyContents',\n 'copyContents',\n 'modifyAnnotations',\n 'fillForms',\n 'extractForAccessibility',\n 'assembleDocument',\n 'printHighQuality',\n];\n\n/**\n * Map from PdfPermissionFlag to human-readable name.\n */\nexport const PERMISSION_FLAG_TO_NAME: Record<PdfPermissionFlag, PermissionName> = {\n [PdfPermissionFlag.Print]: 'print',\n [PdfPermissionFlag.ModifyContents]: 'modifyContents',\n [PdfPermissionFlag.CopyContents]: 'copyContents',\n [PdfPermissionFlag.ModifyAnnotations]: 'modifyAnnotations',\n [PdfPermissionFlag.FillForms]: 'fillForms',\n [PdfPermissionFlag.ExtractForAccessibility]: 'extractForAccessibility',\n [PdfPermissionFlag.AssembleDocument]: 'assembleDocument',\n [PdfPermissionFlag.PrintHighQuality]: 'printHighQuality',\n};\n\n/**\n * Helper to get the override value for a permission flag, checking both numeric and string keys.\n */\nexport function getPermissionOverride(\n overrides: PermissionOverrides | undefined,\n flag: PdfPermissionFlag,\n): boolean | undefined {\n if (!overrides) return undefined;\n\n // Check numeric key first\n if (flag in overrides) {\n return (overrides as Record<PdfPermissionFlag, boolean>)[flag];\n }\n\n // Check string key\n const name = PERMISSION_FLAG_TO_NAME[flag];\n if (name && name in overrides) {\n return (overrides as Record<PermissionName, boolean>)[name];\n }\n\n return undefined;\n}\n","import { PdfPermissionFlag } from '@embedpdf/models';\nimport { CoreState, DocumentState } from './initial-state';\nimport { ALL_PERMISSION_FLAGS, getPermissionOverride } from '../types/permissions';\n\n/**\n * Get the active document state\n */\nexport const getActiveDocumentState = (state: CoreState): DocumentState | null => {\n if (!state.activeDocumentId) return null;\n return state.documents[state.activeDocumentId] ?? null;\n};\n\n/**\n * Get document state by ID\n */\nexport const getDocumentState = (state: CoreState, documentId: string): DocumentState | null => {\n return state.documents[documentId] ?? null;\n};\n\n/**\n * Get all document IDs\n */\nexport const getDocumentIds = (state: CoreState): string[] => {\n return Object.keys(state.documents);\n};\n\n/**\n * Check if a document is loaded\n */\nexport const isDocumentLoaded = (state: CoreState, documentId: string): boolean => {\n return !!state.documents[documentId];\n};\n\n/**\n * Get the number of open documents\n */\nexport const getDocumentCount = (state: CoreState): number => {\n return Object.keys(state.documents).length;\n};\n\n// ─────────────────────────────────────────────────────────\n// Permission Selectors\n// ─────────────────────────────────────────────────────────\n\n/**\n * Check if a specific permission flag is effectively allowed for a document.\n * Applies layered resolution: per-document override → global override → enforceDocumentPermissions → PDF permission.\n *\n * @param state - The core state\n * @param documentId - The document ID to check permissions for\n * @param flag - The permission flag to check\n * @returns true if the permission is allowed, false otherwise\n */\nexport function getEffectivePermission(\n state: CoreState,\n documentId: string,\n flag: PdfPermissionFlag,\n): boolean {\n const docState = state.documents[documentId];\n const docConfig = docState?.permissions;\n const globalConfig = state.globalPermissions;\n const pdfPermissions = docState?.document?.permissions ?? PdfPermissionFlag.AllowAll;\n\n // 1. Per-document override wins (supports both numeric and string keys)\n const docOverride = getPermissionOverride(docConfig?.overrides, flag);\n if (docOverride !== undefined) {\n return docOverride;\n }\n\n // 2. Global override (supports both numeric and string keys)\n const globalOverride = getPermissionOverride(globalConfig?.overrides, flag);\n if (globalOverride !== undefined) {\n return globalOverride;\n }\n\n // 3. Check enforce setting (per-doc takes precedence over global)\n const enforce =\n docConfig?.enforceDocumentPermissions ?? globalConfig?.enforceDocumentPermissions ?? true;\n\n if (!enforce) return true; // Not enforcing = allow all\n\n // 4. Use PDF permission\n return (pdfPermissions & flag) !== 0;\n}\n\n/**\n * Get all effective permissions as a bitmask for a document.\n * Combines all individual permission checks into a single bitmask.\n *\n * @param state - The core state\n * @param documentId - The document ID to get permissions for\n * @returns A bitmask of all effective permissions\n */\nexport function getEffectivePermissions(state: CoreState, documentId: string): number {\n return ALL_PERMISSION_FLAGS.reduce((acc, flag) => {\n return getEffectivePermission(state, documentId, flag) ? acc | flag : acc;\n }, 0);\n}\n","import { useState, useEffect, useRef, useMemo, ReactNode } from '@framework';\nimport { Logger, PdfEngine } from '@embedpdf/models';\nimport { PluginRegistry, CoreState, DocumentState, PluginRegistryConfig } from '@embedpdf/core';\nimport type { PluginBatchRegistrations } from '@embedpdf/core';\n\nimport { PDFContext, PDFContextState } from '../context';\nimport { AutoMount } from './auto-mount';\n\nexport type { PluginBatchRegistrations };\n\ninterface EmbedPDFProps {\n /**\n * The PDF engine to use for the PDF viewer.\n */\n engine: PdfEngine;\n /**\n * Registry configuration including logger, permissions, and defaults.\n */\n config?: PluginRegistryConfig;\n /**\n * @deprecated Use config.logger instead. Will be removed in next major version.\n */\n logger?: Logger;\n /**\n * The callback to call when the PDF viewer is initialized.\n */\n onInitialized?: (registry: PluginRegistry) => Promise<void>;\n /**\n * The plugins to use for the PDF viewer.\n */\n plugins: PluginBatchRegistrations;\n /**\n * The children to render for the PDF viewer.\n */\n children: ReactNode | ((state: PDFContextState) => ReactNode);\n /**\n * Whether to auto-mount specific non-visual DOM elements from plugins.\n * @default true\n */\n autoMountDomElements?: boolean;\n}\n\nexport function EmbedPDF({\n engine,\n config,\n logger,\n onInitialized,\n plugins,\n children,\n autoMountDomElements = true,\n}: EmbedPDFProps) {\n const [registry, setRegistry] = useState<PluginRegistry | null>(null);\n const [coreState, setCoreState] = useState<CoreState | null>(null);\n const [isInitializing, setIsInitializing] = useState<boolean>(true);\n const [pluginsReady, setPluginsReady] = useState<boolean>(false);\n const initRef = useRef<EmbedPDFProps['onInitialized']>(onInitialized);\n\n useEffect(() => {\n initRef.current = onInitialized;\n }, [onInitialized]);\n\n useEffect(() => {\n // Merge deprecated logger prop into config (config.logger takes precedence)\n const finalConfig: PluginRegistryConfig = {\n ...config,\n logger: config?.logger ?? logger,\n };\n const pdfViewer = new PluginRegistry(engine, finalConfig);\n pdfViewer.registerPluginBatch(plugins);\n\n const initialize = async () => {\n await pdfViewer.initialize();\n\n if (pdfViewer.isDestroyed()) {\n return;\n }\n\n const store = pdfViewer.getStore();\n setCoreState(store.getState().core);\n\n const unsubscribe = store.subscribe((action, newState, oldState) => {\n // Only update if it's a core action and the core state changed\n if (store.isCoreAction(action) && newState.core !== oldState.core) {\n setCoreState(newState.core);\n }\n });\n\n /* always call the *latest* callback */\n await initRef.current?.(pdfViewer);\n\n if (pdfViewer.isDestroyed()) {\n unsubscribe();\n return;\n }\n\n pdfViewer.pluginsReady().then(() => {\n if (!pdfViewer.isDestroyed()) {\n setPluginsReady(true);\n }\n });\n\n // Provide the registry to children via context\n setRegistry(pdfViewer);\n setIsInitializing(false);\n\n // Return cleanup function\n return unsubscribe;\n };\n\n let cleanup: (() => void) | undefined;\n initialize()\n .then((unsub) => {\n cleanup = unsub;\n })\n .catch(console.error);\n\n return () => {\n cleanup?.();\n pdfViewer.destroy();\n setRegistry(null);\n setCoreState(null);\n setIsInitializing(true);\n setPluginsReady(false);\n };\n }, [engine, plugins]);\n\n // Compute convenience accessors\n const contextValue: PDFContextState = useMemo(() => {\n const activeDocumentId = coreState?.activeDocumentId ?? null;\n const documents = coreState?.documents ?? {};\n const documentOrder = coreState?.documentOrder ?? [];\n\n // Compute active document\n const activeDocument =\n activeDocumentId && documents[activeDocumentId] ? documents[activeDocumentId] : null;\n\n // Compute open documents in order\n const documentStates = documentOrder\n .map((docId) => documents[docId])\n .filter((doc): doc is DocumentState => doc !== null && doc !== undefined);\n\n return {\n registry,\n coreState,\n isInitializing,\n pluginsReady,\n // Convenience accessors (always safe to use)\n activeDocumentId,\n activeDocument,\n documents,\n documentStates,\n };\n }, [registry, coreState, isInitializing, pluginsReady]);\n\n const content = typeof children === 'function' ? children(contextValue) : children;\n\n return (\n <PDFContext.Provider value={contextValue}>\n {pluginsReady && autoMountDomElements ? (\n <AutoMount plugins={plugins}>{content}</AutoMount>\n ) : (\n content\n )}\n </PDFContext.Provider>\n );\n}\n","import type { BasePlugin } from '@embedpdf/core';\nimport { usePlugin } from './use-plugin';\n\ntype CapabilityState<T extends BasePlugin> = {\n provides: ReturnType<NonNullable<T['provides']>> | null;\n isLoading: boolean;\n ready: Promise<void>;\n};\n\n/**\n * Hook to access a plugin's capability.\n * @param pluginId The ID of the plugin to access\n * @returns The capability provided by the plugin or null during initialization\n * @example\n * // Get zoom capability\n * const zoom = useCapability<ZoomPlugin>(ZoomPlugin.id);\n */\nexport function useCapability<T extends BasePlugin>(pluginId: T['id']): CapabilityState<T> {\n const { plugin, isLoading, ready } = usePlugin<T>(pluginId);\n\n if (!plugin) {\n return {\n provides: null,\n isLoading,\n ready,\n };\n }\n\n if (!plugin.provides) {\n throw new Error(`Plugin ${pluginId} does not provide a capability`);\n }\n\n return {\n provides: plugin.provides() as ReturnType<NonNullable<T['provides']>>,\n isLoading,\n ready,\n };\n}\n","import { useMemo } from '@framework';\nimport { PdfPermissionFlag } from '@embedpdf/models';\nimport { useCoreState } from './use-core-state';\nimport { getEffectivePermission, getEffectivePermissions } from '../../lib/store/selectors';\n\nexport interface DocumentPermissions {\n /** Effective permission flags after applying overrides */\n permissions: number;\n /** Raw PDF permission flags (before overrides) */\n pdfPermissions: number;\n /** Check if a specific permission flag is effectively allowed */\n hasPermission: (flag: PdfPermissionFlag) => boolean;\n /** Check if all specified flags are effectively allowed */\n hasAllPermissions: (...flags: PdfPermissionFlag[]) => boolean;\n\n // Shorthand booleans for all permission flags (using effective permissions):\n /** Can print (possibly degraded quality) */\n canPrint: boolean;\n /** Can modify document contents */\n canModifyContents: boolean;\n /** Can copy/extract text and graphics */\n canCopyContents: boolean;\n /** Can add/modify annotations and fill forms */\n canModifyAnnotations: boolean;\n /** Can fill in existing form fields */\n canFillForms: boolean;\n /** Can extract for accessibility */\n canExtractForAccessibility: boolean;\n /** Can assemble document (insert, rotate, delete pages) */\n canAssembleDocument: boolean;\n /** Can print high quality */\n canPrintHighQuality: boolean;\n}\n\n/**\n * Hook that provides reactive access to a document's effective permission flags.\n * Applies layered resolution: per-document override → global override → PDF permission.\n *\n * @param documentId The ID of the document to check permissions for.\n * @returns An object with effective permissions, raw PDF permissions, helper functions, and shorthand booleans.\n */\nexport function useDocumentPermissions(documentId: string): DocumentPermissions {\n const coreState = useCoreState();\n\n return useMemo(() => {\n if (!coreState) {\n return {\n permissions: PdfPermissionFlag.AllowAll,\n pdfPermissions: PdfPermissionFlag.AllowAll,\n hasPermission: () => true,\n hasAllPermissions: () => true,\n canPrint: true,\n canModifyContents: true,\n canCopyContents: true,\n canModifyAnnotations: true,\n canFillForms: true,\n canExtractForAccessibility: true,\n canAssembleDocument: true,\n canPrintHighQuality: true,\n };\n }\n\n const effectivePermissions = getEffectivePermissions(coreState, documentId);\n const pdfPermissions =\n coreState.documents[documentId]?.document?.permissions ?? PdfPermissionFlag.AllowAll;\n\n const hasPermission = (flag: PdfPermissionFlag) =>\n getEffectivePermission(coreState, documentId, flag);\n const hasAllPermissions = (...flags: PdfPermissionFlag[]) =>\n flags.every((flag) => getEffectivePermission(coreState, documentId, flag));\n\n return {\n permissions: effectivePermissions,\n pdfPermissions,\n hasPermission,\n hasAllPermissions,\n // All permission flags as booleans (using effective permissions)\n canPrint: hasPermission(PdfPermissionFlag.Print),\n canModifyContents: hasPermission(PdfPermissionFlag.ModifyContents),\n canCopyContents: hasPermission(PdfPermissionFlag.CopyContents),\n canModifyAnnotations: hasPermission(PdfPermissionFlag.ModifyAnnotations),\n canFillForms: hasPermission(PdfPermissionFlag.FillForms),\n canExtractForAccessibility: hasPermission(PdfPermissionFlag.ExtractForAccessibility),\n canAssembleDocument: hasPermission(PdfPermissionFlag.AssembleDocument),\n canPrintHighQuality: hasPermission(PdfPermissionFlag.PrintHighQuality),\n };\n }, [coreState, documentId]);\n}\n","import { useMemo } from '@framework';\nimport { DocumentState } from '@embedpdf/core';\nimport { useCoreState } from './use-core-state';\n\n/**\n * Hook that provides reactive access to a specific document's state from the core store.\n *\n * @param documentId The ID of the document to retrieve.\n * @returns The reactive DocumentState object or null if not found.\n */\nexport function useDocumentState(documentId: string | null): DocumentState | null {\n const coreState = useCoreState();\n\n const documentState = useMemo(() => {\n if (!coreState || !documentId) return null;\n return coreState.documents[documentId] ?? null;\n }, [coreState, documentId]);\n\n return documentState;\n}\n","import { useState, useEffect } from '@framework';\nimport { CoreState, StoreState } from '@embedpdf/core';\nimport { useRegistry } from './use-registry';\n\n/**\n * Hook that provides access to the current global store state\n * and re-renders the component when the state changes\n */\nexport function useStoreState<T = CoreState>(): StoreState<T> | null {\n const { registry } = useRegistry();\n const [state, setState] = useState<StoreState<T> | null>(null);\n\n useEffect(() => {\n if (!registry) return;\n\n // Get initial state\n setState(registry.getStore().getState() as StoreState<T>);\n\n // Subscribe to store changes\n const unsubscribe = registry.getStore().subscribe((_action, newState) => {\n setState(newState as StoreState<T>);\n });\n\n return () => unsubscribe();\n }, [registry]);\n\n return state;\n}\n"],"names":["PDFContext","createContext","registry","coreState","isInitializing","pluginsReady","activeDocumentId","activeDocument","documents","documentStates","AutoMount","plugins","children","utilities","wrappers","useMemo","reg","pkg","package","hasAutoMountElements","elements","autoMountElements","element","type","push","component","wrappedContent","reduce","content","Wrapper","jsx","Fragment","map","Utility","i","useRegistry","contextValue","useContext","Error","usePlugin","pluginId","plugin","isLoading","ready","Promise","getPlugin","useCoreState","PdfPermissionFlag","Print","ModifyContents","CopyContents","ModifyAnnotations","FillForms","ExtractForAccessibility","AssembleDocument","PrintHighQuality","ALL_PERMISSION_FLAGS","PERMISSION_FLAG_TO_NAME","getPermissionOverride","overrides","flag","name","getEffectivePermission","state","documentId","docState","docConfig","permissions","globalConfig","globalPermissions","pdfPermissions","_a","document","AllowAll","docOverride","globalOverride","enforceDocumentPermissions","engine","config","logger","onInitialized","autoMountDomElements","setRegistry","useState","setCoreState","setIsInitializing","setPluginsReady","initRef","useRef","useEffect","current","finalConfig","pdfViewer","PluginRegistry","registerPluginBatch","cleanup","async","initialize","isDestroyed","store","getStore","getState","core","unsubscribe","subscribe","action","newState","oldState","isCoreAction","call","then","unsub","catch","console","error","destroy","documentOrder","docId","filter","doc","Provider","value","provides","hasPermission","hasAllPermissions","canPrint","canModifyContents","canCopyContents","canModifyAnnotations","canFillForms","canExtractForAccessibility","canAssembleDocument","canPrintHighQuality","effectivePermissions","acc","getEffectivePermissions","_b","flags","every","setState","_action"],"mappings":"8NAgBaA,EAAaC,EAAAA,cAA+B,CACvDC,SAAU,KACVC,UAAW,KACXC,gBAAgB,EAChBC,cAAc,EACdC,iBAAkB,KAClBC,eAAgB,KAChBC,UAAW,CAAA,EACXC,eAAgB,KCfX,SAASC,GAAUC,QAAEA,EAAAC,SAASA,IACnC,MAAMC,UAAEA,EAAAC,SAAWA,GAAaC,EAAAA,QAAQ,KAEtC,MAAMF,EAA6B,GAC7BC,EAAqD,GAE3D,IAAA,MAAWE,KAAOL,EAAS,CACzB,MAAMM,EAAMD,EAAIE,QAChB,GAAIC,EAAAA,qBAAqBF,GAAM,CAC7B,MAAMG,EAAWH,EAAII,qBAAuB,GAE5C,IAAA,MAAWC,KAAWF,EACC,YAAjBE,EAAQC,KACVV,EAAUW,KAAKF,EAAQG,WACG,YAAjBH,EAAQC,MAEjBT,EAASU,KAAKF,EAAQG,UAG5B,CACF,CACA,MAAO,CAAEZ,UAAAA,EAAWC,SAAAA,IACnB,CAACH,IAGEe,EAAiBZ,EAASa,OAC9B,CAACC,EAASC,IAAYC,EAAAA,IAACD,GAASjB,SAAAgB,IAChChB,GAGF,cACGmB,WAAA,CACEnB,SAAA,CAAAc,EACAb,EAAUmB,IAAI,CAACC,EAASC,UACtBD,EAAA,GAAa,WAAWC,QAIjC,CCxCO,SAASC,IACd,MAAMC,EAAeC,EAAAA,WAAWrC,GAGhC,QAAqB,IAAjBoC,EACF,MAAM,IAAIE,MAAM,2DAGlB,MAAMpC,SAAEA,EAAAE,eAAUA,GAAmBgC,EAGrC,GAAIhC,EACF,OAAOgC,EAIT,GAAiB,OAAblC,EACF,MAAM,IAAIoC,MAAM,8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kBACrD8E,oBAAqBT,EAAc5E,EAAAA,kBAAkBQ,oBAEtD,CAACpD,EAAW6D,GACjB,2BC7EO,SAA0BA,GAC/B,MAAM7D,EAAY2C,IAOlB,OALsB/B,EAAAA,QAAQ,IACvBZ,GAAc6D,EACZ7D,EAAUK,UAAUwD,IAAe,KADJ,KAErC,CAAC7D,EAAW6D,GAGjB,kECXO,WACL,MAAM9D,SAAEA,GAAaiC,KACd4B,EAAO4E,GAAYxD,EAAAA,SAA+B,MAgBzD,OAdAM,EAAAA,UAAU,KACR,IAAKvF,EAAU,OAGfyI,EAASzI,EAASkG,WAAWC,YAG7B,MAAME,EAAcrG,EAASkG,WAAWI,UAAU,CAACoC,EAASlC,KAC1DiC,EAASjC,KAGX,MAAO,IAAMH,KACZ,CAACrG,IAEG6D,CACT"}
|
package/dist/preact/index.js
CHANGED
|
@@ -2,6 +2,7 @@ import { createContext, Fragment } from "preact";
|
|
|
2
2
|
import { useMemo, useState, useRef, useEffect, useContext } from "preact/hooks";
|
|
3
3
|
import { jsx, jsxs } from "preact/jsx-runtime";
|
|
4
4
|
import { hasAutoMountElements, PluginRegistry } from "@embedpdf/core";
|
|
5
|
+
import { PdfPermissionFlag } from "@embedpdf/models";
|
|
5
6
|
const PDFContext = createContext({
|
|
6
7
|
registry: null,
|
|
7
8
|
coreState: null,
|
|
@@ -42,6 +43,7 @@ function AutoMount({ plugins, children }) {
|
|
|
42
43
|
}
|
|
43
44
|
function EmbedPDF({
|
|
44
45
|
engine,
|
|
46
|
+
config,
|
|
45
47
|
logger,
|
|
46
48
|
onInitialized,
|
|
47
49
|
plugins,
|
|
@@ -57,7 +59,11 @@ function EmbedPDF({
|
|
|
57
59
|
initRef.current = onInitialized;
|
|
58
60
|
}, [onInitialized]);
|
|
59
61
|
useEffect(() => {
|
|
60
|
-
const
|
|
62
|
+
const finalConfig = {
|
|
63
|
+
...config,
|
|
64
|
+
logger: (config == null ? void 0 : config.logger) ?? logger
|
|
65
|
+
};
|
|
66
|
+
const pdfViewer = new PluginRegistry(engine, finalConfig);
|
|
61
67
|
pdfViewer.registerPluginBatch(plugins);
|
|
62
68
|
const initialize = async () => {
|
|
63
69
|
var _a;
|
|
@@ -197,11 +203,117 @@ function useDocumentState(documentId) {
|
|
|
197
203
|
}, [coreState, documentId]);
|
|
198
204
|
return documentState;
|
|
199
205
|
}
|
|
206
|
+
({
|
|
207
|
+
print: PdfPermissionFlag.Print,
|
|
208
|
+
modifyContents: PdfPermissionFlag.ModifyContents,
|
|
209
|
+
copyContents: PdfPermissionFlag.CopyContents,
|
|
210
|
+
modifyAnnotations: PdfPermissionFlag.ModifyAnnotations,
|
|
211
|
+
fillForms: PdfPermissionFlag.FillForms,
|
|
212
|
+
extractForAccessibility: PdfPermissionFlag.ExtractForAccessibility,
|
|
213
|
+
assembleDocument: PdfPermissionFlag.AssembleDocument,
|
|
214
|
+
printHighQuality: PdfPermissionFlag.PrintHighQuality
|
|
215
|
+
});
|
|
216
|
+
const ALL_PERMISSION_FLAGS = [
|
|
217
|
+
PdfPermissionFlag.Print,
|
|
218
|
+
PdfPermissionFlag.ModifyContents,
|
|
219
|
+
PdfPermissionFlag.CopyContents,
|
|
220
|
+
PdfPermissionFlag.ModifyAnnotations,
|
|
221
|
+
PdfPermissionFlag.FillForms,
|
|
222
|
+
PdfPermissionFlag.ExtractForAccessibility,
|
|
223
|
+
PdfPermissionFlag.AssembleDocument,
|
|
224
|
+
PdfPermissionFlag.PrintHighQuality
|
|
225
|
+
];
|
|
226
|
+
const PERMISSION_FLAG_TO_NAME = {
|
|
227
|
+
[PdfPermissionFlag.Print]: "print",
|
|
228
|
+
[PdfPermissionFlag.ModifyContents]: "modifyContents",
|
|
229
|
+
[PdfPermissionFlag.CopyContents]: "copyContents",
|
|
230
|
+
[PdfPermissionFlag.ModifyAnnotations]: "modifyAnnotations",
|
|
231
|
+
[PdfPermissionFlag.FillForms]: "fillForms",
|
|
232
|
+
[PdfPermissionFlag.ExtractForAccessibility]: "extractForAccessibility",
|
|
233
|
+
[PdfPermissionFlag.AssembleDocument]: "assembleDocument",
|
|
234
|
+
[PdfPermissionFlag.PrintHighQuality]: "printHighQuality"
|
|
235
|
+
};
|
|
236
|
+
function getPermissionOverride(overrides, flag) {
|
|
237
|
+
if (!overrides) return void 0;
|
|
238
|
+
if (flag in overrides) {
|
|
239
|
+
return overrides[flag];
|
|
240
|
+
}
|
|
241
|
+
const name = PERMISSION_FLAG_TO_NAME[flag];
|
|
242
|
+
if (name && name in overrides) {
|
|
243
|
+
return overrides[name];
|
|
244
|
+
}
|
|
245
|
+
return void 0;
|
|
246
|
+
}
|
|
247
|
+
function getEffectivePermission(state, documentId, flag) {
|
|
248
|
+
var _a;
|
|
249
|
+
const docState = state.documents[documentId];
|
|
250
|
+
const docConfig = docState == null ? void 0 : docState.permissions;
|
|
251
|
+
const globalConfig = state.globalPermissions;
|
|
252
|
+
const pdfPermissions = ((_a = docState == null ? void 0 : docState.document) == null ? void 0 : _a.permissions) ?? PdfPermissionFlag.AllowAll;
|
|
253
|
+
const docOverride = getPermissionOverride(docConfig == null ? void 0 : docConfig.overrides, flag);
|
|
254
|
+
if (docOverride !== void 0) {
|
|
255
|
+
return docOverride;
|
|
256
|
+
}
|
|
257
|
+
const globalOverride = getPermissionOverride(globalConfig == null ? void 0 : globalConfig.overrides, flag);
|
|
258
|
+
if (globalOverride !== void 0) {
|
|
259
|
+
return globalOverride;
|
|
260
|
+
}
|
|
261
|
+
const enforce = (docConfig == null ? void 0 : docConfig.enforceDocumentPermissions) ?? (globalConfig == null ? void 0 : globalConfig.enforceDocumentPermissions) ?? true;
|
|
262
|
+
if (!enforce) return true;
|
|
263
|
+
return (pdfPermissions & flag) !== 0;
|
|
264
|
+
}
|
|
265
|
+
function getEffectivePermissions(state, documentId) {
|
|
266
|
+
return ALL_PERMISSION_FLAGS.reduce((acc, flag) => {
|
|
267
|
+
return getEffectivePermission(state, documentId, flag) ? acc | flag : acc;
|
|
268
|
+
}, 0);
|
|
269
|
+
}
|
|
270
|
+
function useDocumentPermissions(documentId) {
|
|
271
|
+
const coreState = useCoreState();
|
|
272
|
+
return useMemo(() => {
|
|
273
|
+
var _a, _b;
|
|
274
|
+
if (!coreState) {
|
|
275
|
+
return {
|
|
276
|
+
permissions: PdfPermissionFlag.AllowAll,
|
|
277
|
+
pdfPermissions: PdfPermissionFlag.AllowAll,
|
|
278
|
+
hasPermission: () => true,
|
|
279
|
+
hasAllPermissions: () => true,
|
|
280
|
+
canPrint: true,
|
|
281
|
+
canModifyContents: true,
|
|
282
|
+
canCopyContents: true,
|
|
283
|
+
canModifyAnnotations: true,
|
|
284
|
+
canFillForms: true,
|
|
285
|
+
canExtractForAccessibility: true,
|
|
286
|
+
canAssembleDocument: true,
|
|
287
|
+
canPrintHighQuality: true
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
const effectivePermissions = getEffectivePermissions(coreState, documentId);
|
|
291
|
+
const pdfPermissions = ((_b = (_a = coreState.documents[documentId]) == null ? void 0 : _a.document) == null ? void 0 : _b.permissions) ?? PdfPermissionFlag.AllowAll;
|
|
292
|
+
const hasPermission = (flag) => getEffectivePermission(coreState, documentId, flag);
|
|
293
|
+
const hasAllPermissions = (...flags) => flags.every((flag) => getEffectivePermission(coreState, documentId, flag));
|
|
294
|
+
return {
|
|
295
|
+
permissions: effectivePermissions,
|
|
296
|
+
pdfPermissions,
|
|
297
|
+
hasPermission,
|
|
298
|
+
hasAllPermissions,
|
|
299
|
+
// All permission flags as booleans (using effective permissions)
|
|
300
|
+
canPrint: hasPermission(PdfPermissionFlag.Print),
|
|
301
|
+
canModifyContents: hasPermission(PdfPermissionFlag.ModifyContents),
|
|
302
|
+
canCopyContents: hasPermission(PdfPermissionFlag.CopyContents),
|
|
303
|
+
canModifyAnnotations: hasPermission(PdfPermissionFlag.ModifyAnnotations),
|
|
304
|
+
canFillForms: hasPermission(PdfPermissionFlag.FillForms),
|
|
305
|
+
canExtractForAccessibility: hasPermission(PdfPermissionFlag.ExtractForAccessibility),
|
|
306
|
+
canAssembleDocument: hasPermission(PdfPermissionFlag.AssembleDocument),
|
|
307
|
+
canPrintHighQuality: hasPermission(PdfPermissionFlag.PrintHighQuality)
|
|
308
|
+
};
|
|
309
|
+
}, [coreState, documentId]);
|
|
310
|
+
}
|
|
200
311
|
export {
|
|
201
312
|
EmbedPDF,
|
|
202
313
|
PDFContext,
|
|
203
314
|
useCapability,
|
|
204
315
|
useCoreState,
|
|
316
|
+
useDocumentPermissions,
|
|
205
317
|
useDocumentState,
|
|
206
318
|
usePlugin,
|
|
207
319
|
useRegistry,
|