UNPKG

pspdfkit

Version:

View and annotate PDF files in your web app. Full support for mobile and desktop. Runs in the browser using WASM.

13 lines 54.4 kB
/*! * PSPDFKit for Web 2024.8.2 (https://pspdfkit.com/web) * * Copyright (c) 2016-2025 PSPDFKit GmbH. All rights reserved. * * THIS SOURCE CODE AND ANY ACCOMPANYING DOCUMENTATION ARE PROTECTED BY INTERNATIONAL COPYRIGHT LAW * AND MAY NOT BE RESOLD OR REDISTRIBUTED. USAGE IS BOUND TO THE PSPDFKIT LICENSE AGREEMENT. * UNAUTHORIZED REPRODUCTION OR DISTRIBUTION IS SUBJECT TO CIVIL AND CRIMINAL PENALTIES. * This notice may not be removed from this file. * * PSPDFKit uses several open source third-party components: https://pspdfkit.com/acknowledgements/web/ */ "use strict";(globalThis.webpackChunkPSPDFKit=globalThis.webpackChunkPSPDFKit||[]).push([[9042],{26175:(e,t,n)=>{n.d(t,{D:()=>h});var a=n(67136),i=n(2752),s=n(49568),o=n(85409),r=n(55994),c=n(49014),l=n(89574),d=n(97881),u=n(9939),m=n(32784);class h{constructor(e){(0,a.A)(this,"linearizedInstance",null),this.ctx=e}initializeLinearizedInstance(){if(this.linearizedInstance&&!this.linearizedInstance.isDestroyed())throw new o.uE("Linearized loader is already allocated");(0,o.V1)(this.ctx.wasmCtx,"Wasm context is not available");const e=this.linearizedInstance=new i.MX.LinearizedInstance(this.ctx.wasmCtx,r.EA);return(0,o.V1)(this.linearizedInstance,"Linearized loader is not available"),(0,c.attachLinearizedInstance)(this.ctx,e),this.linearizedInstance}async normallyOpenLinearizedDocument(e,t){(0,o.V1)(this.ctx.wasmCtx,"Wasm context is not available"),(0,o.V1)(this.linearizedInstance,"Linearized loader is not available"),(0,o.V1)(this.linearizedInstance.state===i.MX.LinearizedInstanceState.Complete,"PDF isnt completely downloaded"),(0,c.removeLinearizedInstance)(this.ctx),this.linearizedInstance=null,await e.client.openCreateFilePathDocument(t)}destroy(){(0,c.removeLinearizedInstance)(this.ctx)}fetchPageInfoWhileDownloading(e,t){const n=this.linearizedInstance;return(0,o.V1)(n,"Linearized loader is not available"),n.whenPageAvailable(e,t)}renderTile(e,t,n,a,s,o){let r;o&&(r={annotations:o.annotations.filter(l.mH).map(d.eq).toJS().map((e=>({content:e}))),formFieldValues:o.formFieldValues.map(d.cA).toJS(),formFields:o.formFields.map(d.T7).toJS(),signatures:o.signatures||[],attachments:o.attachments});const c=i.MX.Renderer.renderTile(this.ctx,e,t,n,{renderForPrinting:a,renderText:s,priority:t.width===n.width&&t.height===n.height?i.MX.Priority.High:i.MX.Priority.Normal},r).then((e=>(0,u.vB)({buffer:e.buffer,width:n.width,height:n.height,format:e.format}).then((e=>{if(null===e)throw new Error("Image handle is null");return e}))));return{promise:c.promise,cancel:c.cancel}}getTextLines(e){return i.MX.Text.getTextForPage(this.ctx,e).then((t=>(0,m.K0)({textLines:t},e)))}getContentTree(e){return i.MX.Text.getContentTreeForPage(this.ctx,e).then((t=>{let n=[],a=0,i=0;return n=t.reduce(((t,n)=>{let{nodes:s}=n;const o=(0,m.l1)(s,e,t.length,a,i);return a+=o.reduce(((e,t)=>{let{textLines:n}=t;return e+n.size}),0),i+=o.reduce(((e,t)=>{let{contentElements:n}=t;return e+n.size}),0),t.concat(o)}),[]),(0,s.B8)(n)}))}}},72262:(e,t,n)=>{n.d(t,{K:()=>d});var a=n(67136),i=n(49568),s=n(85409),o=n(76117),r=n(89574),c=n(28650),l=n(67748);class d{constructor(){(0,a.A)(this,"attachmentsCache",(0,i.T5)()),(0,a.A)(this,"cachedAPStreams",(0,i.T5)()),(0,a.A)(this,"pageAPStreamsPromises",(0,i.T5)()),(0,a.A)(this,"annotationAPStreamPromises",(0,i.T5)()),(0,a.A)(this,"_cachedRenderedAnnotation",null),(0,a.A)(this,"_objectURLs",{}),(0,a.A)(this,"_makeEnqueuedRelease",((e,t)=>{if("IMG"===e?.element?.tagName){const n=e.element.src;if(!n)return;"number"==typeof this._objectURLs[n]?this._objectURLs[n]++:this._objectURLs[n]=1;const a=e.release;e.release=()=>{this._objectURLs[n]--,this._objectURLs[n]<=0&&(a?.(),this._cachedRenderedAnnotation?.index===t&&(this._cachedRenderedAnnotation=null),delete this._objectURLs[n])}}}))}getAnnotationFormFieldAndValue(e){const t=this.provider;(0,s.V1)(t instanceof t.constructor,"Backend can only use backend annotation provider");const n=e instanceof o.sb?t._readStateCallbacks?.getFormFieldByName(e.formFieldName):null;return{formField:n,formFieldValue:!n||n instanceof o.Vw?null:new o.E2({name:n.name,value:void 0!==n.formattedValue?n.formattedValue:"string"==typeof n.value?n.value:n.values})}}getAnnotationAvailableVariants(e){const t=this.provider;(0,s.V1)(t instanceof t.constructor,"Backend can only use backend annotation provider");return[...t._readStateCallbacks?.getAvailableVariants(e)||[],"normal"]}cachedRenderAnnotation(e,t,n,a,i){const o=this.provider;(0,s.V1)(o instanceof o.constructor,"Backend can only use backend annotation provider");const{formField:c,formFieldValue:l}=this.getAnnotationFormFieldAndValue(e);if(!(0,r.lG)(e,c))return this.renderAnnotation(e,l,t,n,a,i);const d=this.getAnnotationAvailableVariants(e);let u=!1,m=()=>{u=!0};return{promise:new Promise((async(s,o)=>{const r=t=>{const n=this.annotationAPStreamPromises.get(e.id);n&&(this.annotationAPStreamPromises=this.annotationAPStreamPromises.delete(e.id),n(t))},c=this.annotationAPStreamPromises.get(e.id);this.annotationAPStreamPromises=this.annotationAPStreamPromises.set(e.id,s),c&&c(null);try{const o=this.pageAPStreamsPromises.get(e.pageIndex);if(!o){const t=new Promise((t=>{this.annotationAPStreamPromises=this.annotationAPStreamPromises.set(e.id,t)}));return void s(await t)}await o;const c=this.cachedAPStreams.get(e.pageIndex);if(c){const t=c?c.get(e.id):null;if(t)return void r(this.getAPStream(t,i))}const{promise:h,cancel:p}=this.renderAPStream(e,l,t,n,a,d,i);if(u)r(null);else if(m=p,d.length>1){const t=await Promise.all(h.map((e=>e.promise)));r(t[d.indexOf(i||"normal")]),t.some(Boolean)&&this.cacheAPStream(d.reduce(((e,n,a)=>t[a]?{...e,[n]:t[a]}:e),{}),e)}else{const t=await h,n=t?this.getAPStream(t,i):null;r(n),n&&this.cacheAPStream(t,e)}}catch(e){o(e)}})),cancel:m}}cacheAPStream(e,t){let n=this.cachedAPStreams.get(t.pageIndex);n||(this.cachedAPStreams=this.cachedAPStreams.set(t.pageIndex,(0,i.T5)()),n=this.cachedAPStreams.get(t.pageIndex)),this.cachedAPStreams=this.cachedAPStreams.setIn([t.pageIndex,t.id],e)}clearAllPageAPStreams(e){const t=this.cachedAPStreams.get(e);t&&(t.forEach((e=>{this.releaseAPStream(e)})),this.cachedAPStreams=this.cachedAPStreams.delete(e)),this.pageAPStreamsPromises=this.pageAPStreamsPromises.delete(e)}clearPageAPStreams(e,t){const n=this.cachedAPStreams.get(e);n&&(n.filter(((e,n)=>t.has(n))).forEach((e=>{this.releaseAPStream(e)})),this.cachedAPStreams=this.cachedAPStreams.updateIn([e],(e=>e.filter(((e,n)=>!t.has(n))))))}getAPStream(e,t){return e instanceof c.A?e:e?.[t||"normal"]||null}renderAPStream(e,t,n,a,i,s,o){if(s.length>1){const o=s.map((s=>this.renderAnnotation(e,t,n,a,i,"normal"!==s?s:void 0)));return{promise:o,cancel:()=>{o.forEach((e=>{e.cancel()}))}}}return this.renderAnnotation(e,t,n,a,i,o)}releaseAPStream(e){e instanceof c.A?e.release():Object.values(e).forEach((e=>{e.release()}))}isVisuallyIdenticalStampAnnotationCached(e){let{annotation:t,width:n,height:a}=e;const i=(0,r.sS)(t);return!!this._cachedRenderedAnnotation&&(0,l.bp)({annotation:t,annotationVisualPropertiesString:i,width:n,height:a,secondAnnotationVisualPropertiesString:this._cachedRenderedAnnotation.index,secondAnnotationWidth:this._cachedRenderedAnnotation.width,secondAnnotationHeight:this._cachedRenderedAnnotation.height})}cachedStampAnnotationDiscardablePromise(e){let{promise:t,resolve:n,reject:a}=e;(0,s.V1)(this._cachedRenderedAnnotation);const i=this._cachedRenderedAnnotation.index;return this._cachedRenderedAnnotation.APStreamPromise.then((e=>{let t;e&&(t=new c.A(e.element.cloneNode(!0),e.release),this._makeEnqueuedRelease(t,i)),n(t)})).catch(a),{promise:t,cancel:()=>{}}}}},92026:(e,t,n)=>{n.d(t,{mG:()=>oe,Ay:()=>re,DO:()=>ce,mn:()=>le});var a=n(67136),i=n(49568),s=n(55994),o=n(85409),r=n(45646),c=n(6163),l=n(80018),d=n(2752),u=n(41204),m=n(95248),h=n(9939),p=n(41477),f=n(89574),g=n(72262),y=n(37361),b=n(47159),A=n(97881),S=n(7737),P=n(82987),w=n(78625),F=n(74111),_=n(78236);class v extends((0,i.mS)({alreadyLoadedPages:(0,i.T5)(),isLoaded:!1,isDestroyed:!1})){}const k={skippedPdfObjectIds:[],skippedPdfBookmarkIds:[],annotations:[],bookmarks:[],formFieldValues:[],formFields:[],attachments:{}};class C{constructor(e,t){(0,a.A)(this,"_state",new v),(0,a.A)(this,"_formFieldsLoadedPromise",null),(0,a.A)(this,"_objectCreationPromises",(0,i.T5)()),(0,a.A)(this,"_loadBookmarksPromise",null),(0,a.A)(this,"_commentsLoadedPromise",null),(0,a.A)(this,"canCreateBackendOrphanWidgets",!1),(0,a.A)(this,"updateTabOrderTimeout",null),(0,a.A)(this,"pagesTabOrderToUpdate",(0,i.NZ)()),this._core=e,this._json=t?(0,o.$y)(t):null,this._setReadStateCallbacksPromise=new Promise((e=>{this._setReadStateCallbacksPromiseResolve=e}))}async load(){if(this._state=this._state.set("isLoaded",!0),!this._formFieldCallbacks&&await this._loadFormFieldValues(),!this._json)return this;await this._core.importInstantJSON({...k,...this._json}),(0,o.V1)(this._json);const{annotations:e,attachments:t}=this._json;if(this._isDestroyed()||!t||0===Object.entries(t).length)return this;if(e)for(let n=0;n<e.length;n++){let a=null;const i=e[n];if("imageAttachmentId"in i&&i.imageAttachmentId){const e=t?t[i.imageAttachmentId]:null;if(e)try{a=(0,w.lj)(atob(e.binary),e.contentType),(0,o.V1)(this._annotationCallbacks),this._annotationCallbacks.createAttachment(i.imageAttachmentId,a)}catch(e){(0,o.pq)(`Skipped attachment with id ${i.imageAttachmentId} from payload because an error occurred while converting the binary image to blob.`),(0,o.pq)(e)}}}return this}destroy(){this._state=this._state.set("isDestroyed",!0),this._annotationCallbacks=null,this._readStateCallbacks=null,this._bookmarkCallbacks=null,this._formFieldCallbacks=null,this._formFieldValueCallbacks=null,this._commentCallbacks=null}setReadStateCallbacks(e){this._readStateCallbacks=e,this._setReadStateCallbacksPromiseResolve?.()}setAnnotationCallbacks(e){this._annotationCallbacks=e}setBookmarkCallbacks(e){this._bookmarkCallbacks=e}setFormFieldCallbacks(e){this._formFieldCallbacks=e}setFormFieldValueCallbacks(e){this._formFieldValueCallbacks=e}setCommentCallbacks(e){this._commentCallbacks=e}createComment(e,t,n){return this._core.applyComments(t.map((e=>I(e,n))).toArray())}updateComment(e,t,n){return this._core.applyComments(t.map((e=>I(e,n))).toArray())}deleteComment(e,t,n){return this._core.applyComments(t.map((e=>I(e,n))).toArray())}async loadComments(){return this._commentsLoadedPromise||(this._commentsLoadedPromise=this._loadComments()),this._commentsLoadedPromise}async _loadComments(){this._verifyLoaded();const e=await this._core.getComments()??[],t=(0,i.B8)(e.map((e=>{let t;return t=e.pdfObjectId?e.id||e.pdfObjectId?.toString():(0,f.K1)(),(0,A.XL)(t,e)})));await Promise.all(t.map((e=>"number"==typeof e.pageIndex&&this.loadAnnotationsForPageIndex(e.pageIndex))).filter(Boolean).toArray()),this._commentCallbacks?.createComments(t,_.n),this._commentsLoadedPromise=Promise.resolve()}async updateTabOrder(e){this.pagesTabOrderToUpdate=this.pagesTabOrderToUpdate.add(e),this.updateTabOrderTimeout&&clearTimeout(this.updateTabOrderTimeout),this.updateTabOrderTimeout=setTimeout((async()=>{const e=this.pagesTabOrderToUpdate.toArray();if(this.pagesTabOrderToUpdate=(0,i.NZ)(),this._isDestroyed())return;const t=await Promise.all(e.map((e=>this._core.getTabOrder(e))));this._isDestroyed()||((0,o.V1)(this._annotationCallbacks),(0,S.vA)((()=>{e.forEach(((e,n)=>{this._annotationCallbacks?.setPageTabOrder(e,t[n])}))})))}),1e3)}async setTabOrder(e,t){return this._core.setTabOrder(e,t)}async createAnnotation(e,t){this._verifyLoaded();const n=t.find(((t,n)=>((0,o.V1)("imageAttachmentId"in e,"Annotation must have imageAttachmentId."),n===e.imageAttachmentId))),a=await this._core.createAnnotation((0,A.eq)(e),n?n.data:null);"number"!=typeof a||"number"!=typeof e.pdfObjectId||e.pdfObjectId===a||this._isDestroyed()||((0,o.V1)(this._annotationCallbacks),this._annotationCallbacks.updateAnnotations((0,i.B8)([e.set("pdfObjectId",a)]))),await this.updateTabOrder(e.pageIndex)}async updateAnnotation(e){this._verifyLoaded(),await this._core.updateAnnotation((0,A.eq)(e)),await this.updateTabOrder(e.pageIndex)}deleteAnnotation(e){return this._verifyLoaded(),this._core.deleteAnnotation((0,A.eq)(e))}createBookmark(e){return this._verifyLoaded(),this._core.createBookmark((0,P.U)(e))}updateBookmark(e){return this._verifyLoaded(),this._core.updateBookmark((0,P.U)(e))}deleteBookmark(e){return this._verifyLoaded(),this._core.deleteBookmark(e)}createFormField(e){this._verifyLoaded(),(0,o.V1)(this._readStateCallbacks);const t=this._readStateCallbacks.getFormFieldWidgets(e);return this._core.createFormField((0,A.T7)(e),t.map((e=>(0,A.eq)(e))).toArray()).then((async e=>{(0,S.vA)((()=>{e.forEach(((e,n)=>{const a=t.get(n);(0,o.V1)(a),(0,o.V1)(this._annotationCallbacks),"number"!=typeof e||"number"!=typeof a.pdfObjectId||a.pdfObjectId===e||this._isDestroyed()||this._annotationCallbacks.updateAnnotations((0,i.B8)([a.set("pdfObjectId",e)]))}))}))}))}updateFormField(e){this._verifyLoaded(),(0,o.V1)(this._readStateCallbacks);const t=this._readStateCallbacks.getFormFieldWidgets(e);return this._core.updateFormField((0,A.T7)(e),t.map((e=>(0,A.eq)(e))).toArray())}deleteFormField(e){return this._verifyLoaded(),this._core.deleteFormField((0,A.T7)(e))}loadFormFields(){return this._formFieldsLoadedPromise||(this._formFieldsLoadedPromise=this._loadFormFields()),this._formFieldsLoadedPromise}async _loadFormFields(){this._verifyLoaded();const e=await this._core.readFormJSONObjects();if(this._isDestroyed())return;let t=(0,i.B8)(),n=(0,i.B8)().withMutations((n=>{e.forEach((e=>{const{formField:a,widgets:i,value:s}=e;try{let e;e=a.pdfObjectId?a.pdfObjectId.toString():(0,f.K1)();const r=(0,A.mh)(e,a);(0,o.V1)(this._readStateCallbacks),this._readStateCallbacks.isFormFieldInState(r.name)||n.push(r.set("value",s)),i.forEach((e=>{let n;n=e.pdfObjectId?e.id||e.pdfObjectId.toString():(0,f.K1)(),(0,o.V1)(this._readStateCallbacks),t=t.push((0,A.h8)(n,e))}))}catch(e){(0,o.pq)(`Skipped creating form field #${a.pdfObjectId} from payload because an error occurred while deserializing.`),(0,o.pq)(e)}}))}));const a={},s={};t.forEach((e=>{s[e.id]||(s[e.id]=[]),s[e.id].push(e.pdfObjectId)})),t=t.map((e=>{if(s[e.id].filter((t=>t!==e.pdfObjectId)).length>0&&e.pdfObjectId?.toString()!==e.id||this._readStateCallbacks?.isAnnotationInState(e.id)){const t=(0,f.K1)();return a[e.formFieldName]?a[e.formFieldName].push({[e.id]:t}):a[e.formFieldName]=[{[e.id]:t}],n=n.map((n=>n.name===e.formFieldName?n.update("annotationIds",(n=>n?.map((n=>n===e.id?t:n)))):n)),e.set("id",t)}return e})),Object.keys(a).forEach((e=>{const a=n.find((t=>t.name===e));(0,o.V1)(a);const i=t.filter((t=>t.formFieldName===e)).toArray().map((e=>(0,A.eq)(e)));this._core.updateFormField((0,A.T7)(a),i)})),n.size>0&&!this._isDestroyed()&&((0,o.V1)(this._formFieldCallbacks),this._formFieldCallbacks.createFormFields(n,_.n)),await this._loadFormFieldValues(),t.size>0&&!this._isDestroyed()&&((0,o.V1)(this._annotationCallbacks),this._annotationCallbacks.createAnnotations(t,(0,i.T5)(),_.n)),this._formFieldsLoadedPromise=Promise.resolve()}createFormFieldValue(e){return this._verifyLoaded(),this.setFormFieldValue(e)}setFormFieldValue(e){return this._verifyLoaded(),this._core.setFormFieldValue((0,A.cA)(e))}deleteFormFieldValue(e){return this._verifyLoaded(),this._core.deleteFormFieldValue(e.replace("form-field-value/",""))}loadAnnotationsForPageIndex(e){const t=this._state.alreadyLoadedPages.get(e);if(t)return t;const n=this._loadAnnotationsForPageIndex(e);return this._state=this._state.setIn(["alreadyLoadedPages",e],n),n}async _loadAnnotationsForPageIndex(e){this._verifyLoaded();const[t,n]=await Promise.all([this._core.annotationsForPageIndex(e),this._core.getTabOrder(e)]);if(this._isDestroyed())return;const a=[],s=[],r=t.map((e=>{let{rollover:t,down:n,...i}=e;return t&&"number"==typeof i.pdfObjectId&&a.push(i.pdfObjectId),n&&"number"==typeof i.pdfObjectId&&s.push(i.pdfObjectId),i})).filter((e=>"number"==typeof e.pageIndex));this._formFieldCallbacks&&await this.loadFormFields();const c=(0,i.B8)().withMutations((e=>{r.filter((e=>!e.id||this._readStateCallbacks&&!this._readStateCallbacks.isAnnotationInState(e.id))).forEach((t=>{t.pdfObjectId;try{let n;n=function(e){return"pspdfkit/link"===e.type&&0===e.pdfObjectId}(t)?t.id||(0,f.K1)():t.id||t.pdfObjectId.toString(),(e.some((e=>e.id===n))||this._readStateCallbacks?.isAnnotationInState(n))&&(n=(0,f.K1)(),t.id=n,this._core.updateAnnotation(t));const a=(0,A.h8)(n,t);e.push(a)}catch(e){(0,o.pq)(`Skipped creating annotation #${t.pdfObjectId} from payload because an error occurred while deserializing.`),(0,o.pq)(e)}}))}));(0,S.vA)((()=>{(0,o.V1)(this._annotationCallbacks),c.size>0&&this._annotationCallbacks.createAnnotations(c,(0,i.T5)(),_.n),this._annotationCallbacks.setPageTabOrder(e,n),a.length>0&&this._annotationCallbacks.addAnnotationVariants("rollover",a),s.length>0&&this._annotationCallbacks.addAnnotationVariants("down",s)})),this._state=this._state.setIn(["alreadyLoadedPages",e],Promise.resolve())}async _loadFormFieldValues(){this._verifyLoaded();const e=await this._core.getFormValues();if(this._isDestroyed())return;const t=(0,i.B8)().withMutations((t=>{e.forEach((e=>{try{t.push((0,A.R5)(e))}catch(t){(0,o.pq)(`Skipped creating form field value #${e.pdfObjectId} from payload because an error occurred while deserializing.`),(0,o.pq)(t)}}))}));t.size>0&&!this._isDestroyed()&&((0,o.V1)(this._formFieldValueCallbacks),this._formFieldValueCallbacks.setFormFieldValues(t))}async loadBookmarks(){this._verifyLoaded();const e=await this._core.getBookmarks();if(this._isDestroyed())return;const t=(0,i.B8)().withMutations((t=>{e.forEach((e=>{let n;n=e.id?e.id:e.pdfBookmarkId?e.pdfBookmarkId:(0,F.z)();try{t.push((0,P.r)(n,e))}catch(e){(0,o.pq)(`Skipped creating bookmark #${n} from payload because an error occurred while deserializing.`),(0,o.pq)(e)}}))}));t.size>0&&!this._isDestroyed()&&((0,o.V1)(this._bookmarkCallbacks),this._bookmarkCallbacks.createBookmarks(t,_.n))}_verifyLoaded(){(0,o.V1)(this._state.isLoaded,"StandaloneProvider not properly initialized.")}_isDestroyed(){return this._state.isDestroyed}async syncChanges(){}}function I(e,t){(0,o.V1)(e.rootId,"A new comment must have `rootId` present");const n=t.get(e.rootId);return(0,o.V1)(n,"An annotation must be present linked to the comment to create"),(0,A.wG)(e,n.pdfObjectId?.toString()===n.id?parseInt(e.rootId):e.rootId)}class D{constructor(e,t){this.identifier=e,this.callback=t}request(){return this.callback()}}var x=n(30026),T=n(85553);class V extends(i.mS({baseUrl:null,baseCoreUrl:null,baseProcessorEngineUrl:null,licenseKey:null,document:null,backendPermissions:new x.A,documentResponse:null,disableWebAssemblyStreaming:!1,enableAutomaticLinkExtraction:!1,overrideMemoryLimit:null,features:(0,i.B8)(),signatureFeatureAvailability:T.g.NONE,documentHandle:null,trustedCAsCallback:null,signaturesInfoPromise:null,customFonts:null,fontSubstitutions:null,forceLegacySignaturesFeature:!1,forceAnnotationsRender:!1,appName:null,lazyLoadedPages:null,productId:null,processorEngine:null,dynamicFonts:null,inlineWorkers:!0,allowLinearizedLoading:!1})){}var O=n(83720),R=n(44439),L=n(25888),B=n(83145),E=n(14511),U=n(5293),j=n(37094),N=n(15168),z=n(70631),M=n(40927),K=n(76117),q=n(64337),W=n(68322),J=n(20546),$=n(83647),G=n(87374),X=n(96580),H=n(50960),Y=n(26175),Q=n(77270);function Z(e){return"string"==typeof e?.serialNumber&&e.body instanceof ArrayBuffer}function ee(e){return e?.pkcs7 instanceof ArrayBuffer&&(!("ocspResponses"in e)||Array.isArray(e.ocspResponses)&&e.ocspResponses.every((e=>Z(e))))}function te(e){if(!e)return!1;const{signedData:t,timestampResponse:n,ocspResponses:a}=e;if(!(t instanceof ArrayBuffer))return!1;if(n&&!(n instanceof ArrayBuffer))return!1;if(a){if(!Array.isArray(a))return!1;if(!a.every((e=>Z(e))))return!1}return!0}class ne{constructor(e){this.backend=e}async signDocumentAndReload(e,t){const n=e?.signingData,a=n?.certificates;(0,o.V1)(void 0===t||"function"==typeof t,"On a Standalone deployment, when `signaturePreparationData.signingData.privateKey` is not provided, `twoStepSignatureCallbackOrSigningServiceData` must be a function or `PSPDFKit.StandaloneSigningServiceData`."),(0,o.V1)(!n?.timestamp||"string"==typeof n?.timestamp?.url,"The `url` property of `signingData.timestamp` must be a string."),(0,o.V1)(!n?.timestamp||!n?.timestamp?.password||"string"==typeof n?.timestamp?.password,"The `password` property of `signingData.timestamp` must be a string."),(0,o.V1)(!n?.timestamp||!n?.timestamp?.username||"string"==typeof n?.timestamp?.username,"The `username` property of `signingData.timestamp` must be a string."),(0,o.V1)(void 0===n?.ltv||"boolean"==typeof n?.ltv,"The `ltv` property of `signingData` must be a boolean if set."),(0,o.V1)(void 0===n?.ltv||"boolean"==typeof n?.ltv,"The `ltv` property of `signingData` must be a boolean if set."),(0,o.V1)(!n||!n.signatureType||n.signatureType===$.D7.CMS||Array.isArray(a)&&a.length>0&&a.every((e=>Boolean(e instanceof ArrayBuffer&&e.byteLength>0||"string"==typeof e&&e.length>0))),"For signatures of type `PSPDFKit.SignatureType.CAdES` an `Array` of certificates must be provided in `signaturePreparationData.signingData.certificates`.");const i={signatureType:n?.signatureType||(Array.isArray(a)&&a.length>0?$.D7.CAdES:$.D7.CMS),...a&&{certificates:a.map((e=>e instanceof ArrayBuffer?l.o4.fromUint8Array(new Uint8Array(e)):l.o4.encode(e)))},...e?.placeholderSize?{estimatedSize:e.placeholderSize}:null};try{const{hash:a,signatureFormFieldName:s,file:r,fileContents:c,dataToBeSigned:d}=await this.backend.client.prepareSign((0,A.Y6)(i),e?.signatureMetadata?(0,A.sZ)(e.signatureMetadata):null,Boolean(e?.flatten),e?.formFieldName,(0,A.qN)(e?.position),await(0,A.z8)(e?.appearance)),u=function(e){const t=e.trim(),n=t.length/2,a=new Uint8Array(n);for(let e=0;e<n;e++)a[e]=parseInt(t.substr(2*e,2),16);return a}(d);let m,h,p;if(t){try{m=await t({hash:a,fileContents:c,dataToBeSigned:u})}catch(e){throw new o.uE(`\`twoStepSignatureCallback\` threw an error: ${e}`)}if(!(m instanceof ArrayBuffer||ee(m)||te(m)))throw new o.uE(`The resolved value from \`twoStepSignatureCallback\` should be a an \`ArrayBuffer\`, \`SignatureCallbackResponsePkcs7\`, or \`SignatureCallbackResponseRaw\`, but is of type \`${typeof m}\` instead.`);p=m}else{if(!n?.privateKey)throw new o.uE("No `twoStepSignatureCallback` or `signingData.privateKey` was provided.");{const e={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"},modulusLength:2048,extractable:!1,publicExponent:new Uint8Array([1,0,1])},t=await globalThis.crypto.subtle.importKey("pkcs8",function(e){const t=e.split("\n");let n="";for(let e=0;e<t.length;e++)t[e].trim().length>0&&t[e].indexOf("-BEGIN RSA PRIVATE KEY-")<0&&t[e].indexOf("-BEGIN PRIVATE KEY-")<0&&t[e].indexOf("-BEGIN RSA PUBLIC KEY-")<0&&t[e].indexOf("-BEGIN CERTIFICATE-")<0&&t[e].indexOf("-END RSA PRIVATE KEY-")<0&&t[e].indexOf("-END PRIVATE KEY-")<0&&t[e].indexOf("-END RSA PUBLIC KEY-")<0&&t[e].indexOf("-END CERTIFICATE-")<0&&(n+=t[e].trim());return l.o4.toUint8Array(n).buffer}(n.privateKey),e,!0,["sign"]);h=await globalThis.crypto.subtle.sign(e,t,u),p=h}}let f="",g=i.certificates||[];if(p instanceof ArrayBuffer)f=l.o4.fromUint8Array(new Uint8Array(p))||"";else if(ee(p)){const e=p;f=l.o4.fromUint8Array(new Uint8Array(e.pkcs7))||""}else if(te(p)){const e=p;f=l.o4.fromUint8Array(new Uint8Array(e.signedData))||"",g=e.certificates.map((e=>e instanceof ArrayBuffer?l.o4.fromUint8Array(new Uint8Array(e)):l.o4.encode(e)))}let y=null,b=[];if(n?.ltv&&(p instanceof ArrayBuffer?b=await this.backend.getRevocationResponses(g):(ee(p)||te(p))&&((0,o.V1)(null==p.ocspResponses||Array.isArray(p.ocspResponses)&&p.ocspResponses.every((e=>Z(e))),"The `ocspResponses` property of `signatureData` must be a array of `OCSPResponses`."),b=p.ocspResponses?.map((e=>({response_code:200,body:l.o4.fromUint8Array(new Uint8Array(e.body)),token:e.serialNumber})))??[],b.length||((0,o.R8)("The `TwoStepSignatureCallback` didn't return certificate revocation responses; trying to fetch them online."),b=await this.backend.getRevocationResponses(g)))),te(p)){const e=p;(0,o.V1)(null==e.timestampResponse||e.timestampResponse instanceof ArrayBuffer,"The `timestampResponse` property of `signatureData` must be an `ArrayBuffer`."),e.timestampResponse&&(y={response_code:200,body:l.o4.fromUint8Array(new Uint8Array(e.timestampResponse)),token:"1234"})}if(!y&&n?.timestamp&&p instanceof ArrayBuffer){const e=l.o4.toUint8Array(f).buffer;y=await this.backend.timestampData(e,n.timestamp)}const S=await this.backend.client.sign(r,s,a,A.xz[i.signatureType],f,g,ee(p)?"pkcs7":te(p)?"raw":n?.signatureContainer?n.signatureContainer:null,y,b);return n?.ltv&&S.signature.certificateChainValidationStatus===$.k5.ok_but_could_not_check_revocation&&(0,o.R8)("Document signed, but couldn't add certificate revocation information so the signature may not be LTV-enabled."),await this.backend.reloadDocument(),s}catch(e){throw await this.backend.client.restoreToOriginalState(),e}}}var ae=n(40527);class ie extends ne{constructor(e){super(e)}async signDocumentAndReload(e,t){t=(0,ae.kJ)(t),(0,o.V1)(t,"`twoStepSignatureCallbackOrStandaloneSigningServiceData` must be a `PSPDFKit.StandaloneSigningServiceData` object when performing signing via a backend service.");const{jwt:n,signingToken:a}=t,i=this.resolveServerUrl(t),s=await this.getCertificates(i,n,a),r=this.signatureCallbackFactory(i,n,s,e,t);return await super.signDocumentAndReload({...e,signingData:{...e?.signingData,signatureType:e?.signingData?.signatureType||$.D7.CAdES,certificates:s}},r)}async getCertificates(e,t,n){let a;try{a=await fetch(`${e}/api/get_certificates`,{method:"POST",headers:{Authorization:`Bearer ${t}`,Accept:"application/json","Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({signingToken:n})})}catch(t){throw new o.uE(`The signing service failed to retrieve certificates: Failed to fetch from ${e}/api/get_certificates`)}if(!a.ok)throw new o.uE(`The signing service failed to retrieve certificates: ${await a.json()}`);const i=(await a.json())?.data||{};return i.certificates.concat(i.ca_certificates).map((e=>l.o4.fromBase64(e)))}resolveServerUrl(e){const t=e.serverUrl||function(e){try{const t=e.split(".");if(3!==t.length)throw new o.uE("Invalid JWT token format");const n=l.o4.decode(t[1]);return JSON.parse(n)}catch(e){throw new o.uE(`Invalid auth token: ${e.message}`)}}(e.jwt).server_url;return(0,o.V1)(t,"`twoStepSignatureCallbackOrStandaloneSigningServiceData.jwt` must contain claim `server_url` or the `twoStepSignatureCallbackOrStandaloneSigningServiceData.serverUrl` should be set"),t}signatureCallbackFactory(e,t,n,a,i){return async s=>{let r,{hash:c,dataToBeSigned:d}=s;try{r=await fetch(`${e}/api/sign_hash`,{method:"POST",headers:{Authorization:`Bearer ${t}`,Accept:"application/json","Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({dataToBeSigned:l.o4.fromUint8Array(d),hash:c,signatureType:a?.signingData?.signatureType||$.D7.CAdES,signingToken:i.signingToken,cadesLevel:a?.signingData?.padesLevel||$.sX.b_lt})})}catch(t){throw new o.uE(`The signing service failed to retrieve certificates: Failed to fetch from ${e}/api/get_certificates`)}if(!r.ok)throw new o.uE(`The signing service failed to sign: ${await r.text()}`);const u=(await r.json())?.data||{};if(a?.signingData?.signatureContainer===$.Yj.pkcs7){const e={pkcs7:l.o4.toUint8Array(u.pkcs7).buffer};return u.ocspResponses&&(e.ocspResponses=u.ocspResponses.map((e=>({serialNumber:e.serialNumber,body:l.o4.toUint8Array(e.body).buffer})))),e}{const e={certificates:n,signedData:l.o4.toUint8Array(u.signedData).buffer,timestampResponse:l.o4.toUint8Array(u.timestampResponse).buffer};return u.ocspResponses&&(e.ocspResponses=u.ocspResponses.map((e=>({serialNumber:e.serialNumber,body:l.o4.toUint8Array(e.body).buffer})))),e}}}}let se;se=n(55994).Fe;const oe=new s.iy(se);class re extends g.K{constructor(e){super(),(0,a.A)(this,"type","STANDALONE"),(0,a.A)(this,"standaloneDocumentSigner",new ne(this)),(0,a.A)(this,"signingServiceDocumentSigner",new ie(this)),(0,a.A)(this,"_XFDF",null),le(e);const{baseUrl:t,baseCoreUrl:n,baseProcessorEngineUrl:i,instantJSON:s,XFDF:o,enableAutomaticLinkExtraction:c,overrideMemoryLimit:l,trustedCAsCallback:u,electronAppName:m,appName:h,isSharePoint:p,isSalesforce:f,productId:g,processorEngine:b,dynamicFonts:A,inlineWorkers:S,formsConfiguration:P,allowLinearizedLoading:w}=e;"string"==typeof o&&(this._XFDF={source:o,keepCurrentAnnotations:!0===e.XFDFKeepCurrentAnnotations,ignorePageRotation:!0===e.XFDFIgnorePageRotation}),s&&s.annotations&&(s.annotations=s.annotations.map((e=>(e.id=e.id?.toString(),e)))),this._instantJSON=s,this._formsConfiguration=P,"function"==typeof u&&(this._trustedCAsCallback=u);const{disableWebAssemblyStreaming:F,customFonts:_,fontSubstitutions:v}=e,{standaloneInstancesPoolSize:k}=e;void 0!==k&&(oe.size=k);const I=!!e.electronicSignatures&&Boolean(e.electronicSignatures.forceLegacySignaturesFeature);let D=g||null;!p&&!f||D||(D=p?W.v.SharePoint:W.v.Salesforce),this._state=new V(ce({baseUrl:t,baseCoreUrl:n,baseProcessorEngineUrl:i,licenseKey:e.licenseKey,document:e.document,disableWebAssemblyStreaming:F,enableAutomaticLinkExtraction:c,overrideMemoryLimit:l,documentHandle:"0",customFonts:_,fontSubstitutions:v,forceLegacySignaturesFeature:I,appName:h||m,productId:D,processorEngine:b||G.j.fasterProcessing,dynamicFonts:A,inlineWorkers:S,allowLinearizedLoading:w})),this._requestQueue=new r.L(y.z3);const{object:x,checkIn:T}=oe.checkOut();this.client=x,this.checkIn=T,this.corePDFBridge=new Y.D(d.MX.createWASMContext(this.client));const O=s?{annotations:s.annotations||[],formFields:s.formFields||[],formFieldValues:s.formFieldValues||[],skippedPdfObjectIds:s.skippedPdfObjectIds||[],skippedPdfFormFieldIds:s.skippedPdfFormFieldIds||[],attachments:s.attachments||{},bookmarks:s.bookmarks||[],skippedPdfBookmarkIds:s.skippedPdfBookmarkIds||[],comments:s.comments||void 0,skippedComments:s.skippedComments||void 0,format:s.format,...s.pdfId?{pdfId:s.pdfId}:null}:null;this.provider=new C(this.client,O)}isUsingInstantProvider(){return!1}hasClientsPresence(){return!1}async load(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this._isPDFJavaScriptEnabled=e.isPDFJavaScriptEnabled,{features:this._state.features,signatureFeatureAvailability:this._state.signatureFeatureAvailability,hasPassword:!!e.password,password:e.password,allowedTileScales:"all"}}async afterDocumentLoaded(e){}destroy(){this.corePDFBridge.destroy(),this.provider&&this.provider.destroy(),this._requestQueue&&this._requestQueue.destroy(),this.checkIn()}async documentInfo(){return this._state.documentResponse}async lazyLoadPages(){if(!this._state.lazyLoadedPages){const e=await this.client.getAllPageInfos(this._state.documentResponse.pageCount);this._state=this._state.set("lazyLoadedPages",e)}return this._state.lazyLoadedPages}getDocumentHandle(){return this._state.documentHandle}getFormJSON(){return this.client.getFormJSON()}permissions(){return Promise.resolve(this._state.backendPermissions)}textForPageIndex(e){return this.corePDFBridge.getTextLines(e)}getContentTreeForPageIndex(e){return this.corePDFBridge.getContentTree(e)}getTextFromRects(e,t){return this.client.getTextFromRects(e,t.toJS())}getAvailableFontFaces(e){return this.client.getAvailableFontFaces(e)}async getSuggestedLineHeightFactor(e){return"number"!=typeof e.pdfObjectId?1:"number"!=typeof e.pageIndex?((0,o.R8)("Annotation must have a pageIndex."),1):(e.lineHeightFactor&&(0,o.R8)(`Annotation ${e.id} already has a line height factor.`),this.client.getSuggestedLineHeightFactor(e.pdfObjectId,e.pageIndex))}async getClosestSnapPoint(e){const t=await this.client.getClosestSnapPoint(e.x,e.y);return t&&"number"==typeof t[0]&&"number"==typeof t[1]?new H.bR({x:t[0],y:t[1]}):e}configureSnapper(e){return this.client.configureSnapper(e)}renderAnnotation(e,t,n,a,i,s){if(0===Math.floor(a)||0===Math.floor(i))return{promise:Promise.resolve(void 0),cancel:()=>{}};const o=(0,Q.yl)();if(e instanceof K.xY){if(this.isVisuallyIdenticalStampAnnotationCached({annotation:e,width:a,height:i}))return this.cachedStampAnnotationDiscardablePromise(o);(0,f.nH)(e)||(this._cachedRenderedAnnotation={index:(0,f.sS)(e),width:a,height:i,APStreamPromise:o.promise})}const r=e.id,c=new D(r,(()=>this.client.renderAnnotation((0,A.eq)(e),n,a,i,(0,N.LG)(),s).then((e=>e?"string"==typeof e?(0,h.$3)(e):(0,h.vB)({buffer:e,width:a,height:i}):Promise.resolve(null))).then((t=>(e instanceof K.xY&&this._makeEnqueuedRelease(t,(0,f.sS)(e)),o.resolve(t),t)))));return this._requestQueue.enqueue(c,!1)}async getMeasurementSnappingPoints(e){return this.client.getMeasurementSnappingPoints(e)}async getSecondaryMeasurementUnit(){return await this.client.getSecondaryMeasurementUnit()}async setSecondaryMeasurementUnit(e){return await this.client.setSecondaryMeasurementUnit(e)}async compareDocuments(e,t){const n={originalDocument:e.originalDocument,changedDocument:e.changedDocument,comparisonOperation:(0,m.c)(t)};return await this.client.compareDocuments(n)}async renderPageAnnotations(e,t,n){const a=this.provider,i=[],s=[],o=t.some((e=>e instanceof K.sb));o&&await a._setReadStateCallbacksPromise;const r=t.filter((e=>{const t=(o?a._readStateCallbacks.getAnnotationWithFormField(e.id):null)?.formField,n=(0,f.lG)(e,t);if(n&&t){i.find((e=>e.name===t.name))||(i.push((0,A.cA)((0,O.Af)(t))),s.push(t))}return n}));function c(e,t){if(e?.formFieldName){const n=s.find((t=>t.name===e.formFieldName)),a=t.find((t=>t.name===e.formFieldName));if(!(0,O.Ny)(n,a))return!1}return!0}const l=new Promise(((t,i)=>{const o=r.filter((e=>0!==Math.floor(e.boundingBox.width*n)&&0!==Math.floor(e.boundingBox.height*n)));this.client.renderPageAnnotations(e,o.map((e=>e.pdfObjectId)).toArray(),o.map((e=>e.boundingBox.width*n)).toArray(),o.map((e=>e.boundingBox.height*n)).toArray(),(0,N.LG)()).then((e=>{const i=s.map((e=>a._readStateCallbacks?.getFormFieldByName(e.name))).filter(Boolean),r=e.map(((e,t)=>{const a=o.get(t);return c(a,i)&&a&&e?"string"==typeof e?(0,h.$3)(e):(0,h.vB)({buffer:e,width:a.boundingBox.width*n,height:a.boundingBox.height*n}):Promise.resolve(null)}));Promise.all(r).then((e=>{const i=s.map((e=>a._readStateCallbacks?.getFormFieldByName(e.name))).filter(Boolean);e.forEach(((e,t)=>{const a=o.get(t);if(a){const{formFieldValue:t}=this.getAnnotationFormFieldAndValue(a),s=this.getAnnotationAvailableVariants(a),o=this.annotationAPStreamPromises.get(a.id),r=c(a,i);if(o&&(this.annotationAPStreamPromises=this.annotationAPStreamPromises.delete(a.id),o(r?e:null)),s.length>1){const i={normal:e};e&&r&&this.cacheAPStream(i,a);const{promise:o}=this.renderAPStream(a,t,null,a.boundingBox.width*n,a.boundingBox.height*n,s);Promise.all(o.map((e=>e.promise))).then((e=>{e.some(Boolean)&&s.forEach(((t,n)=>{"normal"!==t&&e[n]&&(i[t]=e[n])}))}))}else e&&r&&this.cacheAPStream(e,a)}})),t()}))})).catch(i)}));return this.pageAPStreamsPromises=this.pageAPStreamsPromises.set(e,l),l}renderDetachedAnnotation(e,t,n,a){if(e.id)throw new o.uE(`Detached annotations should not have an \`id\`: ${e.id}`);const i=(0,Q.yl)();if(e instanceof K.xY){if(this.isVisuallyIdenticalStampAnnotationCached({annotation:e,width:n,height:a}))return this.cachedStampAnnotationDiscardablePromise(i);(0,f.nH)(e)||(this._cachedRenderedAnnotation={index:(0,f.sS)(e),width:n,height:a,APStreamPromise:i.promise})}const s=(0,c.Z0)(),r=new D(s,(()=>this.client.renderDetachedAnnotation((0,A.eq)(e),t,n,a,(0,N.LG)()).then((e=>e?(0,h.vB)({buffer:e,width:n,height:a}):Promise.resolve(null))).then((t=>(e instanceof K.xY&&this._makeEnqueuedRelease(t,(0,f.sS)(e)),i.resolve(t),t))))),{promise:l,cancel:d}=this._requestQueue.enqueue(r,!1);return{promise:l,cancel:d}}async getAttachment(e){const[t,n]=await this.client.getAttachment(e);return new Blob([t],{type:n})}async parseXFDF(e,t){const{errors:n,formFieldValues:a,annotations:s}=await this.client.parseXFDF(e,t);return{errors:n?.map((e=>({errorMessage:e.error_message,type:e.type}))),formFieldValues:a?.reduce(((e,t)=>(e[t.fqdn]=t.values,e)),{}),annotations:(0,i.B8)(s?.map((e=>(0,A.h8)((0,f.K1)(),e)))||[])}}async search(e,t,n,a){let i=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:j.n.TEXT;const o=await this.client.search(e,t,n,a,s);return(0,b.g)(o.filter((e=>i||!e.isAnnotation)))}async searchAndRedact(e,t,n){const{totalPages:a}=n,s=await this.client.search(e,t.startPageIndex??0,t.pageRange??a,t.caseSensitive,t.searchType);return(0,i.B8)(s.filter((e=>t.searchInAnnotations||!e.isAnnotation)).map((e=>{const a=e.isAnnotation?[e.annotationRect]:e.rectsOnPage,s=(0,i.B8)(a).map((e=>((0,o.V1)(e),(0,U.a)(e))));return new B.A({...(0,f.mN)(n),...t.annotationPreset,pageIndex:e.pageIndex,rects:s,boundingBox:R.A.union(s)})})))}async exportPDF(){let{flatten:e=!1,incremental:t,saveForPrinting:n=!1,format:a="pdf",excludeAnnotations:i=!1,preserveInstantJSONChanges:s=!0,permissions:r,outputFormat:c=!1,flattenElectronicSignatures:l=e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},d=arguments.length>1?arguments[1]:void 0;if(e&&!l)throw new o.uE("Cannot set `flattenElectronicSignatures` to `false` when `flatten` is set to `true`.");if(c&&"boolean"!=typeof c&&c.conformance&&(0,o.V1)(c.conformance&&Object.values(J.o).includes(c.conformance),"The supplied PDF/A Conformance type is not valid. Valid Conformance should be one of the following options PSPDFKit.Conformance."+Object.keys(J.o).join(", PSPDFKit.Conformance.")),void 0===t)if(this._state.features.includes(q.Y.DIGITAL_SIGNATURES)){const e=await this.getSignaturesInfo();t=!n&&Boolean("not_signed"!==e.status)}else t=!1;return this.client.exportFile(e,t,n,a,i,s,r,d).then((async e=>{let[t,n]=e;if(t.mimeType=n.mimeType,t.extension=n.extension,c){const e="boolean"!=typeof c&&c.conformance?c.conformance:J.o.PDFA_2B;let n;try{return n=await this._setupGdPictureClient(),await n.toPdf(t,e)}finally{n?.destroy(),(0,X.Pm)(null)}}return t}))}async exportOffice(e){let t,{format:n}=e;try{const[e]=await this.client.exportFile(!1,!1,!1,"pdf",!1,!0);return t=await this._setupGdPictureClient(),await t.toOffice(e,n)}catch(e){throw new o.uE(`Exporting to ${n} failed: ${e.message}.`)}finally{t?.destroy(),(0,X.Pm)(null)}}async _setupGdPictureClient(){let e=(0,X.jU)();return e||(e=(0,X.NY)({baseUrl:this._state.baseProcessorEngineUrl,mainThreadOrigin:this._state.appName||(0,u.D5)()||window.location.origin,licenseKey:this._state.licenseKey,processorEngine:this._state.processorEngine,customFonts:this._state.customFonts,dynamicFonts:this._state.dynamicFonts,fontSubstitutions:this._state.fontSubstitutions}),(0,X.Pm)(e)),e}exportXFDF(e){return this.client.exportXFDF(e)}exportInstantJSON(e){return this.client.exportInstantJSON(e)}getPDFURL(){let{includeComments:e=!0,saveForPrinting:t,excludeAnnotations:n}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.generatePDFObjectURL({includeComments:e,saveForPrinting:t,excludeAnnotations:n})}generatePDFObjectURL(){let e,{includeComments:t=!0,saveForPrinting:n,excludeAnnotations:a=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=!1;return{promise:new Promise((s=>{this.exportPDF({flatten:!0,includeComments:t,saveForPrinting:n,excludeAnnotations:a}).then((t=>{if(i)return;const n=new Blob([t],{type:t.mimeType});e=window.URL.createObjectURL(n),s(e)}))})),revoke:()=>{e&&window.URL.revokeObjectURL(e),i=!0}}}async getDocumentOutline(){const e=await this.client.getDocumentOutline();return(0,i.B8)(e.map(p.r))}async setDocumentOutline(e){return this.client.setDocumentOutline(e.map(p.U).toArray())}async getPageGlyphs(e){const t=await this.client.getPageGlyphs(e);return(0,A.Fj)(t)}async onKeystrokeEvent(e){return await this.client.onKeystrokeEvent(e)}async evalFormValuesActions(e){return this.client.evalFormValuesActions(e.map(A.cA).toJS())}async evalScript(e,t,n){return this.client.evalScript(e,t,n)}async setFormJSONUpdateBatchMode(e){return this.client.setFormJSONUpdateBatchMode(e)}async getMeasurementScales(){return(await this.client.getMeasurementScales())?.measurementContentFormats}async addMeasurementScale(e){return await this.client.addMeasurementScale(e)}async removeMeasurementScale(e){return await this.client.removeMeasurementScale(e)}async getAnnotationsByScale(e){return await this.client.getAnnotationsByScale(e)}async applyOperationsAndReload(e){try{const{processedOperations:t,operationsDocuments:n}=await de(e);await this.client.applyOperations(t,n)}catch(e){throw new o.uE(`Applying operations failed: ${e}`)}return this.provider._state=this.provider._state.set("alreadyLoadedPages",(0,i.T5)()),this.reloadDocument()}async applyRedactionsAndReload(){try{await this.client.applyRedactions()}catch(e){throw new o.uE(`Applying redactions failed: ${e}`)}return this.reloadDocument()}async reloadDocument(){try{this.provider?.destroy(),this.provider=new C(this.client,null),this._state=this._state.set("lazyLoadedPages",null);const e=await this.client.reloadDocument();return this._state=this._state.set("documentResponse",e).set("documentHandle",(parseInt(this._state.documentHandle)+1).toString()).set("signaturesInfoPromise",null),{features:this._state.features,signatureFeatureAvailability:this._state.signatureFeatureAvailability,hasPassword:!1,password:void 0,allowedTileScales:"all"}}catch(e){throw new o.uE(`Reloading failed: ${e}`)}}async getEmbeddedFiles(){const e=await this.client.getEmbeddedFilesList();return(0,i.B8)(e.map((e=>{let{id:t,...n}=e;return(0,M.r)(t,n,!0)})))}async exportPDFWithOperations(e){try{const{processedOperations:t,operationsDocuments:n}=await de(e);return this.client.exportPDFWithOperations(t,n)}catch(e){throw new o.uE(`Exporting PDF with operations failed: ${e}`)}}async setSignaturesLTV(e){try{const t=(e??[]).map((e=>e instanceof ArrayBuffer?l.o4.fromUint8Array(new Uint8Array(e)):l.o4.encode(e))),n=await this.getRevocationResponses(t);if((await this.client.setSignaturesLTV(n).then((e=>(0,A.N5)(e)))).signatures?.find((e=>e.certificateChainValidationStatus===$.k5.ok_but_could_not_check_revocation)))throw"Could not set LTV for all signatures. Check that the OCSP response is valid.";return this._state=this._state.set("signaturesInfoPromise",null),this.getSignaturesInfo()}catch(e){throw new o.uE(`Setting signatures LTV failed: ${e}`)}}getSignaturesInfo(){try{if(this._state.signaturesInfoPromise)return this._state.signaturesInfoPromise;const e=this.client.getSignaturesInfo().then((e=>(0,A.N5)(e)));return this._state=this._state.set("signaturesInfoPromise",e),e}catch(e){throw new o.uE(`Getting document signatures info: ${e}`)}}async refreshSignaturesInfo(){this._state=this._state.set("signaturesInfoPromise",null)}async loadCertificates(e){return this.client.loadCertificates(e)}async getRevocationResponses(e){const t=await this.client.getRevocationRequests(e);return await Promise.all(t.map((async e=>{let{method:t,url:n,content_type:a,request_data:i,token:s}=e;try{const e=await fetch(n,{method:t,headers:{"Content-Type":a??"application/ocsp-request"},body:l.o4.toUint8Array(i).buffer}),o=await e.arrayBuffer();return{response_code:e.status,body:l.o4.fromUint8Array(new Uint8Array(o)),token:s}}catch(e){return{response_code:0,body:"",token:s,error_message:e.message}}})))}async signDocumentAndReload(e,t){(0,o.V1)(void 0===t||"function"==typeof t||(0,ae.kJ)(t),"On a Standalone deployment, `twoStepSignatureCallbackOrSigningServiceData` must be a function or `PSPDFKit.StandaloneSigningServiceData` if provided.");const n=(0,ae.kJ)(t);return n?this.signingServiceDocumentSigner.signDocumentAndReload(e,n):this.standaloneDocumentSigner.signDocumentAndReload(e,t)}cancelRequests(){this._requestQueue.cancelAll()}async syncChanges(){}getDefaultGroup(){}isCollaborationPermissionsEnabled(){return!1}async clearAPStreamCache(){return this.client.clearAPStreamCache()}async setComparisonDocument(e,t){return this.client.setComparisonDocument(e,t)}async openComparisonDocument(e){return this._state=this._state.set("forceAnnotationsRender",!1),await this.client.closeDocument(),this._state=this._state.set("forceAnnotationsRender",!0),await this.client.openComparisonDocument(e)||this._state.documentResponse}async documentCompareAndOpen(e){return this.client.documentCompareAndOpen(e)}async persistOpenDocument(e){return this.client.persistOpenDocument(e)}async cleanupDocumentComparison(){return this.client.cleanupDocumentComparison()}async runPDFFormattingScripts(e,t){return this.client.runPDFFormattingScripts(e,t)}async runPDFFormattingScriptsFromWidgets(e,t,n){let a=[];if(this._isPDFJavaScriptEnabled){const{withAPStream:i,withoutAPStream:s}=e.reduce(((e,a)=>{if(a instanceof K.sb){const i=t?.get(a.formFieldName);if(i instanceof K.Vw)return e;n?.(a)?e.withAPStream.push(a.formFieldName):e.withoutAPStream.push(a.formFieldName)}return e}),{withAPStream:[],withoutAPStream:[]});let o=[];if(i.length&&!s.length)o=await this.runPDFFormattingScripts(i,!0);else if(!i.length&&s.length)o=await this.runPDFFormattingScripts(s,!1);else if(i.length&&s.length){const[e,t]=await Promise.all([this.runPDFFormattingScripts(i,!0),this.runPDFFormattingScripts(s,!1)]);o=e.concat(t)}a=(0,O.A5)(this._initialChanges,o)}return a}setFontSubstitutions(e){return this.client.setFontSubstitutions(e)}async contentEditorReload(){return(0,o.V1)(this.provider instanceof C,"Standalone can only use standalone annotation provider"),this.provider._state=this.provider._state.set("alreadyLoadedPages",(0,i.T5)()),this.reloadDocument()}getOCGs(){return this.client.getOCGs()}getOCGVisibilityState(){return this.client.getOCGVisibilityState()}setOCGVisibilityState(e){return this.client.setOCGVisibilityState(e)}updateButtonIcon(e,t,n){return this.client.updateButtonIcon((0,A.eq)(e),t,n)}async timestampData(e,t){const{url:n,username:a="",password:i=""}=t,s=l.o4.fromUint8Array(new Uint8Array(e));try{const e=await this.client.getTimestampRequest(s,{url:n,username:a,password:i}),t={method:e.method,headers:{"Content-Type":e.contentType||"application/timestamp-query"},body:l.o4.toUint8Array(e.requestData).buffer};(e.username||e.password)&&(t.headers.Authorization=`Basic ${btoa(`${e.username}:${e.password}`)}`);try{const n=await fetch(e.url,t),a=await n.arrayBuffer();return{response_code:n.status,body:l.o4.fromUint8Array(new Uint8Array(a)),token:e.token}}catch(t){return{response_code:400,body:"",token:e.token,error_message:t.message}}}catch(e){return{response_code:500,body:"",token:"",error_message:e.message}}}async waitUntilFullyLoaded(e){}}function ce(e){return{baseUrl:e.baseUrl,baseCoreUrl:e.baseCoreUrl,baseProcessorEngineUrl:e.baseProcessorEngineUrl,licenseKey:e.licenseKey,document:e.document,disableWebAssemblyStreaming:!!e.disableWebAssemblyStreaming,enableAutomaticLinkExtraction:!!e.enableAutomaticLinkExtraction,overrideMemoryLimit:"number"==typeof e.overrideMemoryLimit?e.overrideMemoryLimit:null,documentHandle:"number"==typeof e.documentHandle?e.documentHandle:"0",trustedCAsCallback:"function"==typeof e.trustedCAsCallback?e.trustedCAsCallback:null,customFonts:Array.isArray(e.customFonts)?e.customFonts.filter((e=>e instanceof z.A)):null,forceLegacySignaturesFeature:Boolean(e.forceLegacySignaturesFeature),appName:"string"==typeof e.appName?e.appName:null,productId:e.productId,processorEngine:e.processorEngine,dynamicFonts:e.dynamicFonts,fontSubstitutions:e.fontSubstitutions,inlineWorkers:e.inlineWorkers,allowLinearizedLoading:e.allowLinearizedLoading}}function le(e){const{licenseKey:t,instantJSON:n,XFDF:a,disableWebAssemblyStreaming:i,disableIndexedDBCaching:s,enableAutomaticLinkExtraction:r,overrideMemoryLimit:c,standaloneInstancesPoolSize:l,trustedCAsCallback:d,baseUrl:u,baseCoreUrl:m,baseProcessorEngineUrl:h,customFonts:p,isSharePoint:f,isSalesforce:g,dynamicFonts:y,inlineWorkers:b,formsConfiguration:A}=e;if((0,o.V1)("string"==typeof u,"`baseUrl` is mandatory and must be a valid URL, e.g. `https://example.com/"),(0,E.f4)(u),(0,o.V1)(!m||"string"==typeof m,"`baseCoreUrl` must be a valid URL if set, e.g. `https://example.com/"),m&&(0,E.Qo)(m),(0,o.V1)(!h||"string"==typeof h,"`baseProcessorEngineUrl` must be a valid URL if set, e.g. `https://example.com/"),h&&(0,E.hc)(h),(0,o.V1)(null==t||"string"==typeof t,"licenseKey must be a string value if provided. Please obtain yours from https://customers.pspdfkit.com."),"string"==typeof t&&(0,o.V1)(!t.startsWith("TRIAL-"),"You're using the npm key instead of the license key. This key is used to download the PSPDFKit for Web package via the node package manager.\n\nLeave out the license key to activate as a trial."),(0,o.V1)(void 0===a||"string"==typeof a,"XFDF must be a string"),n&&((0,o.yj)(n),(0,o.V1)(void 0===a,"Cannot import from both instantJSON and XFDF")),(0,o.V1)(void 0===i||"boolean"==typeof i,"disableWebAssemblyStreaming must be a boolean"),(0,o.V1)(void 0===r||"boolean"==typeof r,"enableAutomaticLinkExtraction must be a boolean"),(0,o.V1)(void 0===c||"number"==typeof c,"overrideMemoryLimit must be a number"),(0,o.V1)(void 0===l||"number"==typeof l&&l>=0,"standaloneInstancesPoolSize must be a non-negative number"),(0,o.V1)(void 0===d||"function"==typeof d,"trustedCAsCallback must be a function"),(0,o.V1)(void 0===p||Array.isArray(p)&&p.every((e=>e instanceof z.A)),"customFonts must be an array of PSPDFKit.Font instances"),(0,o.V1)(void 0===p||p.every((e=>e.callback)),"All PSPDFKit.Font instances specified on customFonts must have its callback property defined"),void 0!==s&&(0,o.t6)("disableIndexedDbCaching has been deprecated and it no longer has effect. It will be removed in a later version.\nBrowsers dropped IndexedDB serialization of Wasm modules in favor of regular HTTP caching."),(f||g)&&(0,o.t6)("isSharePoint and isSalesforce configuration properties are deprecated and will be removed in the next major release. Please use the new Configuratio