/*************************************************************************
* 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.
**************************************************************************/
export const extractWebpageHTML=async(e,t={})=>{const{customiseHtml:r=null}=t;return window.extractionPromise||(window.extractionPromise=new Promise(t=>{const a=()=>{const a=performance.now(),o=window.location.href,s=e.cloneNode(!0),n=["data:","blob:","chrome-extension:","javascript:","mailto:","tel:","file:","ftp:","about:","chrome:","edge:"],c=()=>{const e=Array.from(s.querySelectorAll("img[src]")),t=Array.from(s.querySelectorAll('*[style*="background-image"]')),r=Array.from(s.querySelectorAll(["*[data-bgsrc]","*[data-bg]","*[data-background]","*[data-background-src]","*[data-bg-src]","*[data-lazy-bg]","*[data-lazy-background]"].join(", "))),a=e.map((e,t)=>e.src.startsWith("data:")?Promise.resolve():fetch(e.src,{mode:"cors"}).then(e=>e.blob()).then(t=>new Promise(r=>{const a=new FileReader;a.onload=()=>{e.src=a.result,e.hasAttribute("srcset")&&e.removeAttribute("srcset"),r()},a.onerror=()=>{e.hasAttribute("srcset")&&e.removeAttribute("srcset"),r()},a.readAsDataURL(t)})).catch(()=>{e.hasAttribute("srcset")&&e.removeAttribute("srcset")})),n=t.map(e=>{const t=e.getAttribute("style"),r=t.match(/background-image:\s*url\(['"]?([^'"()]+)['"]?\)/);return r&&!r[1].startsWith("data:")?fetch(r[1],{mode:"cors"}).then(e=>e.blob()).then(a=>new Promise(o=>{const s=new FileReader;s.onload=()=>{const a=t.replace(r[0],`background-image: url(${s.result})`);e.setAttribute("style",a),o()},s.onerror=()=>o(),s.readAsDataURL(a)})).catch(()=>{}):Promise.resolve()}),c=r.map(e=>{const t=["data-bgsrc","data-bg","data-background","data-background-src","data-bg-src","data-lazy-bg","data-lazy-background"];let r=null,a=null;for(const o of t){const t=e.getAttribute(o);if(t&&t.trim()){r=t.trim(),a=o;break}}if(r&&!r.startsWith("data:"))try{const t=new URL(r,o).href;return fetch(t,{mode:"cors"}).then(e=>e.blob()).then(t=>new Promise(o=>{const s=new FileReader;s.onload=()=>{const t=e.getAttribute("style")||"",r=t+(t&&!t.endsWith(";")?"; ":"")+`background-image: url(${s.result});`;e.setAttribute("style",r),e.removeAttribute(a),o()},s.onerror=()=>{console.warn(`Failed to process data background image: ${r}`),o()},s.readAsDataURL(t)})).catch(e=>(console.warn(`Failed to fetch data background image: ${r}`,e),Promise.resolve()))}catch(e){return console.warn(`Invalid data background URL: ${r}`,e),Promise.resolve()}return Promise.resolve()});return Promise.race([Promise.allSettled([...a,...n,...c]),new Promise(e=>setTimeout(e,15e3))]).then(()=>{})},l=async e=>{const t=e.head,r=window.location.href,a=[],o=Array.from(t.querySelectorAll("link"));for(const e of o){const t=e.getAttribute("rel"),o=e.getAttribute("href");switch(t){case"stylesheet":break;case"icon":case"shortcut icon":case"apple-touch-icon":if(o&&!o.startsWith("data:"))try{const t=new URL(o,r).href;a.push({element:e,url:t,attribute:"href",type:"favicon"})}catch(t){console.warn("Invalid favicon URL:",o),e.remove()}else o||e.remove();break;case"canonical":if(o)try{const t=new URL(o,r).href;e.setAttribute("href",t)}catch(t){console.warn("Invalid canonical URL:",o),e.remove()}break;case"preload":case"prefetch":case"preconnect":case"dns-prefetch":case"modulepreload":case"manifest":e.remove();break;case"alternate":if(o)try{const t=new URL(o,r).href;e.setAttribute("href",t)}catch(t){console.warn("Invalid alternate URL:",o),e.remove()}break;default:if(o&&!o.startsWith("data:")&&!o.startsWith("#"))try{const t=new URL(o,r).href;e.setAttribute("href",t)}catch(e){console.warn("Invalid link URL:",o)}}}const s=Array.from(t.querySelectorAll("meta"));for(const e of s){const t=e.getAttribute("property"),o=e.getAttribute("name"),s=e.getAttribute("content");if(s)if(t&&(t.includes("og:image")||t.includes("twitter:image"))||o&&(o.includes("twitter:image")||o.includes("msapplication-TileImage"))){if(!s.startsWith("data:"))try{const t=new URL(s,r).href;a.push({element:e,url:t,attribute:"content",type:"meta-image"})}catch(t){console.warn("Invalid meta image URL:",s),e.remove()}}else if(t&&(t.includes("og:url")||t.includes("twitter:url"))||o&&o.includes("twitter:url"))try{const t=new URL(s,r).href;e.setAttribute("content",t)}catch(e){console.warn("Invalid meta URL:",s)}else"refresh"===e.getAttribute("http-equiv")&&e.remove()}if(Array.from(t.querySelectorAll("script")).forEach(e=>{(e.getAttribute("src")||e.textContent)&&e.remove()}),a.length>0){const e=a.map(async e=>{try{const t=await fetch(e.url,{mode:"cors",headers:{Accept:"image/*,*/*;q=0.8"}});if(!t.ok)throw new Error(`HTTP ${t.status}`);const r=await t.blob(),a=await new Promise((e,t)=>{const a=new FileReader;a.onload=()=>e(a.result),a.onerror=t,a.readAsDataURL(r)});e.element.setAttribute(e.attribute,a)}catch(t){console.warn(`Failed to embed ${e.type}:`,e.url,t),e.element.remove()}});await Promise.race([Promise.allSettled(e),new Promise(e=>setTimeout(e,15e3))])}if(!t.querySelector("base")){const a=e.createElement("base");a.setAttribute("href",r),t.insertBefore(a,t.firstChild)}return e};s.querySelectorAll("a[href], link[href]").forEach(e=>{const t=e.getAttribute("href");if(t&&!t.startsWith("javascript:")&&!t.startsWith("mailto:")&&!t.startsWith("tel:"))try{const r=new URL(t,o).href;e.setAttribute("href",r)}catch(e){console.warn("Invalid href URL:",t)}}),s.querySelectorAll("[src]").forEach(e=>{const t=e.getAttribute("src");if(t&&!n.some(e=>t.startsWith(e)))try{const r=new URL(t,o).href;e.setAttribute("src",r)}catch(e){console.warn("Invalid src URL:",t)}}),s.querySelectorAll("img[srcset]").forEach(e=>{const t=e.getAttribute("srcset");if(t)try{const r=t.split(",").map(e=>{const t=e.trim().split(/\s+/),r=t[0],a=t[1]||"";if(!n.some(e=>r.startsWith(e))){const e=new URL(r,o).href;return a?`${e} ${a}`:e}return e.trim()});e.setAttribute("srcset",r.join(", "))}catch(e){console.warn("Invalid srcset:",t)}}),s.querySelectorAll("form[action]").forEach(e=>{const t=e.getAttribute("action");if(t&&!t.startsWith("javascript:"))try{const r=new URL(t,o).href;e.setAttribute("action",r)}catch(e){console.warn("Invalid action URL:",t)}}),Promise.all([(()=>{let t="";try{const r=Array.from(e.styleSheets).map((e,t)=>new Promise(r=>{try{if(e.cssRules){let t="";Array.from(e.cssRules).forEach(e=>{t+=e.cssText+"\n"}),r(t)}else r(e.href?`/* External stylesheet: ${e.href} */\n`:"")}catch(a){console.warn(`Cannot access stylesheet ${t}:`,a),r(e.href?`/* External stylesheet: ${e.href} */\n`:"")}}));return e.querySelectorAll("style").forEach((e,r)=>{e.textContent&&(t+=`/* Inline Style Block ${r+1} */\n`,t+=e.textContent+"\n")}),Promise.all(r).then(e=>(t=e.join("")+t,t))}catch(e){return console.warn("Error capturing CSS rules:",e),Promise.resolve(t)}})(),(Array.from(e.querySelectorAll("*")),void Array.from(s.querySelectorAll("*")))]).then(([e])=>Promise.all([c(),l(s)]).then(([,t])=>(e=>{const t=new Set,r=new Map;if([/(-webkit-mask-image|mask-image):\s*url\(['"]?([^'"()]+)['"]?\)/gi,/background-image:\s*url\(['"]?([^'"()]+)['"]?\)/gi,/border-image(-source)?:\s*url\(['"]?([^'"()]+)['"]?\)/gi,/list-style-image:\s*url\(['"]?([^'"()]+)['"]?\)/gi,/@font-face[^}]*src:\s*url\(['"]?([^'"()]+)['"]?\)/gi,/cursor:\s*url\(['"]?([^'"()]+)['"]?\)/gi,/filter:\s*url\(['"]?([^'"()]+)['"]?\)/gi].forEach(r=>{let a;const o=new RegExp(r.source,r.flags);for(;null!==(a=o.exec(e));){let e;if(a[2]?e=a[2]:a[1]&&(e=a[1]),e&&!e.startsWith("data:")&&!e.startsWith("#"))try{const r=new URL(e,window.location.href).href;t.add(r)}catch(t){console.warn("Invalid CSS URL:",e)}}}),0===t.size)return Promise.resolve(e);const a=Array.from(t).map(e=>fetch(e,{mode:"cors",headers:{Accept:"image/*,*/*;q=0.8"}}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.blob()}).then(t=>new Promise((a,o)=>{const s=new FileReader;s.onload=()=>{r.set(e,s.result),a()},s.onerror=()=>{console.warn(`Failed to convert CSS resource to data URL: ${e}`),o()},s.readAsDataURL(t)})).catch(t=>(console.warn(`Failed to fetch CSS resource: ${e}`,t),Promise.resolve())));return Promise.race([Promise.allSettled(a),new Promise(e=>setTimeout(e,2e4))]).then(()=>{let t=e;return r.forEach((e,r)=>{const a=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(a,"g");t=t.replace(o,e)}),t})})(e))).then(async o=>{const n=s.getElementById("html-extraction-progress");n&&n.remove();const c=s.getElementById("addWebpageToProjectExtnIframe");c&&c.remove();const l=Array.from(s.querySelectorAll('link[rel="stylesheet"]')).map(t=>fetch(t.href).then(e=>e.text()).then(r=>{const a=e.createElement("style");a.textContent=r,s.head.appendChild(a),t.remove()}).catch(e=>{console.warn("Failed to fetch stylesheet:",t.href,e),t.remove()}));await Promise.all(l),s.querySelectorAll("script").forEach(e=>e.remove());const i=s.createElement("style");if(i.textContent=`\n/* Original CSS with all media queries intact and embedded resources */\n${o}\n\n/* Screen-specific computed styles (won't affect print) */\n@media screen {\n${window.extractedElementStyles||""}\n}\n`,!s.querySelector("meta[charset]")){const e=s.createElement("meta");e.setAttribute("charset","UTF-8"),s.head.insertBefore(e,s.head.firstChild)}s.head.appendChild(i),delete window.extractedElementStyles;const m=performance.now()-a,u=new Blob([s.documentElement.outerHTML],{type:"text/html"}),d=URL.createObjectURL(u),h=e.createElement("a");h.href=d,h.download="webpage.html",r&&r(s),t({html:s.documentElement.outerHTML,title:e.title,url:window.location.href,processingTime:m,timestamp:Date.now()})}).catch(r=>{t({html:s.documentElement.outerHTML,title:e.title,url:window.location.href,error:r.message,partial:!0})})};if("complete"===e.readyState)setTimeout(a,500);else{let e;const t=setTimeout(()=>{window.removeEventListener("load",e),a()},3e4);e=()=>{a(),clearTimeout(t)},window.addEventListener("load",e)}})),window.extractionPromise};window.extractWebpageHTML=extractWebpageHTML;