/*************************************************************************
* 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{ajax as e,ajaxError as t,each as r,Deferred as n,extend as o,param as a}from"./polyfills.js";import{SETTINGS as s}from"./settings.js";import{validFrictionlessLocales as i,validFrictionlessOCRLocales as c,validFrictionlessChatPdfLocales as u,OFFSCREEN_DOCUMENT_PATH as l}from"../common/constant.js";import{dcLocalStorage as m}from"../common/local-storage.js";var h=["http","https","ftp","file","blob","data","filesystem","drive"],f=chrome.runtime.getURL("/");let d;export const util={extend:o,getFrictionlessLocale:function(e){return i[e]||i.en},getFrictionlessLocaleChatPdf:function(e){return u[e]},getFrictionlessLocaleOcrPdf:function(e){return c[e]},isChrome:function(){return!0},isLocalFileUrl:e=>e.startsWith("file:///")&&(e.endsWith(".pdf")||e.endsWith(".PDF")),isEdge:function(){return navigator.userAgentData?navigator.userAgentData.brands.some(e=>"Microsoft Edge"===e.brand):navigator.userAgent.includes("Edg/")},isChromeOnlyMessage:function(e){return-1!==["web2pdfMissingMac","web2pdfFrictionlessUrl","web2pdfBadVersion","pdfOwnershipExploreAcrobat","pdfOwnershipPromptContent","LearnMoreURL"].indexOf(e)},getBrowser:function(){return this.isEdge()?2:1},stackDelimiter:function(){return"\n"},Deferred:n,each:r,ajax:e,ajaxError:t,param:a,newBlob:function(e){return new Blob(e)},newFormData:function(){return new FormData},newXHR:function(){return new XMLHttpRequest},createTab:(e,t,r={})=>t?chrome.tabs.create({url:e,active:!0,...r},t):chrome.tabs.create({url:e,active:!0,...r}),isDevEnv:function(){var e=n();return chrome.management.getSelf(function(t){e.resolve("development"===t.installType)}),e.promise()},closeWindow:function(e){chrome.windows.remove(e.id)},getTranslation:function(e,t){if(e)return this.isChromeOnlyMessage(e)&&this.isEdge()&&(e+="Edge"),t?chrome.i18n.getMessage(e,t):chrome.i18n.getMessage(e)},sendMessage:function(e,t,r){chrome.tabs.sendMessage(e.tabId,e,r)},consoleLog:function(...e){s.DEBUG_MODE&&console.log(...e)},consoleLogDir:function(...e){s.DEBUG_MODE&&console.dir(...e)},consoleError:function(...e){s.DEBUG_MODE&&console.error(...e)},arrayBufferToSHA256:async function(e){const t=await(self.crypto?.subtle?.digest("SHA-256",e));return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")},stringToSHA256:function(e){return this.arrayBufferToSHA256((new TextEncoder).encode(e))},atob16:function(e){var t,r=atob(e),n=[];for(t=0;t<r.length;t+=2)n.push(String.fromCharCode(r.charCodeAt(t)+256*r.charCodeAt(t+1)));return n.join("")},removeQueryParams:function(e){const t=e.split("?");return null!=t?t[0]:e},parseExtensionURL:function(e){var t=(e=e.substring(f.length)).search(/:|%3A/i);if(-1!==t){var r=e.slice(0,t).toLowerCase();return h.includes(r)?(":"===(e=e.split("#")[0]).charAt(t)&&(e=encodeURIComponent(e)),e):void 0}},isViewerURL:function(e){if(e)try{var t=e.substring(f.length),r=t.search(/:|%3A/i);if(-1!==r){var n=t.slice(0,r).toLowerCase();if(h.includes(n))return!0}return e.startsWith(`chrome-extension://${chrome.runtime.id}/viewer.html`)}catch(e){}return!1},uuid:function(){try{let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){let r=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"===t?r:3&r|8).toString(16)})}catch(e){return Math.random()}},sleep:e=>new Promise(t=>setTimeout(t,e)),verCmp:(e,t)=>e.localeCompare(t,void 0,{numeric:!0,sensitivity:"base"}),isAcrobatAvailable:e=>!(0==e||1==e||e===s.READER_VER||e===s.ERP_READER_VER),mimeReloadAllTabs:()=>{const e=m.getItem("loadedTabsInfo"),t=e?.tabsInfo||[];chrome.tabs.query({},e=>{e.forEach(({id:e})=>{t.includes(e)&&chrome.tabs.reload(e)});const r=m.getItem("settingsWindow");r&&setTimeout(()=>{chrome.tabs.remove(r?.id),m.removeItem("settingsWindow"),chrome.tabs.query({active:!0,currentWindow:!0},e=>{chrome.runtime.sendMessage({content_op:"showLocalFileAccessToast",tabId:e[0].id,action:r?.action})})},1e3)}),m.removeItem("loadedTabsInfo")},isBrowserVersionGreaterThan116:()=>{try{const e=navigator.userAgent.match(/Chrome\/([0-9]+)/)||["0","0"];return!!(e&&e.length>=2)&&+e[1]>=116}catch(e){return!1}},hasOffscreenDocument:async()=>{if("getContexts"in chrome.runtime){const e=await chrome.runtime.getContexts({contextTypes:["OFFSCREEN_DOCUMENT"]});return Boolean(e.length)}return(await clients.matchAll()).some(e=>e.url.includes(l))},setupOffscreenDocument:async e=>{try{if(await util.hasOffscreenDocument())return;if(!d){d=!0;let t=[chrome.offscreen.Reason.IFRAME_SCRIPTING],r="Load iframe in offscreen document";util.isBrowserVersionGreaterThan116()&&(t=[chrome.offscreen.Reason.IFRAME_SCRIPTING,chrome.offscreen.Reason.BLOBS],r="Load iframe in offscreen document and interact with object URLs"),await chrome.offscreen.createDocument({url:e,reasons:t,justification:r})}}finally{d=!1}},isAcrobatOrigin:e=>/^https:\/\/((dev|stage)+\.){0,}acrobat\.adobe\.com?$/.test(e),isAdobeOrigin:e=>/^https:\/\/www\.((dev01|stage)+\.){0,}adobe\.com?$/.test(e),checkOS:async()=>{const e=await chrome.runtime.getPlatformInfo();var t;s.OS=e.os,s.CHROME_VERSION=0,s.EXTENSION_VERSION=0;try{(t=navigator.userAgent.match(/Chrome\/([0-9]+)/))&&(s.CHROME_VERSION=+t[1])}catch(e){}try{s.EXTENSION_VERSION=chrome.runtime.getManifest().version}catch(e){}return e.os},generateUUID:()=>{try{let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){let r=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"===t?r:3&r|8).toString(16)})}catch(e){return Math.random()}},getWelcomePDFUrl:e=>{let t=chrome.i18n.getMessage("@@ui_locale");["ca","da","en_GB","es","fi","hr","it","ko","nl","pt_BR","ru","sl","tr","zh_CN","cs","de","en_US","eu","fr","hu","ja","nb","pl","ro","sk","sv","uk","zh_TW"].includes(t)||(t="en_US");return`${e}/dc-chrome-extension/mv/${t}/Acrobat-for-${util.isEdge()?"Edge":"Chrome"}.pdf`},constructUrlWithParams(e,t={}){const r=e.split("#"),n=r[0],o=r[1],a=new URL(n);return Object.entries(t).forEach(([e,t])=>{a.searchParams.set(e,t)}),o?`${a.toString()}#${o}`:a.toString()},createLocalFilePromptPopup:async(e,t={},r)=>new Promise((n,o)=>{chrome.tabs.query({active:!0,currentWindow:!0},async a=>{try{const s=a[0];if(!s)return void o(new Error("No active tab found"));const i=await chrome.windows.get(s.windowId),c=Math.min(Math.round(.8*i.height),900),u=Math.min(Math.round(.9*i.width),1550),l=Math.round(.5*(i.height-c)+i.top),m={height:c,width:u,left:Math.round(.5*(i.width-u)+i.left),top:l,focused:!0,type:"normal",url:e,...t};chrome.windows.create(m,e=>{r&&r(e),n(e)})}catch(e){o(e)}})}),async createTabWithOptionalTracking(e,t=null,r=12e4){try{const n=await chrome.tabs.create({url:e});return t&&m.setWithTTL(t,n.id,r),{status:"success",tabId:n.id}}catch(e){return{status:"error",message:e?.message}}},isAcrobatTouchPointEnabled(e){const t=m.getItem(e);if(""!==t&&null!=t)return"false"!==t;const r=m.getItem("acrobat-touch-points-in-other-surfaces");return""===r||null==r||"false"!==r}};