/*************************************************************************
* ADOBE CONFIDENTIAL
* ___________________
*
*  Copyright 2015 Adobe Systems Incorporated
*  All Rights Reserved.
*
* NOTICE:  All information contained herein is, and remains
* the property of Adobe Systems Incorporated and its suppliers,
* if any.  The intellectual and technical concepts contained
* herein are proprietary to Adobe Systems Incorporated and its
* suppliers and are protected by all applicable intellectual property laws,
* including trade secret and or copyright laws.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Adobe Systems Incorporated.
**************************************************************************/
import{dcLocalStorage as e,dcSessionStorage as t}from"../../../common/local-storage.js";import{dcTabStorage as a}from"../tab-storage.js";import{util as n}from"../content-util.js";import{signInUtil as r}from"./signInUtils.js";import{privateApi as o}from"../content-privateApi.js";import{COOLDOWN_FOR_LFT_PROMPT as i,OptionPageActions as s,LOCAL_FILE_PERMISSION_URL as c,LOCAL_FTE_WINDOW as l,OptionsPageSource as d,ACROBAT_USER_STATE as m}from"../../../common/constant.js";import{indexedDBScript as g}from"../../../common/indexDB.js";import{loggingApi as f}from"../../../common/loggingApi.js";import{updateExtUserState as u,isNewUser as p,isEdgeBrowser as w,isDemoMode as h,getGenAIServiceVariant as I,getSearchParams as b,isMigrationCompleted as v}from"../../../common/util.js";import{urlParamCleanup as _}from"./urlParamCleanup.js";import y from"./ResponseHeaders.js";import S from"./BookmarkUtils.js";import L from"./LruUtil.js";import{analytics as U,events as E}from"../../../common/analytics.js";import{fileUtil as R}from"./fileUtil.js";import{buildAcrobatPromotionSource as k}from"../../../content_scripts/utils/util.js";import{initializeBlobCacheCleanupAlarm as T}from"../../../content_scripts/blob-cache-cleanup.js";import{EXPERIMENT_VARIANTS_STORAGE_KEY as P}from"../../../sw_modules/constant.js";import{initTemporaryURLBufferIndexedDB as C}from"../../../common/temporaryURLBufferIndexDB.js";import{ALLOWED_IFRAME_SEARCH_PARAMS as D,ALLOWED_IFRAME_HASH_PARAMS as F}from"./iframeUrlParamsAllowlist.js";import{handlePostPDFConversionInDirectFlow as A,sendFileBufferToViewerForDirectFlow as B,isDirectFlowWithoutPreview as x,handleUpsellCloseInDirectFlow as V,isPreviewPostDirectFlow as M,previewOriginalPDF as O}from"./DirectVerb.js";import{getActiveExperimentAnalyticsArray as N}from"../../../common/experimentUtils.js";await e.init(),await t.init();const W=e.getItem("appLocale"),$="acrobatPromotionSource";let G=!1;!function(){let l,H,j,q,z,J,Y,K,X,Z,Q,ee,te,ae,ne,re,oe,ie,se,ce,le,de,me,ge,fe,ue,pe="",we=!1,he=null;const Ie=chrome.runtime.getURL("viewer.html"),be=chrome.runtime.getURL("signInHandler.html"),ve="file:",_e="blob:",ye=["https:","http:",ve],Se=new Map([["gmail","gmail"],["gdrive","gdrive"],["embeddedpdf","embeddedPDF"],["outlook","outlook"],["linkedin","linkedIn"],["gdocs","gdocs"],["gsheets","gsheets"],["gslides","gslides"],["webpage","webpage"]]);let Le,Ue;const Ee=()=>(he||(he=C()),he);Le=new Promise(e=>Ue=e),ke({main_op:"chrome_viewer_opened",activeTabId:Te(document.location.search,"tabId")});function Re(e){const t=a.getItem("search");return new URLSearchParams(t).get(e)}function ke(e,t){return ae?(ne=ne||1,e.tabId=ne,e.mimeHandled=!0,chrome.runtime.sendMessage(e,t)):chrome.runtime.sendMessage(e,t)}function Te(e,t){return new URLSearchParams(e).get(t)||""}async function Pe(){if(q=Te(document.location.search,"pdfurl"),de=Te(document.location.search,"tabId")||(await chrome.tabs.getCurrent())?.id,me=Te(document.location.search,"aw"),fe=await(async e=>{if(!e)return!1;try{const t=new URL(e),a=t.protocol;let n=-1!==ye.indexOf(a);if(n=a===ve?t.pathname.toLowerCase().endsWith(".pdf"):n,a===_e)if(n=await g.hasKey(`chrome-extension://${chrome.runtime.id}/${t.href}`),n)T(),we=!0;else if(t?.origin?.includes("outlook"))return!0;return n}catch(e){return!1}})(q),ue=Te(document.location.search,"acrobatPromotionWorkflow")||a.getItem("acrobatPromotionWorkflow"),ue&&a.setItem("acrobatPromotionWorkflow",ue),!fe)return void(z=!1);we&&(q=`chrome-extension://${chrome.runtime.id}/${q}`),function(){const e=new URLSearchParams(document.location.search),n=t.getItem("rtParams");if(n){const a=n.split(",").map(t=>e.has(t)?`&${t}=${e.get(t)}`:null).join("")||"";t.setItem("payPalUrl",a),t.removeItem("rtParams")}e.has("dialog!dropin")&&a.setItem("dialog!dropin",e.get("dialog!dropin")),e.has("load!dropin")&&a.setItem("load!dropin",e.get("load!dropin"))}();const e=a.getItem("search");if((!e||Te(e,"pdfurl")!==q||e.length<document.location.search)&&a.setItem("search",document.location.search),j=Te(document.location.search,"pdffilename")||Te(e,"pdffilename")||nt(q),document.title=j,!we){const e="/"+q+location.hash;history.replaceState({},j,e)}}function Ce(t,a,n="unknown"){e.setItem(`reloadurl-${t.id}`,q);const r=new URL(q);if(function(t,a="unknown"){if(t?.searchParams?.has($)||Re($)?.length>0)f.info({message:"reloadInNativeViewer",source:t.searchParams.get($)||Re($),domain:t.hostname});else if(e.getItem("nativeFallbackLogging")){const e={message:"reloadInNativeViewer",reason:a,url:t.origin+t.pathname};f.info(e)}}(r,n),kt(r)&&!a?.includes("text/html")){const e=r?.searchParams?.get("id");window.location.href=`https://drive.google.com/file/d/${e}`}else window.location.href=q}function De(e=!1,t,a="unknown"){if(ae)try{e||ke({main_op:"viewer-type",viewer:"mime-native"}),setTimeout(()=>{o.reloadWithNativeViewer({contentLength:parseInt(l)||0})},100)}catch(e){Ae("DCBrowserExt:Viewer:FallbackToNative:Failed")}else try{setTimeout(()=>{chrome.tabs.getCurrent(e=>Ce(e,t,a))},500)}catch(e){Be("DCBrowserExt:Viewer:FallbackToNative:Failed",{tabURL:q})}}const Fe=t=>{try{const a=new URL(e.getItem("cdnUrl")),n=[/^https:\/\/([a-zA-Z\d-]+\.){0,}(adobe|acrobat)\.com(:[0-9]*)?$/];return t===a.origin&&!!n.find(e=>e.test(t))}catch(e){return!1}};function Ae(e){const t={main_op:"analytics"};t.analytics=[[e]],ke(t)}function Be(e,t){const a={main_op:"analytics"};a.analytics=[[e]],t&&a.analytics[0].push(t),ke(a)}const xe=e=>{const t=b(e),a=k("outlook_chrome","native_view");return t.get($)===a||Re($)===a};function Ve(){if(!sessionStorage.getItem("uuid-for-shortened-redirect-url")){const e=n.uuid();sessionStorage.setItem("uuid-for-shortened-redirect-url",e),sessionStorage.setItem(e,q)}return new URL(q)?.origin+"?uuid="+sessionStorage.getItem("uuid-for-shortened-redirect-url")}function Me(){let e=q;return xe(q)&&(e=Ve()),Rt(q)?`${Ie}?pdfurl=${encodeURIComponent(e)}&pdffilename=${encodeURIComponent(document.title)}`:q}function Oe(){let e,t=Ie;if(ae)if(we){const t=new URLSearchParams(window.location.search),a=t.get("pdfurl"),n=t.get("pdffilename");e="?pdfurl="+encodeURIComponent(a)+"&pdffilename="+encodeURIComponent(n)}else e="?mimePdfUrl="+encodeURIComponent(q),t=be;else e=a.getItem("search"),e||(e="?pdfurl="+encodeURIComponent(q)),xe(q)&&(e="?pdfurl="+encodeURIComponent(Ve()));return new URL(t+e)}const Ne=["AdobeID","openid","DCAPI","sign_user_read","sign_user_write","sign_user_login","sign_library_read","sign_library_write","agreement_send","agreement_read","agreement_write","ab.manage","additional_info.account_type","sao.ACOM_ESIGN_TRIAL","widget_read","widget_write","workflow_read","workflow_write"];function We(t={}){if(e.getItem("csi")){const e=Me(),a={...t,pdfUrl:e};return void r.cdnSignIn(a)}const a=Oe(),o=e.getItem("cdnUrl"),i=t.sign_up?1:0,s=n.generateStateCSRF(),c=e.getItem("enableCSRF"),l=JSON.stringify({touchp:t.touchpoint||"",signIn:!0,...c&&{state:s}}),d=e.getItem("theme")||"auto",m=`${o}?la=true&locale=${W||e.getItem("locale")}&theme=${d}&ru=${encodeURIComponent(a.href)}&rp=${l}&su=${i}#/susi`;chrome.tabs.update({url:m,active:!0})}function $e(){const e={main_op:"signout",pdfUrl:Me(),callingApp:chrome.runtime.id};r.cdnSignIn(e)}function Ge(t={}){if(e.getItem("csi")){const e={...t,pdfUrl:q};return void r.cdnSignIn(e)}let n=new URL(be);const o=t.idp_token;return n.searchParams.append("socialSignIn","true"),n.searchParams.append("mimePdfUrl",encodeURIComponent(q)),a.setItem("idp_token",o),n.href}function He(e={}){ae?chrome.tabs.update({url:Ge(e),active:!0}):r.socialSignIn(e,Oe(),q)}function je(t={}){if(e.getItem("csi")){try{const e=new URL(JSON.parse(t.url));delete t.url;const a={...t,pdfUrl:Me()},n=r.getCDNSignURL(a);e.searchParams.append("redirect_uri",n),chrome.tabs.update({url:e.href,active:!0})}catch(e){chrome.tabs.update({url:q})}return}const o=t.application||"google",i=e.getItem("viewerImsClientIdSocial"),s=e.getItem("imsURL"),c=n.uuid(),l=Oe();l.hash=l.hash+"signIn=true";const d=new URL(s+"/ims/authorize/v1"),m={ac:n.getAppCode(),csrf:c};a.setItem("csrf",c),d.searchParams.append("response_type","token"),d.searchParams.append("idp_flow","social.deep_link.web"),d.searchParams.append("client_id",i),d.searchParams.append("provider_id",o),d.searchParams.append("redirect_uri",l),d.searchParams.append("scope",Ne.join(",")),d.searchParams.append("locale",W||e.getItem("locale")),d.searchParams.append("state",JSON.stringify(m)),d.searchParams.append("xApiClientId",i),d.searchParams.append("xApiClientLocation ",o),chrome.tabs.update({url:d.href,active:!0})}const qe={isSharePointURL:!1,isSharePointFeatureEnabled:!1,isFrictionlessEnabled:!0,featureFlags:[],isFillAndSignRegisteryEnabled:!1};class ze{constructor(e){this.iframeElement=void 0,this.parentDiv=e}createIframe=e=>{const t=window.document,a=t.createElement("iframe");a.onerror=()=>{f.error({message:"cdnIframeLoadFailed"})},a.setAttribute("src",e),a.setAttribute("id","dc-view-frame"),a.setAttribute("allowfullscreen","allowfullscreen"),a.setAttribute("allow","clipboard-read; clipboard-write; local-fonts; payment;"),a.style.width="100vw",a.style.height="100vh",a.style.border="none",a.style.overflow="hidden",this.parentDiv.appendChild(a),this.iframeElement=t.getElementById("dc-view-frame")};_sendMessage=(e,t)=>{this.iframeElement&&Fe(t)&&function(e){let t=Date.now();return new Promise(function a(n,r){J&&(z||ae)?n(z||ae):e&&Date.now()-t>=e?r(new Error("timeout")):setTimeout(a.bind(this,n,r),30)})}(1e6).then(a=>a&&this.iframeElement.contentWindow.postMessage(e,t))};sendStartupConfigs=(a,n)=>{this._sendMessage({type:"nativeConfigs",nativeConfigs:qe,extUrl:encodeURI(a),returnParamsUrl:t.getItem("payPalUrl"),isInstallTypeUpsell:G,gmailGDriveData:{gmailFteState:e.getItem("acrobat-gmail-fte-config"),gDriveFteState:e.getItem("acrobat-gdrive-fte-state")}},n),this.sendExperimentInfo(n)};sendFileMetaData=(e,t,a,n,r,o,i,s)=>{this._sendMessage({fileUrl:r,fileName:o,fileSize:a,acceptRanges:n,handShakeTime:t,type:e,isFrictionlessEnabled:qe.isFrictionlessEnabled,isReloadOrBackForward:s,isMimeHandled:ae},i)};executeDirectVerb=(e,t,a,n,r,o,i,s)=>{this._sendMessage({type:e,fileBuffer:t,fileBufferSize:a,fileName:n,downLoadstartTime:r,downLoadEndTime:o,mimeType:i},s)};sendSubmitFormResponse=(e,t)=>{this._sendMessage({type:"submitForm",response:e},t)};sendRecentUrl=async(e,t,a,n=!1)=>{await chrome.extension.isAllowedFileSchemeAccess()||(t=t?.filter(e=>!e.url.startsWith("file://"))),this._sendMessage({type:"RecentUrls",permission:e,showOverlay:n,recentUrls:t},a)};sendProgress=(e,t,a,n)=>{this._sendMessage({total:t,loaded:a,type:e},n)};sendInitialBuffer=(e,t,a,n,r)=>{this._sendMessage({type:e,downLoadstartTime:t,downLoadEndTime:a,buffer:n},r)};sendBufferRanges=(e,t,a,n)=>{this._sendMessage({type:e,range:t,buffer:a},n)};preview=(e,t,n,r,o,i,s)=>{const c="true"===a.getItem("bufferFromIndexedDB");a.removeItem("bufferFromIndexedDB"),this._sendMessage({fileSize:n,type:e,fileBuffer:t,fileName:r,downLoadstartTime:o,downLoadEndTime:i,fromIndexedDB:c,isLocalBlobFile:we},s)};openInAcrobatResponse=(e,t,a)=>{this._sendMessage({type:e,res:t},a)};postLog=(e,t,a,n,r)=>{this._sendMessage({type:e,reqId:t,message:a,error:n},r)};sendCertificateValidationResponse=(e,t)=>{this._sendMessage({type:"certificateValidationResponse",response:e},t)};sendExperimentInfo=t=>{const a=e.getItem(P);let n=Array.isArray(a)?a.sort():[];X._sendMessage({type:"experimentInfo",activeExperiments:n},t)}}function Je(t,a){try{Q=void 0!==Q?Q:"false"!==e.getItem("logAnalytics")&&"false"!==e.getItem("ANALYTICS_OPT_IN_ADMIN"),Q&&(X&&H?X.postLog("log",Z,t,a,H.origin):setTimeout(()=>{X&&H&&X.postLog("log",Z,t,a,H.origin)},500))}catch(e){}}function Ye(){let e;return e=ae?q:window.location.href,e}function Ke(){const t=Ye(),n=(t.split("#")||[]).pop();if(n.indexOf("access_token=")>-1)try{const o=new URLSearchParams(n).get("access_token"),{client_id:i}=JSON.parse(window.atob(o.split(".")[1]))||{},s=e.getItem("viewerImsClientId");if([s,e.getItem("viewerImsClientIdSocial")].includes(i)){const e=a.getItem("csrf");a.removeItem("csrf");const n=r.parseCSRF(new URL(t));(!e||!n||n!==e)&&(Ae("DCBrowserExt:Viewer:User:Error:NonMatchingCsrfToken:FailedToLogin"),$e())}}catch{}}function Xe(t,a,n,r,o){o&&t.forEach(e=>{n.has(e)&&Qe(a,e,n.get(e))}),r&&t.forEach(t=>{""!==e.getItem(t)&&Qe(a,t,e.getItem(t))})}function Ze(e){const t=e?.toLowerCase();for(const[e,a]of Se.entries())if(t?.startsWith(e))return a;return""}function Qe(e,t,a,n=!1){if(!a)return;if(!(D.includes(t)||n&&D.some(e=>t.startsWith(e))))return void console.error({message:`Attempt to use non-allowlisted param: ${t}`});const r="string"==typeof a?a:JSON.stringify(a);e.searchParams.append(t,r)}const et=async()=>{try{let r;r=ae&&!we?new URLSearchParams(new URL(q).search):new URLSearchParams(window.location.search);const o=function(t){const a=e.getItem("cdnUrl");try{if("prod"===e.getItem("env"))return a;const n=t.get("ephemeralUrl");if(!n)return a;const r=new URL(n);return"https:"===r.protocol&&["stage.acrobat.adobe.com","dev.acrobat.adobe.com"].includes(r.hostname)&&r.pathname.startsWith("/ephemeral/dc-chrome-extension/")?n:a}catch(e){return console.error("Error validating ephemeral URL:",e?.message||"Unknown error"),a}}(r),i=new URL(o);if(!Fe(i.origin))return Je("Invalid CDN URL detected","Invalid Origin"),void De(!1,null,"invalid_cdn_origin");H||(H=i);let s=e.getItem("viewer-locale");s||(s=e.getItem("locale"));const c="false"!==e.getItem("logAnalytics"),l="false"!==e.getItem("ANALYTICS_OPT_IN_ADMIN"),d=c&&l?"true":l?"optinOff":"gpoOff",m=r.get("blob-uri");h(m,q)&&(Qe(i,"blob-uri",m),Qe(i,"isDemoMode",!0),w()&&["returnURL","returnTabId"].forEach(e=>{const t=r.get(e);t&&i.searchParams.set(e,t)})),"true"===r.get("ogap")&&Qe(i,"ogap","true"),r.get("olfs")&&Qe(i,"olfs",r.get("olfs")),Qe(i,"aiFAB",e.getItem("enableGenAIFab")),Qe(i,"locale",W||s),Qe(i,"logAnalytics",d),Qe(i,"callingApp",chrome.runtime.id),Qe(i,"lfa",e.getItem("isAllowedLocalFileAccess")||"false"),Qe(i,"enableCaretMode",ie),t.getItem("signInTp")&&Qe(i,"touchp",t.getItem("signInTp")),Qe(i,"rvu",e.getItem("userState")?.rvu??null);const g=e.getItem("installType")||"update",u=e.getItem("installSource");Qe(i,"version",`${chrome.runtime.getManifest().version}:${g}`),Qe(i,"installSource",u),Qe(i,"storage",JSON.stringify(e.getItem("viewerStorage")||{})),Qe(i,"fgContextVars",JSON.stringify(e.getItem("fgContextVars")||{})),Qe(i,"tabId",de),Qe(i,"anonUserUUID",e.getItem("anonUserUUID")),Qe(i,"evc",e.getItem("viewerComp")?"1":"0"),"true"!==Re("googlePrint")&&!0!==re||"false"===a.getItem("googleAppsPrint")||Qe(i,"googleAppsPrint","true"),Qe(i,"lf",e.getItem("lf")?"1":"0");const b=le.read(q);b&&(delete b.filename,delete b.lastVisited,Qe(i,"docState",JSON.stringify(b))),Qe(i,"nu",p()),Qe(i,"md",v()?"1":"0"),Qe(i,"dpt",e.getItem("isDarkPageThemeEnabled")?"1":"0");const y=t.getWithTTL("pdfMarkerAction");y&&(Qe(i,"action",y),t.removeItem("pdfMarkerAction")),i.searchParams.append("wn",e.getItem("whatsNew")?"1":"0"),Qe(i,"adminDisableGenAI","true"===e.getItem("DISABLE_GENAI_BY_ADMIN")?"1":"0"),SETTINGS.DEBUG_MODE&&Qe(i,"serVar",I()),Qe(i,"autoSum","false"!==e.getItem("autoSum"));if("true"===e.getItem("adobeInternal")){const t="true"===e.getItem("betaOptOut");Qe(i,"betaOptOut",t)}let S=a.getItem("signinTouchPointData");S=JSON.parse(S||"{}"),S&&"object"==typeof S&&Object.keys(S).length&&(Qe(i,"tp",S.touchpoint),Qe(i,"acmt",S.allowCommentsInShare?"1":"0")),a.removeItem("signinTouchPointData");const L=e.getItem("env"),U=new URLSearchParams(new URL(q).search).get($)||Re($),E=Ze(U),R=U?.split("-")||[];if(R.length>1&&(i.searchParams.append("xId",R[0]),i.searchParams.append("xLoc",R[1])),U&&E){if(Qe(i,"sfceId",E),a.getItem("acrobatPromotionWorkflow"))Qe(i,"sfceIdWf",ue);else{const t=("true"===e.getItem(`${E}-pdf-default-viewership`)).toString();Qe(i,"aDFrSfce",t),"true"===e.getItem(`${E}-pdf-implicit-dv-feature-enabled`)?Qe(i,"sfceIDVFe",!0):Qe(i,"sfceDVFe","true"===e.getItem(`${E}-pdf-dv-feature-enablement-status`)),Qe(i,"aDFrSfceUsrDsbl",function(t,a){return"true"===e.getItem(`${t}-pdf-default-viewership-user-disabled`)||"gdrive_chrome-native_view-NDV"===a}(E,U))}const t="webpage"===E||e.getItem(`enableMeterIQ${E}`)?"1":"0";Qe(i,"emi",t)}n=i,["dialog!dropin","load!dropin"].forEach(e=>{""!==(a.getItem(e)||"")&&Qe(n,e,a.getItem(e))});Xe(["analytics","logToConsole","enableLogging","frictionless","sessionId","linearization","ev","ao"],i,r,!1,!0);Xe(["rrv","fgRearch","isDeskTop","isAcrobat","SFV","theme","defaultOwnerShipExperiment","sessionId","ev","ao","ip","genAI","mv","pi","ks","edd","lft","fsu","dcs","egal","ots","egaf","pnb","subv2","s3d","ripe","od","kwgn","rat"],i,r,!0,!1);"prod"!==L&&["dropin!","provider!","app!","forceDisableGenAI"].forEach(e=>{r.forEach((t,a)=>{a.startsWith(e)&&Qe(i,a,t,!0)})});let k=i.href;""===t.getItem("payPalUrl")||""===a.getItem("dialog!dropin")&&""===a.getItem("load!dropin")||(k+=t.getItem("payPalUrl")),k=await(async e=>{if(e.length>6553.6&&f.warn({message:"CDN iframe length breached 80% limit",iframeUrl:e}),e.length>8192)return f.error({message:"CDN iframe length breached threshold",iframeUrl:e}),await _.cleanUrl(e);return e})(k);let T=new URLSearchParams;const P=a.getItem("access_token");a.removeItem("access_token"),function(e,t,a){if(!a)return;if(!F.includes(t))return void console.error({message:`Attempt to use non-allowlisted hash param: ${t}`});const n=["access_token"].includes(t)?2048:128,r="string"==typeof a?a:JSON.stringify(a);r.length>n&&f.warn({message:`Hash param value too long: ${t}`,length:a.length}),e.set(t,r)}(T,"access_token",P);const C=`${k}${T.toString()?`#${T.toString()}`:""}`;return e.setItem("lastPdfOpenTimestamp",(new Date).getTime()),C}catch(e){throw Ae("DCBrowserExt:Viewer:Iframe:Creation:Failed"),e}var n},tt=(a,n,r="localStorage")=>{if(n){const o="localStorage"===r?e.getItem(a):t.getItem(a);let i;o&&o.tabsInfo?(i=o.tabsInfo,i.includes(n)||i.push(n)):i=[n],"localStorage"===r?e.setItem(a,{tabsInfo:i}):t.setItem(a,{tabsInfo:i})}},at=async()=>{try{!function(){try{let e=Ye();e&&e.indexOf("#")>-1&&(r.saveAccessToken(e),r.signInAnalyticsLogging(e),r.checkSignInFromEditVerbPaywall(e),e=e.split("#")[0],ae?q=e:(window.location.hash=e,history.replaceState(null,document.title,e)))}catch(e){}}(),ae&&(de=ne);const a=window.document.getElementById("Adobe-dc-view");ae||(l=Re("clen")||-1),X=new ze(a);const n=await et();X.createIframe(n),u(),window.addEventListener("message",a=>{!a.data||!Fe(a.origin)||Y||"hsready"!==a.data.type&&"ready"!==a.data.type||(Y=!0,K=(new Date).getTime(),Z=a.data.requestId,"on"===a.data.killSwitch?(Ae("DCBrowserExt:Viewer:KillSwitch:Turned:On"),e.setItem("pdfViewer","false"),o.setViewerState("disabled"),e.setItem("killSwitch","on"),ae?De(!0):setTimeout(()=>{window.location.href=q},200)):e.getItem("killSwitch")&&(Ae("DCBrowserExt:Viewer:KillSwitch:Turned:Off"),e.removeItem("killSwitch")),t.getItem("signInTp")&&t.removeItem("signInTp"))})}catch(e){throw Je("Error create Iframe",e),e}};function nt(e){if(j)return j;let t=e;try{const a=e.split("?")[0].split("/").filter(e=>e.length>0),n=a.length>0?a[a.length-1]:"untitled";t=n;const r=n.length-4;(n.length<4||n.toLowerCase().indexOf(".pdf")!==r)&&(t+=".pdf")}catch(e){Je("Error in getFileNameFromURL",e)}return t}function rt(e,t){return function(a){if(this.readyState==this.HEADERS_RECEIVED){if(!function(e,t){const a=e.getResponseHeader("content-type"),n=Rt(t),r=e.getResponseHeader("content-disposition");if(a){const e=a.toLowerCase().split(";",1)[0].trim();if(!n&&r&&/^\s*attachment[;]?/i.test(r))return!1;if("application/pdf"===e)return!0;if("application/octet-stream"===e&&r&&/\.pdf(["']|$)/i.test(r))return!0}return!1}(e,t)&&!x())return Je("Fall back to native - not pdf from headers"),De(!1,e.getResponseHeader("content-type"),"invalid_content_type");if(z=!0,"true"===me){const e=this.getResponseHeader("accept-ranges"),a=this.getResponseHeader("content-length");e&&"bytes"===e&&a&&Number(a)>0&&ke({main_op:"setupWorkerOffscreen",pdfURL:t,pdfSize:+a,acceptRanges:!0,tabId:de})}}}}function ot(e,t){let a=!1;return function(n){n.lengthComputable&&(l=n.total,e.sendProgress("progress",n.total,n.loaded,t),a||(!function(e){const t=le.read(q)||{},a={main_op:"getFileSize",fileSize:e,tabId:de,docLastOpenState:t,target:"offscreen"};chrome.runtime.sendMessage(a)}(l),a=!0))}}function it(e,t){"PDF"===function(e){if(e)try{let t=new URL(e).pathname;return t.substr(t.lastIndexOf(".")+1).toUpperCase()}catch(e){return""}return""}(e)&&(z=!0);const a=new XMLHttpRequest;a.open("GET",e),a.responseType="arraybuffer",a.onreadystatechange=function(){4===a.readyState&&(200!==a.status&&0!=a.status||(t({buffer:a.response,mimeType:a.getResponseHeader("content-type")}),ct(a.response)))},a.send(null)}async function st(t){try{const n=a.getItem("bufferTabId"),r=(xe(q)||M())&&await Ee().hasKey(t);if(function(e,t){"preview"!==a.getItem("acrobatPromotionWorkflow")||e||Je("Direct Flow : Tab storage has acrobatPromotionWorkflow equivalent to preview but does not have key in indexedDB",t)}(r,t),n||r){const e=n&&await g.getDataFromIndexedDB(n)||await Ee().getDataFromIndexedDB(t);if(e&&e.fileBuffer)return a.setItem("bufferFromIndexedDB",!!n),z=!0,{buffer:e.fileBuffer}}else{const t=e.getItem("tabIdMap");if(t){const n=(ae?await chrome.tabs.query({active:!0,currentWindow:!0}):[await chrome.tabs.getCurrent()])[0];if(n&&t[n.id]){a.setItem("bufferTabId",t[n.id]);const r=await g.getDataFromIndexedDB(t[n.id]);if(Object.keys(t).length>1?(delete t[n.id],e.setItem("tabIdMap",t)):e.removeItem("tabIdMap"),r&&r.fileBuffer)return a.setItem("bufferFromIndexedDB",!0),z=!0,{buffer:r.fileBuffer}}}}}catch(e){}return a.setItem("bufferFromIndexedDB",!1),{}}function ct(e){const t=le.read(q)||{},a=new Blob([e],{type:"application/pdf"}),n={main_op:"getFileBuffer",fileBufferBlob:URL.createObjectURL(a),tabId:de,docLastOpenState:t,target:"offscreen"};chrome.runtime.sendMessage(n)}async function lt(e){const t=xe(q),a=x();if(t||a){const t=(await chrome.tabs.getCurrent())?.id;try{await Ee().storeInIndexedDB(e,t)}catch(e){}}}const dt=["embeddedpdfs_chrome","linkedin_chrome-chat_view","linkedin_chrome-message_view"];function mt(e,t,a){return new Promise((n,r)=>{const o=new URL(q),i=o.searchParams.get("acrobatPromotionSource");if("webpage_chrome-convert_to_pdf"===i&&o.searchParams.has("tabId")){const e=o.searchParams.get("tabId"),t=o.searchParams.get("tabOriginalUrl");return void(e?chrome.runtime.sendMessage({main_op:"get-webpage-html-by-tab-id",sourceTabId:parseInt(e)},e=>{if(e&&e.success&&e.html){const t={buffer:(new TextEncoder).encode(e.html).buffer,mimeType:"text/html",downLoadEndTime:(new Date).getTime(),pdffilename:(e.title||"webpage")+".html"};Ae("DCBrowserExt:Viewer:WebpageConversion:HtmlExtract:Success"),x()?(z=!0,n(t)):(Ae("DCBrowserExt:Viewer:WebpageConversion:Error:UnexpectedPreviewWorkflow"),r({message:"Unexpected preview workflow for webpage conversion"}))}else t?(Ae("DCBrowserExt:Viewer:WebpageConversion:Fallback:TabClosed"),window.location.href=t):(Ae("DCBrowserExt:Viewer:WebpageConversion:Error:NoFallbackUrl"),r({message:"Failed to get webpage HTML and no fallback URL available",error:e?.error||"Unknown error"}))}):(Ae("DCBrowserExt:Viewer:WebpageConversion:Error:MissingTabId"),r({message:"Invalid webpage conversion request",error:"Tab ID is required for webpage conversion"})))}dt.includes(i)&&o.searchParams.delete("acrobatPromotionSource");const s=o.toString();if(s.startsWith("file://"))return void it(s,n);const c=new XMLHttpRequest;c.open("GET",s),c.responseType="arraybuffer",t&&c.setRequestHeader("If-Range","randomrange"),c.onreadystatechange=rt(c,q),c.onprogress=ot(e,a),c.onload=()=>{if(c.status>=200&&c.status<400){const e={buffer:c.response,mimeType:c.getResponseHeader("content-type"),downLoadEndTime:(new Date).getTime()};if(x())return e.pdffilename=j,z=!0,void n(e);n(e),ct(c.response),lt(c.response)}else{const e={status:c.status,statusText:c.statusText};r({message:"Invalid response fetching content",error:e})}},c.onerror=e=>{we?g.getFileByHash(q).then(async e=>{if(e)z=!0,l=e.byteLength,n({buffer:e,mimeType:"application/pdf",downLoadEndTime:(new Date).getTime(),fileSize:e.byteLength});else{f.info({message:"User tried opening blob file after expiry"});const e=chrome.runtime.getURL("browser/js/viewer/sessionExpired.html");chrome.tabs.update({url:e})}}).catch(e=>{r({message:"Error to get file contents from indexedDB",error:e})}):r({message:"Error to download file contents",error:e})},c.ontimeout=e=>{r({message:"Timeout to download file contents",error:e})},c.send()})}function gt(e,t){Ae(`DCBrowserExt:Viewer:SignIn:AdobeYolo:${e}:clicked`),chrome.tabs.query({active:!0,currentWindow:!0},function(e){var t=e[0]&&e[0].id;tt("adobeYoloTabsInfo",t,"sessionStorage")}),ke({main_op:"launchJumpUrl",details:{source:e,userGuid:t}},t=>{X._sendMessage({type:"adobeYoloJumpResponse",response:t,source:e},H.origin)})}function ft(e,t,...a){ae?g.storeBufferAndCall(e,t,ne,...a):chrome.tabs.getCurrent(function(n){g.storeBufferAndCall(e,t,n.id,...a)})}function ut(e){X._sendMessage({type:"redirectToAcrobatWeb",response:e},H.origin)}function pt(){ae?chrome.tabs.reload(ne):chrome.tabs.getCurrent(e=>{chrome.tabs.reload(e.id)})}async function wt(e){x()||Je("Convert to PDF : tab stoage does not have acrobatPromotionWorkflow equivalent to createpdf",a.getItem("acrobatPromotionWorkflow")),await lt(e.data.buffer);"webpage_chrome-convert_to_pdf"===b(q).get($)&&Ae("DCBrowserExt:Viewer:WebpageConversion:Success"),ue=null,A(e,Ie,q)}function ht(r,l){switch(l.data.main_op){case"processPreviewPostPDFConversion":wt(l);break;case"directVerbExecutionError":O();break;case"open_in_acrobat":case"fillsign":!async function(t,a){const r={main_op:"open_in_acrobat"};if("fillsign"===a.data.main_op?r.paramName="FillnSign":a.data.paramName&&(r.paramName=a.data.paramName),r.url=a.data.url,r.click_context="pdfviewer",r.timeStamp=Date.now(),r.filename=a.data&&a.data.filename,a.data.fileBuffer){const e=new Blob([a.data.fileBuffer],{type:"application/pdf"});r.dataURL=URL.createObjectURL(e)}if(oe=function(e){"fillsign"===a.data.main_op?t.openInAcrobatResponse("FILLSIGN_IN_DESKTOP_APP",e,a.origin):t.openInAcrobatResponse("OPEN_IN_DESKTOP_APP",e,a.origin),Je(`Open In Acrobat - (${a.data.main_op}) response- ${e}`)},e.getItem("isSharepointFeatureEnabled"))if(qe.isSharePointURL)r.workflow_name="SharePoint",r.isSharePointURL=!0,ke(r,oe);else{const e=await n.checkForSharePointURL(r.url);r.isSharePointURL=e,e&&(r.workflow_name="SharePoint"),ke(r,oe)}else ke(r,oe)}(r,l);break;case"complete_conversion":Ae("DCBrowserExt:Viewer:Verbs:Conversion:Redirection"),function(e){const t={};t.main_op=e.data.main_op,t.conversion_url=decodeURIComponent(e.data.conversion_url),t.timeStamp=Date.now(),ke(t)}(l);break;case"updateLocale":Ae("DCBrowserExt:Viewer:User:Locale:Updated"),e.setItem("viewer-locale",l.data.locale),ke({main_op:"localeChange",locale:l.data.locale}),chrome.tabs.reload();break;case"setInitialLocale":let w=!1;e.getItem("viewer-locale")||(w=!0,e.setItem("viewer-locale",l.data.locale),Ae("DCBrowserExt:Viewer:User:Locale:Initial")),l.data.reloadReq&&w&&chrome.tabs.reload();break;case"error-sign-in":!function(e){const t=n.uuid();a.setItem("csrf",t);const r=new URL(e),o=Oe();o.hash=o.hash+`state=${t}&signInError=true`,r.searchParams.set("redirect_uri",o),chrome.tabs.update({url:r.href,active:!0})}(l.data.url);break;case"deleteViewerLocale":e.getItem("viewer-locale")&&(e.removeItem("viewer-locale"),chrome.tabs.reload());break;case"signin":Ae("DCBrowserExt:Viewer:Ims:Sign:In"),a.setItem("signInSource",l.data.source),a.setItem("signinTouchPointData",JSON.stringify({touchpoint:l.data.tp,allowCommentsInShare:l.data.allowCommentsInShare})),Ae(`DCBrowserExt:Viewer:Ims:Sign:In:${l.data.source}`),ft(l.data.fileBuffer,We,l.data);break;case"googleSignIn":Ae("DCBrowserExt:Viewer:Ims:Sign:In"),Ae(`DCBrowserExt:Viewer:Ims:Sign:In:${l.data.source}`),a.setItem("signInSource",l.data.source),ft(l.data.fileBuffer,je,l.data);break;case"signup":Ae("DCBrowserExt:Viewer:Ims:Sign:Up"),a.setItem("signUpSource",l.data.source),Ae(`DCBrowserExt:Viewer:Ims:Sign:Up:${l.data.source}`),ft(l.data.fileBuffer,We,l.data);break;case"reload_viewer":chrome.tabs.reload();break;case"reload_current_tab":pt();case"upsell_event":!function(e){if(e&&e.url){const a=new URL(decodeURIComponent(e.url));e.returnUrlParams&&t.setItem("rtParams",e.returnUrlParams.toString()),"_blank"===e.target?chrome.tabs.create({url:a.href,active:!0}):chrome.tabs.update({url:a.href,active:!0})}}(l.data);break;case"upsell_remove_urlParams":t.removeItem("rtParams"),t.removeItem("payPalUrl"),a.removeItem("dialog!dropin"),a.removeItem("load!dropin");break;case"fetchLocalRecents":const h=new URL(e.getItem("cdnUrl")).origin;if(l.data.fetchRecents){const e=l.data.showOverlay;!async function(e,t,a=!1){const n=le.getAllItems();e.sendRecentUrl(!0,n,t,a)}(X,h,e)}else X.sendRecentUrl(!0,null,h);break;case"socialSignIn":Ae("DCBrowserExt:Viewer:Ims:Sign:In"),Ae(`DCBrowserExt:Viewer:Ims:Sign:In:${l.data.source}`),a.setItem("signInSource",l.data.source),ft(l.data.fileBuffer,He,l.data);break;case"openRecentFileLink":const I={};I.main_op=l.data.main_op,I.recent_file_url=decodeURIComponent(l.data.recent_file_url),I.file_name=l.data.file_name,ke(I);break;case"updateCurrentURL":!async function(e){const{redirectURL:t,copyToClipboard:a}=e;if(a)try{await navigator.clipboard.writeText(a)}catch(e){}const n=ae?ne:(await chrome.tabs.getCurrent())?.id;chrome.tabs.update(n,{url:t})}(l.data);break;case"saveFileBufferAndReload":ft(l.data.fileBuffer,pt);break;case"userSubscriptionData":if(e.getItem("enableFabForPaidUsers")){const{userSubscriptionData:t,main_op:a}=l.data;(function(e=[]){return e.some(e=>"GenAIServices"===e?.name&&e?.level!==m.free)})(t)&&(e.getItem("enableGenAIFab")||(e.setItem("isGenAIPaidUser",!0),Ae("DCBrowserExt:SidePanel:GenAIPaid:FABEnabled")))}if(ae){ke({eventType:main_op,userSubscriptionData:userSubscriptionData,data:l.data,main_op:main_op},function(e){e&&"showUninstallPopUp"===e.main_op&&X._sendMessage({type:"showUninstallPopUp"},H.origin)})}break;case"uninstall":ae&&ke({main_op:"uninstall",defaultUrl:q});break;case"submit_form":fetch(l.data.resource,l.data.options).then(e=>{X.sendSubmitFormResponse(e.ok,l.origin)}).catch(()=>{X.sendSubmitFormResponse(!1,l.origin)});break;case"ownerShipExperimentShown":e.removeItem("defaultOwnerShipExperiment");break;case"openAcrobatOptions":e.setItem("optionsPageSource",d.VIEWER_PREFERENCES).then(()=>{chrome.runtime.openOptionsPage()}),Ae(`DCBrowserExt:Viewer:ManagePref:clicked:${l.data.source}`);break;case"openOnboardingTutorialFile":const b={};b.main_op=l.data.main_op,b.onboardingDemoFileURL=l.data.onboardingDemoFileURL,b.blobParam=l.data.blobParam,b.pdfURL=l.data.pdfURL,ke(b);break;case"returnToYourFile":const v={};v.main_op=l.data.main_op,v.returnTabId=l.data.returnTabId,v.returnURL=l.data.returnURL,ke(v);break;case"openLocalFileThoughFilePicker":!async function(e,t,a,n,r,o){g.storeFileByHash(t,`chrome-extension://${chrome.runtime.id}/${n}`).then(()=>{const t={};t.main_op=e,t.file_name=a,t.fileURL=n,t.openGenAIAssistantPanel=r,t.openLocalFileSource=o,ke(t)})}(l.data.main_op,l.data.fileBuffer,l.data.file_name,l.data.fileURL,l.data.openGenAIAssistantPanel,l.data.openLocalFileSource);break;case"openExtensionSettings":if("pinToolbar"===l.data.action)chrome.tabs.query({active:!0,currentWindow:!0},function(e){const t=e[0];n.openExtensionSettingsInWindow({tab:t,action:l.data.action})});else{const t=e.getItem("openSettingsInWindow");t?chrome.tabs.query({active:!0,currentWindow:!0},function(t){const a=t[0];e.setItem("lastOpenTabId",a.id),n.openExtensionSettingsInWindow({tab:a,action:l.data.action})}):chrome.tabs.create({url:n.constructUrlWithParams(c,{context:POPUP_CONTEXT.LOCAL_FILE_COACHMARK,autoDismiss:!0}),active:!0},e=>{chrome.windows.update(e.windowId,{focused:!0},()=>{chrome.action.openPopup().catch(e=>console.error(e))})}),U.event(E.LOCAL_FILE_ACCESS_TOUCHPOINT_SETTINGS_OPENED,{VARIANT:t?"InWindow":"InTab"}),e.setWithTTL("LocalFileAccessTouchpointsFromViewer",!0,i),"localFileAccessBannerChallenger"===l.data.variant?e.setWithTTL("LocalFileAccessBannerChallengerTouchpointsFromViewer",!0,i):"localFileAccessBannerControl"===l.data.variant&&e.setWithTTL("LocalFileAccessBannerControlTouchpointsFromViewer",!0,i),ke({main_op:"triggerBufferSave"})}break;case"encryptedWriteFile":({secureString:pe}=l.data),_t(document.title);break;case"showAutoSummaryPreference":e.setItem("autoSummaryEligible",l.data.isEligible);break;case"genAIAutoSummarizeToggledFromViewer":p=l.data,e.getItem("autoSum")!==p.isEnabled&&(e.setItem("autoSum",p.isEnabled.toString()),ke({panel_op:"options_page",requestType:s.OPTIONS_UPDATE_TOGGLE,toggleId:"enableGenAIAutoSummarizeTitle",toggleVal:p.isEnabled}));break;case"launchJump":ft(l.data.fileBuffer,gt,l.data.source,l.data.userGuid);break;case"saveAsEvent":!async function(e){try{if(Ae("DCBrowserExt:Viewer:SaveToMyComputer:"+(ce?"fileHandlerExist":"fileHandlerNotExist")),ce)ge=!1;else{const t={suggestedName:`${e.fileName}.pdf`,types:[{description:"PDF file",accept:{"application/pdf":[".pdf"]}}]};ce=await window.showSaveFilePicker(t),ge=!0,_t(ce?.name)}X._sendMessage({type:"newSaveToLocalResponse",newAsset:ge,updatedFileName:ce?.name},H.origin)}catch(e){ce=null,Je("Save As Handler Error",e),X._sendMessage({type:"newSaveToLocalResponse",error:e},H.origin)}}(l.data);break;case"downloadFile":!async function(e){let t=null,a=null;try{let n=e.fileUrl;const r=e.fileName||j||"untitled";if(!n){const a=new Blob([e.fileBuffer],{type:"application/pdf"});t=URL.createObjectURL(a),n=t}const o=e.silentDownload||!1;a=await chrome.downloads.download({url:n,conflictAction:"uniquify",saveAs:!o,filename:e?.fileNameWithExtension?e?.fileNameWithExtension:`${r}.pdf`}),a&&function(e){const t=a=>{a?.id===e&&(a?.state&&"complete"===a?.state?.current?(X._sendMessage({type:"showDownloadCompletedOnCard"},H.origin),f.info({message:"File downloaded successfully",downloadId:e}),chrome.downloads.onChanged.removeListener(t)):a?.state&&"interrupted"===a?.state?.current&&(chrome.downloads.onChanged.removeListener(t),f.info({message:"File download interrupted",downloadId:e})))};chrome.downloads.onChanged.addListener(t)}(a),f.info({message:"File downloaded",url:n,fileName:r,fileNamefromViewer:e.fileName})}catch(e){Je("downloadFile error",e),X._sendMessage({type:"downloadFileError"},H.origin)}finally{t&&URL.revokeObjectURL(t)}}(l.data);break;case"rememberSaveLocationPreference":!function(t){let a="";t.cloudStorage&&!e.getItem("selectedSaveLocationPreference")?a="PreferenceMigrationSuccess":t.cloudStorage||(a="SaveDialogRememberMe");a&&Ae(`DCBrowserExt:Viewer:ChangeSaveLocationPreference:${a}`);(!t.cloudStorage||t.cloudStorage&&!e.getItem("selectedSaveLocationPreference"))&&(e.setItem("saveLocation",t.saveLocation),e.setItem("selectedSaveLocationPreference",!0),ke({panel_op:"options_page",requestType:s.OPTIONS_UPDATE_TOGGLE,toggleId:"saveLocationPreferenceTitle",toggleVal:t.saveLocation}))}(l.data);break;case"appRenderingDone":Bt();break;case"saveFileBuffer":ft(l.data.fileBuffer);break;case"deleteFileBuffer":const _=a.getItem("bufferTabId");_&&g.deleteDataFromIndexedDB(_),a.removeItem("bufferTabId");case"appRenderingDone":Bt();break;case"writeToLocalSavedFile":!async function(e){try{const t=await ce.createWritable();await t.write(e.fileBuffer),await t.close(),X._sendMessage({type:"newSaveToLocalResponse",newAsset:ge,updatedFileName:ce?.name,isFileWriteStage:!0},H.origin)}catch(e){ce=null,Je("Write to Local File Error",e),X._sendMessage({type:"newSaveToLocalResponse",error:e,isFileWriteStage:!0},H.origin)}}(l.data);break;case"bookmarkWeb":S(l.data.url,ut,Ae);break;case"updateDocumentViewState":!function(e){const{documentViewState:t}=e;le.writeAndSyncWithHistory(q,t)}(l.data);break;case"validateEdgeCertificateForDigitalSignature":o.validateCertificate(l.data).then(e=>X.sendCertificateValidationResponse(e,l.origin));break;case"documentViewThemeChange":!function(t){e.getItem("theme")!==t.data&&(e.setItem("theme",t.theme),ke({panel_op:"options_page",requestType:s.OPTIONS_UPDATE_TOGGLE,toggleId:"appearancePrefTitle",toggleVal:t.theme}));e.getItem("isDarkPageThemeEnabled")!==t.isDarkPageThemeEnabled&&e.setItem("isDarkPageThemeEnabled",t.isDarkPageThemeEnabled)}(l.data);break;case"enableGenAIFeaturesToggledFromViewer":!function(t){e.getItem("egaf")!==t.isEnabled&&(e.setItem("egaf",t.isEnabled.toString()),ke({panel_op:"options_page",requestType:s.OPTIONS_UPDATE_TOGGLE,toggleId:"enableGenAIFeaturesTitle",toggleVal:t.isEnabled}))}(l.data);break;case"genAIEligible":!function(t){e.setItem("genAIEligible",t?.isEligible?.toString()),Ue(t?.isEligible||!1)}(l.data);break;case"rrvLayerRemoved":chrome.runtime.sendMessage({main_op:"rrvLayerRemoved",tabId:l.data.tabId,target:"offscreen"});break;case"setFloodgateResponseFromViewer":chrome.runtime.sendMessage({main_op:"handleViewerFloodgateResponse",fgResponse:l.data.fgResponse});break;case"getSignedInCachedffResponse":u=l.data.userId,X._sendMessage({type:"signedInCachedffResponse",ffResponse:e.getItem(`ffResponse_${u}`)||"{}"},H.origin);break;case"changeDefaultViewershipForSurface":chrome.runtime.sendMessage({...l.data});break;case"openWhatsNew":ke({main_op:"openWhatsNew",source:l.data.source});break;case"sendAnalytics":Ae(l?.data?.event);break;case"openCollectionTab":chrome.runtime?.sendMessage({...l.data});break;case"upsell_dialog_close":V(l)}var u,p}function It(e){try{const t=new TextDecoder("utf-8").decode(e.buffer);let a=!1;-1!=t.indexOf("Linearized 1")?a=!0:-1!=t.indexOf("Linearized")&&Ae("DCBrowserExt:Viewer:Linearization:Linearized:Version:Other"),X._sendMessage({type:"Linearization",linearized:a},H.origin)}catch(e){Ae("DCBrowserExt:Viewer:Linearization:Linearized:Detection:Failed"),Je("Linearization Detection failed",e)}}function bt(t,a,n,r){n.then(n=>{const o=n.downLoadEndTime,i=n.buffer;n.buffer.byteLength;t.preview("preview",i,l,j,r,o,a.origin),X._sendMessage({type:"NavigationStartTime",time:window.performance&&window.performance.timing&&window.performance.timing.navigationStart},H.origin),!0===e.getItem("isSaveLocationPrefEnabled")&&X._sendMessage({type:"changeSaveLocationPreference",saveLocation:e.getItem("saveLocation"),onLoad:!0},H.origin)}).catch(e=>(Be("DCBrowserExt:Viewer:Error:FallbackToNative:FileDownload:Failed",{tabURL:q,source:b(q).get($)}),De(!1,null,"file_download_failed"))).finally(()=>{e.removeItem("sessionStarted")})}class vt{constructor(){this.request={main_op:"analytics"}}analytics=e=>{this.request.analytics||(this.request.analytics=[]),this.request.analytics.push([e])};sendAnalytics=()=>{ke(this.request)}}function _t(e){e&&(document.title=e+pe)}const yt=(t,a,n)=>{const r=n?"viewerStorage":"viewerStorageAsync",o=e.getItem(r)||{};o[t]=a,e.setItem(r,o)},St=(t,a=null)=>{if(null!==a){const n=a?"viewerStorage":"viewerStorageAsync",r=e.getItem(n)||{};delete r[t],e.setItem(n,r)}else{const a=e.getItem("viewerStorage")||{},n=e.getItem("viewerStorageAsync")||{};delete a[t],delete n[t],e.setItem("viewerStorage",a),e.setItem("viewerStorageAsync",n)}};function Lt(t,n,r,o){return i=>{try{if(i.data&&i.origin&&Fe(i.origin)&&(e=>{try{return e&&e.source&&e.source.top.location.origin==="chrome-extension://"+chrome.runtime.id}catch(e){return!1}})(i)){if(i.data.main_op)return ht(t,i);switch(i.data.type){case"ready":if(window.hideLoader&&window.hideLoader(),ae?async function(t,n,r,o){let i=new vt;J=!0;let s=q;if(we){const e=q.substring(q.indexOf("blob"));s=Ie+"?pdfurl="+encodeURIComponent(e)+"&pdffilename="+encodeURIComponent(j)}document.title=j;const c=se.getHeaderValue("accept-ranges"),d=!a.getItem("bufferTabId")&&c&&"bytes"===c.toLowerCase()?"true":"false";Dt(),t.sendFileMetaData("metadata",K,l,d,s,encodeURIComponent(j),n.origin,!1),Pt(),r&&r.then(e=>{t.sendInitialBuffer("initialBuffer",e.startTime,e.endTime,e.buffer,n.origin),It(e)}).catch(e=>{t.sendInitialBuffer("initialBuffer",0,0,-1,n.origin),i.analytics("DCBrowserExt:Viewer:Error:Linearization:InitialBufiled")}),e.removeItem("isReload"),e.removeItem("isBackForward");const m=window.performance&&window.performance.timing&&window.performance.timing.navigationStart,g=st(),f=await g;if(we){const a=new URL(e.getItem("cdnUrl"));bt(t,n,mt(X,!1,a.origin),m)}else f.buffer?bt(t,n,g,m):(fetch(o.streamUrl).then(e=>{let a=0;return new Response(new ReadableStream({start(r){const o=e.body.getReader();!function e(){o.read().then(({done:o,value:i})=>{o?r.close():(a+=i.byteLength,t.sendProgress("progress",l,a,n.origin),r.enqueue(i),e())}).catch(e=>{r.error(e)})}()}}))}).then(e=>e.arrayBuffer()).then(a=>{l=a.byteLength,ct(a),t.preview("preview",a,a.byteLength,j,m,(new Date).getTime(),n.origin),X._sendMessage({type:"NavigationStartTime",time:window.performance&&window.performance.timing&&window.performance.timing.navigationStart},n.origin),!0===e.getItem("isSaveLocationPrefEnabled")&&X._sendMessage({type:"changeSaveLocationPreference",saveLocation:e.getItem("saveLocation"),onLoad:!0},n.origin)}).catch(e=>(i.analytics("DCBrowserExt:Viewer:Error:FallbackToNative:FileDownload:Failed"),De(!1,null,"mime_file_download_failed"))),i.sendAnalytics());Je("Viewer loaded")}(t,i,r,n):function(e,t,n,r,o){J=!0;let i=q;if(we){const e=q.substring(q.indexOf("blob"));i=Ie+"?pdfurl="+encodeURIComponent(e)+"&pdffilename="+encodeURIComponent(j)}const s=!a.getItem("bufferTabId")&&Re("chunk")||"false",c=window.performance.getEntriesByType("navigation").map(e=>e.type).includes("reload"),d=window.performance.getEntriesByType("navigation").map(e=>e.type).includes("back_forward");Dt(),e.sendFileMetaData("metadata",K,l,s,encodeURI(i),encodeURIComponent(j),t.origin,c||d),Pt(),n?n.then(a=>{e.sendInitialBuffer("initialBuffer",a.startTime,a.endTime,a.buffer,t.origin),It(a)}).catch(a=>{e.sendInitialBuffer("initialBuffer",0,0,-1,t.origin)}):e.sendInitialBuffer("initialBuffer",0,0,-1,t.origin),x()?B(e,t,r,o):bt(e,t,r,o),Je("Viewer loaded")}(t,i,r,n,o),ke({main_op:"getUserInfoFromAcrobat"},e=>{X._sendMessage({type:"adobeYoloUserData",...e},H.origin)}),i.data.visitorID){const t=e.getItem("viewerVisitorID");e.setItem("viewerVisitorID",i.data.visitorID),t&&t!==i.data.visitorID&&Ae("DCBrowserExt:Analytics:viewerVisitorID:MCMID:Changed")}ke({main_op:"getWhatsNewAutoOpenEligibility"},(e={})=>{X._sendMessage({type:"whatsNewAutoOpenEligibility",eligible:!!e.eligible},H.origin)});break;case"getFileBufferRange":!function(e,t){let a={url:q};R.getFileBufferRange(a,e.data.range).then(a=>{te||(te=!0),t.sendBufferRanges("bufferRanges",`${e.data.range.start}-${e.data.range.end}`,a.buffer,e.origin)}).catch(a=>{Ae("DCBrowserExt:Viewer:Error:Linearization:Range:Failed"),t.sendBufferRanges("bufferRanges",`${e.data.range.start}-${e.data.range.end}`,-1,e.origin)})}(i,t);break;case"previewFailed":ee||(Ae("DCBrowserExt:Viewer:Error:FallbackToNative:Preview:Failed"),ee=!0,De(!1,null,"preview_failed"));break;case"lastUserGuid":e.setItem("lastUserGuid",i.data.value);break;case"signin":Ae("DCBrowserExt:Viewer:Ims:Sign:In"),We();break;case"signout":Ae("DCBrowserExt:Viewer:Ims:Sign:Out"),e.removeItem("viewer-locale"),e.removeItem("userDetailsFetchedTimeStamp"),e.removeItem("discoveryExpiryTime"),e.removeItem("viewer-locale"),ft(i.data.fileBuffer,$e);break;case"googleAppsPrintShown":a.setItem("googleAppsPrint","false"),Ae("DCBrowserExt:Viewer:GoogleApps:Print:Shown");break;case"signInExperimentShown":chrome.tabs.query({active:!0,currentWindow:!0},function(t){const a=t[0],n=(new Date).getTime();e.setItem("signInExperimentShown",JSON.stringify({currTabId:a.id,timestamp:n}))});break;case"disableViewer":e.setItem("pdfViewer","false"),chrome.tabs.reload();break;case"signInExperimentClosed":case"signInExperimentSkipped":e.setItem("signInExperimentSuppressed","true");break;case"enableBeta":e.setItem("betaOptOut","false"),chrome.tabs.reload();break;case"disableBeta":e.setItem("betaOptOut","true"),chrome.tabs.reload();break;case"updateTitle":_t(i.data.title);break;case"viewer_set_item":yt(i.data.key,i.data.value,i.data.startup);break;case"viewer_remove_item":St(i.data.key,i.data.startup);break;case"storage_sync_to_async_cleanup":ke({main_op:"storage-migration-sync-to-async-cleanup"});break;case"adminStatus":e.setItem("isAdminUser",i.data.isAdmin);break;case"toggleGenAIFab":!function(t){const a=null==t.value?"false":`${t.value}`;e.setItem("enableGenAIFab",a),ke({panel_op:"options_page",requestType:s.OPTIONS_UPDATE_TOGGLE,toggleId:"genAIFabPreferenceTitle",toggleVal:a})}(i.data)}}}catch(e){Ae("DCBrowserExt:Viewer:Error:MessageHandler:Unknown")}}}function Ut(){if(!Y)return Ae("DCBrowserExt:Viewer:Error:Handshake:TimedOut"),De(!1,null,"handshake_timeout"),!1}const Et=async t=>{try{e.getItem("enableCSRF")&&Ke();const n=se.getHeaderValue("content-length");l=n;const r=se.getHeaderValue("accept-ranges"),o=r&&"bytes"===r.toLowerCase();q=t.originalUrl,await at();const i=new URLSearchParams(new URL(q).search).get("blob-uri");h(i,q)?j="Acrobat Tutorial.pdf":j||(j=function(){let e;const t=se.getHeaderValue("content-disposition");if(t&&/\.pdf(["']|$)/i.test(t)){const a=/filename[^;=\n\*]?=((['"]).*?\2|[^;\n]*)/.exec(t);null!=a&&a.length>1&&(e=a[1].replace(/['"]/g,""))}return e||(e=nt(q)),decodeURIComponent(e)}());const s={url:q},c=new URL(e.getItem("cdnUrl"));H||(H=c);let d=null;const m="false"!==Re("linearization")&&!a.getItem("bufferTabId");m&&o&&n>0&&(d=R.getFileBufferRange(s,{start:0,end:1024})),window.addEventListener("message",Lt(X,t,d)),Ct(),setTimeout(Ut,25e3)}catch(e){Je("InitMimeHandlerScript failed",e),De(!1,null,"mime_handler_init_failed")}},Rt=e=>b(e).has($)||Re($)?.length>0,kt=e=>"https://drive.usercontent.google.com"===e?.origin&&e?.searchParams?.has($),Tt=async()=>{try{if(e.getItem("enableCSRF")&&Ke(),!1===fe)return void(z=!1);await at();const t=Re("clen")||-1,n=Re("chunk")||!1,r="false"!==Re("linearization")&&!a.getItem("bufferTabId"),o={url:q},i=(new Date).getTime(),s=new URL(e.getItem("cdnUrl")),c=new URLSearchParams(new URL(q).search).get("blob-uri");h(c,q)?j="Acrobat Tutorial.pdf":(j=Re("pdffilename"),j=j?encodeURIComponent(j):nt(q)),document.title=decodeURIComponent(j),H||(H=s);let l=null;const d=r&&n&&t>0;d&&(l=R.getFileBufferRange(o,{start:0,end:1024}));const m=(await chrome.tabs.getCurrent())?.id,g=st(m),f=(await g).buffer?g:mt(X,d,s.origin);window.addEventListener("message",Lt(X,f,l,i)),setTimeout(Ut,25e3),(()=>{try{if(q&&Rt(q)&&!a.getItem("acrobatPromotionWorkflow")){const t=Te(new URL(q)?.search,$)||Re($),a=Ze(t);Be(`DCBrowserExt:Viewer:ExtnViewerPdfOpened:${t}`,{experimentEnablementStatus:e.getItem(`${a}-pdf-default-viewership`)})}}catch(e){}})()}catch(e){Je("InitScript failed",e),De(!1,null,"init_script_failed")}};function Pt(){if(a.getItem("signInAction")){const e=a.getItem("signInAction");X._sendMessage({type:"signInInformation",action:e,source:"signIn"===e?a.getItem("signInSource"):a.getItem("signUpSource")},H.origin),a.removeItem("signInSource"),a.removeItem("signUpSource"),a.removeItem("signInAction")}}async function Ct(){chrome.storage.onChanged.addListener((t,a)=>{"local"===a&&Object.entries(t).forEach(([t,{newValue:a}])=>{switch(t){case"theme":X._sendMessage({type:"themeChange",theme:a},H.origin);break;case"ANALYTICS_OPT_IN_ADMIN":{const t="false"!==e.getItem("logAnalytics"),n="false"!==a;X._sendMessage({type:"analyticsTrackingChange",value:t&&n},H.origin);break}case"saveLocation":X._sendMessage({type:"changeSaveLocationPreference",saveLocation:a},H.origin);break;case"isDarkPageThemeEnabled":X._sendMessage({type:"darkPageThemeChange",isDarkPageThemeEnabled:a},H.origin);break;case"egaf":X._sendMessage({type:"enableGenAIFeaturesToggled",enableGenAIFeatures:a},H.origin);break;case"akamai":ke({main_op:"reRegisterUninstallUrl"})}})}),await async function(){return G=await o.isInstalledViaUpsell(),G}(),X._sendMessage({type:"setAsyncStorage",storage:e.getItem("viewerStorageAsync")},H.origin),ke({main_op:"viewer-startup",url:q,startup_time:Date.now(),viewer:!0},e=>{qe.isSharePointURL=!!e.isSharePointURL,qe.isSharePointFeatureEnabled=!!e.isSharePointEnabled,qe.isFrictionlessEnabled=!!e.isFrictionlessEnabled,qe.featureFlags=e.featureFlags,qe.isFillAndSignRegisteryEnabled=e.isFillnSignEnabled;const t=Oe().href;X.sendStartupConfigs(t,H.origin)}),ke({main_op:"get-features&groups",cachePurge:"LAZY"},e=>{X._sendMessage({type:"featureGroups",featureGroups:e.featureGroups,featureFlags:e.featureFlags,ffResponse:e.ffResponse},H.origin)}),ae?setTimeout(()=>tt("loadedTabsInfo",ne),2e3):ke({main_op:"updateLoadedTabsInfo"}),we||"preview"===a.getItem("acrobatPromotionWorkflow")||le.writeAndSyncWithHistory(q,{filename:j,lastVisited:Date.now()})}function Dt(){X._sendMessage({type:"fgFlagsResponse",ffResponse:e.getItem("ffResponse_anon")||"{}",anonUserUUID:e.getItem("anonUserUUID")},H.origin)}function Ft(e){ke({main_op:"caret_mode_toggle_handler",toggleCaretModeValue:e})}function At(t,a,n){switch(t.panel_op&&!0===t.reload_in_native&&(delete t.is_viewer,chrome.tabs.reload(t.tabId)),t.content_op){case"showLocalFileAccessToast":if(!t.tabId||t.tabId===e.getItem("lastOpenTabId")){const e=["CLP","LSC"],a=N().filter(t=>e.includes(t));X._sendMessage({type:"showLocalFileAccessToast",activeLocalExperiments:a,action:t.action},H.origin)}break;case"rapidRenditionResponse":X._sendMessage({type:"rapidRenditionResponse",pageRendition:t.pageRendition,perfMarker:t.perfMarker},H.origin);break;case"rapidRenditionError":X._sendMessage({type:"rapidRenditionError",error:t.error},H.origin);break;case"removeAnonGenAIProvisionResponse":X._sendMessage({type:"removeAnonGenAIProvisionResponse"},H.origin)}switch(t.main_op){case"relay_to_content":if("dismiss"===t.content_op){delete t.content_op,delete t.reload_in_native;let e=document.getElementById("__acrobatDialog__");return void(e&&(e.remove(),e=null))}"caret_mode_toggle_handler"===t.content_op&&X._sendMessage({type:"toggleCaretMode",toggleCaretModeValue:t.status},H.origin);break;case"reset":X._sendMessage({type:"toggleAnalytics",logAnalytics:t.analytics_on},H.origin);break;case"showUninstallPopUp":X._sendMessage({type:"showUninstallPopUp"},H.origin);break;case"jumpUrlSuccess":(!ae||t.tabInfo&&t.tabInfo.includes(ne))&&X._sendMessage({type:"adobeYoloJumpUrlSuccess"},H.origin);break;case"triggerBufferSave":X._sendMessage({type:"triggerBufferSave"},H.origin);break;case"downloadFileSuccess":X._sendMessage({type:"downloadFileSuccess"},H.origin);break;case"openViewerAIAssistant":X._sendMessage({type:"openViewerAIAssistant"},H.origin);break;case"isGenAIEligibleInCDN":if(t.activeTabId==de)return Le.then(n),!0}return!1}function Bt(){const t=e.getItem("userState");let a=!1;if(void 0!==t?.rvu&&(a=!0),!0!==t.rvu){const t={rvu:a};e.setItem("userState",t)}}document.addEventListener("DOMContentLoaded",function(e){const t=(new Date).getTime();let a=window.setInterval(function(){(function(){const e=document.getElementById("dc-view-frame");return e&&e.contentWindow&&1===e.contentWindow.length}()||(new Date).getTime()-t>15e3)&&(window.clearInterval(a),e.call(this))},200)}(function(){const e=document.getElementById("dc-view-frame");e&&e.contentWindow&&e.contentWindow.focus()})),window.onerror=e=>{f.error({message:"Viewer errored out",error:e})},window.addEventListener("unhandledrejection",e=>{const t=(e=>{if(e instanceof Error)return e?.message||e?.toString?.();if("string"==typeof e)return e;if("object"==typeof e&&null!==e)try{return JSON.stringify(e)}catch(t){return String(e)}return String(e)})(e.reason);t?.includes("the message channel closed before a response was received")||f.error({message:"Viewer unhandled promise rejection",reason:t,stack:e.reason?.stack})}),void 0!==chrome.runtime&&(le=new L,o.isMimeHandlerAvailable().then(async function(t){if(chrome.runtime.onMessage.addListener(At),t){ae=!0,e.getItem("sessionStarted")||(e.setItem("sessionId",n.uuid()),e.setItem("sessionStarted",!0));let t=await o.getStreamInfo()||{};if(se=new y(t.responseHeaders),ne=t.tabId,0===Object.keys(t).length){const e=new URLSearchParams(window.location.search),a=e.get("pdfurl"),n=new URL(a);if(n.protocol===_e){j=e.get("pdffilename");if(await g.hasKey(`chrome-extension://${chrome.runtime.id}/${n.href}`)){const e=await g.getFileByHash(`chrome-extension://${chrome.runtime.id}/${n.href}`);T(),we=!0,z=!0,se=new y({"content-type":"application/pdf","content-length":e.byteLength}),t={mimeType:"application/pdf",originalUrl:`chrome-extension://${chrome.runtime.id}/${n.href}`,responseHeaders:se},ne=(await chrome.tabs.getCurrent())?.id}}}let a=await ke({main_op:"check-is-google-print"});re=a&&a.isGooglePrint,ie=await o.caretModeStatus(),o.addCaretModeListener(Ft),ke({main_op:"viewer-preview",startup_time:Date.now(),viewer:!0},()=>Et(t));const r=se.getHeaderValue("content-length"),i=se.getHeaderValue("accept-ranges"),s=i&&"bytes"===i.toLowerCase();r>0&&s&&ke({main_op:"setupWorkerOffscreen",pdfURL:t.originalUrl,pdfSize:+r,acceptRanges:s});e.getItem("firstOpenedTabId")||e.setItem("firstOpenedTabId",ne)}else!function(){const e=new URL(window.location.href);if(e?.searchParams?.has("pdfurl")){const t=e.searchParams.get("pdfurl"),a=new URL(t);if(a?.searchParams.has("uuid")&&sessionStorage.getItem(a?.searchParams?.get("uuid"))){e.searchParams.set("pdfurl",sessionStorage.getItem(a?.searchParams?.get("uuid")));const t=Te(document.location.search,"pdffilename");history.replaceState({},t,e)}}}(),await Pe(),Tt(),Ct()}))}();