/*************************************************************************
* 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{analytics as e,events as t}from"../../common/analytics.js";import{dcLocalStorage as o,dcSessionStorage as a}from"../../common/local-storage.js";import{loggingApi as n}from"../../common/loggingApi.js";import{common as s}from"../../sw_modules/common.js";import{EXPRESS as i}from"../../sw_modules/constant.js";import{Deferred as r}from"../../sw_modules/polyfills.js";import{PromiseTimeout as c}from"../../sw_modules/TimeoutPromise.js";import{util as l}from"../../sw_modules/util.js";import{verbNameToIntent as p,imageUrlToBase64 as d,getExpressSession as m}from"../../sw_modules/express.js";(async()=>{const g="expressPluginIframe";let u,E,h,f,w,_,T,y,b,S,D,x,v,R,I,A,L,U,C=["image/jpeg","image/png","image/webp"],M={},O=[];function P(e){return e?.message?.includes("Cannot access contents of url")?"Error: Cannot access contents of url. Extension manifest must request permission to access this host.":e}function k(t,o){O.includes("swAnalytics")?chrome.runtime.sendMessage({main_op:"analytics",analytics:[[t,o]]}):e.event(t,o)}async function B(e){const t=document.createElement("iframe");t.setAttribute("src",u),t.setAttribute("id",g),t.setAttribute("allowfullscreen","true"),t.setAttribute("style","position:fixed; top:0; left:0; bottom:0; right:0; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"),document.body.appendChild(t),L=r(),A=c(L.promise(),e),await A.catch(e=>{throw t.remove(),e})}async function V(e=1,t=1e4){x=Date.now();let o=0;for(;o<e;)try{await B(t);break}catch(t){o++,o===e?(N(),F(),H("embed sdk ready flow "+t.toString())):n.error({message:`Error injecting express plugin iframe. Retrying ${o} of ${e}. Error: ${t.toString()}`})}}function N(){const e=document.getElementById("loaderId");e&&e.parentNode&&e.parentNode.removeChild(e)}function j(){chrome.runtime.sendMessage({main_op:"removeSessionFromUnloadedExpressSessions",touchpoint:_?.touchpoint,domain:w})}function F(e,t){let o="525px";if(t){const a=t.cause?.status;_.touchpoint?.startsWith("chatgpt")&&403===a&&(e="sessionExpired",o="600px")}let a=chrome.runtime.getURL("browser/js/failToast.html");e&&(a+="?errorType="+e);var n=$("#expressAcrobatExtensionIframe");0===n.length?(n=$("<iframe>")).attr("id","expressAcrobatExtensionIframe").css({border:"0px","z-index":2147483647,position:"fixed",width:o,height:"50px",display:"block",margin:"auto",background:"transparent","color-scheme":"auto",bottom:"50px",right:"calc(50% - 250px)","border-radius":"4px"}).attr("src",a).appendTo("html"):"none"===n.css("display")&&n.css({display:"block"})}function H(e){e=P(e);const o=e.cause?.status;j(),k(t.EXPRESS_EXECUTE_VERB_FAILED,{VERB:f,eventContext:e.toString(),expressTouchpoint:_.touchpoint,domain:w,...o&&{dvDisableSessionCount:o}}),n.error({message:"Error received in express flow",error:e.toString()})}function W(e,t){const a=[{id:"extension_download",label:l.getTranslation("expressExportOptionsDownloadLabel"),action:{target:"publish",closeTargetOnExport:!1},style:{uiType:"button"}}],n={gmailNativeViewer:"gmail",whatsappPreview:"whatsapp",whatsappHover:"whatsapp_hover_cta",ContextMenu:"webpage",googleImagePreview:"google-image",gmailMessageView:"gmail_hover_cta",gdriveNativeViewer:"gdrive",facebookPreview:"facebook",chatgptPreview:"chatgpt",chatgptChatView:"chatgpt_chatview",chatgptWebImagesPreview:"chatgpt_webimagespreview",outlookNativeViewer:"outlook",outlookAttachmentView:"outlook_attachment_view"}[_?.touchpoint]||"Unknown",r=t.sort(),c=_?.pageDomain;return{type:"LAUNCH_MODULE",data:{hostInfo:{clientId:s.getViewerIMSClientId(),appName:"Adobe Acrobat Extension",coiEnabled:_?.coiEnabled},intent:"edit-image",component:"MODULE",configParams:{locale:l.getFrictionlessLocale(chrome.i18n.getMessage("@@ui_locale")),env:s.getEnv()},appConfig:{allowedFileTypes:["image/png"],metaData:{touStatus:o.getItem(i.TOU_ACCEPTED),workflowStartTimeStamp:y,siteHeaderMap:{..._?.coepHeaderValue&&{"cross-origin-embedder-policy":_?.coepHeaderValue},..._?.coopHeaderValue&&{"cross-origin-opener-policy":_?.coopHeaderValue}}},publishModalTitle:l.getTranslation("expressPublishModalTitle"),inlineTOUConsent:!0,openPaywallInNewTab:!0,analyticsData:{hostAppTrigger:n,hostAnalyticsTestIds:r,hostAppDomain:c},convertUnsupportedImages:!0,appVersion:"2"},containerConfig:{showExpressIconWithText:!0,showDarkerBackgroundForLoader:!1},docConfig:e,exportConfig:a}}}function K(){const e=chrome.runtime.sendMessage({main_op:"getFloodgateFlag",flag:"dc-cv-express-nba"}),o=chrome.runtime.sendMessage({main_op:"getExperimentCodes"});Promise.all([h,e,o]).then(([e,o,a])=>{let s=e.base64data;b=e.imageDownloadTime,S=s.length;const r={"data:image/jpeg;":["data:binary/octet-stream;","data:application/octet-stream;","data:image/jpg;"],"data:image/png;":["data:img/png;"]};for(let e of Object.keys(r))for(let t of r[e])s=s.replace(t,e);const c=s.substring(s.indexOf(":")+1,s.indexOf(";"));if(function(e){return C.includes(e)}(c)){const e={asset:{data:s,dataType:"base64",type:"image"}};f!==i.VERBS.EDIT_IMAGE&&(e.intent=p(f));let t=W(e,a);o&&(t.data.appConfig.showNextBestActionDialog=!0);const n=document.getElementById(g);D=Date.now()-y,n.contentWindow.postMessage(t,E.origin)}else j(),N(),F("unsupportedFileType"),k(t.EXPRESS_UNSUPPORTED_FILE_TYPE,{VERB:f,eventContext:c,domain:w,expressTouchpoint:_.touchpoint}),n.error({message:"Error received in express flow",error:"Unsupported image type",fileType:c})}).catch(e=>{N(),F(void 0,e),H(e)})}try{if(await o.init(),await a.init(),function(){const e=o.getItem("env");s.reset(e),u=s.getExpressURLs().pluginUrl,E=new URL(u);const t=new URLSearchParams(window.location.search);if(T="true"===t.get("precache"),T)return;const a=t.get("sessionId");if(_=m(a),!_)throw new Error("invalid sessionId");M=_.errorHandlingConfig,O=Object.keys(M).filter(e=>M[e]),h=async function(e){const t=O.includes("imgFetchRetry")?M.imgFetchRetry?.maxRetries??3:1;let o=0;for(;o<t;)try{return await d(e,O.includes("offscreenFetch"))}catch(e){if(o++,o===t)throw e;n.error({message:`Error fetching image. Retrying ${o} of ${t}. Error: ${P(e)}`})}}(_.imageURL),f=_.intent,w=_.pageDomain,y=_.clickTimeStamp}(),window.addEventListener("message",e=>{try{if(e.origin===E.origin)switch(e.data?.type){case"EMBED_SDK_ON_LOAD_INIT":N(),document.getElementById(g).focus();break;case"EMBED_SDK_ON_LOAD":document.getElementById(g).focus();break;case"EMBED_SDK_EVENT":switch(e.data.data?.type){case"ASSET_LOADED":j();const a=Date.now()-y,s={loadTime:a,imageDownloadTime:b,timeRequiredToHandoverToExpress:D,expressPluginLoadingTime:v,imageSize:S,VERB:f,domain:w,expressTouchpoint:_.touchpoint},r=i.PERF_METRIC_LOG_MESSAGE;"true"===o.getItem("adobeInternal")&&(console.log("Express Plugin Loading Time "+v),console.log("Express Supported Image Types Fetching Time "+I),console.log("Image Download Time "+b),console.log("Time required to handover to express "+D),console.log(r+" "+a)),n.info({message:r,...s}),k(t.EXPRESS_EXECUTE_VERB_EDITOR_ASSET_LOADED,s);break;case"SET_TOU_STATE":o.setItem(i.TOU_ACCEPTED,JSON.stringify(e.data?.data?.data?.data));break;case"SHOW_DOWNLOADS":chrome.runtime.sendMessage({main_op:"createNewTabWithUrl",url:"chrome://downloads"})}break;case"EMBED_SDK_READY":L.resolve(),v=Date.now()-x,R=Date.now();const a=document.getElementById(g);if(T){const e=W({},[]);e.type="WARMUP_MODULE",e.data.intent="edit-image-v2",a.contentWindow.postMessage(e,E.origin)}else a.contentWindow.postMessage({type:"REQUEST_MODULE_SUPPORTED_IMAGE_TYPES",data:{convertUnsupportedImages:!0}},E.origin),U=r(),A=c(U.promise(),1e3),A.catch(e=>{H("unsupported file types fetching flow "+e.toString()),K()});break;case"MODULE_SUPPORTED_IMAGE_TYPES":U.resolve(),I=Date.now()-R,C=e.data.data??C,K();break;case"EMBED_SDK_PUBLISH":const s=e.data.data?.asset[0];if(s)try{const e="image."+s.fileType?.split("/")[1];!function(e,t,o){let a=e.split(",")[1],n=atob(a),s=new ArrayBuffer(n.length),i=new Uint8Array(s);for(let e=0;e<n.length;e++)i[e]=n.charCodeAt(e);let r=new Blob([s],{type:o}),c=URL.createObjectURL(r);chrome.downloads.download({url:c,filename:t,conflictAction:"uniquify"},function(e){chrome.downloads.onChanged.addListener(function t(o){o.id===e&&o.state&&"complete"===o.state.current&&(c&&URL.revokeObjectURL(c),chrome.downloads.onChanged.removeListener(t))}),chrome.runtime.lastError&&H(chrome.runtime.lastError)})}(s.data,e,s.fileType)}catch(e){H("Save Image error: "+e.toString())}else H("Save Image error: No asset data found while publishing");break;case"EMBED_SDK_CANCEL":e.data.data?.isEscapePressed&&(j(),k(t.EXPRESS_EXECUTE_VERB_ESCAPE_CANCELLED,{VERB:f,expressTouchpoint:_.touchpoint,domain:w})),chrome.runtime.sendMessage({main_op:"closeExpressApp"});break;case"EMBED_SDK_ERROR":N(),F(),H("EMBED_SDK_ERROR "+e.data.data?.message)}}catch(e){N(),F(),H("Express Message Listener "+e.toString())}}),O.includes("pluginLoadRetry")){const e=M.pluginLoadRetry;V(e?.maxRetries??2,e?.timeout??5e3)}else V()}catch(e){N(),F(),H("Init Express Content Script "+e.toString())}})();