/*!
 * Nutrient Web SDK 1.14.0-0ff9156 (https://www.nutrient.io/sdk/web)
 *
 * Copyright (c) 2016-2026 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://www.nutrient.io/legal/acknowledgements/web-acknowledgements/
 */
"use strict";(globalThis.webpackChunkNutrientViewer=globalThis.webpackChunkNutrientViewer||[]).push([[42],{71530(e,t,n){n.d(t,{L:()=>o});var i=n(57191),a=n(89339),s=n(7871);function r(){return!0}class o{constructor(e){this.queue=(0,i.uY)(),this.priorityQueue=(0,i.uY)(),this.inFlightRequests=(0,i.T5)(),this.inflightRequestLimit=e,this.isDestroyed=!1}enqueue(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(this.isDestroyed)return{promise:new Promise(()=>{}),cancel:()=>{}};let n,a;const s=new Promise((e,t)=>{n=e,a=t}),r=t?this.priorityQueue:this.queue,o=(0,i.hZ)(r,e,{promise:s,resolve:n,reject:a});return t?this.priorityQueue=o:this.queue=o,t?this.next():setTimeout(()=>this.next(),35),{promise:s,cancel:()=>this._cancel(e)}}_cancel(e){this.queue.has(e)&&(this.queue=this.queue.delete(e)),this.priorityQueue.has(e)&&(this.priorityQueue=this.priorityQueue.delete(e)),this.inFlightRequests.has(e)&&(this.inFlightRequests=this.inFlightRequests.delete(e))}cancelAll(){this.queue=(0,i.uY)(),this.priorityQueue=(0,i.uY)(),this.inFlightRequests=(0,i.T5)()}cancel(e){const t=(t,n)=>e(n);this.queue=this.queue.filter(t),this.priorityQueue=this.priorityQueue.filter(t),this.inFlightRequests=this.inFlightRequests.filter(t)}_requestFinished(e,t){if(this.isDestroyed)return;const n=this.inFlightRequests.get(e);n&&(n.resolve(t),this.inFlightRequests=this.inFlightRequests.delete(e)),this.next()}_requestFailed(e,t){if(this.isDestroyed)return;const n=this.inFlightRequests.get(e);n&&(n.reject(t),this.inFlightRequests=this.inFlightRequests.delete(e)),this.next()}next(){if(!(this.isDestroyed||this.inFlightRequests.size>=this.inflightRequestLimit)){if(this.priorityQueue.size>=1){let e,t,n,i=1/0;this.priorityQueue.forEach((a,r)=>{const o=r?.loadingStrategy?.queueOrder;if(o&&o!==s.wp.LIFO)if(o!==s.wp.FIFO||t){if(o===s.wp.Bidirectional){const e=r.loadingStrategy?.loadPriority??0;e<i&&(i=e,n=[r,a])}}else t=[r,a];else e=[r,a]});const r=e||t||n;(0,a.V1)(r);const[o,c]=r;return this.priorityQueue=this.priorityQueue.delete(o),this.inFlightRequests=this.inFlightRequests.set(o,c),void o.request().then(e=>this._requestFinished(o,e)).catch(e=>this._requestFailed(o,e))}if(this.queue.size>=1){const e=this.queue.findEntry(r);(0,a.V1)(e);const[t,n]=e;this.queue=this.queue.delete(t),this.inFlightRequests=this.inFlightRequests.set(t,n),t.request().then(e=>this._requestFinished(t,e)).catch(e=>this._requestFailed(t,e))}}}destroy(){this.isDestroyed=!0}}},82725(e,t,n){n.d(t,{N:()=>A});var i=n(64136),a=n(80069),s=n(9505),r=n(77872),o=n(89339),c=n(57191),l=n(45252),d=n(75378),h=n(90037),u=n(52041);function m(e,t,n){(function(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")})(e,t),t.set(e,n)}function p(e,t){return e.get(f(e,t))}function g(e,t,n){return e.set(f(e,t),n),n}function f(e,t,n){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:n;throw new TypeError("Private element is not present on this object")}var y=new WeakMap,b=new WeakMap;class A{constructor(e,t){m(this,y,void 0),m(this,b,null),this.pdfLibrary=new i.T7.Qz(e),g(y,this,this.pdfLibrary.openDocument(t))}get rawDocument(){return p(y,this)}get linearizedDocument(){return(0,o.V1)(p(b,this),"Document is not linearized."),p(b,this)}async openLinearizedDocument(e){return g(b,this,await this.pdfLibrary.openLinarizedDocument(e)),g(y,this,p(b,this).document),p(b,this)}async normallyOpenLinearizedDocument(e,t){(0,o.V1)(p(b,this),"Document is not linearized.");const n=p(b,this);let i;return n.isUsingOPFS?(i=await e.client.openDocumentWithOPFS(t),await n.destroyPreservingOPFSAsync()):(i=await e.client.openCreateFilePathDocument(t),await n.destroyAsync()),g(b,this,null),i}destroy(){this.cancelRequests(),i.MX.clearPreflightCache(this.rawDocument.ctx.documentKey),i.MX.clearFailedFontsCache(this.rawDocument.ctx.documentKey),this.rawDocument.destroyOffscreenCanvasRenderer?.(),(0,a.removeLinearizedInstanceAsync)(this.rawDocument.ctx)}cancelRequests(){this.rawDocument.ctx.requestQueue.cancelRequests(()=>!0)}parseAndEstimateComplexity(e){return this.rawDocument.renderer.parseAndEstimateComplexity(e)}isLinearizedLoading(){return(0,a.isLinearizedLoading)(this.rawDocument.ctx)}renderTileDirectlyWithProgress(e,t,n,a,r){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:new i.ql;const c=this.rawDocument.renderer.renderTile(e,t,n,{renderForPrinting:!1,renderText:a,priority:i.MX.Priority.High});c.cancel&&o.addCancelFn(c.cancel);const l=c.promise.then(e=>{r({status:s.ProgressiveStatus.Done,buffer:e.buffer,format:e.format})});return(0,i.ZO)(o.wrapPromise(l),{abortedMessage:"render request aborted"})}renderTile(e,t,n,a,s,r,o,c){let d;r&&(d={annotations:r.annotations.filter(l.mH).map(u.eq).toJS().map(e=>({content:e})),formFieldValues:r.formFieldValues.map(u.cA).toJS(),formFields:r.formFields.map(u.T7).toJS(),signatures:r.signatures||[],attachments:r.attachments});const m=this.rawDocument.renderer.renderTile(e,t,n,{renderForPrinting:a,renderText:s,priority:t.width===n.width&&t.height===n.height?i.MX.Priority.High:i.MX.Priority.Normal,queueOrder:o,loadPriority:c},d).then(e=>(0,h.vB)({buffer:e.buffer.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:m.promise,cancel:m.cancel}}renderTileRaw(e,t,n,a,s,r,o){let c,d;r&&(c={annotations:r.annotations.filter(l.mH).map(u.eq).toJS().map(e=>({content:e})),formFieldValues:r.formFieldValues.map(u.cA).toJS(),formFields:r.formFields.map(u.T7).toJS(),signatures:r.signatures||[],attachments:r.attachments}),d="high"===o?i.MX.Priority.High:"normal"===o?i.MX.Priority.Normal:t.width===n.width&&t.height===n.height?i.MX.Priority.High:i.MX.Priority.Normal;const h=this.rawDocument.renderer.renderTile(e,t,n,{renderForPrinting:a,renderText:s,priority:d},c);return{promise:h.promise.then(e=>({buffer:e.buffer.buffer,format:e.format})),cancel:h.cancel}}renderTileWithProgress(e,t,n,o,c){const l=this.rawDocument.ctx,d=(0,a.isLinearizedLoading)(l);if(l.wasmCtx&&!d){const a=new i.ql,d=(0,s.renderTileProgressively)(l,e,{width:t.width,height:t.height},{left:n.left,top:n.top,width:n.width,height:n.height},o,c);a.addCancelFn(d.cancel);const h=d.promise.catch(i=>{const s=i instanceof Error?i.message:"",l=s.includes("Unserializable return value")||s.includes("startProgressiveRender failed");if(!(i instanceof r.S||l))throw i;return console.warn("[CorePDFDocument] Progressive render failed, falling back to direct render:",i),this.renderTileDirectlyWithProgress(e,t,n,c.renderText,o,a).promise});return(0,i.ZO)(a.wrapPromise(h),{abortedMessage:"render request aborted"})}return this.renderTileDirectlyWithProgress(e,t,n,c.renderText,o)}getTextLines(e){return this.rawDocument.text.getTextLines(e).then(t=>(0,d.K0)({textLines:t},e))}getContentTree(e){return this.rawDocument.text.getContentTree(e).then(t=>{let n=[],i=0,a=0;return n=t.reduce((t,n)=>{let{nodes:s}=n;const r=(0,d.l1)(s,e,t.length,i,a);return i+=r.reduce((e,t)=>{let{content:n}=t;return e+(0,d.Y_)(n).size},0),a+=r.reduce((e,t)=>{let{content:n}=t;return e+(0,d.M3)(n).size},0),t.concat(r)},[]),(0,c.B8)(n)})}compareText(e){const t={data:e.originalDocument.arrayBuffer,password:e.originalDocument.password,pageIndexes:e.originalDocument.pageIndexes},n={data:e.changedDocument.arrayBuffer,password:e.changedDocument.password,pageIndexes:e.changedDocument.pageIndexes},a={numberOfContextWords:e.comparisonOperation.options?.numberOfContextWords,wordLevel:e.comparisonOperation.options?.wordLevel};return i.MX.TextComparison.compareText(this.rawDocument.ctx,t,n,a).then(e=>e)}}},5386(e,t,n){n.d(t,{K:()=>p});var i=n(34724),a=n(57191),s=n(89339),r=n(99114);class o{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(0,i.A)(this,"cache",new Map),(0,i.A)(this,"hotQueue",new Set),(0,i.A)(this,"coldQueue",new Set),(0,i.A)(this,"pinnedTiles",new Set),(0,i.A)(this,"listeners",new Set),(0,i.A)(this,"currentBytes",0),(0,i.A)(this,"hits",0),(0,i.A)(this,"misses",0),(0,i.A)(this,"totalEvictedTiles",0),(0,i.A)(this,"totalEvictedBytes",0),(0,i.A)(this,"lastEvictedAt",null),(0,i.A)(this,"debugEvents",[]),(0,i.A)(this,"tileSizeCounts",new Map);const{maxMemoryMB:t,deviceType:n}=e,a="number"==typeof t?t:this.getAdaptiveCacheSize(n);this.maxBytes=1024*a*1024,this.registerDebugHandle()}getAdaptiveCacheSize(e){const t="mobile"===e||null==e&&/iPhone|iPad|iPod|Android|Mobile/i.test(navigator.userAgent),n="deviceMemory"in navigator&&"number"==typeof navigator.deviceMemory?navigator.deviceMemory:null;let i;return i=t?n&&n<=2?96:128:n&&n>=16?1024:n&&n>=8?768:512,i}generateKey(e,t,n,i){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,s=arguments.length>5?arguments[5]:void 0,r=!(arguments.length>6&&void 0!==arguments[6])||arguments[6];const o=Math.floor(n),c=Math.floor(i),l=Math.round(1e3*t)/1e3,d=Math.round(s),h=r?"":"/nt";return 0!==a?`${e}/mip${l}/x${o}y${c}/rot${a}/ts${d}${h}`:`${e}/mip${l}/x${o}y${c}/ts${d}${h}`}get(e,t,n,i){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,s=arguments.length>5?arguments[5]:void 0,r=!(arguments.length>6&&void 0!==arguments[6])||arguments[6];const o=this.generateKey(e,t,n,i,a,s,r),c=this.cache.get(o);return c?(this.hits++,c.lastAccessTime=Date.now(),c.accessCount++,this.coldQueue.has(o)&&c.accessCount>2&&(this.coldQueue.delete(o),this.hotQueue.add(o)),this.recordDebugEvent("hit",this.createDebugTilePayload(c)),c):(this.misses++,this.recordDebugEvent("miss",{key:o,pageIndex:e,mip:t,tileX:n,tileY:i,tileSize:s}),null)}has(e,t,n,i){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,s=arguments.length>5?arguments[5]:void 0,r=!(arguments.length>6&&void 0!==arguments[6])||arguments[6];const o=this.generateKey(e,t,n,i,a,s,r);return this.cache.has(o)}put(e,t,n,i,a){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:"bitmap",r=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,o=arguments.length>7?arguments[7]:void 0,c=arguments.length>8?arguments[8]:void 0,l=arguments.length>9?arguments[9]:void 0,d=!(arguments.length>10&&void 0!==arguments[10])||arguments[10];const h=this.generateKey(e,t,n,i,r,o,d),u=this.calculateTileMemorySize(c,l,s);this.ensureMemoryBudget(u);const m={key:h,pageIndex:e,mip:t,tileX:n,tileY:i,tileSize:o,imageData:a,format:s,width:c,height:l,byteSize:u,lastAccessTime:Date.now(),createdTime:Date.now(),accessCount:1,isPinned:!1},p=this.cache.get(h);p&&(this.currentBytes-=p.byteSize,this.hotQueue.delete(h),this.coldQueue.delete(h),this.updateTileSizeCount(p.tileSize,-1)),this.cache.set(h,m),this.hotQueue.add(h),this.currentBytes+=u,this.updateTileSizeCount(m.tileSize,1),this.emitStats(),this.recordDebugEvent("put",this.createDebugTilePayload(m))}pin(e,t,n,i){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,s=arguments.length>5?arguments[5]:void 0,r=!(arguments.length>6&&void 0!==arguments[6])||arguments[6];const o=this.generateKey(e,t,n,i,a,s,r),c=this.cache.get(o);c&&(this.pinnedTiles.add(o),c.isPinned=!0,this.emitStats(),this.recordDebugEvent("pin",this.createDebugTilePayload(c)))}clearPage(e){const t=[];this.cache.forEach((n,i)=>{n.pageIndex!==e||n.isPinned||t.push(i)}),t.forEach(e=>{this.removeTile(e)}),t.length>0&&(this.emitStats(),this.recordDebugEvent("clear_page",{pageIndex:e,details:{removed:t.length}}))}clear(){const e=[];this.cache.forEach((t,n)=>{t.isPinned||e.push(n)}),e.forEach(e=>{this.removeTile(e)}),e.length>0&&(this.emitStats(),this.recordDebugEvent("clear_all",{details:{removed:e.length}}))}getStats(){const e=this.hits+this.misses>0?this.hits/(this.hits+this.misses):0,t={};return this.tileSizeCounts.forEach((e,n)=>{t[n]=e}),{totalTiles:this.cache.size,totalBytes:this.currentBytes,hotTiles:this.hotQueue.size,coldTiles:this.coldQueue.size,pinnedTiles:this.pinnedTiles.size,hitRate:e,maxBytes:this.maxBytes,evictions:this.totalEvictedTiles,evictedBytes:this.totalEvictedBytes,lastEvictedAt:this.lastEvictedAt,tileSizeHistogram:t}}subscribe(e){return this.listeners.add(e),e(this.getStats()),()=>{this.listeners.delete(e)}}emitStats(){if(0===this.listeners.size)return;const e=this.getStats();this.listeners.forEach(t=>{t(e)})}ensureMemoryBudget(e){if(this.currentBytes+e<=this.maxBytes)return;const t=this.currentBytes+e-this.maxBytes;let n=0;const i=Date.now(),a=Array.from(this.hotQueue);for(const e of a){const t=this.cache.get(e);t&&!t.isPinned&&i-t.lastAccessTime>5e3&&(this.hotQueue.delete(e),this.coldQueue.add(e))}n+=this.evictOldestFromQueue(this.coldQueue,t-n),n<t&&(n+=this.evictOldestFromQueue(this.hotQueue,t-n))}evictOldestFromQueue(e,t){if(t<=0)return 0;const n=[];let i=0;for(const a of e){const e=this.cache.get(a);if(!e||e.isPinned)continue;if(i<t){n.push({key:a,tile:e}),i+=e.byteSize;continue}let s=0,r=n[0]?.tile.lastAccessTime??0;for(let e=1;e<n.length;e++){const t=n[e].tile.lastAccessTime;t>r&&(r=t,s=e)}e.lastAccessTime<r&&(i-=n[s].tile.byteSize,n[s]={key:a,tile:e},i+=e.byteSize)}let a=0;for(const{key:e,tile:i}of n){if(a>=t)break;a+=i.byteSize,this.removeTile(e,!0)}return a}removeTile(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=this.cache.get(e);return n?(n.imageData.close(),this.cache.delete(e),this.hotQueue.delete(e),this.coldQueue.delete(e),this.pinnedTiles.delete(e),this.currentBytes-=n.byteSize,this.currentBytes=Math.max(this.currentBytes,0),this.updateTileSizeCount(n.tileSize,-1),t&&(this.totalEvictedTiles++,this.totalEvictedBytes+=n.byteSize,this.lastEvictedAt=Date.now(),this.recordDebugEvent("evict",this.createDebugTilePayload(n))),n):null}calculateTileMemorySize(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"bitmap",i=0;if("bitmap"===n)i=e*t*4;else{const a=e*t;i="jpeg"===n?Math.ceil(4*a*.15):Math.ceil(4*a*.4)}return i}getDebugTrace(){return[...this.debugEvents]}clearDebugTrace(){this.debugEvents=[]}createDebugTilePayload(e){return{key:e.key,pageIndex:e.pageIndex,mip:e.mip,tileX:e.tileX,tileY:e.tileY,tileSize:e.tileSize,bytes:e.byteSize}}recordDebugEvent(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!r.a)return;const n={timestamp:Date.now(),type:e,...t};this.debugEvents.push(n),this.debugEvents.length>2e3&&this.debugEvents.shift()}registerDebugHandle(){if(!r.a)return;if("undefined"==typeof window)return;const e=window,t={id:`tile-cache-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,getStats:()=>this.getStats(),getTrace:()=>this.getDebugTrace(),clearTrace:()=>this.clearDebugTrace()};e.__PSPDFKIT_TILE_CACHE_DEBUG__||(e.__PSPDFKIT_TILE_CACHE_DEBUG__=[]),e.__PSPDFKIT_TILE_CACHE_DEBUG__?.push(t)}updateTileSizeCount(e,t){if(!Number.isFinite(e))return;const n=(this.tileSizeCounts.get(e)||0)+t;n<=0?this.tileSizeCounts.delete(e):this.tileSizeCounts.set(e,n)}}var c=n(4689),l=n(97947),d=n(45252),h=n(63620),u=n(76037),m=n(98046);class p{constructor(){(0,i.A)(this,"tileCache",new o({deviceType:c.LZ?"mobile":"desktop"})),(0,i.A)(this,"attachmentsCache",(0,a.T5)()),(0,i.A)(this,"cachedAPStreams",(0,a.T5)()),(0,i.A)(this,"pageAPStreamsPromises",(0,a.T5)()),(0,i.A)(this,"annotationAPStreamPromises",(0,a.T5)()),(0,i.A)(this,"_cachedRenderedAnnotations",(0,a.uY)()),(0,i.A)(this,"_objectURLs",{}),(0,i.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 i=e.release;e.release=()=>{this._objectURLs[n]--,this._objectURLs[n]<=0&&(i?.(),this._cachedRenderedAnnotations.has(t)&&(this._cachedRenderedAnnotations=this._cachedRenderedAnnotations.delete(t)),delete this._objectURLs[n])}}}),(0,i.A)(this,"_cacheableRenderedAnnotationSetExpire",e=>{const t=this._cachedRenderedAnnotations.get(e);(0,s.V1)(t),t.timeout&&clearTimeout(t.timeout);const n=setTimeout(()=>{this._cachedRenderedAnnotations.has(e)&&(this._cachedRenderedAnnotations=this._cachedRenderedAnnotations.delete(e))},3e4);this._cachedRenderedAnnotations=this._cachedRenderedAnnotations.update(e,e=>({...e,timeout:n}))}),(0,i.A)(this,"_addCachedRenderedAnnotation",(e,t)=>{let{width:n,height:i,noZoom:a,APStreamPromise:s}=t;if(this._cachedRenderedAnnotations.size>1e3){const e=this._cachedRenderedAnnotations.keySeq().first();e&&(this._cachedRenderedAnnotations=this._cachedRenderedAnnotations.delete(e))}this._cachedRenderedAnnotations=this._cachedRenderedAnnotations.set(e,{width:n,height:i,noZoom:a,APStreamPromise:s}),this._cacheableRenderedAnnotationSetExpire(e)})}getAnnotationFormFieldAndValue(e){const t=this.provider;(0,s.V1)(t instanceof t.constructor,"Backend can only use backend annotation provider");const n=e instanceof l.sb?t._readStateCallbacks?.getFormFieldByName(e.formFieldName):null;return{formField:n,formFieldValue:!n||n instanceof l.Vw?null:new l.E2({name:n.name,value:void 0!==n.formattedValue?n.formattedValue:"string"==typeof n.value?n.value:n.values})}}getAnnotationFormFieldRevision(e){const t=this.provider;if((0,s.V1)(t instanceof t.constructor,"Backend can only use backend annotation provider"),!(e instanceof l.sb))return null;const n=t._readStateCallbacks?.getFormFieldRevision?.(e.formFieldName);return"number"==typeof n?n:0}isWidgetRenderFreshAtCompletion(e,t,n){if(!(e instanceof l.sb))return!0;const i=this.provider;(0,s.V1)(i instanceof i.constructor,"Backend can only use backend annotation provider");const a=i._readStateCallbacks?.getFormFieldByName(e.formFieldName);if(!(0,m.Ny)(t,a))return!1;if(t&&null!=n){const e=i._readStateCallbacks?.getFormFieldRevision?.(t.name);if("number"==typeof e&&e!==n)return!1}return!0}isCachedAPStreamEntryValid(e,t){return null==e.formFieldRevision||e.formFieldRevision===this.getAnnotationFormFieldRevision(t)}getValidCachedAPStream(e){const t=this.cachedAPStreams.get(e.pageIndex),n=t?.get(e.id);return n?this.isCachedAPStreamEntryValid(n,e)?n.APStream:(this.releaseAPStream(n.APStream),this.cachedAPStreams=this.cachedAPStreams.updateIn([e.pageIndex],(0,u.C$)(t=>t.delete(e.id))),null):null}resolvePendingAnnotationAPStreams(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;for(const n of e){const e=this.annotationAPStreamPromises.get(n);e&&(this.annotationAPStreamPromises=this.annotationAPStreamPromises.delete(n),e(t))}}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,i,a,r){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,d.lG)(e,c))return this.renderAnnotation(e,l,t,n,i,a,r);const h=this.getAnnotationAvailableVariants(e);let u=!1,m=()=>{u=!0};return{promise:new Promise(async(s,o)=>{try{const o=this.pageAPStreamsPromises.get(e.pageIndex);if(!o){const t=this.annotationAPStreamPromises.get(e.id);this.annotationAPStreamPromises=this.annotationAPStreamPromises.set(e.id,s),t&&t(null);const n=new Promise(t=>{this.annotationAPStreamPromises=this.annotationAPStreamPromises.set(e.id,t)});return void s(await n)}await o;const c=this.getValidCachedAPStream(e);if(c)return void s(this.getAPStream(c,a));const{formField:l,formFieldValue:d}=this.getAnnotationFormFieldAndValue(e),p=this.getAnnotationFormFieldRevision(e),{promise:g,cancel:f}=this.renderAPStream(e,d,t,n,i,h,a,r);if(u)s(null);else if(m=f,h.length>1){const t=await Promise.all(g.map(e=>e.promise));if(!this.isWidgetRenderFreshAtCompletion(e,l,p))return t.forEach(e=>{e?.release()}),void s(null);s(t[h.indexOf(a||"normal")]),t.some(Boolean)&&this.cacheAPStream(h.reduce((e,n,i)=>t[i]?{...e,[n]:t[i]}:e,{}),e)}else{const t=await g,n=t?this.getAPStream(t,a):null;if(!this.isWidgetRenderFreshAtCompletion(e,l,p))return n?.release(),void s(null);s(n),n&&this.cacheAPStream(t,e)}}catch(e){o(e)}}),cancel:m}}cacheAPStream(e,t){let n=this.cachedAPStreams.get(t.pageIndex),i=null;if(t instanceof l.sb){const{formField:e}=this.getAnnotationFormFieldAndValue(t);(0,d.lG)(t,e)&&(i=this.getAnnotationFormFieldRevision(t))}n||(this.cachedAPStreams=this.cachedAPStreams.set(t.pageIndex,(0,a.T5)()),n=this.cachedAPStreams.get(t.pageIndex)),this.cachedAPStreams=this.cachedAPStreams.setIn([t.pageIndex,t.id],{APStream:e,formFieldRevision:i})}clearAllPageAPStreams(e){const t=this.cachedAPStreams.get(e);t&&(t.forEach(e=>{this.releaseAPStream(e.APStream)}),this.cachedAPStreams=this.cachedAPStreams.delete(e)),this.pageAPStreamsPromises=this.pageAPStreamsPromises.delete(e)}clearPageAPStreamsPromise(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.APStream)}),this.cachedAPStreams=this.cachedAPStreams.updateIn([e],(0,u.C$)(e=>e.filter((e,n)=>!t.has(n)))))}getAPStream(e,t){return e instanceof h.A?e:e?.[t||"normal"]||null}renderAPStream(e,t,n,i,a,s,r,o){if(s.length>1){const r=s.map(s=>this.renderAnnotation(e,t,n,i,a,"normal"!==s?s:void 0,o));return{promise:r,cancel:()=>{r.forEach(e=>{e.cancel()})}}}return this.renderAnnotation(e,t,n,i,a,r,o)}releaseAPStream(e){e instanceof h.A?e.release():Object.values(e).forEach(e=>{e.release()})}isVisuallyIdenticalAnnotationCached(e){let{annotation:t,providedVisualAnnotationIndex:n,width:i,height:a}=e;if(!(0,d.cu)(t))return!1;const r=n||(0,d.sS)(t);if(!this._cachedRenderedAnnotations.has(r))return!1;const o=this._cachedRenderedAnnotations.get(r);return(0,s.V1)(o),(0,d.Ab)({noZoom:o.noZoom&&t.noZoom,cachedRenderedAnnotationWidth:o.width,cachedRenderedAnnotationHeight:o.height,testAnnotationWidth:i,testAnnotationHeight:a})}cachedRenderedAnnotationDiscardablePromise(e,t){let{promise:n,resolve:i,reject:a}=t;const r=this._cachedRenderedAnnotations.get(e);return(0,s.V1)(r),r.APStreamPromise.then(t=>{let n;return t&&(n=new h.A(t.element.cloneNode(!0),t.release),this._makeEnqueuedRelease(n,e),this._cacheableRenderedAnnotationSetExpire(e)),i(n),n}).catch(a),{promise:n,cancel:()=>{}}}clearRenderedAnnotationsCache(){this._cachedRenderedAnnotations.forEach(e=>{let{APStreamPromise:t,timeout:n}=e;t.then(e=>{e?.release()}),n&&clearTimeout(n)}),this._cachedRenderedAnnotations=(0,a.T5)(),this._objectURLs={}}}},74129(e,t,n){n.d(t,{mG:()=>le,Ay:()=>ue,DO:()=>me,mn:()=>pe});var i=n(34724),a=n(95420),s=n(64136),r=n(71530),o=n(89339),c=n(57191),l=n(13803),d=n(84008),h=n(53379),u=n(99819),m=n(600),p=n(68592),g=n(33704),f=n(67880),y=n(5366),b=n(77112),A=n(97947),S=n(32591),v=n(20053),F=n(4357),w=n(25094),P=n(64893),_=n(45252),C=n(2090),k=n(90037),D=n(92182),T=n(98046),R=n(41417),I=n(64662),E=n(19896),x=n(62389),V=n(16933);class O{constructor(e,t){this.identifier=e,this.callback=t}request(){return this.callback()}}var B=n(22019),L=n(29655),U=n(52041),z=n(5386),N=n(25668),q=n(23485),j=n(1024),M=n(23529),$=n(51670);class W extends((0,c.mS)({alreadyLoadedPages:(0,c.T5)(),isLoaded:!1,isDestroyed:!1})){}const K={skippedPdfObjectIds:[],skippedPdfBookmarkIds:[],annotations:[],bookmarks:[],formFieldValues:[],formFields:[],attachments:{}};class H{constructor(e,t){(0,i.A)(this,"_state",new W),(0,i.A)(this,"_formFieldsLoadedPromise",null),(0,i.A)(this,"_objectCreationPromises",(0,c.T5)()),(0,i.A)(this,"_loadBookmarksPromise",null),(0,i.A)(this,"_commentsLoadedPromise",null),(0,i.A)(this,"canCreateBackendOrphanWidgets",!1),(0,i.A)(this,"updateTabOrderTimeout",null),(0,i.A)(this,"pagesTabOrderToUpdate",(0,c.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 i=null;const a=e[n];if("imageAttachmentId"in a&&a.imageAttachmentId){const e=t?t[a.imageAttachmentId]:null;if(e)try{i=(0,j.lj)(atob(e.binary),e.contentType),(0,o.V1)(this._annotationCallbacks),this._annotationCallbacks.createAttachment(a.imageAttachmentId,i)}catch(e){(0,o.pq)(`Skipped attachment with id ${a.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=>Q(e,n)).toArray())}updateComment(e,t,n){return this._core.applyComments(t.map(e=>Q(e,n)).toArray())}deleteComment(e,t,n){return this._core.applyComments(t.map(e=>Q(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,c.B8)(e.map(e=>{let t;return t=e.pdfObjectId?e.id||e.pdfObjectId?.toString():(0,_.K1)(),(0,U.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,c.NZ)(),this._isDestroyed())return;const t=await Promise.all(e.map(e=>this._core.getTabOrder(e)));this._isDestroyed()||((0,o.V1)(this._annotationCallbacks),(0,N.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)),i=await this._core.createAnnotation((0,U.eq)(e),n?n.data:null),a="multiline"in e&&!!e.multiline&&"imageAttachmentId"in e&&!!e.imageAttachmentId;"number"!=typeof i||"number"!=typeof e.pdfObjectId&&!a||e.pdfObjectId===i||this._isDestroyed()||((0,o.V1)(this._annotationCallbacks),this._annotationCallbacks.updateAnnotations((0,c.B8)([e.set("pdfObjectId",i)]))),await this.updateTabOrder(e.pageIndex)}async updateAnnotation(e){this._verifyLoaded(),await this._core.updateAnnotation((0,U.eq)(e)),await this.updateTabOrder(e.pageIndex)}deleteAnnotation(e){return this._verifyLoaded(),this._core.deleteAnnotation((0,U.eq)(e))}createBookmark(e){return this._verifyLoaded(),this._core.createBookmark((0,q.U)(e))}updateBookmark(e){return this._verifyLoaded(),this._core.updateBookmark((0,q.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,U.T7)(e),t.map(e=>(0,U.eq)(e)).toArray()).then(async e=>{(0,N.vA)(()=>{e.forEach((e,n)=>{const i=t.get(n);(0,o.V1)(i),(0,o.V1)(this._annotationCallbacks),"number"!=typeof e||"number"!=typeof i.pdfObjectId||i.pdfObjectId===e||this._isDestroyed()||this._annotationCallbacks.updateAnnotations((0,c.B8)([i.set("pdfObjectId",e)]))})})})}updateFormField(e){this._verifyLoaded(),(0,o.V1)(this._readStateCallbacks);const t=this._readStateCallbacks.getFormFieldWidgets(e);return this._core.updateFormField((0,U.T7)(e),t.map(e=>(0,U.eq)(e)).toArray())}deleteFormField(e){return this._verifyLoaded(),this._core.deleteFormField((0,U.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,c.B8)(),n=(0,c.B8)().withMutations(n=>{e.forEach(e=>{const{formField:i,widgets:a,value:s}=e;try{let e;e=i.pdfObjectId?i.pdfObjectId.toString():(0,_.K1)();const r=(0,U.mh)(e,i);(0,o.V1)(this._readStateCallbacks),this._readStateCallbacks.isFormFieldInState(r.name)||n.push(r.set("value",s)),a.forEach(e=>{if(e.formFieldName!==r.name)return;let n;n=e.pdfObjectId?e.id||e.pdfObjectId.toString():(0,_.K1)(),(0,o.V1)(this._readStateCallbacks),t=t.push((0,U.h8)(n,e))})}catch(e){(0,o.pq)(`Skipped creating form field #${i.pdfObjectId} from payload because an error occurred while deserializing.`),(0,o.pq)(e)}})});const i={},a={};t.forEach(e=>{a[e.id]||(a[e.id]=[]),a[e.id].push(e.pdfObjectId)}),t=t.map(e=>{if(a[e.id].filter(t=>t!==e.pdfObjectId).length>0&&e.pdfObjectId?.toString()!==e.id||this._readStateCallbacks?.isAnnotationInState(e.id)){const t=(0,_.K1)();return i[e.formFieldName]?i[e.formFieldName].push({[e.id]:t}):i[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(i).forEach(e=>{const i=n.find(t=>t.name===e);(0,o.V1)(i);const a=t.filter(t=>t.formFieldName===e).toArray().map(e=>(0,U.eq)(e));this._core.updateFormField((0,U.T7)(i),a)}),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,c.T5)(),$.n)),this._formFieldsLoadedPromise=Promise.resolve()}createFormFieldValue(e){return this._verifyLoaded(),this.setFormFieldValue(e)}setFormFieldValue(e){return this._verifyLoaded(),this._core.setFormFieldValue((0,U.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 i=[],a=[],s=t.map(e=>{let{rollover:t,down:n,...s}=e;return t&&"number"==typeof s.pdfObjectId&&i.push(s.pdfObjectId),n&&"number"==typeof s.pdfObjectId&&a.push(s.pdfObjectId),s}).filter(e=>"number"==typeof e.pageIndex);this._formFieldCallbacks&&await this.loadFormFields();const r=(0,c.B8)().withMutations(e=>{s.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,_.K1)():t.id||t.pdfObjectId.toString(),(e.some(e=>e.id===n)||this._readStateCallbacks?.isAnnotationInState(n))&&(n=(0,_.K1)(),t.id=n,this._core.updateAnnotation(t));const i=(0,U.h8)(n,t);e.push(i)}catch(e){(0,o.pq)(`Skipped creating annotation #${t.pdfObjectId} from payload because an error occurred while deserializing.`),(0,o.pq)(e)}})});(0,N.vA)(()=>{(0,o.V1)(this._annotationCallbacks),r.size>0&&this._annotationCallbacks.createAnnotations(r,(0,c.T5)(),$.n),this._annotationCallbacks.setPageTabOrder(e,n),i.length>0&&this._annotationCallbacks.addAnnotationVariants("rollover",i),a.length>0&&this._annotationCallbacks.addAnnotationVariants("down",a)}),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,c.B8)().withMutations(t=>{e.forEach(e=>{try{t.push((0,U.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,c.B8)().withMutations(t=>{for(const n of e){let e;e=n.id?n.id:n.pdfBookmarkId?n.pdfBookmarkId:(0,M.z)();try{t.push((0,q.r)(e,n))}catch(t){(0,o.pq)(`Skipped creating bookmark #${e} from payload because an error occurred while deserializing.`),(0,o.pq)(t)}}});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 Q(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,U.wG)(e,n.pdfObjectId?.toString()===n.id?parseInt(e.rootId):e.rootId)}function J(e){return"string"==typeof e?.serialNumber&&e.body instanceof ArrayBuffer}function G(e){return e?.pkcs7 instanceof ArrayBuffer&&(!("ocspResponses"in e)||Array.isArray(e.ocspResponses)&&e.ocspResponses.every(e=>J(e)))}function X(e){if(!e)return!1;const{signedData:t,timestampResponse:n,ocspResponses:i}=e;if(!(t instanceof ArrayBuffer))return!1;if(n&&!(n instanceof ArrayBuffer))return!1;if(i){if(!Array.isArray(i))return!1;if(!i.every(e=>J(e)))return!1}return!0}var Y=n(37052),Z=n(70081);class ee{constructor(e){this.backend=e}async signDocumentAndReload(e,t){const n=e?.signingData,i=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 `NutrientViewer.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===Y.D.CMS||Array.isArray(i)&&i.length>0&&i.every(e=>Boolean(e instanceof ArrayBuffer&&e.byteLength>0||"string"==typeof e&&e.length>0)),"For signatures of type `NutrientViewer.SignatureType.CAdES` an `Array` of certificates must be provided in `signaturePreparationData.signingData.certificates`.");const a={signatureType:n?.signatureType||(Array.isArray(i)&&i.length>0?Y.D.CAdES:Y.D.CMS),...i&&{certificates:i.map(e=>e instanceof ArrayBuffer?l.o4.fromUint8Array(new Uint8Array(e)):l.o4.encode(e))},...e?.placeholderSize?{estimatedSize:e.placeholderSize}:null};try{const{hash:i,signatureFormFieldName:s,file:r,fileContents:c,dataToBeSigned:d}=await this.backend.client.prepareSign((0,U.Y6)(a),e?.signatureMetadata?(0,U.sZ)(e.signatureMetadata):null,Boolean(e?.flatten),e?.formFieldName,(0,U.qN)(e?.position),await(0,U.z8)(e?.appearance),this.backend._state.certificateCheckTime),h=function(e){const t=e.trim(),n=t.length/2,i=new Uint8Array(n);for(let e=0;e<n;e++)i[e]=parseInt(t.substr(2*e,2),16);return i}(d);let u,m,p;if(t){try{u=await t({hash:i,fileContents:c,dataToBeSigned:h})}catch(e){throw new o.uE(`\`twoStepSignatureCallback\` threw an error: ${e}`)}if(!(u instanceof ArrayBuffer||G(u)||X(u)))throw new o.uE(`The resolved value from \`twoStepSignatureCallback\` should be a an \`ArrayBuffer\`, \`SignatureCallbackResponsePkcs7\`, or \`SignatureCallbackResponseRaw\`, but is of type \`${typeof u}\` instead.`);p=u}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"]);m=await globalThis.crypto.subtle.sign(e,t,h),p=m}}let g="",f=a.certificates||[];if(p instanceof ArrayBuffer)g=l.o4.fromUint8Array(new Uint8Array(p))||"";else if(G(p)){const e=p;g=l.o4.fromUint8Array(new Uint8Array(e.pkcs7))||""}else if(X(p)){const e=p;g=l.o4.fromUint8Array(new Uint8Array(e.signedData))||"",f=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(f):(G(p)||X(p))&&((0,o.V1)(null==p.ocspResponses||Array.isArray(p.ocspResponses)&&p.ocspResponses.every(e=>J(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(f)))),X(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(g).buffer;y=await this.backend.timestampData(e,n.timestamp)}const A=await this.backend.client.sign(r,s,i,U.xz[a.signatureType],g,f,G(p)?"pkcs7":X(p)?"raw":n?.signatureContainer?n.signatureContainer:null,y,b);return n?.ltv&&A.signature.certificateChainValidationStatus===Z.k.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(this.backend._state.certificateCheckTime),e}}}var te=n(62700),ne=n(87737),ie=n(89353);class ae extends ee{constructor(e){super(e)}async signDocumentAndReload(e,t){t=(0,v.k)(t),(0,o.V1)(t,"`twoStepSignatureCallbackOrStandaloneSigningServiceData` must be a `NutrientViewer.StandaloneSigningServiceData` object when performing signing via a backend service.");const{jwt:n,signingToken:i}=t,a=this.resolveApiBasePath(t),s=this.resolveServerUrl(t),r=await this.getCertificates(s,n,`${a}get_certificates`,i),c=this.signatureCallbackFactory(s,n,r,e,t,`${a}sign_hash`);return await super.signDocumentAndReload({...e,signingData:{...e?.signingData,signatureType:e?.signingData?.signatureType||Y.D.CAdES,certificates:r}},c)}async getCertificates(e,t,n,i){let a;const s=`${e}${n}`;try{a=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${t}`,Accept:"application/json","Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({signingToken:i})})}catch(e){throw new o.uE(`The signing service failed to retrieve certificates: Failed to fetch from ${s}`)}if(!a.ok)throw new o.uE(`The signing service failed to retrieve certificates: ${await a.json()}`);const r=(await a.json())?.data||{};return r.certificates.concat(r.ca_certificates).map(e=>l.o4.fromBase64(e))}resolveApiBasePath(e){return(0,te.i)(e.jwt).api_base_path||"/api/"}resolveServerUrl(e){const t=e.serverUrl||(0,te.i)(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,i,a,s){return async r=>{let c,{hash:d,dataToBeSigned:h}=r;try{c=await fetch(`${e}${s}`,{method:"POST",headers:{Authorization:`Bearer ${t}`,Accept:"application/json","Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({dataToBeSigned:l.o4.fromUint8Array(h),hash:d,signatureType:i?.signingData?.signatureType||Y.D.CAdES,signingToken:a.signingToken,cadesLevel:i?.signingData?.padesLevel||ne.s.b_lt})})}catch(t){throw new o.uE(`The signing service failed to retrieve certificates: Failed to fetch from ${e}${s}`)}if(!c.ok)throw new o.uE(`The signing service failed to sign: ${await c.text()}`);const u=(await c.json())?.data||{};if(i?.signingData?.signatureContainer===ie.Y.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}}}}var se=n(53276),re=n(9855);class oe extends(c.mS({baseUrl:null,baseCoreUrl:null,baseProcessorEngineUrl:null,licenseKey:null,document:null,backendPermissions:new se.A,documentResponse:null,disableWebAssemblyStreaming:!1,enableAutomaticLinkExtraction:!1,overrideMemoryLimit:null,features:(0,c.B8)(),signatureFeatureAvailability:re.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:!0,enableCoreUnifiedComments:!1,enableCorePreservePDFAccessibility:!1,httpHeaders:null,canvasRendering:!1,certificateCheckTime:"signing_time",storage:{mode:"opfs",minFileSize:52428800,isAuto:!0}})){}const ce=n(95420).Fe,le=new a.iy(ce),de=52428800;function he(e){return e&&"object"==typeof e&&"isAuto"in e||e&&"object"==typeof e&&"memory"===e.mode?e:"memory"===e?{mode:"memory"}:"auto"===e?{mode:"opfs",minFileSize:de,isAuto:!0}:"opfs"===e?{mode:"opfs",minFileSize:null,isAuto:!1}:e&&"object"==typeof e&&"opfs"===e.mode?{mode:"opfs",minFileSize:"number"==typeof e.minFileSize?e.minFileSize:null,isAuto:!1}:(null!=e&&(0,o.R8)(`tempStorage: unrecognized value ${JSON.stringify(e)}. Valid values are "memory", "auto", "opfs", or { mode: "opfs", minFileSize?: number }. Defaulting to "auto".`),{mode:"opfs",minFileSize:de,isAuto:!0})}class ue extends z.K{constructor(e){super(),(0,i.A)(this,"type","STANDALONE"),(0,i.A)(this,"standaloneDocumentSigner",new ee(this)),(0,i.A)(this,"signingServiceDocumentSigner",new ae(this)),(0,i.A)(this,"_XFDF",null),pe(e);const{baseUrl:t,baseCoreUrl:n,baseProcessorEngineUrl:a,instantJSON:s,XFDF:o,enableAutomaticLinkExtraction:c,overrideMemoryLimit:l,trustedCAsCallback:d,electronAppName:u,appName:m,isSharePoint:f,isSalesforce:y,productId:b,processorEngine:A,dynamicFonts:S,inlineWorkers:v,formsConfiguration:F,allowLinearizedLoading:w,unifiedCommentsSupport:P,preservePDFAccessibility:_,canvasRendering:C}=e;"string"==typeof o&&(this._XFDF={source:o,keepCurrentAnnotations:!0===e.XFDFKeepCurrentAnnotations,ignorePageRotation:!0===e.XFDFIgnorePageRotation,richTextEnabled:!0===e.XFDFRichTextEnabled}),s&&s.annotations&&(s.annotations=s.annotations.map(e=>(e.id=e.id?.toString(),e))),this._instantJSON=s,this._formsConfiguration=F,"function"==typeof d&&(this._trustedCAsCallback=d);const{disableWebAssemblyStreaming:k,customFonts:D,fontSubstitutions:T}=e,{standaloneInstancesPoolSize:R}=e;void 0!==R&&(le.size=R);const I=!!e.electronicSignatures&&Boolean(e.electronicSignatures.forceLegacySignaturesFeature);let E=b||null;!f&&!y||E||(E=f?g.v.SharePoint:g.v.Salesforce),this._state=new oe(me({baseUrl:t,baseCoreUrl:n,baseProcessorEngineUrl:a,licenseKey:e.licenseKey,document:e.document,disableWebAssemblyStreaming:k,enableAutomaticLinkExtraction:c,overrideMemoryLimit:l,documentHandle:"0",customFonts:D,fontSubstitutions:T,forceLegacySignaturesFeature:I,appName:m||u,productId:E,processorEngine:A||p.j.fasterProcessing,dynamicFonts:S,inlineWorkers:v,allowLinearizedLoading:w,enableCoreUnifiedComments:P,enableCorePreservePDFAccessibility:_,httpHeaders:e.httpHeaders,canvasRendering:C??!1,certificateCheckTime:e.certificateCheckTime,tempStorage:he(e.tempStorage)})),this._requestQueue=new r.L(h.z3);const{object:x,checkIn:V}=le.checkOut();this.client=x,this.checkIn=V;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 H(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",clientInfo:null}}async afterDocumentLoaded(e){}destroyResources(){this.corePDFDocument?.destroy(),this.provider?.destroy(),this._requestQueue?.destroy()}destroy(){this.destroyResources(),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.corePDFDocument.getTextLines(e)}getContentTreeForPageIndex(e){return this.corePDFDocument.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 w.bR({x:t[0],y:t[1]}):e}configureSnapper(e){return this.client.configureSnapper(e)}renderAnnotation(e,t,n,i,a,s,r){if(0===Math.floor(i)||0===Math.floor(a))return{promise:Promise.resolve(void 0),cancel:()=>{}};const o=(0,E.yl)();let c;if((0,_.cu)(e)){if(c=(0,_.sS)(e),this.isVisuallyIdenticalAnnotationCached({annotation:e,providedVisualAnnotationIndex:c,width:i,height:a}))return this.cachedRenderedAnnotationDiscardablePromise(c,o);this._addCachedRenderedAnnotation(c,{width:i,height:a,noZoom:e.noZoom,APStreamPromise:o.promise})}const l=e.id,d=new O(l,()=>this.client.renderAnnotation((0,U.eq)(e),n,i,a,(0,D.LG)(),s,r).then(e=>e?"string"==typeof e?(0,k.$3)(e):(0,k.vB)({buffer:e,width:i,height:a}):Promise.resolve(void 0)).then(t=>{(0,_.cu)(e)&&this._makeEnqueuedRelease(t??null,c);const n=t??void 0;return o.resolve(n),t??void 0}));return this._requestQueue.enqueue(d,!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,y.c)(t)};return this.corePDFDocument.compareText(n).promise}async renderPageAnnotations(e,t,n){const i=this.provider,a=[],s=[],r=new globalThis.Map,c=t.some(e=>e instanceof A.sb);c&&await i._setReadStateCallbacksPromise;const l=t.filter(e=>{const t=c?i._readStateCallbacks.getAnnotationWithFormField(e.id):null,n=t?.formField,o=(0,_.lG)(e,n);if(o&&n){a.find(e=>e.name===n.name)||(a.push((0,U.cA)((0,T.Af)(n))),s.push(n),r.set(n.name,i._readStateCallbacks?.getFormFieldRevision?.(n.name)??0))}return o});function d(){const e=i._readStateCallbacks?.getFormFieldByName;return s.map(t=>e?.(t.name)).filter(Boolean)}const h=new Promise((t,a)=>{const c=l.filter(e=>0!==Math.floor(e.boundingBox.width*n)&&0!==Math.floor(e.boundingBox.height*n));this.client.renderPageAnnotations(e,c.map(e=>e.pdfObjectId).toArray(),c.map(e=>e.boundingBox.width*n).toArray(),c.map(e=>e.boundingBox.height*n).toArray(),(0,D.LG)()).then(e=>{const a=d(),l=e.map((e,t)=>{const l=c.get(t);return(0,o.V1)(l),(0,T.rD)({annotation:l,formFieldsAtRenderStart:s,formFieldsAtCompletion:a,formFieldRevisionsAtRenderStart:r,getFormFieldRevision:i._readStateCallbacks?.getFormFieldRevision})&&l&&e?"string"==typeof e?(0,k.$3)(e):(0,k.vB)({buffer:e,width:l.boundingBox.width*n,height:l.boundingBox.height*n}):Promise.resolve(null)});Promise.all(l).then(e=>{const a=d();e.forEach((e,t)=>{const o=c.get(t);if(o){const{formFieldValue:t}=this.getAnnotationFormFieldAndValue(o),c=this.getAnnotationAvailableVariants(o),l=this.annotationAPStreamPromises.get(o.id),h=(0,T.rD)({annotation:o,formFieldsAtRenderStart:s,formFieldsAtCompletion:a,formFieldRevisionsAtRenderStart:r,getFormFieldRevision:i._readStateCallbacks?.getFormFieldRevision});if(l&&(this.annotationAPStreamPromises=this.annotationAPStreamPromises.delete(o.id),l(h?e:null)),!h&&e&&e.release(),!h)return;if(c.length>1){const a={normal:e};e&&h&&this.cacheAPStream(a,o);const{promise:l}=this.renderAPStream(o,t,null,o.boundingBox.width*n,o.boundingBox.height*n,c);Promise.all(l.map(e=>e.promise)).then(e=>{const t=d();(0,T.rD)({annotation:o,formFieldsAtRenderStart:s,formFieldsAtCompletion:t,formFieldRevisionsAtRenderStart:r,getFormFieldRevision:i._readStateCallbacks?.getFormFieldRevision})?e.some(Boolean)&&c.forEach((t,n)=>{"normal"!==t&&e[n]&&(a[t]=e[n])}):e.forEach(e=>{e?.release()})})}else e&&h&&this.cacheAPStream(e,o)}}),t()})}).catch(e=>{this.resolvePendingAnnotationAPStreams(c.map(e=>e.id).toArray()),a(e)})});return this.pageAPStreamsPromises=this.pageAPStreamsPromises.set(e,h),h}renderDetachedAnnotation(e,t,n,i){if(e.id)throw new o.uE(`Detached annotations should not have an \`id\`: ${e.id}`);const a=(0,E.yl)();let s;if((0,_.cu)(e)){if(s=(0,_.sS)(e),this.isVisuallyIdenticalAnnotationCached({annotation:e,providedVisualAnnotationIndex:s,width:n,height:i}))return this.cachedRenderedAnnotationDiscardablePromise(s,a);this._addCachedRenderedAnnotation(s,{width:n,height:i,noZoom:e.noZoom,APStreamPromise:a.promise})}const r=(0,d.Z0)(),c=new O(r,()=>this.client.renderDetachedAnnotation((0,U.eq)(e),t,n,i,(0,D.LG)()).then(e=>e?(0,k.vB)({buffer:e,width:n,height:i}):Promise.resolve(null)).then(t=>((0,_.cu)(e)&&this._makeEnqueuedRelease(t,s),a.resolve(t),t)).catch(()=>{const e=this._cachedRenderedAnnotations.get(s);e&&e.timeout&&clearTimeout(e.timeout),this._cachedRenderedAnnotations.delete(s)})),{promise:l,cancel:h}=this._requestQueue.enqueue(c,!1);return{promise:l,cancel:h}}async getAttachment(e){const[t,n]=await this.client.getAttachment(e);return new Blob([t],{type:n})}async parseXFDF(e,t,n){const{errors:i,formFieldValues:a,annotations:s}=await this.client.parseXFDF(e,t,n);return{errors:i?.map(e=>({errorMessage:e.error_message,type:e.type})),formFieldValues:a?.reduce((e,t)=>(e[t.fqdn]=t.values,e),{}),annotations:(0,c.B8)(s?.map(e=>(0,U.h8)((0,_.K1)(),e))||[])}}async search(e,t,n,i){let a=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:f.n.TEXT;const r=await this.client.search(e,t,n,i,s);return(0,x.g)(r.filter(e=>a||!e.isAnnotation))}async searchAndRedact(e,t,n){const{totalPages:i}=n,a=await this.client.search(e,t.startPageIndex??0,t.pageRange??i,t.caseSensitive,t.searchType);return(0,c.B8)(a.filter(e=>t.searchInAnnotations||!e.isAnnotation).map(e=>{const i=e.isAnnotation?[e.annotationRect]:e.rectsOnPage,a=(0,c.B8)(i).map(e=>((0,o.V1)(e),(0,L.a)(e)));return new S.A({...(0,_.mN)(n),...t.annotationPreset,pageIndex:e.pageIndex,rects:a,boundingBox:P.A.union(a)})}))}async exportPDF(){let{flatten:e=!1,incremental:t,saveForPrinting:n=!1,format:i="pdf",excludeAnnotations:a=!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(m.o).includes(c.conformance),"The supplied PDF/A Conformance type is not valid. Valid Conformance should be one of the following options NutrientViewer.Conformance."+Object.keys(m.o).join(", NutrientViewer.Conformance.")),void 0===t)if(this._state.features.includes(u.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,i,a,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:m.o.PDFA_2B;let i;try{return i=await this._setupGdPictureClient(),await i.toPdf({document:t,contentType:n.mimeType,extension:n.extension,conformance:e})}finally{i?.destroy(),(0,V.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,V.Pm)(null)}}async _setupGdPictureClient(){let e=(0,V.jU)();return e||(e=(0,V.NY)({baseUrl:this._state.baseProcessorEngineUrl,mainThreadOrigin:this._state.appName||(0,I.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,V.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:i=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},a=!1;return{promise:new Promise(s=>{this.exportPDF({flatten:!0,includeComments:t,saveForPrinting:n,excludeAnnotations:i}).then(t=>{if(a)return;const n=new Blob([t],{type:t.mimeType});e=window.URL.createObjectURL(n),s(e)})}),revoke:()=>{e&&window.URL.revokeObjectURL(e),a=!0}}}async getDocumentOutline(){const e=await this.client.getDocumentOutline();return(0,c.B8)(e.map(B.r))}async setDocumentOutline(e){return this.client.setDocumentOutline(e.map(B.U).toArray())}async getPageGlyphs(e){const t=await this.client.getPageGlyphs(e);return(0,U.Fj)(t)}async onKeystrokeEvent(e){return await this.client.onKeystrokeEvent(e)}async evalFormValuesActions(e){return this.client.evalFormValuesActions(e.map(U.cA).toJS())}async evalScript(e,t,n){return this.client.evalScript(e,t,n)}async setFormJSONUpdateBatchMode(e){return this.client.setFormJSONUpdateBatchMode(e)}async getMeasurementScales(){const e=await this.client.getMeasurementScales();return e?.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(0,C.t)(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,c.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 H(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),this.clearRenderedAnnotationsCache(),this._initialChanges=[],{features:this._state.features,signatureFeatureAvailability:this._state.signatureFeatureAvailability,hasPassword:!1,password:void 0,allowedTileScales:"all",clientInfo:null}}catch(e){throw new o.uE(`Reloading failed: ${e}`)}}async getEmbeddedFiles(){const e=await this.client.getEmbeddedFilesList();return(0,c.B8)(e.map(e=>{let{id:t,...n}=e;return(0,b.r)(t,n,!0)}))}async exportPDFWithOperations(e){try{const{processedOperations:t,operationsDocuments:n}=await(0,C.t)(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),i=await this.client.setSignaturesLTV(n,this._state.certificateCheckTime).then(e=>(0,U.N5)(e));if(i.signatures?.find(e=>e.certificateChainValidationStatus===Z.k.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(this._state.certificateCheckTime).then(e=>(0,U.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:i,request_data:a,token:s}=e;try{const e=await fetch(n,{method:t,headers:{"Content-Type":i??"application/ocsp-request"},body:l.o4.toUint8Array(a).buffer}),r=await e.arrayBuffer();return{response_code:e.status,body:l.o4.fromUint8Array(new Uint8Array(r)),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,v.k)(t),"On a Standalone deployment, `twoStepSignatureCallbackOrSigningServiceData` must be a function or `NutrientViewer.StandaloneSigningServiceData` if provided.");const n=(0,v.k)(t);return n?this.signingServiceDocumentSigner.signDocumentAndReload(e,n):this.standaloneDocumentSigner.signDocumentAndReload(e,t)}cancelRequests(){this.corePDFDocument?.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){this._state=this._state.set("forceAnnotationsRender",!1),await this.client.closeDocument();const t=this.corePDFDocument.rawDocument.ctx.documentKey;return s.MX.clearPreflightCache(t),s.MX.clearFailedFontsCache(t),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){const n=[...new Set(e)];return this.client.runPDFFormattingScripts(n,t)}async runPDFFormattingScriptsFromWidgets(e,t,n){let i=[];if(this._isPDFJavaScriptEnabled){const{withAPStream:a,withoutAPStream:s}=e.reduce((e,i)=>{if(i instanceof A.sb){if(!i.formFieldName)return e;const a=t?.get(i.formFieldName);if(a instanceof A.Vw)return e;n?.(i)?e.withAPStream.push(i.formFieldName):e.withoutAPStream.push(i.formFieldName)}return e},{withAPStream:[],withoutAPStream:[]});let r=[];if(a.length&&!s.length)r=await this.runPDFFormattingScripts(a,!0);else if(!a.length&&s.length)r=await this.runPDFFormattingScripts(s,!1);else if(a.length&&s.length){const[e,t]=await Promise.all([this.runPDFFormattingScripts(a,!0),this.runPDFFormattingScripts(s,!1)]);r=e.concat(t)}i=(0,T.A5)(this._initialChanges,r)}return i}setFontSubstitutions(e){return this.client.setFontSubstitutions(e)}async contentEditorReload(){return(0,o.V1)(this.provider instanceof H,"Standalone can only use standalone annotation provider"),this.provider._state=this.provider._state.set("alreadyLoadedPages",(0,c.T5)()),this.reloadDocument()}getOCGs(){return this.client.getOCGs()}getOCGVisibilityState(){return this.client.getOCGVisibilityState()}setOCGVisibilityState(e){return this.client.setOCGVisibilityState(e)}createLayer(e){return this.client.createLayer(e)}updateButtonIcon(e,t,n){return this.client.updateButtonIcon((0,U.eq)(e),t,n)}async timestampData(e,t){const{url:n,username:i="",password:a=""}=t,s=l.o4.fromUint8Array(new Uint8Array(e));try{const e=await this.client.getTimestampRequest(s,{url:n,username:i,password:a}),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),i=await n.arrayBuffer();return{response_code:n.status,body:l.o4.fromUint8Array(new Uint8Array(i)),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 me(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,certificateCheckTime:e.certificateCheckTime??"signing_time",customFonts:Array.isArray(e.customFonts)?e.customFonts.filter(e=>e instanceof F.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??!0,enableCoreUnifiedComments:e.enableCoreUnifiedComments,enableCorePreservePDFAccessibility:e.enableCorePreservePDFAccessibility,httpHeaders:e.httpHeaders||null,canvasRendering:e.canvasRendering??!1,storage:he(e.tempStorage)}}function pe(e){const{licenseKey:t,instantJSON:n,XFDF:i,disableWebAssemblyStreaming:a,disableIndexedDBCaching:s,enableAutomaticLinkExtraction:r,overrideMemoryLimit:c,standaloneInstancesPoolSize:l,trustedCAsCallback:d,baseUrl:h,baseCoreUrl:u,baseProcessorEngineUrl:m,customFonts:p,isSharePoint:g,isSalesforce:f,dynamicFonts:y,inlineWorkers:b,formsConfiguration:A,httpHeaders:S}=e;if((0,o.V1)("string"==typeof h,"`baseUrl` is mandatory and must be a valid URL, e.g. `https://example.com/"),(0,R.f4)(h),(0,o.V1)(!u||"string"==typeof u,"`baseCoreUrl` must be a valid URL if set, e.g. `https://example.com/"),u&&(0,R.Qo)(u),(0,o.V1)(!m||"string"==typeof m,"`baseProcessorEngineUrl` must be a valid URL if set, e.g. `https://example.com/"),m&&(0,R.hc)(m),(0,o.V1)(null==t||"string"==typeof t,"licenseKey must be a string value if provided. Please obtain yours from https://my.nutrient.io/."),"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 Nutrient Web SDK package via the node package manager.\n\nLeave out the license key to activate as a trial."),(0,o.V1)(void 0===i||"string"==typeof i,"XFDF must be a string"),n&&((0,o.yj)(n),(0,o.V1)(void 0===i,"Cannot import from both instantJSON and XFDF")),(0,o.V1)(void 0===a||"boolean"==typeof a,"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===e.certificateCheckTime||"current_time"===e.certificateCheckTime||"signing_time"===e.certificateCheckTime,"certificateCheckTime must be either 'current_time' or 'signing_time'"),(0,o.V1)(void 0===p||Array.isArray(p)&&p.every(e=>e instanceof F.A),"customFonts must be an array of NutrientViewer.Font instances"),(0,o.V1)(void 0===p||p.every(e=>e.callback),"All NutrientViewer.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."),(g||f)&&(0,o.t6)("isSharePoint and isSalesforce configuration properties are deprecated and will be removed in the next major release. Please use the new Configuration#productId property instead. For more information, please check the migration guide."),(0,o.V1)(!(g&&f),"You cannot enable both SharePoint and Salesforce integrations at the same time. Please set either isSharePoint or isSalesforce to true, but not both."),"string"==typeof y)try{new URL(y)}catch(e){throw new o.uE("dynamicFonts must be a valid URL to a JSON file containing the data for fonts to be dynamically loaded.")}if((0,o.V1)(void 0===b||"boolean"==typeof b,"inlineWorkers must be a boolean"),A&&(0,o.V1)(void 0===A.export?.disableComboBoxArrow||"boolean"==typeof A.export?.disableComboBoxArrow,"formsConfiguration.export.disableComboBoxArrow must be a boolean"),void 0!==e.tempStorage){const{tempStorage:t}=e;(0,o.V1)("memory"===t||"auto"===t||"opfs"===t||null!==t&&"object"==typeof t&&"opfs"===t.mode&&(void 0===t.minFileSize||"number"==typeof t.minFileSize&&t.minFileSize>=0),'`tempStorage` must be "memory", "auto", "opfs", or { mode: "opfs", minFileSize?: number }')}if(void 0!==S){(0,o.V1)(null!==S&&"object"==typeof S&&!Array.isArray(S),'httpHeaders must be an object with string key-value pairs, e.g. { "Authorization": "Bearer token" }'),Object.entries(S).forEach(e=>{let[t,n]=e;(0,o.V1)("string"==typeof t&&t.length>0,"httpHeaders keys must be non-empty strings representing valid HTTP header names"),(0,o.V1)("string"==typeof n,`httpHeaders value for key "${t}" must be a string. Received: ${typeof n}`)});const e=Object.keys(S).map(e=>e.toLowerCase());["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","date","dnt","expect","host","keep-alive","origin","permissions-policy","referer","te","trailer","transfer-encoding","upgrade","via"].forEach(t=>{(0,o.V1)(!e.includes(t),`httpHeaders cannot include the "${t}" header as it is controlled by the browser. For more information, see https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header`)});const t=["proxy-","sec-"];e.forEach(e=>{t.forEach(t=>{(0,o.V1)(!e.startsWith(t),`httpHeaders cannot include headers starting with "${t}" (found: "${e}") as they are controlled by the browser. For more information, see https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header`)})}),e.includes("range")&&console.warn('The "Range" header in httpHeaders will be overridden during progressive loading (allowLinearizedLoading: true) to manage document chunks. Your custom Range header will only be used for non-linearized document loading.')}}},61469(e,t,n){n.d(t,{O:()=>a,n:()=>i});let i=function(e){return e[e.EVALUATION=0]="EVALUATION",e[e.DEMO=1]="DEMO",e[e.DEVELOPMENT=2]="DEVELOPMENT",e[e.PRODUCTION=3]="PRODUCTION",e}({}),a=function(e){return e[e.WEB=59]="WEB",e[e.DOCUMENT_ENGINE=60]="DOCUMENT_ENGINE",e}({})},77112(e,t,n){n.d(t,{r:()=>r});var i=n(57191);class a extends(i.mS({id:"",attachmentId:"",description:null,fileName:null,fileSize:null,updatedAt:null})){}var s=n(48746);function r(e,t){return function(e,t){return t}(0,arguments.length>2&&void 0!==arguments[2]&&arguments[2])?new a({id:(0,s.A)(),description:t.fileDescription,attachmentId:e,fileName:t.fileName||null,fileSize:t.fileSize||null,updatedAt:t.modificationDate?new Date(t.modificationDate):null}):new a({id:e,description:t.description,attachmentId:t.fileAttachmentId,fileName:t.fileName||null,fileSize:t.fileSize||null,updatedAt:t.updatedAt?new Date(t.updatedAt):null})}},22019(e,t,n){n.d(t,{U:()=>c,r:()=>l});var i=n(89339),a=n(57191),s=n(95555),r=n(64894),o=n(97947);function c(e){return{type:"pspdfkit/outline-element",children:e.children&&e.children.map(e=>c(e)).toJS(),title:e.title,color:e.color&&(0,r.J)(e.color),isBold:e.isBold,isItalic:e.isItalic,isExpanded:e.isExpanded,action:e.action&&(0,s.Ix)(e.action)}}function l(e){let t,n;(0,i.V1)("pspdfkit/outline-element"===e.type,"invalid outline element type."),(0,i.V1)(null==e.children||Array.isArray(e.children),"children must be an Array<OutlineElement>."),(0,i.V1)("string"==typeof e.title,"title must be a string."),(0,i.V1)(null==e.isBold||"boolean"==typeof e.isBold,"isBold must be a boolean."),(0,i.V1)(null==e.isItalic||"boolean"==typeof e.isItalic,"isItalic must be a boolean."),(0,i.V1)(null==e.isExpanded||"boolean"==typeof e.isExpanded,"isExpanded must be a boolean.");try{t=e.action&&(0,s._8)(e.action)}catch(t){(0,i.R8)(`PDF Action not supported ${JSON.stringify(e.action)})`)}try{n=e.color&&(0,r.p)(e.color)}catch(t){(0,i.R8)(`Invalid color:\n\n${e.color}`)}const c={title:e.title,color:n,isBold:!0===e.isBold,isItalic:!0===e.isItalic,isExpanded:!0===e.isExpanded,action:t,children:e.children&&e.children.length>0?(0,a.B8)(e.children.map(l)):(0,a.B8)()};return new o.LC(c)}},2090(e,t,n){n.d(t,{g:()=>a,t:()=>s});var i=n(89339);function a(e,t,n,i,a,s){let r;return e.has(n)?r=e.get(n):(r=a.toString(),t[r]=n,e.set(n,r)),{...i,[s]:r}}async function s(e){const t=new WeakMap,n={};return{processedOperations:await Promise.all(e.map(async(e,s)=>{if("importDocument"===e.type){const{document:r}=e;return(0,i.V1)(r instanceof File||r instanceof Blob,"Wrong `importDocument` operation `document` value: it must be a File or a Blob"),a(t,n,r,e,s,"document")}if("applyInstantJson"===e.type){const r=e.instantJson;(0,i.V1)("object"==typeof r&&null!==r,"Wrong `applyInstantJson` operation `instantJson` value: it must be an object");const o=JSON.stringify(r),c=new Blob([o],{type:"application/json"});return a(t,n,c,e,s,"dataFilePath")}if("applyXfdf"===e.type){const r=e.xfdf;(0,i.V1)("string"==typeof r,"Wrong `applyXfdf` operation `xfdf` value: it must be a string");const o=new Blob([r],{type:"application/vnd.adobe.xfdf"});return a(t,n,o,e,s,"dataFilePath")}return e})),operationsDocuments:n}}},62389(e,t,n){n.d(t,{g:()=>o});var i=n(57191),a=n(89339),s=n(29655),r=n(17342);function o(e){return(0,a.V1)(Array.isArray(e),"Wrong `json` field"),(0,i.B8)(e.map(e=>((0,a.V1)("number"==typeof e.pageIndex,"Wrong `pageIndex` field"),(0,a.V1)("string"==typeof e.previewText,"Wrong `previewText` field"),(0,a.V1)(Array.isArray(e.rangeInPreview),"Wrong `rangeInPreview` field"),(0,a.V1)(Array.isArray(e.rectsOnPage),"Wrong `rectsOnPage` field"),new r.A({pageIndex:e.pageIndex,previewText:e.previewText,locationInPreview:e.rangeInPreview[0],lengthInPreview:e.rangeInPreview[1],rectsOnPage:(0,i.B8)(e.rectsOnPage).map(e=>(0,s.a)(e)),isAnnotation:!!e.isAnnotation,annotationRect:e.annotationRect?(0,s.a)(e.annotationRect):null}))).filter(Boolean))}}}]);