diff --git a/dist/extension-background.js b/dist/extension-background.js index 03157330e..05651f494 100644 --- a/dist/extension-background.js +++ b/dist/extension-background.js @@ -1 +1 @@ -!function(){"use strict";async function e(t,a){let n;try{n=await browser.downloads.download(t)}catch(n){if(n.message){const o=n.message.toLowerCase(),r=o.includes("illegal characters")||o.includes("invalid filename");if(r&&t.filename.startsWith("."))return t.filename=a+t.filename,e(t,a);if(r&&t.filename.includes(","))return t.filename=t.filename.replace(/,/g,a),e(t,a);if(r&&!t.filename.match(/^[\x00-\x7F]+$/))return t.filename=t.filename.replace(/[^\x00-\x7F]+/g,a),e(t,a);if((o.includes("'incognito'")||o.includes('"incognito"'))&&t.incognito)return delete t.incognito,e(t,a);if("conflictaction prompt not yet implemented"==o&&t.conflictAction)return delete t.conflictAction,e(t,a);if(o.includes("canceled"))return{};throw n}throw n}return new Promise(((e,t)=>{browser.downloads.onChanged.addListener((function a(o){o.id==n&&o.state&&("complete"==o.state.current&&(browser.downloads.search({id:n}).then((t=>e({filename:t[0]&&t[0].filename}))).catch((()=>e({}))),browser.downloads.onChanged.removeListener(a)),"interrupted"==o.state.current&&(o.error&&"USER_CANCELED"==o.error.current?e({}):t(new Error(o.state.current)),browser.downloads.onChanged.removeListener(a)))}))}))}let t,a,n;async function o(e){a&&delete a[e];const t=await s();if(t[e]){const a=t[e].autoSave;t[e]={autoSave:a},await i(t)}}function r(e){return a||(a={}),void 0===e||a[e]||(a[e]={}),a}async function s(e){if(!t){const e=await browser.storage.local.get();t=e.tabsData||{}}return async function(){if(!n){n=!0;const e=await browser.tabs.query({currentWindow:!0,highlighted:!0});Object.keys(t).filter((t=>{if("autoSaveAll"!=t&&"autoSaveUnpinned"!=t&&"profileName"!=t)return!e.find((e=>e.id==t))})).forEach((e=>delete t[e])),await browser.storage.local.set({tabsData:t})}}(),void 0===e||t[e]||(t[e]={}),t}async function i(e){t=e,await browser.storage.local.set({tabsData:e})}setTimeout((()=>s().then((e=>t=e))),0);const c="-",l="__Default_Settings__",d="__Disabled_Settings__",u="regexp:",f={removeHiddenElements:!0,removeUnusedStyles:!0,removeUnusedFonts:!0,removeFrames:!1,removeImports:!0,removeScripts:!0,compressHTML:!0,compressCSS:!1,loadDeferredImages:!0,loadDeferredImagesMaxIdleTime:1500,loadDeferredImagesBlockCookies:!1,loadDeferredImagesBlockStorage:!1,loadDeferredImagesKeepZoomLevel:!1,filenameTemplate:"{page-title} ({date-locale} {time-locale}).html",infobarTemplate:"",includeInfobar:!1,confirmInfobarContent:!1,autoClose:!1,confirmFilename:!1,filenameConflictAction:"uniquify",filenameMaxLength:192,filenameMaxLengthUnit:"bytes",filenameReplacedCharacters:["~","+","\\\\","?","%","*",":","|",'"',"<",">","\0-",""],filenameReplacementCharacter:"_",contextMenuEnabled:!0,tabMenuEnabled:!0,browserActionMenuEnabled:!0,shadowEnabled:!0,logsEnabled:!0,progressBarEnabled:!0,maxResourceSizeEnabled:!1,maxResourceSize:10,removeAudioSrc:!0,removeVideoSrc:!0,displayInfobar:!0,displayStats:!1,backgroundSave:!/Mobile.*Firefox/.test(navigator.userAgent),defaultEditorMode:"normal",applySystemTheme:!0,autoSaveDelay:1,autoSaveLoad:!1,autoSaveUnload:!1,autoSaveLoadOrUnload:!0,autoSaveDiscard:!1,autoSaveRemove:!1,autoSaveRepeat:!1,autoSaveRepeatDelay:10,removeAlternativeFonts:!0,removeAlternativeMedias:!0,removeAlternativeImages:!0,groupDuplicateImages:!0,saveRawPage:!1,saveToClipboard:!1,addProof:!1,saveToGDrive:!1,saveToGitHub:!1,githubToken:"",githubUser:"",githubRepository:"SingleFile-Archives",githubBranch:"main",saveWithCompanion:!1,forceWebAuthFlow:!1,extractAuthCode:!0,resolveFragmentIdentifierURLs:!1,userScriptEnabled:!1,openEditor:!1,openSavedPage:!1,autoOpenEditor:!1,saveCreatedBookmarks:!1,allowedBookmarkFolders:[],ignoredBookmarkFolders:[],replaceBookmarkURL:!0,saveFavicon:!0,includeBOM:!1,warnUnsavedPage:!0,autoSaveExternalSave:!1,insertMetaNoIndex:!1,insertMetaCSP:!0,passReferrerOnError:!1,insertSingleFileComment:!0,blockMixedContent:!1,saveOriginalURLs:!1,acceptHeaders:{font:"application/font-woff2;q=1.0,application/font-woff;q=0.9,*/*;q=0.8",image:"image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",stylesheet:"text/css,*/*;q=0.1",script:"*/*",document:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"},moveStylesInHead:!1,woleetKey:""};let m,h=w();async function w(){const{sync:e}=await browser.storage.local.get();m=e?browser.storage.sync:browser.storage.local;const t=await m.get();if(t.profiles)t.rules||(t.rules=[]),Object.keys(t.profiles).forEach((e=>p(t.profiles[e]))),await m.remove(["profiles","defaultProfile","rules"]),await m.set({profiles:t.profiles,rules:t.rules});else{const e=t;delete e.tabsData,p(e);const a={profiles:{},rules:[]};a.profiles.__Default_Settings__=e,m.remove(Object.keys(f)),await m.set(a)}t.maxParallelWorkers||await m.set({maxParallelWorkers:navigator.hardwareConcurrency||4})}function p(e){Object.keys(f).forEach((t=>function(e,t){void 0===e[t]&&(e[t]=f[t])}(e,t)))}async function b(e,t){const a=await g(),n=a.rules.filter((e=>v(e)));let o=n.sort(y).find((t=>e&&e.match(new RegExp(t.url.split(u)[1]))));if(!o){const n=a.rules.filter((e=>!v(e)));o=n.sort(y).find((a=>!t&&"*"==a.url||e&&e.includes(a.url)))}return o}async function g(){return await h,m.get(["profiles","rules","maxParallelWorkers"])}function y(e,t){return t.url.length-e.url.length}function v(e){return e.url.toLowerCase().startsWith(u)}async function k(t){if(t.method.endsWith(".deleteRules")&&await async function(e){const t=await g();t.rules=t.rules=e?t.rules.filter((t=>t.autoSaveProfile!=e&&t.profile!=e)):[],await m.set({rules:t.rules})}(t.profileName),t.method.endsWith(".deleteRule")&&await async function(e){if(!e)throw new Error("URL is empty");const t=await g();t.rules=t.rules.filter((t=>t.url!=e)),await m.set({rules:t.rules})}(t.url),t.method.endsWith(".addRule")&&await S(t.url,t.profileName,t.autoSaveProfileName),t.method.endsWith(".createProfile")&&await async function(e,t){const a=await g();if(Object.keys(a.profiles).includes(e))throw new Error("Duplicate profile name");a.profiles[e]=JSON.parse(JSON.stringify(a.profiles[t])),await m.set({profiles:a.profiles})}(t.profileName,t.fromProfileName||l),t.method.endsWith(".renameProfile")&&await async function(e,t){const[a,n]=await Promise.all([g(),s()]);if(!Object.keys(a.profiles).includes(e))throw new Error("Profile not found");if(Object.keys(a.profiles).includes(t))throw new Error("Duplicate profile name");if(e==l)throw new Error("Default settings cannot be renamed");n.profileName==e&&(n.profileName=t,await i(n));a.profiles[t]=a.profiles[e],a.rules.forEach((a=>{a.profile==e&&(a.profile=t),a.autoSaveProfile==e&&(a.autoSaveProfile=t)})),delete a.profiles[e],await m.set({profiles:a.profiles,rules:a.rules})}(t.profileName,t.newProfileName),t.method.endsWith(".deleteProfile")&&await async function(e){const[t,a]=await Promise.all([g(),s()]);if(!Object.keys(t.profiles).includes(e))throw new Error("Profile not found");if(e==l)throw new Error("Default settings cannot be deleted");a.profileName==e&&(delete a.profileName,await i(a));t.rules.forEach((t=>{t.profile==e&&(t.profile=l),t.autoSaveProfile==e&&(t.autoSaveProfile=l)})),delete t.profiles[e],await m.set({profiles:t.profiles,rules:t.rules})}(t.profileName),t.method.endsWith(".resetProfiles")&&await async function(){await h;const e=await s();delete e.profileName,await i(e),await m.remove(["profiles","rules","maxParallelWorkers"]),await browser.storage.local.set({sync:!1}),m=browser.storage.local,await w()}(),t.method.endsWith(".resetProfile")&&await async function(e){const t=await g();if(!Object.keys(t.profiles).includes(e))throw new Error("Profile not found");t.profiles[e]=f,await m.set({profiles:t.profiles})}(t.profileName),t.method.endsWith(".importConfig")&&await async function(e){await m.remove(["profiles","rules","maxParallelWorkers"]),await m.set({profiles:e.profiles,rules:e.rules,maxParallelWorkers:e.maxParallelWorkers}),await w()}(t.config),t.method.endsWith(".updateProfile")&&await async function(e,t){const a=await g();if(!Object.keys(a.profiles).includes(e))throw new Error("Profile not found");Object.keys(t).forEach((n=>a.profiles[e][n]=t[n])),await m.set({profiles:a.profiles})}(t.profileName,t.profile),t.method.endsWith(".updateRule")&&await T(t.url,t.newUrl,t.profileName,t.autoSaveProfileName),t.method.endsWith(".getConstants"))return{DISABLED_PROFILE_NAME:d,DEFAULT_PROFILE_NAME:l,CURRENT_PROFILE_NAME:c};if(t.method.endsWith(".getRules"))return async function(){return(await g()).rules}();if(t.method.endsWith(".getProfiles"))return I();if(t.method.endsWith(".exportConfig"))return async function(){const t=await g(),a=URL.createObjectURL(new Blob([JSON.stringify({profiles:t.profiles,rules:t.rules,maxParallelWorkers:t.maxParallelWorkers},null,2)],{type:"text/json"})),n={url:a,filename:`singlefile-settings-${(new Date).toISOString().replace(/:/g,"_")}.json`,saveAs:!0};try{await e(n,"_")}finally{URL.revokeObjectURL(a)}}();if(t.method.endsWith(".enableSync")){await browser.storage.local.set({sync:!0});const e=await browser.storage.sync.get();if(!e||!e.profiles){const e=await browser.storage.local.get();await browser.storage.sync.set({profiles:e.profiles,rules:e.rules,maxParallelWorkers:e.maxParallelWorkers})}return m=browser.storage.sync,{}}if(t.method.endsWith(".disableSync")){await browser.storage.local.set({sync:!1});const e=await browser.storage.sync.get();e&&e.profiles&&await browser.storage.local.set({profiles:e.profiles,rules:e.rules,maxParallelWorkers:e.maxParallelWorkers}),m=browser.storage.local}return t.method.endsWith(".isSync")?{sync:(await browser.storage.local.get()).sync}:{}}async function I(){return(await g()).profiles}async function x(e,t){const[a,n,o]=await Promise.all([g(),b(e),s()]),r=o.profileName||l;let i;if(n){const e=n[t?"autoSaveProfile":"profile"];i=e==c?r:e}else i=r;return Object.assign({profileName:i},a.profiles[i])}async function S(e,t,a){if(!e)throw new Error("URL is empty");const n=await g();if(n.rules.find((t=>t.url==e)))throw new Error("URL already exists");n.rules.push({url:e,profile:t,autoSaveProfile:a}),await m.set({rules:n.rules})}async function T(e,t,a,n){if(!e||!t)throw new Error("URL is empty");const o=await g(),r=o.rules.find((t=>t.url==e));if(!r)throw new Error("URL not found");if(o.rules.find((a=>a.url==t&&a.url!=e)))throw new Error("New URL already exists");r.url=t,r.profile=a,r.autoSaveProfile=n,await m.set({rules:o.rules})}async function E(){return(await m.get()).authInfo}async function P(e){await m.set({authInfo:e})}async function M(){let e=E();e.revokableAccessToken?P({revokableAccessToken:e.revokableAccessToken}):await m.remove(["authInfo"])}async function W(e){if(e){const[t,a]=await Promise.all([s(),b(e.url)]);return Boolean(t.autoSaveAll||t.autoSaveUnpinned&&!e.pinned||t[e.id]&&t[e.id].autoSave)&&(!a||a.autoSaveProfile!=d)}}const A=33554432,L="/extension/ui/pages/editor.html",C=new Map,R=new Map,U=browser.runtime.getURL(L);function B(e){return e.url==U}const _=new Map,D="x-single-file-request-id";function O(e,t={},a){return new Promise(((n,o)=>{const r=new XMLHttpRequest;if(r.withCredentials=!0,r.responseType="arraybuffer",r.onerror=e=>o(new Error(e.detail)),r.onreadystatechange=()=>{r.readyState==XMLHttpRequest.DONE&&(r.status||r.response.byteLength?401!=r.status&&403!=r.status&&404!=r.status||a?n({array:Array.from(new Uint8Array(r.response)),headers:{"content-type":r.getResponseHeader("Content-Type")},status:r.status}):O(e,t,!0).then(n).catch(o):o())},r.open("GET",e,!0),t.headers)for(const e of Object.entries(t.headers))r.setRequestHeader(e[0],e[1]);if(a){const e=String(Math.random()).substring(2);s=e,i=t.referrer,_.set(s,i),r.setRequestHeader(D,e)}var s,i;r.send()}))}browser.runtime.onMessage.addListener(((e,t)=>{if(e.method&&e.method.startsWith("singlefile.fetch"))return new Promise((a=>{(function(e,t){if("singlefile.fetch"==e.method)return O(e.url,{referrer:e.referrer,headers:e.headers});if("singlefile.fetchFrame"==e.method)return browser.tabs.sendMessage(t.tab.id,e)})(e,t).then(a).catch((e=>a({error:e&&e.toString()})))}))}));let j=!1;function N(e){return e.method.endsWith(".enableReferrerOnError")?(q(),{}):e.method.endsWith(".disableReferrerOnError")?(function(){try{browser.webRequest.onBeforeSendHeaders.removeListener(F)}catch(e){}j=!1}(),{}):void 0}function F(e){if(j){let t=e.requestHeaders.find((e=>e.name===D));if(t){e.requestHeaders=e.requestHeaders.filter((e=>e.name!==D));const a=_.get(t.value);if(a){_.delete(t.value);if(!e.requestHeaders.find((e=>"referer"===e.name.toLowerCase())))return e.requestHeaders.push({name:"Referer",value:a}),{requestHeaders:e.requestHeaders}}}}}function q(){if(!j){try{browser.webRequest.onBeforeSendHeaders.addListener(F,{urls:[""]},["blocking","requestHeaders","extraHeaders"])}catch(e){browser.webRequest.onBeforeSendHeaders.addListener(F,{urls:[""]},["blocking","requestHeaders"])}j=!0}}const z=new Map;async function H(e){return(await browser.tabs.query(e)).sort(((e,t)=>e.index-t.index))}const J="/extension/ui/resources/icon_128.png",G="/extension/ui/resources/icon_128_wait",K=browser.i18n.getMessage("buttonDefaultTooltip"),$=browser.i18n.getMessage("buttonBlockedTooltip"),X=browser.i18n.getMessage("buttonInitializingBadge"),Y=browser.i18n.getMessage("buttonInitializingTooltip"),Z=browser.i18n.getMessage("buttonErrorBadge"),V=browser.i18n.getMessage("buttonBlockedBadge"),Q=browser.i18n.getMessage("buttonOKBadge"),ee=browser.i18n.getMessage("buttonSaveProgressTooltip"),te=browser.i18n.getMessage("buttonUploadProgressTooltip"),ae=browser.i18n.getMessage("buttonAutoSaveActiveBadge"),ne=browser.i18n.getMessage("buttonAutoSaveActiveTooltip"),oe=[2,147,20,192],re=[4,229,36,192],se={default:{setBadgeBackgroundColor:{color:oe},setBadgeText:{text:""},setTitle:{title:K},setIcon:{path:J}},inject:{setBadgeBackgroundColor:{color:oe},setBadgeText:{text:X},setTitle:{title:Y}},execute:{setBadgeBackgroundColor:{color:re},setBadgeText:{text:X}},progress:{setBadgeBackgroundColor:{color:re},setBadgeText:{text:""}},edit:{setBadgeBackgroundColor:{color:oe},setBadgeText:{text:""},setTitle:{title:K},setIcon:{path:J}},end:{setBadgeBackgroundColor:{color:re},setBadgeText:{text:Q},setTitle:{title:K},setIcon:{path:J}},error:{setBadgeBackgroundColor:{color:[229,4,12,192]},setBadgeText:{text:Z},setTitle:{title:""},setIcon:{path:J}},forbidden:{setBadgeBackgroundColor:{color:[255,255,255,1]},setBadgeText:{text:V},setTitle:{title:$},setIcon:{path:J}},autosave:{inject:{setBadgeBackgroundColor:{color:[64,64,64,192]},setBadgeText:{text:ae},setTitle:{title:ne},setIcon:{path:J}},default:{setBadgeBackgroundColor:{color:[208,208,208,192]},setBadgeText:{text:ae},setTitle:{title:ne},setIcon:{path:J}}}};let ie;function ce(e,t){if(e.method.endsWith(".processInit")){delete r(t.tab.id)[t.tab.id].button,me(t.tab)}var a,n,o;return e.method.endsWith(".processProgress")&&e.maxIndex&&(a=t.tab.id,n=e.index,o=e.maxIndex,fe(a,n,o,ee)),e.method.endsWith(".processEnd")&&de(t.tab.id),e.method.endsWith(".processError")&&(e.error&&console.error("Initialization error",e.error),le(t.tab.id)),e.method.endsWith(".processCancelled")&&ue(t.tab),Promise.resolve({})}function le(e){he(e,pe("error"))}function de(e,t){he(e,t?pe("default",!0):pe("end"))}function ue(e){me(e)}function fe(e,t,a,n){const o=Math.max(Math.min(20,Math.floor(t/a*20)),0),r=Math.min(Math.floor(t/a*8),8),s=G+r+".png",i=pe("progress");i.setTitle={title:n+5*o+"%"},i.setIcon={path:s},he(e,i)}async function me(e){const t=pe("default",await W(e));await he(e.id,t)}async function he(e,t){const a=r(e);if(t){a[e].button||(a[e].button={lastState:null});const n=a[e].button.lastState||{},o={};Object.keys(t).forEach((e=>{void 0!==t[e]&&JSON.stringify(n[e])!=JSON.stringify(t[e])&&(o[e]=t[e])})),Object.keys(o).length&&(a[e].button.lastState=t,await async function(e,t){for(const a of Object.keys(t))await we(e,a,t[a])}(e,o))}}async function we(e,t,a){if(browser.browserAction[t]){const n=JSON.parse(JSON.stringify(a));n.tabId=e,await browser.browserAction[t](n)}}function pe(e,t){return JSON.parse(JSON.stringify(t?se.autosave[e]:se[e]))}browser.browserAction.onClicked.addListener((async e=>{const t=await H({currentWindow:!0,highlighted:!0});t.length<=1?function(e){ie.isSavingTab(e)?ie.cancelTab(e.id):ie.saveTabs([e])}(e):ie.saveTabs(t)}));const be=browser.menus,ge=be&&be.onClicked&&be.create&&be.update&&be.removeAll,ye="save-page",ve="edit-and-save-page",ke="save-with-profile",Ie="save-selected-links",xe="view-pendings",Se="select-profile",Te="wasve-with-profile-",Ee="select-profile-",Pe="associate-with-profile",Me="associate-with-profile-",We="save-selected",Ae="save-frame",Le="save-tabs",Ce="save-selected-tabs",Re="save-unpinned-tabs",Ue="save-all-tabs",Be="button-save-selected-tabs",_e="button-save-unpinned-tabs",De="button-save-all-tabs",Oe="auto-save",je="auto-save-disabled",Ne="auto-save-tab",Fe="auto-save-unpinned",qe="auto-save-all",ze=browser.i18n.getMessage("menuCreateDomainRule"),He=browser.i18n.getMessage("menuUpdateRule"),Je=browser.i18n.getMessage("menuSavePage"),Ge=browser.i18n.getMessage("menuSaveWithProfile"),Ke=browser.i18n.getMessage("menuSaveSelectedLinks"),$e=browser.i18n.getMessage("menuEditPage"),Xe=browser.i18n.getMessage("menuEditAndSavePage"),Ye=browser.i18n.getMessage("menuViewPendingSaves"),Ze=browser.i18n.getMessage("menuSaveSelection"),Ve=browser.i18n.getMessage("menuSaveFrame"),Qe=browser.i18n.getMessage("menuSaveTabs"),et=browser.i18n.getMessage("menuSaveSelectedTabs"),tt=browser.i18n.getMessage("menuSaveUnpinnedTabs"),at=browser.i18n.getMessage("menuSaveAllTabs"),nt=browser.i18n.getMessage("menuSelectProfile"),ot=browser.i18n.getMessage("profileDefaultSettings"),rt=browser.i18n.getMessage("menuAutoSave"),st=browser.i18n.getMessage("menuAutoSaveDisabled"),it=browser.i18n.getMessage("menuAutoSaveTab"),ct=browser.i18n.getMessage("menuAutoSaveUnpinnedTabs"),lt=browser.i18n.getMessage("menuAutoSaveAllTabs"),dt=[ve,Ie,We,Ae,Oe,Pe],ut=new Map,ft=new Map;let mt,ht,wt,pt=!0,bt=!0,gt=new Map;async function yt(e){const[t,a]=await Promise.all([I(),s()]),n=await x(e&&e.url);if(ge&&n){const o=["page","frame","image","link","video","audio","selection"],r=[];if(n.browserActionMenuEnabled&&r.push("browser_action"),n.tabMenuEnabled)try{be.create({id:"temporary-id",contexts:["tab"],title:"title"}),r.push("tab")}catch(e){n.tabMenuEnabled=!1}await be.removeAll();const s=r.concat(...o),i=n.contextMenuEnabled?s:r;if(be.create({id:ye,contexts:i,title:Je}),be.create({id:ve,contexts:i,title:Xe}),be.create({id:Ie,contexts:n.contextMenuEnabled?r.concat(["selection"]):r,title:Ke}),Object.keys(t).length>1&&be.create({id:ke,contexts:i,title:Ge}),n.contextMenuEnabled&&be.create({id:"separator-1",contexts:o,type:"separator"}),be.create({id:We,contexts:i,title:Ze}),n.contextMenuEnabled&&be.create({id:Ae,contexts:["frame"],title:Ve}),be.create({id:Le,contexts:r,title:Qe}),be.create({id:Be,contexts:r,title:et,parentId:Le}),be.create({id:_e,contexts:r,title:tt,parentId:Le}),be.create({id:De,contexts:r,title:at,parentId:Le}),n.contextMenuEnabled&&(be.create({id:Ce,contexts:o,title:et}),be.create({id:Re,contexts:o,title:tt}),be.create({id:Ue,contexts:o,title:at}),be.create({id:"separator-2",contexts:o,type:"separator"})),Object.keys(t).length>1){be.create({id:Se,title:nt,contexts:i}),be.create({id:"wasve-with-profile-default",contexts:i,title:ot,parentId:ke});const r="select-profile-default",s=!a.profileName||a.profileName==l;let d;be.create({id:r,type:"radio",contexts:i,title:ot,checked:s,parentId:Se}),ut.set(r,s),be.create({id:Pe,title:ze,contexts:i}),ft.set(Pe,ze),e&&e.url&&(d=await b(e.url,!0));const u="associate-with-profile-current",f=!d||d.profile==c;be.create({id:u,type:"radio",contexts:i,title:c,checked:f,parentId:Pe}),ut.set(u,f);const m="associate-with-profile-default",h=Boolean(d)&&d.profile==l;be.create({id:m,type:"radio",contexts:i,title:ot,checked:h,parentId:Pe}),ut.set(m,h),gt=new Map,Object.keys(t).forEach(((e,t)=>{if(e!=l){let n=Te+t;be.create({id:n,contexts:i,title:e,parentId:ke}),n=Ee+t;let o=a.profileName==e;be.create({id:n,type:"radio",contexts:i,title:e,checked:o,parentId:Se}),ut.set(n,o),n=Me+t,o=Boolean(d)&&d.profile==e,be.create({id:n,type:"radio",contexts:i,title:e,checked:o,parentId:Pe}),ut.set(n,o),gt.set(e,t)}})),n.contextMenuEnabled&&be.create({id:"separator-3",contexts:o,type:"separator"})}be.create({id:Oe,contexts:i,title:rt}),be.create({id:je,type:"radio",title:st,contexts:i,checked:!0,parentId:Oe}),ut.set(je,!0),be.create({id:Ne,type:"radio",title:it,contexts:i,checked:!1,parentId:Oe}),ut.set(Ne,!1),be.create({id:Fe,type:"radio",title:ct,contexts:i,checked:!1,parentId:Oe}),ut.set(Fe,!1),be.create({id:qe,type:"radio",title:lt,contexts:i,checked:!1,parentId:Oe}),ut.set(qe,!1),be.create({id:"separator-4",contexts:i,type:"separator"}),be.create({id:xe,contexts:i,title:Ye})}mt=!0,ht&&(ht=!1,(await browser.tabs.query({})).forEach((async e=>await kt(e))))}async function vt(e){const t=await s(e.id);await async function(){const e=await browser.tabs.query({});return Promise.all(e.map((async e=>{const[t,a]=await Promise.all([x(e.url,!0),W(e)]);try{await browser.tabs.sendMessage(e.id,{method:"content.init",autoSaveEnabled:a,options:t})}catch(e){}})))}(),await me(e);try{await browser.runtime.sendMessage({method:"options.refresh",profileName:t.profileName})}catch(e){}}async function kt(e){if(ge&&mt){const t=[],a=await s(e.id);if(a[e.id].editorDetected)It(!1);else if(It(!0),t.push(St(je,!a[e.id].autoSave)),t.push(St(Ne,a[e.id].autoSave)),t.push(St(Fe,Boolean(a.autoSaveUnpinned))),t.push(St(qe,Boolean(a.autoSaveAll))),e&&e.url){const n=await x(e.url);t.push(async function(e,t){const a=pt;pt=t,(void 0===a||a!=t)&&await yt(e)}(e,n.contextMenuEnabled)),t.push(xt(ve,a[e.id].savedPageDetected?$e:Xe)),t.push(be.update(We,{visible:!n.saveRawPage})),t.push(be.update(ve,{visible:!n.openEditor||a[e.id].savedPageDetected}));let o="associate-with-profile-default",r=ze;const[s,i]=await Promise.all([I(),b(e.url)]);if(i){const e=gt.get(i.profile);e&&(o=Me+e,r=He)}Object.keys(s).length>1&&(Object.keys(s).forEach(((e,a)=>{e==l?t.push(St("associate-with-profile-default","associate-with-profile-default"==o)):t.push(St(Me+a,o==Me+a))})),t.push(xt(Pe,r)))}await Promise.all(t)}}async function It(e){const t=bt;if(bt=e,void 0===t||t!=e){const t=[];try{dt.forEach((a=>t.push(be.update(a,{visible:e})))),await Promise.all(t)}catch(e){}}}function xt(e,t){const a=ft.get(e);return ft.set(e,t),void 0===a||a!=t?be.update(e,{title:t}):void 0}async function St(e,t){t=Boolean(t),ut.set(e,t),await be.update(e,{checked:t})}Promise.resolve().then((async function(){ge&&(yt(),be.onClicked.addListener((async(e,t)=>{if(e.menuItemId==ye&&(e.linkUrl?wt.saveUrls([e.linkUrl]):wt.saveTabs([t])),e.menuItemId==ve){(await s(t.id))[t.id].savedPageDetected?wt.openEditor(t):e.linkUrl?wt.saveUrls([e.linkUrl],{openEditor:!0}):wt.saveTabs([t],{openEditor:!0})}if(e.menuItemId==Ie&&wt.saveSelectedLinks(t),e.menuItemId==xe&&await browser.tabs.create({active:!0,url:"/extension/ui/pages/pendings.html"}),e.menuItemId==We&&wt.saveTabs([t],{selected:!0}),e.menuItemId==Ae&&wt.saveTabs([t],{frameId:e.frameId}),e.menuItemId==Ce||e.menuItemId==Be){const e=await H({currentWindow:!0,highlighted:!0});wt.saveTabs(e)}if(e.menuItemId==Re||e.menuItemId==_e){const e=await H({currentWindow:!0,pinned:!1});wt.saveTabs(e)}if(e.menuItemId==Ue||e.menuItemId==De){const e=await H({currentWindow:!0});wt.saveTabs(e)}if(e.menuItemId==Ne){const e=await s(t.id);e[t.id].autoSave=!0,await i(e),vt(t)}if(e.menuItemId==je){const e=await s();Object.keys(e).forEach((t=>{"object"==typeof e[t]&&e[t].autoSave&&(e[t].autoSave=!1)})),e.autoSaveUnpinned=e.autoSaveAll=!1,await i(e),vt(t)}if(e.menuItemId==qe){const a=await s();a.autoSaveAll=e.checked,await i(a),vt(t)}if(e.menuItemId==Fe){const a=await s();a.autoSaveUnpinned=e.checked,await i(a),vt(t)}if(e.menuItemId.startsWith(Te)){const a=await I(),n=e.menuItemId.split(Te)[1];let o;if("default"==n)o=l;else{const e=Number(n);o=Object.keys(a)[e]}a[o].profileName=o,wt.saveTabs([t],a[o])}if(e.menuItemId.startsWith(Ee)){const[a,n]=await Promise.all([I(),s()]),o=e.menuItemId.split(Ee)[1];if("default"==o)n.profileName=l;else{const e=Number(o);n.profileName=Object.keys(a)[e]}await i(n),vt(t)}if(e.menuItemId.startsWith(Me)){const[a,n]=await Promise.all([I(),b(t.url,!0)]),o=e.menuItemId.split(Me)[1];let r;if("default"==o)r=l;else if("current"==o)r=c;else{const e=Number(o);r=Object.keys(a)[e]}n?await T(n.url,n.url,r,r):(await xt(Pe,He),await S(new URL(t.url).hostname,r,r))}})),mt?ht=!0:(await browser.tabs.query({})).forEach((async e=>await kt(e))))}));const Tt=browser.commands;let Et,Pt,Mt;function Wt(e,t){return e.method.endsWith(".refreshMenu")?function(e){if(e.method.endsWith("refreshMenu"))return yt(),Promise.resolve({})}(e):ce(e,t)}function At(e){!function(e){he(e.id,pe("forbidden"))}(e)}function Lt(e,t,a){!function(e,t,a){let n;a?n=pe("inject",!0):(n=pe(1==t?"inject":"execute"),n.setTitle={title:Y+" ("+t+"/2)"},n.setIcon={path:G+"0.png"}),he(e,n)}(e,t,a)}async function Ct(e,t,a){le(e),t&&await browser.tabs.sendMessage(e,{method:"content.error",error:t.toString(),link:a})}function Rt(e){!function(e){he(e,pe("edit"))}(e)}function Ut(e,t){de(e,t)}function Bt(e,t,a){!function(e,t,a){fe(e,t,a,te)}(e,t,a)}function _t(e){kt(e)}Tt&&Tt.onCommand&&Tt.onCommand.addListener&&Tt.onCommand.addListener((async e=>{if("save-selected-tabs"==e){const e=await H({currentWindow:!0,highlighted:!0});Et.saveTabs(e,{optionallySelected:!0})}if("save-all-tabs"==e){const e=await H({currentWindow:!0});Et.saveTabs(e)}}));const Dt=["dist/chrome-browser-polyfill.js","dist/single-file.js"],Ot=["dist/chrome-browser-polyfill.js","dist/single-file-frames.js"];async function jt(e,t){let a;if(await async function(e){const t=e.extensionScriptFiles||[];Pt||Mt||([Pt,Mt]=await Promise.all([Nt(Dt.concat(t)),Nt(Ot)]))}(t),!t.removeFrames)try{await browser.tabs.executeScript(e,{code:Mt,allFrames:!0,matchAboutBlank:!0,runAt:"document_start"})}catch(e){}try{await browser.tabs.executeScript(e,{code:Pt,allFrames:!1,runAt:"document_idle"}),a=!0}catch(e){}return a&&t.frameId&&await browser.tabs.executeScript(e,{code:"document.documentElement.dataset.requestedFrameId = true",frameId:t.frameId,matchAboutBlank:!0,runAt:"document_start"}),a}async function Nt(e){const t=e.map((async e=>{if("function"==typeof e)return"("+e.toString()+")();";{const t=await fetch(browser.runtime.getURL("../../../"+e));return(new TextDecoder).decode(await t.arrayBuffer())}}));let a="";for(const e of t)a+=await e;return a}const Ft="single-file-response-fetch",qt=(e,t)=>window.fetch(e,t);async function zt(e,t={}){try{let a=await qt(e,{cache:"force-cache",headers:t.headers});return 401!=a.status&&403!=a.status&&404!=a.status||(a=await Gt(e)),a}catch(a){const n=await Jt({method:"singlefile.fetch",url:e,referrer:t.referrer,headers:t.headers});return{status:n.status,headers:{get:e=>n.headers&&n.headers[e]},arrayBuffer:async()=>new Uint8Array(n.array).buffer}}}async function Ht(e,t){const a=await Jt({method:"singlefile.fetchFrame",url:e,frameId:t.frameId,referrer:t.referrer,headers:t.headers});return{status:a.status,headers:new Map(a.headers),arrayBuffer:async()=>new Uint8Array(a.array).buffer}}async function Jt(e){const t=await browser.runtime.sendMessage(e);if(!t||t.error)throw new Error(t&&t.error&&t.error.toString());return t}function Gt(e){return new Promise(((t,a)=>{var n,o,r,s;n=new CustomEvent("single-file-request-fetch",{detail:e}),window.dispatchEvent(n),o=Ft,r=function n(o){var r,s,i;o.detail?o.detail.url==e&&(r=Ft,s=n,i=!1,window.removeEventListener(r,s,i),o.detail.response?t({status:o.detail.status,headers:new Map(o.detail.headers),arrayBuffer:async()=>o.detail.response}):a(o.detail.error)):a()},s=!1,window.addEventListener(o,r,s)}))}function Kt(e,t){return jt(e,t)}browser.runtime.onMessage.addListener((e=>{if("singlefile.fetchFrame"==e.method&&window.frameId&&window.frameId==e.frameId)return async function(e){try{let t=await qt(e.url,{cache:"force-cache",headers:e.headers});return 401!=t.status&&403!=t.status&&404!=t.status||(t=await Promise.race([Gt(e.url),new Promise(((e,t)=>setTimeout((()=>t()),5e3)))])),{status:t.status,headers:[...t.headers],array:Array.from(new Uint8Array(await t.arrayBuffer()))}}catch(e){return{error:e&&e.toString()}}}(e)}));const $t="Could not establish connection. Receiving end does not exist.",Xt="The message port closed before a response was received.",Yt="Message manager disconnected",Zt="Cannot access contents of url ",Vt="pending",Qt="processing",ea=["dist/infobar.js","dist/extension.js"],ta=[];let aa,na=0;var oa;async function ra(e,t={}){await ca(),await Promise.all(e.map((async e=>{const a=await x(e);Object.keys(t).forEach((e=>a[e]=t[e])),a.autoClose=!0,a.extensionScriptFiles=ea,a.passReferrerOnError&&await q(),ia({tab:{url:e},status:Vt,options:a,method:"content.save"})}))),la()}async function sa(e,t={}){await ca(),await Promise.all(e.map((async e=>{const a=e.id,n=await x(e.url);if(Object.keys(t).forEach((e=>n[e]=t[e])),n.tabId=a,n.tabIndex=e.index,n.extensionScriptFiles=ea,n.passReferrerOnError&&await q(),t.autoSave){if(W(e)){da(ia({status:Qt,tab:e,options:n,method:"content.autosave"}))}}else{Lt(a,1);await Kt(a,n)||B(e)?(Lt(a,2),ia({status:Vt,tab:e,options:n,method:"content.save"})):At(e)}}))),la()}function ia(e){const t={id:na,status:e.status,tab:e.tab,options:e.options,method:e.method,done:function(){ta.splice(ta.findIndex((e=>e.id==this.id)),1),la()}};return ta.push(t),na++,t}async function ca(){aa||(aa=(await g()).maxParallelWorkers)}function la(){const e=ta.filter((e=>e.status==Qt)).length;for(let t=0;te.status==Vt));e&&da(e)}}async function da(e){const t=e.id;if(e.status=Qt,!e.tab.id){let t;try{const a=await async function(e){const t=await browser.tabs.create(e);return new Promise(((e,a)=>{function n(a,r){a==t.id&&"complete"==r.status&&(e(t),browser.tabs.onUpdated.removeListener(n),browser.tabs.onRemoved.removeListener(o))}function o(e){e==t.id&&(a(e),browser.tabs.onRemoved.removeListener(o))}browser.tabs.onUpdated.addListener(n),browser.tabs.onRemoved.addListener(o)}))}({url:e.tab.url,active:!1});e.tab.id=e.options.tabId=a.id,e.tab.index=e.options.tabIndex=a.index,Lt(e.tab.id,1),t=await Kt(e.tab.id,e.options)}catch(t){e.tab.id=t}if(!t)return void e.done();Lt(e.tab.id,2)}e.options.taskId=t;try{await browser.tabs.sendMessage(e.tab.id,{method:e.method,options:e.options})}catch(t){!t||t.message&&function(e){return e.message==Xt||e.message==$t||e.message==Yt||e.message.startsWith(Zt+JSON.stringify(U))}(t)||(console.log(t.message?t.message:t),Ct(e.tab.id,t.message,t.link),e.done())}}function ua(e){const t=ta.find((t=>t.id==e));t&&(t.options.autoClose&&!t.cancelled&&browser.tabs.remove(t.tab.id),t.done())}function fa(e,t){const a=ta.find((t=>t.id==e));a&&(a.cancel=t)}function ma(e){Array.from(ta).filter((t=>t.tab.id==e&&!t.options.autoSave)).forEach(wa)}function ha(e){return ta.find((t=>t.id==e))}function wa(e){const t=e.tab.id;e.cancelled=!0,browser.tabs.sendMessage(t,{method:"content.cancelSave",options:{loadDeferredImages:e.options.loadDeferredImages,loadDeferredImagesKeepZoomLevel:e.options.loadDeferredImagesKeepZoomLevel}}),e.cancel&&e.cancel(),"content.autosave"==e.method&&Ut(t,!0),function(e){ue(e)}(e.tab),e.done()}function pa(e){return{id:e.id,tabId:e.tab.id,index:e.tab.index,url:e.tab.url,title:e.tab.title,cancelled:e.cancelled,status:e.status}}(function(e){wt=e})(oa={isSavingTab:function(e){return Boolean(ta.find((t=>t.tab.id==e.id)))},saveTabs:sa,saveUrls:ra,cancelTab:ma,openEditor:function(e){browser.tabs.sendMessage(e.id,{method:"content.openEditor"})},saveSelectedLinks:async function(e){const t={extensionScriptFiles:ea,tabId:e.id,tabIndex:e.index};if(await Kt(e.id,t)){const t=await browser.tabs.sendMessage(e.id,{method:"content.getSelectedLinks"});t.urls&&t.urls.length&&await ra(t.urls)}else At(e)}}),function(e){ie=e}(oa),function(e){Et=e}(oa);async function ba(e){const t=browser.runtime.connectNative("singlefile_companion");t.postMessage({method:"save",pageData:e}),await new Promise(((e,a)=>{t.onDisconnect.addListener((()=>{t.error?a(new Error(t.error.message+" (Companion)")):browser.runtime.lastError&&!browser.runtime.lastError.message.includes("Native host has exited")||e()}))}))}async function ga(e){return e.method.endsWith(".saveCreatedBookmarks")?(ya(),{}):e.method.endsWith(".disable")?(async function(){let e;const t=await I();Object.keys(t).forEach((a=>e=e||!t[a].saveCreatedBookmarks)),e&&browser.bookmarks.onCreated.removeListener(va)}(),{}):void 0}async function ya(){try{browser.bookmarks.onCreated.removeListener(va)}catch(e){}let e;const t=await I();Object.keys(t).forEach((a=>{t[a].saveCreatedBookmarks&&(e=!0)})),e&&browser.bookmarks.onCreated.addListener(va)}async function va(e,t){const a=await browser.tabs.query({lastFocusedWindow:!0,active:!0}),n=await x(t.url);if(n.saveCreatedBookmarks){const r=await async function e(t,a=[]){if(t){const n=(await browser.bookmarks.get(t))[0];n&&n.title&&(a.unshift(n.title),await e(n.parentId,a))}return a}(t.parentId),s=n.allowedBookmarkFolders.toString(),i=r.find((e=>n.allowedBookmarkFolders.includes(e))),c=n.ignoredBookmarkFolders.toString(),l=r.find((e=>n.ignoredBookmarkFolders.includes(e)));if((s&&i||!s)&&(c&&!l||!c))if(a.length&&a[0].url==t.url)sa(a,{bookmarkId:e,bookmarkFolders:r});else{const a=await browser.tabs.query({});if(a.length){const n=a.find((e=>e.url==t.url));n?sa([n],{bookmarkId:e,bookmarkFolders:r}):t.url&&("about:blank"==t.url?browser.bookmarks.onChanged.addListener((function t(a,n){a==e&&n.url&&(browser.bookmarks.onChanged.removeListener(t),o(n.url))})):o(t.url))}}}function o(t){ra([t],{bookmarkId:e})}}Promise.resolve().then(ya);async function ka(e,t){let a=t||"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhYzZmZTMzMi0wODNjLTRjZmMtYmYxNC0xNWU5MTJmMWY4OWIiLCJpYXQiOjE1NzYxNzQzNDV9.n31j9ctJj7R1Vjwyc5yd1d6Cmg0NDnpwSaLWsqtZJQA";const n=await fetch("https://api.woleet.io/v1/anchor",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:"Bearer "+a},body:JSON.stringify({name:e,hash:e,public:!0})});if(401==n.status){const e=new Error("Your access token on Woleet is invalid. Go to __DOC_LINK__ to create your account.");throw e.link="https://app.woleet.io/",e}if(402==n.status){const e=new Error("You have no more credits on Woleet. Go to __DOC_LINK__ to recharge them.");throw e.link="https://app.woleet.io/",e}if(n.status>=400)throw new Error((n.statusText||"Error "+n.status)+" (Woleet)");return n.json()}const Ia="https://oauth2.googleapis.com/token",xa="https://www.googleapis.com/drive/v3/files";let Sa,Ta=!0;class Ea{constructor(e){this.file=e.file,this.onProgress=e.onProgress,this.contentType=this.file.type||"application/octet-stream",this.metadata={name:e.filename,mimeType:this.contentType,parents:e.parents||["root"]},this.token=e.token,this.offset=0,this.chunkSize=e.chunkSize||524288}async upload(){const e=Ua(await fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",{method:"POST",headers:{Authorization:"Bearer "+this.token,"Content-Type":"application/json","X-Upload-Content-Length":this.file.size,"X-Upload-Content-Type":this.contentType},body:JSON.stringify(this.metadata)})).headers.get("Location");if(this.url=e,!this.cancelled)return this.onProgress&&this.onProgress(0,this.file.size),Ca(this)}}async function Pa(e,t){const a=await fetch(Ia,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"client_id="+e.clientId+"&grant_type=authorization_code&code="+t.code+"&redirect_uri="+e.redirectURI}),n=await Ra(a);return e.accessToken=n.access_token,e.refreshToken=n.refresh_token,e.expirationDate=Date.now()+1e3*n.expires_in,{accessToken:e.accessToken,refreshToken:e.refreshToken,expirationDate:e.expirationDate}}function Ma(e,t={}){return e.redirectURI=encodeURIComponent("urn:ietf:wg:oauth:2.0:oob"+(t.auto?":auto":"")),e.authURL="https://accounts.google.com/o/oauth2/v2/auth?client_id="+e.clientId+"&response_type=code&access_type=offline&redirect_uri="+e.redirectURI+"&scope="+e.scopes.join(" "),e.authURL}function Wa(e={}){return Boolean(browser.identity&&browser.identity.getAuthToken)&&!e.forceWebAuthFlow}async function Aa(e,t,a=!0){const n=t.split("/");n.pop();const o=e.folderIds.get(n.join("/"));if(o)return o;let r="root";if(n.length){let o="";for(const s of n){o&&(o+="/"),o+=s;const n=e.folderIds.get(o);if(n)r=n;else try{r=await La(e,s,r),e.folderIds.set(o,r)}catch(n){if("path_not_found"==n.message&&a)return e.folderIds.clear(),Aa(e,t,!1);throw n}}}return r}async function La(e,t,a){const n=await async function(e,t,a){return Ra(await fetch(xa+"?q=mimeType = 'application/vnd.google-apps.folder' and name = '"+t+"' and trashed != true and '"+a+"' in parents",{headers:{Authorization:"Bearer "+e.accessToken}}))}(e,t,a);if(n.files.length)return n.files[0].id;{const n=await async function(e,t,a){return Ra(await fetch(xa,{method:"POST",headers:{Authorization:"Bearer "+e.accessToken,"Content-Type":"application/json"},body:JSON.stringify({name:t,parents:[a],mimeType:"application/vnd.google-apps.folder"})}))}(e,t,a);return n.id}}async function Ca(e){let t=e.file,a=e.file.size;(e.offset||e.chunkSize)&&(e.chunkSize&&(a=Math.min(e.offset+e.chunkSize,e.file.size)),t=t.slice(e.offset,a));const n=await fetch(e.url,{method:"PUT",headers:{Authorization:"Bearer "+e.token,"Content-Type":e.contentType,"Content-Range":"bytes "+e.offset+"-"+(a-1)+"/"+e.file.size,"X-Upload-Content-Type":e.contentType},body:t});if(e.onProgress&&!e.cancelled&&e.onProgress(e.offset+e.chunkSize,e.file.size),200==n.status||201==n.status)return n.json();if(308==n.status){const t=n.headers.get("Range");if(t&&(e.offset=parseInt(t.match(/\d+/g).pop(),10)+1),e.cancelled)throw new Error("upload_cancelled");return Ca(e)}Ua(n)}async function Ra(e){e=Ua(e);const t=await e.json();if(t.error)throw new Error(t.error);return t}function Ua(e){if(200==e.status)return e;throw 404==e.status?new Error("path_not_found"):401==e.status?new Error("invalid_token"):new Error("unknown_error ("+e.status+")")}async function Ba(e,t,a,n,o,r){for(;Sa;)await Sa;const s=new AbortController;return Sa=(async()=>{try{await async function({path:o,content:r,message:s=""},i){try{const c=await fetch(`https://api.github.com/repos/${t}/${a}/contents/${o.replace(/#/g,"%23")}`,{method:"PUT",headers:new Map([["Authorization",`token ${e}`],["Accept","application/vnd.github.v3+json"]]),body:JSON.stringify({content:btoa(unescape(encodeURIComponent(r))),message:s,branch:n}),signal:i}),l=await c.json();if(c.status<400)return l;throw new Error(l.message)}catch(e){if("AbortError"!=e.name)throw e}}({path:o,content:r},s.signal)}finally{Sa=null}})(),{cancelPush:()=>s.abort(),pushPromise:Sa}}const _a=new Map,Da="text/html",Oa=/([{}()^$&.*?/+|[\\\\]|\]|-)/g,ja=browser.runtime.getManifest(),Na=ja.optional_permissions&&ja.optional_permissions.includes("identity"),Fa=new class{constructor(e,t){this.clientId=e,this.scopes=t,this.folderIds=new Map,setInterval((()=>this.folderIds.clear()),6e4)}async auth(e={interactive:!0,auto:!0}){if(e.requestPermissionIdentity&&Ta)try{await browser.permissions.request({permissions:["identity"]}),Ta=!1}catch(e){}return Wa(e)?(this.accessToken=await browser.identity.getAuthToken({interactive:e.interactive}),{revokableAccessToken:this.accessToken}):(Ma(this,e),e.code?Pa(this,e):async function(e,t){let a;t.extractAuthCode&&t.extractAuthCode(Ma(e,t)).then((e=>a=e)).catch((()=>{}));try{if(browser.identity&&browser.identity.launchWebAuthFlow&&!t.forceWebAuthFlow)return await browser.identity.launchWebAuthFlow({interactive:t.interactive,url:e.authURL});if(t.launchWebAuthFlow)return await t.launchWebAuthFlow({url:e.authURL});throw new Error("auth_not_supported")}catch(n){if(n.message&&("code_required"==n.message||n.message.includes("access"))){if(t.auto||a||!t.promptAuthCode||(a=await t.promptAuthCode()),a)return t.code=a,await Pa(e,t);throw new Error("code_required")}throw n}}(this,e))}setAuthInfo(e,t){Wa(t)||(e?(this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationDate=e.expirationDate):(delete this.accessToken,delete this.refreshToken,delete this.expirationDate))}async refreshAuthToken(){if(this.refreshToken){const e=await fetch(Ia,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"client_id="+this.clientId+"&refresh_token="+this.refreshToken+"&grant_type=refresh_token"});if(400==e.status)throw new Error("unknown_token");const t=await Ra(e);return this.accessToken=t.access_token,t.refresh_token&&(this.refreshToken=t.refresh_token),t.expires_in&&(this.expirationDate=Date.now()+1e3*t.expires_in),{accessToken:this.accessToken,refreshToken:this.refreshToken,expirationDate:this.expirationDate}}}async revokeAuthToken(e){if(e){if(browser.identity&&browser.identity.removeCachedAuthToken)try{await browser.identity.removeCachedAuthToken({token:e})}catch(e){}const t=await fetch("https://accounts.google.com/o/oauth2/revoke",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"token="+e});try{await Ra(t)}catch(e){if("invalid_token"!=e.message)throw e}finally{delete this.accessToken,delete this.refreshToken,delete this.expirationDate}}}async upload(e,t,a,n=!0){const o=await Aa(this,e),r=e.split("/").pop(),s=new Ea({token:this.accessToken,file:t,parents:[o],filename:r,onProgress:a.onProgress});try{return{cancelUpload:()=>s.cancelled=!0,uploadPromise:s.upload()}}catch(o){if("path_not_found"==o.message&&n)return this.folderIds.clear(),this.upload(e,t,a,!1);throw o}}}("207618107333-3pj2pmelhnl4sf3rpctghs9cean3q8nj.apps.googleusercontent.com",["https://www.googleapis.com/auth/drive.file"]);async function qa(e,t){if(e.method.endsWith(".download"))return async function(e,t){let a;e.truncated?(a=_a.get(t.id),a||(a=[],_a.set(t.id,a)),a.push(e.content),e.finished&&_a.delete(t.id)):e.content&&(a=[e.content]);e.truncated&&!e.finished||(e.openEditor?(Rt(t.id),await async function({tabIndex:e,content:t,filename:a}){const n={active:!0,url:L};null!=e&&(n.index=e);const o=await browser.tabs.create(n);C.set(o.id,{content:t,filename:a})}({tabIndex:t.index+1,filename:e.filename,content:a.join("")})):e.saveToClipboard?(e.content=a.join(""),function(e){const t="copy";function a(t){t.clipboardData.setData(Da,e.content),t.clipboardData.setData("text/plain",e.content),t.preventDefault()}document.addEventListener(t,a),document.execCommand(t),document.removeEventListener(t,a)}(e),Ut(t.id)):await async function(e,t,a,n){try{if(n.saveToGDrive?await(await Ja(n.taskId,n.filename,new Blob(e,{type:Da}),{forceWebAuthFlow:n.forceWebAuthFlow,extractAuthCode:n.extractAuthCode},{onProgress:(e,a)=>Bt(t.id,e,a)})).uploadPromise:n.saveToGitHub?await(await Ha(n.taskId,n.filename,e.join(""),n.githubToken,n.githubUser,n.githubRepository,n.githubBranch)).pushPromise:n.saveWithCompanion?await ba({filename:n.filename,content:n.content,filenameConflictAction:n.filenameConflictAction}):(n.url=URL.createObjectURL(new Blob(e,{type:Da})),await Ga(n,{confirmFilename:n.confirmFilename,incognito:a,filenameConflictAction:n.filenameConflictAction,filenameReplacementCharacter:n.filenameReplacementCharacter,includeInfobar:n.includeInfobar})),Ut(t.id),n.openSavedPage){const a={active:!0,url:URL.createObjectURL(new Blob(e,{type:Da}))};null!=t.index&&(a.index=t.index+1),browser.tabs.create(a)}}catch(e){e.message&&"upload_cancelled"==e.message||(console.error(e),Ct(t.id,e.message,e.link))}finally{n.url&&URL.revokeObjectURL(n.url)}}(a,t,t.incognito,e));return{}}(e,t.tab);if(e.method.endsWith(".disableGDrive")){const e=await E();return M(),await Fa.revokeAuthToken(e&&(e.accessToken||e.revokableAccessToken)),{}}if(e.method.endsWith(".end")){if(e.hash)try{await ka(e.hash,e.woleetKey)}catch(e){Ct(t.tab.id,e.message,e.link)}return ua(e.taskId),{}}return e.method.endsWith(".getInfo")?ta.map(pa):e.method.endsWith(".cancel")?(a=e.taskId,wa(ta.find((e=>e.id==a))),{}):e.method.endsWith(".cancelAll")?(Array.from(ta).forEach(wa),{}):e.method.endsWith(".saveUrls")?(ra(e.urls),{}):void 0;var a}async function za(e,t){let a=await E();const n={interactive:!0,auto:e.extractAuthCode,forceWebAuthFlow:e.forceWebAuthFlow,requestPermissionIdentity:Na,launchWebAuthFlow:e=>async function(e){const t=await browser.tabs.create({url:e.url,active:!0});return new Promise(((e,a)=>{browser.tabs.onRemoved.addListener((function e(n){n==t.id&&(browser.tabs.onRemoved.removeListener(e),a(new Error("code_required")))}))}))}(e),extractAuthCode:e=>function(e){return new Promise(((t,a)=>{let n;function o(a,s){s&&s.url==e&&(n=a),n==a&&s&&s.title&&s.title.startsWith("Success code=")&&(browser.tabs.onUpdated.removeListener(o),browser.tabs.onUpdated.removeListener(r),t(s.title.substring(13,s.title.length-49)))}function r(e){e==n&&(browser.tabs.onUpdated.removeListener(o),browser.tabs.onUpdated.removeListener(r),a())}browser.tabs.onUpdated.addListener(o),browser.tabs.onRemoved.addListener(r)}))}(e),promptAuthCode:()=>async function(e){const t=await browser.tabs.query({currentWindow:!0,active:!0});return new Promise(((a,n)=>{const o=t[0].id;browser.tabs.onRemoved.addListener((function e(t){t==o&&(z.delete(t),browser.tabs.onUpdated.removeListener(e),n())})),z.set(o,{resolve:a,reject:n}),browser.tabs.sendMessage(o,{method:"common.promptValueRequest",promptMessage:e})}))}("Please enter the access code for Google Drive")};return Fa.setAuthInfo(a,n),a&&a.accessToken&&!t||(a=await Fa.auth(n),a?await P(a):await M()),a}async function Ha(e,t,a,n,o,r,s){const i=ha(e);if(!i||!i.cancelled){const i=Ba(n,o,r,s,t,a);fa(e,i.cancelPush);try{return await(await i).pushPromise,i}catch(e){throw new Error(e.message+" (GitHub)")}}}async function Ja(e,t,a,n,o){try{await za(n);const r=ha(e);if(!r||!r.cancelled){const n=await Fa.upload(t,a,o);return fa(e,n.cancelUpload),n}}catch(r){if("invalid_token"!=r.message)throw new Error(r.message+" (Google Drive)");{let r;try{r=await Fa.refreshAuthToken()}catch(e){if("unknown_token"!=e.message)throw new Error(e.message+" (Google Drive)");r=await za(n,!0)}r?await P(r):await M(),await Ja(e,t,a,n,o)}}}async function Ga(t,a){let n;if("skip"==a.filenameConflictAction){(await browser.downloads.search({filenameRegex:"(\\\\|/)"+(o=t.filename,o.replace(Oa,"\\$1")+"$"),exists:!0})).length?n=!0:a.filenameConflictAction="uniquify"}var o;if(!n){const n={url:t.url,saveAs:a.confirmFilename,filename:t.filename,conflictAction:a.filenameConflictAction};a.incognito&&(n.incognito=!0);const o=await e(n,a.filenameReplacementCharacter);o.filename&&t.bookmarkId&&t.replaceBookmarkURL&&(o.filename.startsWith("file:")||(o.filename.startsWith("/")&&(o.filename=o.filename.substring(1)),o.filename="file:///"+o.filename.replace(/#/g,"%23")),await async function(e,t){try{await browser.bookmarks.update(e,t)}catch(e){}}(t.bookmarkId,{url:o.filename}))}}const Ka={},$a={};async function Xa(e,t){if("enableAutoSave"==e.method){const a=await s(t.id);a[t.id].autoSave=e.enabled,await i(a),async function(e){Promise.all([yt(e),me(e)])}(t)}if("isAutoSaveEnabled"==e.method)return W(t)}async function Ya(e,t){const a=t.id,n=await x(t.url,!0);if(n){let o;Lt(a,1,!0),n.content=e.content,n.url=e.url,n.frames=e.frames,n.canvases=e.canvases,n.fonts=e.fonts,n.stylesheets=e.stylesheets,n.images=e.images,n.posters=e.posters,n.usedFonts=e.usedFonts,n.shadowRoots=e.shadowRoots,n.imports=e.imports,n.referrer=e.referrer,n.updatedResources=e.updatedResources,n.visitDate=new Date(e.visitDate),n.backgroundTab=!0,n.autoSave=!0,n.incognito=t.incognito,n.tabId=a,n.tabIndex=t.index;try{if(n.autoSaveExternalSave)await async function(e){e.autoSaveExternalSave=!1;const t=browser.runtime.connectNative("singlefile_companion");t.postMessage({method:"externalSave",pageData:e}),await new Promise(((e,a)=>{t.onDisconnect.addListener((()=>{t.error?a(new Error(t.error.message+" (Companion)")):browser.runtime.lastError&&!browser.runtime.lastError.message.includes("Native host has exited")||e()}))}))}(n);else{if(o=await function(e,t,a,n={fetch:zt,frameFetch:Ht}){return globalThis.singlefile.getPageData(e,n,t,a)}(n,null,null,{fetch:Za}),n.includeInfobar&&await infobar.includeScript(o),n.saveToGDrive){const t=new Blob([o.content],{type:"text/html"});await(await Ja(e.taskId,o.filename,t,n,{})).uploadPromise}else if(n.saveToGitHub)await(await Ha(e.taskId,o.filename,o.content,n.githubToken,n.githubUser,n.githubRepository,n.githubBranch)).pushPromise;else if(n.saveWithCompanion)await ba({filename:o.filename,content:o.content,filenameConflictAction:o.filenameConflictAction});else{const e=new Blob([o.content],{type:"text/html"});if(o.url=URL.createObjectURL(e),await Ga(o,n),n.openSavedPage){const n={active:!0,url:URL.createObjectURL(e),windowId:t.windowId},o=t.index;try{await browser.tabs.get(a),n.index=o+1}catch(e){n.index=o}browser.tabs.create(n)}}o.hash&&await ka(o.hash,n.woleetKey)}}finally{e.taskId?ua(e.taskId):n.autoClose&&(browser.tabs.remove($a[a]||a),delete $a[a]),o&&o.url&&URL.revokeObjectURL(o.url),Ut(a,!0)}}}function Za(e,t={}){return new Promise(((a,n)=>{const o=new XMLHttpRequest;if(o.withCredentials=!0,o.responseType="arraybuffer",o.onerror=e=>n(new Error(e.detail)),o.onreadystatechange=()=>{o.readyState==XMLHttpRequest.DONE&&a({status:o.status,headers:{get:e=>o.getResponseHeader(e)},arrayBuffer:async()=>o.response})},o.open("GET",e,!0),t.headers)for(const e of Object.entries(t.headers))o.setRequestHeader(e[0],e[1]);o.send()}))}async function Va(e,t){if(e.method.endsWith(".init")&&(await async function(e,t){await o(e.id);const a=await s(e.id);a[e.id].savedPageDetected=t.savedPageDetected,await i(a)}(t.tab,e),kt(t.tab),function(e){ma(e.id)}(t.tab),async function(e){const[t,a]=await Promise.all([x(e.url,!0),W(e)]);t&&(t.autoSaveLoad||t.autoSaveLoadOrUnload)&&a&&sa([e],{autoSave:!0})}(t.tab)),e.method.endsWith(".promptValueResponse")&&async function(e,t){const a=z.get(t.tab.id);a&&(a.resolve(e.value),z.delete(t.tab.id))}(e,t),e.method.endsWith(".getOptions"))return x(e.url);e.method.endsWith(".activate")&&await browser.tabs.update(e.tabId,{active:!0})}browser.tabs.onCreated.addListener((e=>function(e){!function(e){kt(e)}(e)}(e))),browser.tabs.onActivated.addListener((e=>async function(e){_t(await browser.tabs.get(e.tabId))}(e))),browser.tabs.onRemoved.addListener((e=>function(e){o(e),function(e){C.delete(e)}(e),ma(e),async function(e){const t=Ka[e];t?t.autoSaveRemove&&(delete Ka[e],await Ya(t,t.tab)):Ka[e]={removed:!0}}(e)}(e))),browser.tabs.onUpdated.addListener(((e,t)=>async function(e,t){if("complete"==t.status){setTimeout((async()=>{try{await browser.tabs.sendMessage(e,{method:"content.maybeInit"})}catch(e){}}),1500),function(e){delete Ka[e]}(e);const t=await browser.tabs.get(e);if(B(t)){const e=await s(t.id);e[t.id].editorDetected=!0,await i(e),_t(t)}}t.discarded&&async function(e){const t=Ka[e];t?(delete Ka[e],await Ya(t,t.tab)):Ka[e]={discarded:!0}}(e)}(e,t))),browser.tabs.onReplaced.addListener(((e,t)=>function(e,t){!async function(e,t){Ka[t]&&!Ka[e]&&(Ka[e]=Ka[t],delete Ka[t],$a[t]=e);const a=await s();a[t]&&!a[e]&&(a[e]=a[t],delete a[t],await i(a))}(e,t)}(e,t))),browser.runtime.onMessage.addListener(((e,t)=>{if("singlefile.frameTree.initResponse"==e.method||"singlefile.frameTree.ackInitRequest"==e.method)return browser.tabs.sendMessage(t.tab.id,e,{frameId:0}),Promise.resolve({})}));const Qa=new Map;function en(e,t){e.delete(t)}browser.runtime.onMessage.addListener(((e,t)=>{if("singlefile.lazyTimeout.setTimeout"==e.method){let a,n=Qa.get(t.tab.id);if(n)if(a=n.get(t.frameId),a){const t=a.get(e.type);t&&clearTimeout(t)}else a=new Map;const o=setTimeout((async()=>{try{const a=Qa.get(t.tab.id),n=a.get(t.frameId);a&&n&&en(n,e.type),await browser.tabs.sendMessage(t.tab.id,{method:"singlefile.lazyTimeout.onTimeout",type:e.type})}catch(e){}}),e.delay);return n||(n=new Map,a=new Map,n.set(t.frameId,a),Qa.set(t.tab.id,n)),a.set(e.type,o),Promise.resolve({})}if("singlefile.lazyTimeout.clearTimeout"==e.method){let a=Qa.get(t.tab.id);if(a){const n=a.get(t.frameId);if(n){const t=n.get(e.type);t&&clearTimeout(t),en(n,e.type)}}return Promise.resolve({})}})),browser.tabs.onRemoved.addListener((e=>Qa.delete(e))),browser.runtime.onMessage.addListener(((e,t)=>e.method.startsWith("tabs.")?Va(e,t):e.method.startsWith("downloads.")?qa(e,t):e.method.startsWith("autosave.")?async function(e,t){if(e.method.endsWith(".save"))return e.autoSaveDiscard||e.autoSaveRemove?(t.tab?(e.tab=t.tab,Ka[t.tab.id]=e):Ka[e.tabId]&&(Ka[e.tabId].removed&&e.autoSaveRemove||Ka[e.tabId].discarded&&e.autoSaveDiscard)&&(delete Ka[e.tabId],await Ya(e,{id:e.tabId,index:e.tabIndex,url:t.url})),e.autoSaveUnload&&(delete Ka[e.tabId],await Ya(e,t.tab))):(delete Ka[e.tabId],await Ya(e,t.tab)),{}}(e,t):e.method.startsWith("ui.")?Wt(e,t):e.method.startsWith("config.")?k(e):e.method.startsWith("tabsData.")?function(e){return e.method.endsWith(".get")?s():e.method.endsWith(".set")?i(e.tabsData):void 0}(e):e.method.startsWith("devtools.")?async function(e){e.method.endsWith(".resourceCommitted")&&e.tabId&&e.url&&("stylesheet"==e.type||"script"==e.type)&&await browser.tabs.sendMessage(e.tabId,e)}(e):e.method.startsWith("editor.")?async function(e,t){if(e.method.endsWith(".getTabData")){const e=t.tab,a=C.get(e.id);if(a){const t=await x(a.url),n=JSON.stringify(a);for(let a=0;a*AA,o.truncated?(o.finished=(a+1)*A>n.length,o.content=n.substring(a*A,(a+1)*A)):(o.content=n,o.options=t),await browser.tabs.sendMessage(e.id,o)}}}if(e.method.endsWith(".open")){let a;const n=t.tab;if(e.truncated?(a=R.get(n.id),a||(a=[],R.set(n.id,a)),a.push(e.content),e.finished&&R.delete(n.id)):e.content&&(a=[e.content]),!e.truncated||e.finished){const t={url:L};await browser.tabs.update(n.id,t),C.set(n.id,{url:n.url,content:a.join(""),filename:e.filename})}}}(e,t):e.method.startsWith("bookmarks.")?ga(e):e.method.startsWith("companion.")?async function(e){if(e.method.endsWith(".state"))return{enabled:!0}}(e):e.method.startsWith("requests.")?N(e):e.method.startsWith("bootstrap.")?async function(e,t){if(e.method.endsWith(".init")){const[e,a]=await Promise.all([x(t.tab.url,!0),W(t.tab)]);return{options:e,autoSaveEnabled:a,tabId:t.tab.id,tabIndex:t.tab.index}}}(e,t):void 0)),browser.runtime.onMessageExternal&&browser.runtime.onMessageExternal.addListener((async(e,t)=>{const a=(await browser.tabs.query({currentWindow:!0,active:!0}))[0];return!!a&&Xa(e,a)}))}(); +!function(){"use strict";async function e(t,a){let n;try{n=await browser.downloads.download(t)}catch(n){if(n.message){const r=n.message.toLowerCase(),o=r.includes("illegal characters")||r.includes("invalid filename");if(o&&t.filename.startsWith("."))return t.filename=a+t.filename,e(t,a);if(o&&t.filename.includes(","))return t.filename=t.filename.replace(/,/g,a),e(t,a);if(o&&!t.filename.match(/^[\x00-\x7F]+$/))return t.filename=t.filename.replace(/[^\x00-\x7F]+/g,a),e(t,a);if((r.includes("'incognito'")||r.includes('"incognito"'))&&t.incognito)return delete t.incognito,e(t,a);if("conflictaction prompt not yet implemented"==r&&t.conflictAction)return delete t.conflictAction,e(t,a);if(r.includes("canceled"))return{};throw n}throw n}return new Promise(((e,t)=>{browser.downloads.onChanged.addListener((function a(r){r.id==n&&r.state&&("complete"==r.state.current&&(browser.downloads.search({id:n}).then((t=>e({filename:t[0]&&t[0].filename}))).catch((()=>e({}))),browser.downloads.onChanged.removeListener(a)),"interrupted"==r.state.current&&(r.error&&"USER_CANCELED"==r.error.current?e({}):t(new Error(r.state.current)),browser.downloads.onChanged.removeListener(a)))}))}))}let t,a,n;async function r(e){a&&delete a[e];const t=await s();if(t[e]){const a=t[e].autoSave;t[e]={autoSave:a},await i(t)}}function o(e){return a||(a={}),void 0===e||a[e]||(a[e]={}),a}async function s(e){if(!t){const e=await browser.storage.local.get();t=e.tabsData||{}}return async function(){if(!n){n=!0;const e=await browser.tabs.query({currentWindow:!0,highlighted:!0});Object.keys(t).filter((t=>{if("autoSaveAll"!=t&&"autoSaveUnpinned"!=t&&"profileName"!=t)return!e.find((e=>e.id==t))})).forEach((e=>delete t[e])),await browser.storage.local.set({tabsData:t})}}(),void 0===e||t[e]||(t[e]={}),t}async function i(e){t=e,await browser.storage.local.set({tabsData:e})}setTimeout((()=>s().then((e=>t=e))),0);const c="-",l="__Default_Settings__",d="__Disabled_Settings__",u="regexp:",f={removeHiddenElements:!0,removeUnusedStyles:!0,removeUnusedFonts:!0,removeFrames:!1,removeImports:!0,removeScripts:!0,compressHTML:!0,compressCSS:!1,loadDeferredImages:!0,loadDeferredImagesMaxIdleTime:1500,loadDeferredImagesBlockCookies:!1,loadDeferredImagesBlockStorage:!1,loadDeferredImagesKeepZoomLevel:!1,filenameTemplate:"{page-title} ({date-locale} {time-locale}).html",infobarTemplate:"",includeInfobar:!1,confirmInfobarContent:!1,autoClose:!1,confirmFilename:!1,filenameConflictAction:"uniquify",filenameMaxLength:192,filenameMaxLengthUnit:"bytes",filenameReplacedCharacters:["~","+","\\\\","?","%","*",":","|",'"',"<",">","\0-",""],filenameReplacementCharacter:"_",contextMenuEnabled:!0,tabMenuEnabled:!0,browserActionMenuEnabled:!0,shadowEnabled:!0,logsEnabled:!0,progressBarEnabled:!0,maxResourceSizeEnabled:!1,maxResourceSize:10,removeAudioSrc:!0,removeVideoSrc:!0,displayInfobar:!0,displayStats:!1,backgroundSave:!/Mobile.*Firefox/.test(navigator.userAgent),defaultEditorMode:"normal",applySystemTheme:!0,autoSaveDelay:1,autoSaveLoad:!1,autoSaveUnload:!1,autoSaveLoadOrUnload:!0,autoSaveDiscard:!1,autoSaveRemove:!1,autoSaveRepeat:!1,autoSaveRepeatDelay:10,removeAlternativeFonts:!0,removeAlternativeMedias:!0,removeAlternativeImages:!0,groupDuplicateImages:!0,saveRawPage:!1,saveToClipboard:!1,addProof:!1,saveToGDrive:!1,saveToGitHub:!1,githubToken:"",githubUser:"",githubRepository:"SingleFile-Archives",githubBranch:"main",saveWithCompanion:!1,forceWebAuthFlow:!1,extractAuthCode:!0,resolveFragmentIdentifierURLs:!1,userScriptEnabled:!1,openEditor:!1,openSavedPage:!1,autoOpenEditor:!1,saveCreatedBookmarks:!1,allowedBookmarkFolders:[],ignoredBookmarkFolders:[],replaceBookmarkURL:!0,saveFavicon:!0,includeBOM:!1,warnUnsavedPage:!0,autoSaveExternalSave:!1,insertMetaNoIndex:!1,insertMetaCSP:!0,passReferrerOnError:!1,insertSingleFileComment:!0,blockMixedContent:!1,saveOriginalURLs:!1,acceptHeaders:{font:"application/font-woff2;q=1.0,application/font-woff;q=0.9,*/*;q=0.8",image:"image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",stylesheet:"text/css,*/*;q=0.1",script:"*/*",document:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"},moveStylesInHead:!1,woleetKey:""};let h,m=w();async function w(){const{sync:e}=await browser.storage.local.get();h=e?browser.storage.sync:browser.storage.local;const t=await h.get();if(t.profiles)t.rules||(t.rules=[]),Object.keys(t.profiles).forEach((e=>p(t.profiles[e]))),await h.remove(["profiles","defaultProfile","rules"]),await h.set({profiles:t.profiles,rules:t.rules});else{const e=t;delete e.tabsData,p(e);const a={profiles:{},rules:[]};a.profiles.__Default_Settings__=e,h.remove(Object.keys(f)),await h.set(a)}t.maxParallelWorkers||await h.set({maxParallelWorkers:navigator.hardwareConcurrency||4})}function p(e){Object.keys(f).forEach((t=>function(e,t){void 0===e[t]&&(e[t]=f[t])}(e,t)))}async function b(e,t){const a=await g(),n=a.rules.filter((e=>v(e)));let r=n.sort(y).find((t=>e&&e.match(new RegExp(t.url.split(u)[1]))));if(!r){const n=a.rules.filter((e=>!v(e)));r=n.sort(y).find((a=>!t&&"*"==a.url||e&&e.includes(a.url)))}return r}async function g(){return await m,h.get(["profiles","rules","maxParallelWorkers"])}function y(e,t){return t.url.length-e.url.length}function v(e){return e.url.toLowerCase().startsWith(u)}async function k(t){if(t.method.endsWith(".deleteRules")&&await async function(e){const t=await g();t.rules=t.rules=e?t.rules.filter((t=>t.autoSaveProfile!=e&&t.profile!=e)):[],await h.set({rules:t.rules})}(t.profileName),t.method.endsWith(".deleteRule")&&await async function(e){if(!e)throw new Error("URL is empty");const t=await g();t.rules=t.rules.filter((t=>t.url!=e)),await h.set({rules:t.rules})}(t.url),t.method.endsWith(".addRule")&&await S(t.url,t.profileName,t.autoSaveProfileName),t.method.endsWith(".createProfile")&&await async function(e,t){const a=await g();if(Object.keys(a.profiles).includes(e))throw new Error("Duplicate profile name");a.profiles[e]=JSON.parse(JSON.stringify(a.profiles[t])),await h.set({profiles:a.profiles})}(t.profileName,t.fromProfileName||l),t.method.endsWith(".renameProfile")&&await async function(e,t){const[a,n]=await Promise.all([g(),s()]);if(!Object.keys(a.profiles).includes(e))throw new Error("Profile not found");if(Object.keys(a.profiles).includes(t))throw new Error("Duplicate profile name");if(e==l)throw new Error("Default settings cannot be renamed");n.profileName==e&&(n.profileName=t,await i(n));a.profiles[t]=a.profiles[e],a.rules.forEach((a=>{a.profile==e&&(a.profile=t),a.autoSaveProfile==e&&(a.autoSaveProfile=t)})),delete a.profiles[e],await h.set({profiles:a.profiles,rules:a.rules})}(t.profileName,t.newProfileName),t.method.endsWith(".deleteProfile")&&await async function(e){const[t,a]=await Promise.all([g(),s()]);if(!Object.keys(t.profiles).includes(e))throw new Error("Profile not found");if(e==l)throw new Error("Default settings cannot be deleted");a.profileName==e&&(delete a.profileName,await i(a));t.rules.forEach((t=>{t.profile==e&&(t.profile=l),t.autoSaveProfile==e&&(t.autoSaveProfile=l)})),delete t.profiles[e],await h.set({profiles:t.profiles,rules:t.rules})}(t.profileName),t.method.endsWith(".resetProfiles")&&await async function(){await m;const e=await s();delete e.profileName,await i(e),await h.remove(["profiles","rules","maxParallelWorkers"]),await browser.storage.local.set({sync:!1}),h=browser.storage.local,await w()}(),t.method.endsWith(".resetProfile")&&await async function(e){const t=await g();if(!Object.keys(t.profiles).includes(e))throw new Error("Profile not found");t.profiles[e]=f,await h.set({profiles:t.profiles})}(t.profileName),t.method.endsWith(".importConfig")&&await async function(e){await h.remove(["profiles","rules","maxParallelWorkers"]),await h.set({profiles:e.profiles,rules:e.rules,maxParallelWorkers:e.maxParallelWorkers}),await w()}(t.config),t.method.endsWith(".updateProfile")&&await async function(e,t){const a=await g();if(!Object.keys(a.profiles).includes(e))throw new Error("Profile not found");Object.keys(t).forEach((n=>a.profiles[e][n]=t[n])),await h.set({profiles:a.profiles})}(t.profileName,t.profile),t.method.endsWith(".updateRule")&&await T(t.url,t.newUrl,t.profileName,t.autoSaveProfileName),t.method.endsWith(".getConstants"))return{DISABLED_PROFILE_NAME:d,DEFAULT_PROFILE_NAME:l,CURRENT_PROFILE_NAME:c};if(t.method.endsWith(".getRules"))return async function(){return(await g()).rules}();if(t.method.endsWith(".getProfiles"))return I();if(t.method.endsWith(".exportConfig"))return async function(){const t=await g(),a=URL.createObjectURL(new Blob([JSON.stringify({profiles:t.profiles,rules:t.rules,maxParallelWorkers:t.maxParallelWorkers},null,2)],{type:"text/json"})),n={url:a,filename:`singlefile-settings-${(new Date).toISOString().replace(/:/g,"_")}.json`,saveAs:!0};try{await e(n,"_")}finally{URL.revokeObjectURL(a)}}();if(t.method.endsWith(".enableSync")){await browser.storage.local.set({sync:!0});const e=await browser.storage.sync.get();if(!e||!e.profiles){const e=await browser.storage.local.get();await browser.storage.sync.set({profiles:e.profiles,rules:e.rules,maxParallelWorkers:e.maxParallelWorkers})}return h=browser.storage.sync,{}}if(t.method.endsWith(".disableSync")){await browser.storage.local.set({sync:!1});const e=await browser.storage.sync.get();e&&e.profiles&&await browser.storage.local.set({profiles:e.profiles,rules:e.rules,maxParallelWorkers:e.maxParallelWorkers}),h=browser.storage.local}return t.method.endsWith(".isSync")?{sync:(await browser.storage.local.get()).sync}:{}}async function I(){return(await g()).profiles}async function x(e,t){const[a,n,r]=await Promise.all([g(),b(e),s()]),o=r.profileName||l;let i;if(n){const e=n[t?"autoSaveProfile":"profile"];i=e==c?o:e}else i=o;return Object.assign({profileName:i},a.profiles[i])}async function S(e,t,a){if(!e)throw new Error("URL is empty");const n=await g();if(n.rules.find((t=>t.url==e)))throw new Error("URL already exists");n.rules.push({url:e,profile:t,autoSaveProfile:a}),await h.set({rules:n.rules})}async function T(e,t,a,n){if(!e||!t)throw new Error("URL is empty");const r=await g(),o=r.rules.find((t=>t.url==e));if(!o)throw new Error("URL not found");if(r.rules.find((a=>a.url==t&&a.url!=e)))throw new Error("New URL already exists");o.url=t,o.profile=a,o.autoSaveProfile=n,await h.set({rules:r.rules})}async function E(){return(await h.get()).authInfo}async function P(e){await h.set({authInfo:e})}async function M(){let e=E();e.revokableAccessToken?P({revokableAccessToken:e.revokableAccessToken}):await h.remove(["authInfo"])}async function W(e){if(e){const[t,a]=await Promise.all([s(),b(e.url)]);return Boolean(t.autoSaveAll||t.autoSaveUnpinned&&!e.pinned||t[e.id]&&t[e.id].autoSave)&&(!a||a.autoSaveProfile!=d)}}const A=33554432,L="/extension/ui/pages/editor.html",R=new Map,C=new Map,U=browser.runtime.getURL(L);function B(e){return e.url==U}const _=new Map,D="x-single-file-request-id",O=8388608;async function j(e,t,a){for(let n=0;n*OO,r.truncated?(r.finished=(n+1)*O>a.array.length,r.array=a.array.slice(n*O,(n+1)*O)):r.array=a.array,await browser.tabs.sendMessage(e,r)}return{}}function N(e,t={},a){return new Promise(((n,r)=>{const o=new XMLHttpRequest;if(o.withCredentials=!0,o.responseType="arraybuffer",o.onerror=e=>r(new Error(e.detail)),o.onreadystatechange=()=>{o.readyState==XMLHttpRequest.DONE&&(o.status||o.response.byteLength?401!=o.status&&403!=o.status&&404!=o.status||a?n({array:Array.from(new Uint8Array(o.response)),headers:{"content-type":o.getResponseHeader("Content-Type")},status:o.status}):N(e,t,!0).then(n).catch(r):r())},o.open("GET",e,!0),t.headers)for(const e of Object.entries(t.headers))o.setRequestHeader(e[0],e[1]);if(a){const e=String(Math.random()).substring(2);!function(e,t){_.set(e,t)}(e,t.referrer),o.setRequestHeader(D,e)}o.send()}))}browser.runtime.onMessage.addListener(((e,t)=>{if(e.method&&e.method.startsWith("singlefile.fetch"))return new Promise((a=>{(async function(e,t){if("singlefile.fetch"==e.method)try{const a=await N(e.url,{referrer:e.referrer,headers:e.headers});return j(t.tab.id,e.requestId,a)}catch(a){return j(t.tab.id,e.requestId,{error:a.message,arrray:[]})}else if("singlefile.fetchFrame"==e.method)return browser.tabs.sendMessage(t.tab.id,e)})(e,t).then(a).catch((e=>a({error:e&&e.toString()})))}))}));let q=!1;function F(e){return e.method.endsWith(".enableReferrerOnError")?(H(),{}):e.method.endsWith(".disableReferrerOnError")?(function(){try{browser.webRequest.onBeforeSendHeaders.removeListener(z)}catch(e){}q=!1}(),{}):void 0}function z(e){if(q){let t=e.requestHeaders.find((e=>e.name===D));if(t){e.requestHeaders=e.requestHeaders.filter((e=>e.name!==D));const a=_.get(t.value);if(a){_.delete(t.value);if(!e.requestHeaders.find((e=>"referer"===e.name.toLowerCase())))return e.requestHeaders.push({name:"Referer",value:a}),{requestHeaders:e.requestHeaders}}}}}function H(){if(!q){try{browser.webRequest.onBeforeSendHeaders.addListener(z,{urls:[""]},["blocking","requestHeaders","extraHeaders"])}catch(e){browser.webRequest.onBeforeSendHeaders.addListener(z,{urls:[""]},["blocking","requestHeaders"])}q=!0}}const J=new Map;async function G(e){return(await browser.tabs.query(e)).sort(((e,t)=>e.index-t.index))}const K="/extension/ui/resources/icon_128.png",$="/extension/ui/resources/icon_128_wait",X=browser.i18n.getMessage("buttonDefaultTooltip"),Y=browser.i18n.getMessage("buttonBlockedTooltip"),Z=browser.i18n.getMessage("buttonInitializingBadge"),V=browser.i18n.getMessage("buttonInitializingTooltip"),Q=browser.i18n.getMessage("buttonErrorBadge"),ee=browser.i18n.getMessage("buttonBlockedBadge"),te=browser.i18n.getMessage("buttonOKBadge"),ae=browser.i18n.getMessage("buttonSaveProgressTooltip"),ne=browser.i18n.getMessage("buttonUploadProgressTooltip"),re=browser.i18n.getMessage("buttonAutoSaveActiveBadge"),oe=browser.i18n.getMessage("buttonAutoSaveActiveTooltip"),se=[2,147,20,192],ie=[4,229,36,192],ce={default:{setBadgeBackgroundColor:{color:se},setBadgeText:{text:""},setTitle:{title:X},setIcon:{path:K}},inject:{setBadgeBackgroundColor:{color:se},setBadgeText:{text:Z},setTitle:{title:V}},execute:{setBadgeBackgroundColor:{color:ie},setBadgeText:{text:Z}},progress:{setBadgeBackgroundColor:{color:ie},setBadgeText:{text:""}},edit:{setBadgeBackgroundColor:{color:se},setBadgeText:{text:""},setTitle:{title:X},setIcon:{path:K}},end:{setBadgeBackgroundColor:{color:ie},setBadgeText:{text:te},setTitle:{title:X},setIcon:{path:K}},error:{setBadgeBackgroundColor:{color:[229,4,12,192]},setBadgeText:{text:Q},setTitle:{title:""},setIcon:{path:K}},forbidden:{setBadgeBackgroundColor:{color:[255,255,255,1]},setBadgeText:{text:ee},setTitle:{title:Y},setIcon:{path:K}},autosave:{inject:{setBadgeBackgroundColor:{color:[64,64,64,192]},setBadgeText:{text:re},setTitle:{title:oe},setIcon:{path:K}},default:{setBadgeBackgroundColor:{color:[208,208,208,192]},setBadgeText:{text:re},setTitle:{title:oe},setIcon:{path:K}}}};let le;function de(e,t){if(e.method.endsWith(".processInit")){delete o(t.tab.id)[t.tab.id].button,we(t.tab)}var a,n,r;return e.method.endsWith(".processProgress")&&e.maxIndex&&(a=t.tab.id,n=e.index,r=e.maxIndex,me(a,n,r,ae)),e.method.endsWith(".processEnd")&&fe(t.tab.id),e.method.endsWith(".processError")&&(e.error&&console.error("Initialization error",e.error),ue(t.tab.id)),e.method.endsWith(".processCancelled")&&he(t.tab),Promise.resolve({})}function ue(e){pe(e,ge("error"))}function fe(e,t){pe(e,t?ge("default",!0):ge("end"))}function he(e){we(e)}function me(e,t,a,n){const r=Math.max(Math.min(20,Math.floor(t/a*20)),0),o=Math.min(Math.floor(t/a*8),8),s=$+o+".png",i=ge("progress");i.setTitle={title:n+5*r+"%"},i.setIcon={path:s},pe(e,i)}async function we(e){const t=ge("default",await W(e));await pe(e.id,t)}async function pe(e,t){const a=o(e);if(t){a[e].button||(a[e].button={lastState:null});const n=a[e].button.lastState||{},r={};Object.keys(t).forEach((e=>{void 0!==t[e]&&JSON.stringify(n[e])!=JSON.stringify(t[e])&&(r[e]=t[e])})),Object.keys(r).length&&(a[e].button.lastState=t,await async function(e,t){for(const a of Object.keys(t))await be(e,a,t[a])}(e,r))}}async function be(e,t,a){if(browser.browserAction[t]){const n=JSON.parse(JSON.stringify(a));n.tabId=e,await browser.browserAction[t](n)}}function ge(e,t){return JSON.parse(JSON.stringify(t?ce.autosave[e]:ce[e]))}browser.browserAction.onClicked.addListener((async e=>{const t=await G({currentWindow:!0,highlighted:!0});t.length<=1?function(e){le.isSavingTab(e)?le.cancelTab(e.id):le.saveTabs([e])}(e):le.saveTabs(t)}));const ye=browser.menus,ve=ye&&ye.onClicked&&ye.create&&ye.update&&ye.removeAll,ke="save-page",Ie="edit-and-save-page",xe="save-with-profile",Se="save-selected-links",Te="view-pendings",Ee="select-profile",Pe="wasve-with-profile-",Me="select-profile-",We="associate-with-profile",Ae="associate-with-profile-",Le="save-selected",Re="save-frame",Ce="save-tabs",Ue="save-selected-tabs",Be="save-unpinned-tabs",_e="save-all-tabs",De="button-save-selected-tabs",Oe="button-save-unpinned-tabs",je="button-save-all-tabs",Ne="auto-save",qe="auto-save-disabled",Fe="auto-save-tab",ze="auto-save-unpinned",He="auto-save-all",Je=browser.i18n.getMessage("menuCreateDomainRule"),Ge=browser.i18n.getMessage("menuUpdateRule"),Ke=browser.i18n.getMessage("menuSavePage"),$e=browser.i18n.getMessage("menuSaveWithProfile"),Xe=browser.i18n.getMessage("menuSaveSelectedLinks"),Ye=browser.i18n.getMessage("menuEditPage"),Ze=browser.i18n.getMessage("menuEditAndSavePage"),Ve=browser.i18n.getMessage("menuViewPendingSaves"),Qe=browser.i18n.getMessage("menuSaveSelection"),et=browser.i18n.getMessage("menuSaveFrame"),tt=browser.i18n.getMessage("menuSaveTabs"),at=browser.i18n.getMessage("menuSaveSelectedTabs"),nt=browser.i18n.getMessage("menuSaveUnpinnedTabs"),rt=browser.i18n.getMessage("menuSaveAllTabs"),ot=browser.i18n.getMessage("menuSelectProfile"),st=browser.i18n.getMessage("profileDefaultSettings"),it=browser.i18n.getMessage("menuAutoSave"),ct=browser.i18n.getMessage("menuAutoSaveDisabled"),lt=browser.i18n.getMessage("menuAutoSaveTab"),dt=browser.i18n.getMessage("menuAutoSaveUnpinnedTabs"),ut=browser.i18n.getMessage("menuAutoSaveAllTabs"),ft=[Ie,Se,Le,Re,Ne,We],ht=new Map,mt=new Map;let wt,pt,bt,gt=!0,yt=!0,vt=new Map;async function kt(e){const[t,a]=await Promise.all([I(),s()]),n=await x(e&&e.url);if(ve&&n){const r=["page","frame","image","link","video","audio","selection"],o=[];if(n.browserActionMenuEnabled&&o.push("browser_action"),n.tabMenuEnabled)try{ye.create({id:"temporary-id",contexts:["tab"],title:"title"}),o.push("tab")}catch(e){n.tabMenuEnabled=!1}await ye.removeAll();const s=o.concat(...r),i=n.contextMenuEnabled?s:o;if(ye.create({id:ke,contexts:i,title:Ke}),ye.create({id:Ie,contexts:i,title:Ze}),ye.create({id:Se,contexts:n.contextMenuEnabled?o.concat(["selection"]):o,title:Xe}),Object.keys(t).length>1&&ye.create({id:xe,contexts:i,title:$e}),n.contextMenuEnabled&&ye.create({id:"separator-1",contexts:r,type:"separator"}),ye.create({id:Le,contexts:i,title:Qe}),n.contextMenuEnabled&&ye.create({id:Re,contexts:["frame"],title:et}),ye.create({id:Ce,contexts:o,title:tt}),ye.create({id:De,contexts:o,title:at,parentId:Ce}),ye.create({id:Oe,contexts:o,title:nt,parentId:Ce}),ye.create({id:je,contexts:o,title:rt,parentId:Ce}),n.contextMenuEnabled&&(ye.create({id:Ue,contexts:r,title:at}),ye.create({id:Be,contexts:r,title:nt}),ye.create({id:_e,contexts:r,title:rt}),ye.create({id:"separator-2",contexts:r,type:"separator"})),Object.keys(t).length>1){ye.create({id:Ee,title:ot,contexts:i}),ye.create({id:"wasve-with-profile-default",contexts:i,title:st,parentId:xe});const o="select-profile-default",s=!a.profileName||a.profileName==l;let d;ye.create({id:o,type:"radio",contexts:i,title:st,checked:s,parentId:Ee}),ht.set(o,s),ye.create({id:We,title:Je,contexts:i}),mt.set(We,Je),e&&e.url&&(d=await b(e.url,!0));const u="associate-with-profile-current",f=!d||d.profile==c;ye.create({id:u,type:"radio",contexts:i,title:c,checked:f,parentId:We}),ht.set(u,f);const h="associate-with-profile-default",m=Boolean(d)&&d.profile==l;ye.create({id:h,type:"radio",contexts:i,title:st,checked:m,parentId:We}),ht.set(h,m),vt=new Map,Object.keys(t).forEach(((e,t)=>{if(e!=l){let n=Pe+t;ye.create({id:n,contexts:i,title:e,parentId:xe}),n=Me+t;let r=a.profileName==e;ye.create({id:n,type:"radio",contexts:i,title:e,checked:r,parentId:Ee}),ht.set(n,r),n=Ae+t,r=Boolean(d)&&d.profile==e,ye.create({id:n,type:"radio",contexts:i,title:e,checked:r,parentId:We}),ht.set(n,r),vt.set(e,t)}})),n.contextMenuEnabled&&ye.create({id:"separator-3",contexts:r,type:"separator"})}ye.create({id:Ne,contexts:i,title:it}),ye.create({id:qe,type:"radio",title:ct,contexts:i,checked:!0,parentId:Ne}),ht.set(qe,!0),ye.create({id:Fe,type:"radio",title:lt,contexts:i,checked:!1,parentId:Ne}),ht.set(Fe,!1),ye.create({id:ze,type:"radio",title:dt,contexts:i,checked:!1,parentId:Ne}),ht.set(ze,!1),ye.create({id:He,type:"radio",title:ut,contexts:i,checked:!1,parentId:Ne}),ht.set(He,!1),ye.create({id:"separator-4",contexts:i,type:"separator"}),ye.create({id:Te,contexts:i,title:Ve})}wt=!0,pt&&(pt=!1,(await browser.tabs.query({})).forEach((async e=>await xt(e))))}async function It(e){const t=await s(e.id);await async function(){const e=await browser.tabs.query({});return Promise.all(e.map((async e=>{const[t,a]=await Promise.all([x(e.url,!0),W(e)]);try{await browser.tabs.sendMessage(e.id,{method:"content.init",autoSaveEnabled:a,options:t})}catch(e){}})))}(),await we(e);try{await browser.runtime.sendMessage({method:"options.refresh",profileName:t.profileName})}catch(e){}}async function xt(e){if(ve&&wt){const t=[],a=await s(e.id);if(a[e.id].editorDetected)St(!1);else if(St(!0),t.push(Et(qe,!a[e.id].autoSave)),t.push(Et(Fe,a[e.id].autoSave)),t.push(Et(ze,Boolean(a.autoSaveUnpinned))),t.push(Et(He,Boolean(a.autoSaveAll))),e&&e.url){const n=await x(e.url);t.push(async function(e,t){const a=gt;gt=t,(void 0===a||a!=t)&&await kt(e)}(e,n.contextMenuEnabled)),t.push(Tt(Ie,a[e.id].savedPageDetected?Ye:Ze)),t.push(ye.update(Le,{visible:!n.saveRawPage})),t.push(ye.update(Ie,{visible:!n.openEditor||a[e.id].savedPageDetected}));let r="associate-with-profile-default",o=Je;const[s,i]=await Promise.all([I(),b(e.url)]);if(i){const e=vt.get(i.profile);e&&(r=Ae+e,o=Ge)}Object.keys(s).length>1&&(Object.keys(s).forEach(((e,a)=>{e==l?t.push(Et("associate-with-profile-default","associate-with-profile-default"==r)):t.push(Et(Ae+a,r==Ae+a))})),t.push(Tt(We,o)))}await Promise.all(t)}}async function St(e){const t=yt;if(yt=e,void 0===t||t!=e){const t=[];try{ft.forEach((a=>t.push(ye.update(a,{visible:e})))),await Promise.all(t)}catch(e){}}}function Tt(e,t){const a=mt.get(e);return mt.set(e,t),void 0===a||a!=t?ye.update(e,{title:t}):void 0}async function Et(e,t){t=Boolean(t),ht.set(e,t),await ye.update(e,{checked:t})}Promise.resolve().then((async function(){ve&&(kt(),ye.onClicked.addListener((async(e,t)=>{if(e.menuItemId==ke&&(e.linkUrl?bt.saveUrls([e.linkUrl]):bt.saveTabs([t])),e.menuItemId==Ie){(await s(t.id))[t.id].savedPageDetected?bt.openEditor(t):e.linkUrl?bt.saveUrls([e.linkUrl],{openEditor:!0}):bt.saveTabs([t],{openEditor:!0})}if(e.menuItemId==Se&&bt.saveSelectedLinks(t),e.menuItemId==Te&&await browser.tabs.create({active:!0,url:"/extension/ui/pages/pendings.html"}),e.menuItemId==Le&&bt.saveTabs([t],{selected:!0}),e.menuItemId==Re&&bt.saveTabs([t],{frameId:e.frameId}),e.menuItemId==Ue||e.menuItemId==De){const e=await G({currentWindow:!0,highlighted:!0});bt.saveTabs(e)}if(e.menuItemId==Be||e.menuItemId==Oe){const e=await G({currentWindow:!0,pinned:!1});bt.saveTabs(e)}if(e.menuItemId==_e||e.menuItemId==je){const e=await G({currentWindow:!0});bt.saveTabs(e)}if(e.menuItemId==Fe){const e=await s(t.id);e[t.id].autoSave=!0,await i(e),It(t)}if(e.menuItemId==qe){const e=await s();Object.keys(e).forEach((t=>{"object"==typeof e[t]&&e[t].autoSave&&(e[t].autoSave=!1)})),e.autoSaveUnpinned=e.autoSaveAll=!1,await i(e),It(t)}if(e.menuItemId==He){const a=await s();a.autoSaveAll=e.checked,await i(a),It(t)}if(e.menuItemId==ze){const a=await s();a.autoSaveUnpinned=e.checked,await i(a),It(t)}if(e.menuItemId.startsWith(Pe)){const a=await I(),n=e.menuItemId.split(Pe)[1];let r;if("default"==n)r=l;else{const e=Number(n);r=Object.keys(a)[e]}a[r].profileName=r,bt.saveTabs([t],a[r])}if(e.menuItemId.startsWith(Me)){const[a,n]=await Promise.all([I(),s()]),r=e.menuItemId.split(Me)[1];if("default"==r)n.profileName=l;else{const e=Number(r);n.profileName=Object.keys(a)[e]}await i(n),It(t)}if(e.menuItemId.startsWith(Ae)){const[a,n]=await Promise.all([I(),b(t.url,!0)]),r=e.menuItemId.split(Ae)[1];let o;if("default"==r)o=l;else if("current"==r)o=c;else{const e=Number(r);o=Object.keys(a)[e]}n?await T(n.url,n.url,o,o):(await Tt(We,Ge),await S(new URL(t.url).hostname,o,o))}})),wt?pt=!0:(await browser.tabs.query({})).forEach((async e=>await xt(e))))}));const Pt=browser.commands;let Mt,Wt,At;function Lt(e,t){return e.method.endsWith(".refreshMenu")?function(e){if(e.method.endsWith("refreshMenu"))return kt(),Promise.resolve({})}(e):de(e,t)}function Rt(e){!function(e){pe(e.id,ge("forbidden"))}(e)}function Ct(e,t,a){!function(e,t,a){let n;a?n=ge("inject",!0):(n=ge(1==t?"inject":"execute"),n.setTitle={title:V+" ("+t+"/2)"},n.setIcon={path:$+"0.png"}),pe(e,n)}(e,t,a)}async function Ut(e,t,a){ue(e),t&&await browser.tabs.sendMessage(e,{method:"content.error",error:t.toString(),link:a})}function Bt(e){!function(e){pe(e,ge("edit"))}(e)}function _t(e,t){fe(e,t)}function Dt(e,t,a){!function(e,t,a){me(e,t,a,ne)}(e,t,a)}function Ot(e){xt(e)}Pt&&Pt.onCommand&&Pt.onCommand.addListener&&Pt.onCommand.addListener((async e=>{if("save-selected-tabs"==e){const e=await G({currentWindow:!0,highlighted:!0});Mt.saveTabs(e,{optionallySelected:!0})}if("save-all-tabs"==e){const e=await G({currentWindow:!0});Mt.saveTabs(e)}}));const jt=["dist/chrome-browser-polyfill.js","dist/single-file.js"],Nt=["dist/chrome-browser-polyfill.js","dist/single-file-frames.js"];async function qt(e,t){let a;if(await async function(e){const t=e.extensionScriptFiles||[];Wt||At||([Wt,At]=await Promise.all([Ft(jt.concat(t)),Ft(Nt)]))}(t),!t.removeFrames)try{await browser.tabs.executeScript(e,{code:At,allFrames:!0,matchAboutBlank:!0,runAt:"document_start"})}catch(e){}try{await browser.tabs.executeScript(e,{code:Wt,allFrames:!1,runAt:"document_idle"}),a=!0}catch(e){}return a&&t.frameId&&await browser.tabs.executeScript(e,{code:"document.documentElement.dataset.requestedFrameId = true",frameId:t.frameId,matchAboutBlank:!0,runAt:"document_start"}),a}async function Ft(e){const t=e.map((async e=>{if("function"==typeof e)return"("+e.toString()+")();";{const t=await fetch(browser.runtime.getURL("../../../"+e));return(new TextDecoder).decode(await t.arrayBuffer())}}));let a="";for(const e of t)a+=await e;return a}const zt="single-file-response-fetch",Ht=(e,t)=>window.fetch(e,t);let Jt=0,Gt=new Map;async function Kt(e,t={}){try{let a=await Ht(e,{cache:"force-cache",headers:t.headers});return 401!=a.status&&403!=a.status&&404!=a.status||(a=await Yt(e)),a}catch(a){Jt++;const n=new Promise(((e,t)=>Gt.set(Jt,{resolve:e,reject:t})));return await Xt({method:"singlefile.fetch",url:e,requestId:Jt,referrer:t.referrer,headers:t.headers}),n}}async function $t(e,t){const a=await Xt({method:"singlefile.fetchFrame",url:e,frameId:t.frameId,referrer:t.referrer,headers:t.headers});return{status:a.status,headers:new Map(a.headers),arrayBuffer:async()=>new Uint8Array(a.array).buffer}}async function Xt(e){const t=await browser.runtime.sendMessage(e);if(!t||t.error)throw new Error(t&&t.error&&t.error.toString());return t}function Yt(e){return new Promise(((t,a)=>{var n,r,o,s;n=new CustomEvent("single-file-request-fetch",{detail:e}),window.dispatchEvent(n),r=zt,o=function n(r){var o,s,i;r.detail?r.detail.url==e&&(o=zt,s=n,i=!1,window.removeEventListener(o,s,i),r.detail.response?t({status:r.detail.status,headers:new Map(r.detail.headers),arrayBuffer:async()=>r.detail.response}):a(r.detail.error)):a()},s=!1,window.addEventListener(r,o,s)}))}function Zt(e,t){return qt(e,t)}browser.runtime.onMessage.addListener((e=>"singlefile.fetchFrame"==e.method&&window.frameId&&window.frameId==e.frameId?async function(e){try{let t=await Ht(e.url,{cache:"force-cache",headers:e.headers});return 401!=t.status&&403!=t.status&&404!=t.status||(t=await Promise.race([Yt(e.url),new Promise(((e,t)=>setTimeout((()=>t()),5e3)))])),{status:t.status,headers:[...t.headers],array:Array.from(new Uint8Array(await t.arrayBuffer()))}}catch(e){return{error:e&&e.toString()}}}(e):"singlefile.fetchResponse"==e.method?async function(e){const t=Gt.get(e.requestId);t&&(e.error?(t.reject(new Error(e.error)),Gt.delete(e.requestId)):(e.truncated&&(t.array?t.array=t.array.concat(e.array):(t.array=e.array,Gt.set(e.requestId,t)),e.finished&&(e.array=t.array)),e.truncated&&!e.finished||(t.resolve({status:e.status,headers:{get:t=>e.headers&&e.headers[t]},arrayBuffer:async()=>new Uint8Array(e.array).buffer}),Gt.delete(e.requestId))));return{}}(e):void 0));const Vt="Could not establish connection. Receiving end does not exist.",Qt="The message port closed before a response was received.",ea="Message manager disconnected",ta="Cannot access contents of url ",aa="pending",na="processing",ra=["dist/infobar.js","dist/extension.js"],oa=[];let sa,ia=0;var ca;async function la(e,t={}){await fa(),await Promise.all(e.map((async e=>{const a=await x(e);Object.keys(t).forEach((e=>a[e]=t[e])),a.autoClose=!0,a.extensionScriptFiles=ra,a.passReferrerOnError&&await H(),ua({tab:{url:e},status:aa,options:a,method:"content.save"})}))),ha()}async function da(e,t={}){await fa(),await Promise.all(e.map((async e=>{const a=e.id,n=await x(e.url);if(Object.keys(t).forEach((e=>n[e]=t[e])),n.tabId=a,n.tabIndex=e.index,n.extensionScriptFiles=ra,n.passReferrerOnError&&await H(),t.autoSave){if(W(e)){ma(ua({status:na,tab:e,options:n,method:"content.autosave"}))}}else{Ct(a,1);await Zt(a,n)||B(e)?(Ct(a,2),ua({status:aa,tab:e,options:n,method:"content.save"})):Rt(e)}}))),ha()}function ua(e){const t={id:ia,status:e.status,tab:e.tab,options:e.options,method:e.method,done:function(){oa.splice(oa.findIndex((e=>e.id==this.id)),1),ha()}};return oa.push(t),ia++,t}async function fa(){sa||(sa=(await g()).maxParallelWorkers)}function ha(){const e=oa.filter((e=>e.status==na)).length;for(let t=0;te.status==aa));e&&ma(e)}}async function ma(e){const t=e.id;if(e.status=na,!e.tab.id){let t;try{const a=await async function(e){const t=await browser.tabs.create(e);return new Promise(((e,a)=>{function n(a,o){a==t.id&&"complete"==o.status&&(e(t),browser.tabs.onUpdated.removeListener(n),browser.tabs.onRemoved.removeListener(r))}function r(e){e==t.id&&(a(e),browser.tabs.onRemoved.removeListener(r))}browser.tabs.onUpdated.addListener(n),browser.tabs.onRemoved.addListener(r)}))}({url:e.tab.url,active:!1});e.tab.id=e.options.tabId=a.id,e.tab.index=e.options.tabIndex=a.index,Ct(e.tab.id,1),t=await Zt(e.tab.id,e.options)}catch(t){e.tab.id=t}if(!t)return void e.done();Ct(e.tab.id,2)}e.options.taskId=t;try{await browser.tabs.sendMessage(e.tab.id,{method:e.method,options:e.options})}catch(t){!t||t.message&&function(e){return e.message==Qt||e.message==Vt||e.message==ea||e.message.startsWith(ta+JSON.stringify(U))}(t)||(console.log(t.message?t.message:t),Ut(e.tab.id,t.message,t.link),e.done())}}function wa(e){const t=oa.find((t=>t.id==e));t&&(t.options.autoClose&&!t.cancelled&&browser.tabs.remove(t.tab.id),t.done())}function pa(e,t){const a=oa.find((t=>t.id==e));a&&(a.cancel=t)}function ba(e){Array.from(oa).filter((t=>t.tab.id==e&&!t.options.autoSave)).forEach(ya)}function ga(e){return oa.find((t=>t.id==e))}function ya(e){const t=e.tab.id;e.cancelled=!0,browser.tabs.sendMessage(t,{method:"content.cancelSave",options:{loadDeferredImages:e.options.loadDeferredImages,loadDeferredImagesKeepZoomLevel:e.options.loadDeferredImagesKeepZoomLevel}}),e.cancel&&e.cancel(),"content.autosave"==e.method&&_t(t,!0),function(e){he(e)}(e.tab),e.done()}function va(e){return{id:e.id,tabId:e.tab.id,index:e.tab.index,url:e.tab.url,title:e.tab.title,cancelled:e.cancelled,status:e.status}}(function(e){bt=e})(ca={isSavingTab:function(e){return Boolean(oa.find((t=>t.tab.id==e.id)))},saveTabs:da,saveUrls:la,cancelTab:ba,openEditor:function(e){browser.tabs.sendMessage(e.id,{method:"content.openEditor"})},saveSelectedLinks:async function(e){const t={extensionScriptFiles:ra,tabId:e.id,tabIndex:e.index};if(await Zt(e.id,t)){const t=await browser.tabs.sendMessage(e.id,{method:"content.getSelectedLinks"});t.urls&&t.urls.length&&await la(t.urls)}else Rt(e)}}),function(e){le=e}(ca),function(e){Mt=e}(ca);async function ka(e){const t=browser.runtime.connectNative("singlefile_companion");t.postMessage({method:"save",pageData:e}),await new Promise(((e,a)=>{t.onDisconnect.addListener((()=>{t.error?a(new Error(t.error.message+" (Companion)")):browser.runtime.lastError&&!browser.runtime.lastError.message.includes("Native host has exited")||e()}))}))}async function Ia(e){return e.method.endsWith(".saveCreatedBookmarks")?(xa(),{}):e.method.endsWith(".disable")?(async function(){let e;const t=await I();Object.keys(t).forEach((a=>e=e||!t[a].saveCreatedBookmarks)),e&&browser.bookmarks.onCreated.removeListener(Sa)}(),{}):void 0}async function xa(){try{browser.bookmarks.onCreated.removeListener(Sa)}catch(e){}let e;const t=await I();Object.keys(t).forEach((a=>{t[a].saveCreatedBookmarks&&(e=!0)})),e&&browser.bookmarks.onCreated.addListener(Sa)}async function Sa(e,t){const a=await browser.tabs.query({lastFocusedWindow:!0,active:!0}),n=await x(t.url);if(n.saveCreatedBookmarks){const o=await async function e(t,a=[]){if(t){const n=(await browser.bookmarks.get(t))[0];n&&n.title&&(a.unshift(n.title),await e(n.parentId,a))}return a}(t.parentId),s=n.allowedBookmarkFolders.toString(),i=o.find((e=>n.allowedBookmarkFolders.includes(e))),c=n.ignoredBookmarkFolders.toString(),l=o.find((e=>n.ignoredBookmarkFolders.includes(e)));if((s&&i||!s)&&(c&&!l||!c))if(a.length&&a[0].url==t.url)da(a,{bookmarkId:e,bookmarkFolders:o});else{const a=await browser.tabs.query({});if(a.length){const n=a.find((e=>e.url==t.url));n?da([n],{bookmarkId:e,bookmarkFolders:o}):t.url&&("about:blank"==t.url?browser.bookmarks.onChanged.addListener((function t(a,n){a==e&&n.url&&(browser.bookmarks.onChanged.removeListener(t),r(n.url))})):r(t.url))}}}function r(t){la([t],{bookmarkId:e})}}Promise.resolve().then(xa);async function Ta(e,t){let a=t||"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhYzZmZTMzMi0wODNjLTRjZmMtYmYxNC0xNWU5MTJmMWY4OWIiLCJpYXQiOjE1NzYxNzQzNDV9.n31j9ctJj7R1Vjwyc5yd1d6Cmg0NDnpwSaLWsqtZJQA";const n=await fetch("https://api.woleet.io/v1/anchor",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:"Bearer "+a},body:JSON.stringify({name:e,hash:e,public:!0})});if(401==n.status){const e=new Error("Your access token on Woleet is invalid. Go to __DOC_LINK__ to create your account.");throw e.link="https://app.woleet.io/",e}if(402==n.status){const e=new Error("You have no more credits on Woleet. Go to __DOC_LINK__ to recharge them.");throw e.link="https://app.woleet.io/",e}if(n.status>=400)throw new Error((n.statusText||"Error "+n.status)+" (Woleet)");return n.json()}const Ea="https://oauth2.googleapis.com/token",Pa="https://www.googleapis.com/drive/v3/files";let Ma,Wa=!0;class Aa{constructor(e){this.file=e.file,this.onProgress=e.onProgress,this.contentType=this.file.type||"application/octet-stream",this.metadata={name:e.filename,mimeType:this.contentType,parents:e.parents||["root"]},this.token=e.token,this.offset=0,this.chunkSize=e.chunkSize||524288}async upload(){const e=Oa(await fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",{method:"POST",headers:{Authorization:"Bearer "+this.token,"Content-Type":"application/json","X-Upload-Content-Length":this.file.size,"X-Upload-Content-Type":this.contentType},body:JSON.stringify(this.metadata)})).headers.get("Location");if(this.url=e,!this.cancelled)return this.onProgress&&this.onProgress(0,this.file.size),_a(this)}}async function La(e,t){const a=await fetch(Ea,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"client_id="+e.clientId+"&grant_type=authorization_code&code="+t.code+"&redirect_uri="+e.redirectURI}),n=await Da(a);return e.accessToken=n.access_token,e.refreshToken=n.refresh_token,e.expirationDate=Date.now()+1e3*n.expires_in,{accessToken:e.accessToken,refreshToken:e.refreshToken,expirationDate:e.expirationDate}}function Ra(e,t={}){return e.redirectURI=encodeURIComponent("urn:ietf:wg:oauth:2.0:oob"+(t.auto?":auto":"")),e.authURL="https://accounts.google.com/o/oauth2/v2/auth?client_id="+e.clientId+"&response_type=code&access_type=offline&redirect_uri="+e.redirectURI+"&scope="+e.scopes.join(" "),e.authURL}function Ca(e={}){return Boolean(browser.identity&&browser.identity.getAuthToken)&&!e.forceWebAuthFlow}async function Ua(e,t,a=!0){const n=t.split("/");n.pop();const r=e.folderIds.get(n.join("/"));if(r)return r;let o="root";if(n.length){let r="";for(const s of n){r&&(r+="/"),r+=s;const n=e.folderIds.get(r);if(n)o=n;else try{o=await Ba(e,s,o),e.folderIds.set(r,o)}catch(n){if("path_not_found"==n.message&&a)return e.folderIds.clear(),Ua(e,t,!1);throw n}}}return o}async function Ba(e,t,a){const n=await async function(e,t,a){return Da(await fetch(Pa+"?q=mimeType = 'application/vnd.google-apps.folder' and name = '"+t+"' and trashed != true and '"+a+"' in parents",{headers:{Authorization:"Bearer "+e.accessToken}}))}(e,t,a);if(n.files.length)return n.files[0].id;{const n=await async function(e,t,a){return Da(await fetch(Pa,{method:"POST",headers:{Authorization:"Bearer "+e.accessToken,"Content-Type":"application/json"},body:JSON.stringify({name:t,parents:[a],mimeType:"application/vnd.google-apps.folder"})}))}(e,t,a);return n.id}}async function _a(e){let t=e.file,a=e.file.size;(e.offset||e.chunkSize)&&(e.chunkSize&&(a=Math.min(e.offset+e.chunkSize,e.file.size)),t=t.slice(e.offset,a));const n=await fetch(e.url,{method:"PUT",headers:{Authorization:"Bearer "+e.token,"Content-Type":e.contentType,"Content-Range":"bytes "+e.offset+"-"+(a-1)+"/"+e.file.size,"X-Upload-Content-Type":e.contentType},body:t});if(e.onProgress&&!e.cancelled&&e.onProgress(e.offset+e.chunkSize,e.file.size),200==n.status||201==n.status)return n.json();if(308==n.status){const t=n.headers.get("Range");if(t&&(e.offset=parseInt(t.match(/\d+/g).pop(),10)+1),e.cancelled)throw new Error("upload_cancelled");return _a(e)}Oa(n)}async function Da(e){e=Oa(e);const t=await e.json();if(t.error)throw new Error(t.error);return t}function Oa(e){if(200==e.status)return e;throw 404==e.status?new Error("path_not_found"):401==e.status?new Error("invalid_token"):new Error("unknown_error ("+e.status+")")}async function ja(e,t,a,n,r,o){for(;Ma;)await Ma;const s=new AbortController;return Ma=(async()=>{try{await async function({path:r,content:o,message:s=""},i){try{const c=await fetch(`https://api.github.com/repos/${t}/${a}/contents/${r.replace(/#/g,"%23")}`,{method:"PUT",headers:new Map([["Authorization",`token ${e}`],["Accept","application/vnd.github.v3+json"]]),body:JSON.stringify({content:btoa(unescape(encodeURIComponent(o))),message:s,branch:n}),signal:i}),l=await c.json();if(c.status<400)return l;throw new Error(l.message)}catch(e){if("AbortError"!=e.name)throw e}}({path:r,content:o},s.signal)}finally{Ma=null}})(),{cancelPush:()=>s.abort(),pushPromise:Ma}}const Na=new Map,qa="text/html",Fa=/([{}()^$&.*?/+|[\\\\]|\]|-)/g,za=browser.runtime.getManifest(),Ha=za.optional_permissions&&za.optional_permissions.includes("identity"),Ja=new class{constructor(e,t){this.clientId=e,this.scopes=t,this.folderIds=new Map,setInterval((()=>this.folderIds.clear()),6e4)}async auth(e={interactive:!0,auto:!0}){if(e.requestPermissionIdentity&&Wa)try{await browser.permissions.request({permissions:["identity"]}),Wa=!1}catch(e){}return Ca(e)?(this.accessToken=await browser.identity.getAuthToken({interactive:e.interactive}),{revokableAccessToken:this.accessToken}):(Ra(this,e),e.code?La(this,e):async function(e,t){let a;t.extractAuthCode&&t.extractAuthCode(Ra(e,t)).then((e=>a=e)).catch((()=>{}));try{if(browser.identity&&browser.identity.launchWebAuthFlow&&!t.forceWebAuthFlow)return await browser.identity.launchWebAuthFlow({interactive:t.interactive,url:e.authURL});if(t.launchWebAuthFlow)return await t.launchWebAuthFlow({url:e.authURL});throw new Error("auth_not_supported")}catch(n){if(n.message&&("code_required"==n.message||n.message.includes("access"))){if(t.auto||a||!t.promptAuthCode||(a=await t.promptAuthCode()),a)return t.code=a,await La(e,t);throw new Error("code_required")}throw n}}(this,e))}setAuthInfo(e,t){Ca(t)||(e?(this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationDate=e.expirationDate):(delete this.accessToken,delete this.refreshToken,delete this.expirationDate))}async refreshAuthToken(){if(this.refreshToken){const e=await fetch(Ea,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"client_id="+this.clientId+"&refresh_token="+this.refreshToken+"&grant_type=refresh_token"});if(400==e.status)throw new Error("unknown_token");const t=await Da(e);return this.accessToken=t.access_token,t.refresh_token&&(this.refreshToken=t.refresh_token),t.expires_in&&(this.expirationDate=Date.now()+1e3*t.expires_in),{accessToken:this.accessToken,refreshToken:this.refreshToken,expirationDate:this.expirationDate}}}async revokeAuthToken(e){if(e){if(browser.identity&&browser.identity.removeCachedAuthToken)try{await browser.identity.removeCachedAuthToken({token:e})}catch(e){}const t=await fetch("https://accounts.google.com/o/oauth2/revoke",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"token="+e});try{await Da(t)}catch(e){if("invalid_token"!=e.message)throw e}finally{delete this.accessToken,delete this.refreshToken,delete this.expirationDate}}}async upload(e,t,a,n=!0){const r=await Ua(this,e),o=e.split("/").pop(),s=new Aa({token:this.accessToken,file:t,parents:[r],filename:o,onProgress:a.onProgress});try{return{cancelUpload:()=>s.cancelled=!0,uploadPromise:s.upload()}}catch(r){if("path_not_found"==r.message&&n)return this.folderIds.clear(),this.upload(e,t,a,!1);throw r}}}("207618107333-3pj2pmelhnl4sf3rpctghs9cean3q8nj.apps.googleusercontent.com",["https://www.googleapis.com/auth/drive.file"]);async function Ga(e,t){if(e.method.endsWith(".download"))return async function(e,t){let a;e.truncated?(a=Na.get(t.id),a||(a=[],Na.set(t.id,a)),a.push(e.content),e.finished&&Na.delete(t.id)):e.content&&(a=[e.content]);e.truncated&&!e.finished||(e.openEditor?(Bt(t.id),await async function({tabIndex:e,content:t,filename:a}){const n={active:!0,url:L};null!=e&&(n.index=e);const r=await browser.tabs.create(n);R.set(r.id,{content:t,filename:a})}({tabIndex:t.index+1,filename:e.filename,content:a.join("")})):e.saveToClipboard?(e.content=a.join(""),function(e){const t="copy";function a(t){t.clipboardData.setData(qa,e.content),t.clipboardData.setData("text/plain",e.content),t.preventDefault()}document.addEventListener(t,a),document.execCommand(t),document.removeEventListener(t,a)}(e),_t(t.id)):await async function(e,t,a,n){try{if(n.saveToGDrive?await(await Xa(n.taskId,n.filename,new Blob(e,{type:qa}),{forceWebAuthFlow:n.forceWebAuthFlow,extractAuthCode:n.extractAuthCode},{onProgress:(e,a)=>Dt(t.id,e,a)})).uploadPromise:n.saveToGitHub?await(await $a(n.taskId,n.filename,e.join(""),n.githubToken,n.githubUser,n.githubRepository,n.githubBranch)).pushPromise:n.saveWithCompanion?await ka({filename:n.filename,content:n.content,filenameConflictAction:n.filenameConflictAction}):(n.url=URL.createObjectURL(new Blob(e,{type:qa})),await Ya(n,{confirmFilename:n.confirmFilename,incognito:a,filenameConflictAction:n.filenameConflictAction,filenameReplacementCharacter:n.filenameReplacementCharacter,includeInfobar:n.includeInfobar})),_t(t.id),n.openSavedPage){const a={active:!0,url:URL.createObjectURL(new Blob(e,{type:qa}))};null!=t.index&&(a.index=t.index+1),browser.tabs.create(a)}}catch(e){e.message&&"upload_cancelled"==e.message||(console.error(e),Ut(t.id,e.message,e.link))}finally{n.url&&URL.revokeObjectURL(n.url)}}(a,t,t.incognito,e));return{}}(e,t.tab);if(e.method.endsWith(".disableGDrive")){const e=await E();return M(),await Ja.revokeAuthToken(e&&(e.accessToken||e.revokableAccessToken)),{}}if(e.method.endsWith(".end")){if(e.hash)try{await Ta(e.hash,e.woleetKey)}catch(e){Ut(t.tab.id,e.message,e.link)}return wa(e.taskId),{}}return e.method.endsWith(".getInfo")?oa.map(va):e.method.endsWith(".cancel")?(a=e.taskId,ya(oa.find((e=>e.id==a))),{}):e.method.endsWith(".cancelAll")?(Array.from(oa).forEach(ya),{}):e.method.endsWith(".saveUrls")?(la(e.urls),{}):void 0;var a}async function Ka(e,t){let a=await E();const n={interactive:!0,auto:e.extractAuthCode,forceWebAuthFlow:e.forceWebAuthFlow,requestPermissionIdentity:Ha,launchWebAuthFlow:e=>async function(e){const t=await browser.tabs.create({url:e.url,active:!0});return new Promise(((e,a)=>{browser.tabs.onRemoved.addListener((function e(n){n==t.id&&(browser.tabs.onRemoved.removeListener(e),a(new Error("code_required")))}))}))}(e),extractAuthCode:e=>function(e){return new Promise(((t,a)=>{let n;function r(a,s){s&&s.url==e&&(n=a),n==a&&s&&s.title&&s.title.startsWith("Success code=")&&(browser.tabs.onUpdated.removeListener(r),browser.tabs.onUpdated.removeListener(o),t(s.title.substring(13,s.title.length-49)))}function o(e){e==n&&(browser.tabs.onUpdated.removeListener(r),browser.tabs.onUpdated.removeListener(o),a())}browser.tabs.onUpdated.addListener(r),browser.tabs.onRemoved.addListener(o)}))}(e),promptAuthCode:()=>async function(e){const t=await browser.tabs.query({currentWindow:!0,active:!0});return new Promise(((a,n)=>{const r=t[0].id;browser.tabs.onRemoved.addListener((function e(t){t==r&&(J.delete(t),browser.tabs.onUpdated.removeListener(e),n())})),J.set(r,{resolve:a,reject:n}),browser.tabs.sendMessage(r,{method:"common.promptValueRequest",promptMessage:e})}))}("Please enter the access code for Google Drive")};return Ja.setAuthInfo(a,n),a&&a.accessToken&&!t||(a=await Ja.auth(n),a?await P(a):await M()),a}async function $a(e,t,a,n,r,o,s){const i=ga(e);if(!i||!i.cancelled){const i=ja(n,r,o,s,t,a);pa(e,i.cancelPush);try{return await(await i).pushPromise,i}catch(e){throw new Error(e.message+" (GitHub)")}}}async function Xa(e,t,a,n,r){try{await Ka(n);const o=ga(e);if(!o||!o.cancelled){const n=await Ja.upload(t,a,r);return pa(e,n.cancelUpload),n}}catch(o){if("invalid_token"!=o.message)throw new Error(o.message+" (Google Drive)");{let o;try{o=await Ja.refreshAuthToken()}catch(e){if("unknown_token"!=e.message)throw new Error(e.message+" (Google Drive)");o=await Ka(n,!0)}o?await P(o):await M(),await Xa(e,t,a,n,r)}}}async function Ya(t,a){let n;if("skip"==a.filenameConflictAction){(await browser.downloads.search({filenameRegex:"(\\\\|/)"+(r=t.filename,r.replace(Fa,"\\$1")+"$"),exists:!0})).length?n=!0:a.filenameConflictAction="uniquify"}var r;if(!n){const n={url:t.url,saveAs:a.confirmFilename,filename:t.filename,conflictAction:a.filenameConflictAction};a.incognito&&(n.incognito=!0);const r=await e(n,a.filenameReplacementCharacter);r.filename&&t.bookmarkId&&t.replaceBookmarkURL&&(r.filename.startsWith("file:")||(r.filename.startsWith("/")&&(r.filename=r.filename.substring(1)),r.filename="file:///"+r.filename.replace(/#/g,"%23")),await async function(e,t){try{await browser.bookmarks.update(e,t)}catch(e){}}(t.bookmarkId,{url:r.filename}))}}const Za={},Va={};async function Qa(e,t){if("enableAutoSave"==e.method){const a=await s(t.id);a[t.id].autoSave=e.enabled,await i(a),async function(e){Promise.all([kt(e),we(e)])}(t)}if("isAutoSaveEnabled"==e.method)return W(t)}async function en(e,t){const a=t.id,n=await x(t.url,!0);if(n){let r;Ct(a,1,!0),n.content=e.content,n.url=e.url,n.frames=e.frames,n.canvases=e.canvases,n.fonts=e.fonts,n.stylesheets=e.stylesheets,n.images=e.images,n.posters=e.posters,n.usedFonts=e.usedFonts,n.shadowRoots=e.shadowRoots,n.imports=e.imports,n.referrer=e.referrer,n.updatedResources=e.updatedResources,n.visitDate=new Date(e.visitDate),n.backgroundTab=!0,n.autoSave=!0,n.incognito=t.incognito,n.tabId=a,n.tabIndex=t.index;try{if(n.autoSaveExternalSave)await async function(e){e.autoSaveExternalSave=!1;const t=browser.runtime.connectNative("singlefile_companion");t.postMessage({method:"externalSave",pageData:e}),await new Promise(((e,a)=>{t.onDisconnect.addListener((()=>{t.error?a(new Error(t.error.message+" (Companion)")):browser.runtime.lastError&&!browser.runtime.lastError.message.includes("Native host has exited")||e()}))}))}(n);else{if(r=await function(e,t,a,n={fetch:Kt,frameFetch:$t}){return globalThis.singlefile.getPageData(e,n,t,a)}(n,null,null,{fetch:tn}),n.includeInfobar&&await infobar.includeScript(r),n.saveToGDrive){const t=new Blob([r.content],{type:"text/html"});await(await Xa(e.taskId,r.filename,t,n,{})).uploadPromise}else if(n.saveToGitHub)await(await $a(e.taskId,r.filename,r.content,n.githubToken,n.githubUser,n.githubRepository,n.githubBranch)).pushPromise;else if(n.saveWithCompanion)await ka({filename:r.filename,content:r.content,filenameConflictAction:r.filenameConflictAction});else{const e=new Blob([r.content],{type:"text/html"});if(r.url=URL.createObjectURL(e),await Ya(r,n),n.openSavedPage){const n={active:!0,url:URL.createObjectURL(e),windowId:t.windowId},r=t.index;try{await browser.tabs.get(a),n.index=r+1}catch(e){n.index=r}browser.tabs.create(n)}}r.hash&&await Ta(r.hash,n.woleetKey)}}finally{e.taskId?wa(e.taskId):n.autoClose&&(browser.tabs.remove(Va[a]||a),delete Va[a]),r&&r.url&&URL.revokeObjectURL(r.url),_t(a,!0)}}}function tn(e,t={}){return new Promise(((a,n)=>{const r=new XMLHttpRequest;if(r.withCredentials=!0,r.responseType="arraybuffer",r.onerror=e=>n(new Error(e.detail)),r.onreadystatechange=()=>{r.readyState==XMLHttpRequest.DONE&&a({status:r.status,headers:{get:e=>r.getResponseHeader(e)},arrayBuffer:async()=>r.response})},r.open("GET",e,!0),t.headers)for(const e of Object.entries(t.headers))r.setRequestHeader(e[0],e[1]);r.send()}))}async function an(e,t){if(e.method.endsWith(".init")&&(await async function(e,t){await r(e.id);const a=await s(e.id);a[e.id].savedPageDetected=t.savedPageDetected,await i(a)}(t.tab,e),xt(t.tab),function(e){ba(e.id)}(t.tab),async function(e){const[t,a]=await Promise.all([x(e.url,!0),W(e)]);t&&(t.autoSaveLoad||t.autoSaveLoadOrUnload)&&a&&da([e],{autoSave:!0})}(t.tab)),e.method.endsWith(".promptValueResponse")&&async function(e,t){const a=J.get(t.tab.id);a&&(a.resolve(e.value),J.delete(t.tab.id))}(e,t),e.method.endsWith(".getOptions"))return x(e.url);e.method.endsWith(".activate")&&await browser.tabs.update(e.tabId,{active:!0})}browser.tabs.onCreated.addListener((e=>function(e){!function(e){xt(e)}(e)}(e))),browser.tabs.onActivated.addListener((e=>async function(e){Ot(await browser.tabs.get(e.tabId))}(e))),browser.tabs.onRemoved.addListener((e=>function(e){r(e),function(e){R.delete(e)}(e),ba(e),async function(e){const t=Za[e];t?t.autoSaveRemove&&(delete Za[e],await en(t,t.tab)):Za[e]={removed:!0}}(e)}(e))),browser.tabs.onUpdated.addListener(((e,t)=>async function(e,t){if("complete"==t.status){setTimeout((async()=>{try{await browser.tabs.sendMessage(e,{method:"content.maybeInit"})}catch(e){}}),1500),function(e){delete Za[e]}(e);const t=await browser.tabs.get(e);if(B(t)){const e=await s(t.id);e[t.id].editorDetected=!0,await i(e),Ot(t)}}t.discarded&&async function(e){const t=Za[e];t?(delete Za[e],await en(t,t.tab)):Za[e]={discarded:!0}}(e)}(e,t))),browser.tabs.onReplaced.addListener(((e,t)=>function(e,t){!async function(e,t){Za[t]&&!Za[e]&&(Za[e]=Za[t],delete Za[t],Va[t]=e);const a=await s();a[t]&&!a[e]&&(a[e]=a[t],delete a[t],await i(a))}(e,t)}(e,t))),browser.runtime.onMessage.addListener(((e,t)=>{if("singlefile.frameTree.initResponse"==e.method||"singlefile.frameTree.ackInitRequest"==e.method)return browser.tabs.sendMessage(t.tab.id,e,{frameId:0}),Promise.resolve({})}));const nn=new Map;function rn(e,t){e.delete(t)}browser.runtime.onMessage.addListener(((e,t)=>{if("singlefile.lazyTimeout.setTimeout"==e.method){let a,n=nn.get(t.tab.id);if(n)if(a=n.get(t.frameId),a){const t=a.get(e.type);t&&clearTimeout(t)}else a=new Map;const r=setTimeout((async()=>{try{const a=nn.get(t.tab.id),n=a.get(t.frameId);a&&n&&rn(n,e.type),await browser.tabs.sendMessage(t.tab.id,{method:"singlefile.lazyTimeout.onTimeout",type:e.type})}catch(e){}}),e.delay);return n||(n=new Map,a=new Map,n.set(t.frameId,a),nn.set(t.tab.id,n)),a.set(e.type,r),Promise.resolve({})}if("singlefile.lazyTimeout.clearTimeout"==e.method){let a=nn.get(t.tab.id);if(a){const n=a.get(t.frameId);if(n){const t=n.get(e.type);t&&clearTimeout(t),rn(n,e.type)}}return Promise.resolve({})}})),browser.tabs.onRemoved.addListener((e=>nn.delete(e))),browser.runtime.onMessage.addListener(((e,t)=>e.method.startsWith("tabs.")?an(e,t):e.method.startsWith("downloads.")?Ga(e,t):e.method.startsWith("autosave.")?async function(e,t){if(e.method.endsWith(".save"))return e.autoSaveDiscard||e.autoSaveRemove?(t.tab?(e.tab=t.tab,Za[t.tab.id]=e):Za[e.tabId]&&(Za[e.tabId].removed&&e.autoSaveRemove||Za[e.tabId].discarded&&e.autoSaveDiscard)&&(delete Za[e.tabId],await en(e,{id:e.tabId,index:e.tabIndex,url:t.url})),e.autoSaveUnload&&(delete Za[e.tabId],await en(e,t.tab))):(delete Za[e.tabId],await en(e,t.tab)),{}}(e,t):e.method.startsWith("ui.")?Lt(e,t):e.method.startsWith("config.")?k(e):e.method.startsWith("tabsData.")?function(e){return e.method.endsWith(".get")?s():e.method.endsWith(".set")?i(e.tabsData):void 0}(e):e.method.startsWith("devtools.")?async function(e){e.method.endsWith(".resourceCommitted")&&e.tabId&&e.url&&("stylesheet"==e.type||"script"==e.type)&&await browser.tabs.sendMessage(e.tabId,e)}(e):e.method.startsWith("editor.")?async function(e,t){if(e.method.endsWith(".getTabData")){const e=t.tab,a=R.get(e.id);if(a){const t=await x(a.url),n=JSON.stringify(a);for(let a=0;a*AA,r.truncated?(r.finished=(a+1)*A>n.length,r.content=n.substring(a*A,(a+1)*A)):(r.content=n,r.options=t),await browser.tabs.sendMessage(e.id,r)}}}if(e.method.endsWith(".open")){let a;const n=t.tab;if(e.truncated?(a=C.get(n.id),a||(a=[],C.set(n.id,a)),a.push(e.content),e.finished&&C.delete(n.id)):e.content&&(a=[e.content]),!e.truncated||e.finished){const t={url:L};await browser.tabs.update(n.id,t),R.set(n.id,{url:n.url,content:a.join(""),filename:e.filename})}}}(e,t):e.method.startsWith("bookmarks.")?Ia(e):e.method.startsWith("companion.")?async function(e){if(e.method.endsWith(".state"))return{enabled:!0}}(e):e.method.startsWith("requests.")?F(e):e.method.startsWith("bootstrap.")?async function(e,t){if(e.method.endsWith(".init")){const[e,a]=await Promise.all([x(t.tab.url,!0),W(t.tab)]);return{options:e,autoSaveEnabled:a,tabId:t.tab.id,tabIndex:t.tab.index}}}(e,t):void 0)),browser.runtime.onMessageExternal&&browser.runtime.onMessageExternal.addListener((async(e,t)=>{const a=(await browser.tabs.query({currentWindow:!0,active:!0}))[0];return!!a&&Qa(e,a)}))}(); diff --git a/dist/extension-core.js b/dist/extension-core.js index f7798c21d..dca8cf4ca 100644 --- a/dist/extension-core.js +++ b/dist/extension-core.js @@ -1 +1 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).extension={})}(this,(function(e){"use strict";let t,r;const a=["dist/chrome-browser-polyfill.js","dist/single-file.js"],s=["dist/chrome-browser-polyfill.js","dist/single-file-frames.js"];async function n(e,n){let o;if(await async function(e){const n=e.extensionScriptFiles||[];t||r||([t,r]=await Promise.all([i(a.concat(n)),i(s)]))}(n),!n.removeFrames)try{await browser.tabs.executeScript(e,{code:r,allFrames:!0,matchAboutBlank:!0,runAt:"document_start"})}catch(e){}try{await browser.tabs.executeScript(e,{code:t,allFrames:!1,runAt:"document_idle"}),o=!0}catch(e){}return o&&n.frameId&&await browser.tabs.executeScript(e,{code:"document.documentElement.dataset.requestedFrameId = true",frameId:n.frameId,matchAboutBlank:!0,runAt:"document_start"}),o}async function i(e){const t=e.map((async e=>{if("function"==typeof e)return"("+e.toString()+")();";{const t=await fetch(browser.runtime.getURL("../../../"+e));return(new TextDecoder).decode(await t.arrayBuffer())}}));let r="";for(const e of t)r+=await e;return r}const o="single-file-response-fetch",c=(e,t)=>window.fetch(e,t);async function f(e,t={}){try{let r=await c(e,{cache:"force-cache",headers:t.headers});return 401!=r.status&&403!=r.status&&404!=r.status||(r=await l(e)),r}catch(r){const a=await d({method:"singlefile.fetch",url:e,referrer:t.referrer,headers:t.headers});return{status:a.status,headers:{get:e=>a.headers&&a.headers[e]},arrayBuffer:async()=>new Uint8Array(a.array).buffer}}}async function u(e,t){const r=await d({method:"singlefile.fetchFrame",url:e,frameId:t.frameId,referrer:t.referrer,headers:t.headers});return{status:r.status,headers:new Map(r.headers),arrayBuffer:async()=>new Uint8Array(r.array).buffer}}async function d(e){const t=await browser.runtime.sendMessage(e);if(!t||t.error)throw new Error(t&&t.error&&t.error.toString());return t}function l(e){return new Promise(((t,r)=>{var a,s,n,i;a=new CustomEvent("single-file-request-fetch",{detail:e}),window.dispatchEvent(a),s=o,n=function a(s){var n,i,c;s.detail?s.detail.url==e&&(n=o,i=a,c=!1,window.removeEventListener(n,i,c),s.detail.response?t({status:s.detail.status,headers:new Map(s.detail.headers),arrayBuffer:async()=>s.detail.response}):r(s.detail.error)):r()},i=!1,window.addEventListener(s,n,i)}))}browser.runtime.onMessage.addListener((e=>{if("singlefile.fetchFrame"==e.method&&window.frameId&&window.frameId==e.frameId)return async function(e){try{let t=await c(e.url,{cache:"force-cache",headers:e.headers});return 401!=t.status&&403!=t.status&&404!=t.status||(t=await Promise.race([l(e.url),new Promise(((e,t)=>setTimeout((()=>t()),5e3)))])),{status:t.status,headers:[...t.headers],array:Array.from(new Uint8Array(await t.arrayBuffer()))}}catch(e){return{error:e&&e.toString()}}}(e)})),e.getPageData=function(e,t,r,a={fetch:f,frameFetch:u}){return globalThis.singlefile.getPageData(e,a,t,r)},e.injectScript=function(e,t){return n(e,t)},Object.defineProperty(e,"__esModule",{value:!0})})); +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).extension={})}(this,(function(e){"use strict";let r,t;const a=["dist/chrome-browser-polyfill.js","dist/single-file.js"],s=["dist/chrome-browser-polyfill.js","dist/single-file-frames.js"];async function n(e,n){let o;if(await async function(e){const n=e.extensionScriptFiles||[];r||t||([r,t]=await Promise.all([i(a.concat(n)),i(s)]))}(n),!n.removeFrames)try{await browser.tabs.executeScript(e,{code:t,allFrames:!0,matchAboutBlank:!0,runAt:"document_start"})}catch(e){}try{await browser.tabs.executeScript(e,{code:r,allFrames:!1,runAt:"document_idle"}),o=!0}catch(e){}return o&&n.frameId&&await browser.tabs.executeScript(e,{code:"document.documentElement.dataset.requestedFrameId = true",frameId:n.frameId,matchAboutBlank:!0,runAt:"document_start"}),o}async function i(e){const r=e.map((async e=>{if("function"==typeof e)return"("+e.toString()+")();";{const r=await fetch(browser.runtime.getURL("../../../"+e));return(new TextDecoder).decode(await r.arrayBuffer())}}));let t="";for(const e of r)t+=await e;return t}const o="single-file-response-fetch",c=(e,r)=>window.fetch(e,r);let d=0,u=new Map;async function f(e,r={}){try{let t=await c(e,{cache:"force-cache",headers:r.headers});return 401!=t.status&&403!=t.status&&404!=t.status||(t=await w(e)),t}catch(t){d++;const a=new Promise(((e,r)=>u.set(d,{resolve:e,reject:r})));return await h({method:"singlefile.fetch",url:e,requestId:d,referrer:r.referrer,headers:r.headers}),a}}async function l(e,r){const t=await h({method:"singlefile.fetchFrame",url:e,frameId:r.frameId,referrer:r.referrer,headers:r.headers});return{status:t.status,headers:new Map(t.headers),arrayBuffer:async()=>new Uint8Array(t.array).buffer}}async function h(e){const r=await browser.runtime.sendMessage(e);if(!r||r.error)throw new Error(r&&r.error&&r.error.toString());return r}function w(e){return new Promise(((r,t)=>{var a,s,n,i;a=new CustomEvent("single-file-request-fetch",{detail:e}),window.dispatchEvent(a),s=o,n=function a(s){var n,i,c;s.detail?s.detail.url==e&&(n=o,i=a,c=!1,window.removeEventListener(n,i,c),s.detail.response?r({status:s.detail.status,headers:new Map(s.detail.headers),arrayBuffer:async()=>s.detail.response}):t(s.detail.error)):t()},i=!1,window.addEventListener(s,n,i)}))}browser.runtime.onMessage.addListener((e=>"singlefile.fetchFrame"==e.method&&window.frameId&&window.frameId==e.frameId?async function(e){try{let r=await c(e.url,{cache:"force-cache",headers:e.headers});return 401!=r.status&&403!=r.status&&404!=r.status||(r=await Promise.race([w(e.url),new Promise(((e,r)=>setTimeout((()=>r()),5e3)))])),{status:r.status,headers:[...r.headers],array:Array.from(new Uint8Array(await r.arrayBuffer()))}}catch(e){return{error:e&&e.toString()}}}(e):"singlefile.fetchResponse"==e.method?async function(e){const r=u.get(e.requestId);r&&(e.error?(r.reject(new Error(e.error)),u.delete(e.requestId)):(e.truncated&&(r.array?r.array=r.array.concat(e.array):(r.array=e.array,u.set(e.requestId,r)),e.finished&&(e.array=r.array)),e.truncated&&!e.finished||(r.resolve({status:e.status,headers:{get:r=>e.headers&&e.headers[r]},arrayBuffer:async()=>new Uint8Array(e.array).buffer}),u.delete(e.requestId))));return{}}(e):void 0)),e.getPageData=function(e,r,t,a={fetch:f,frameFetch:l}){return globalThis.singlefile.getPageData(e,a,r,t)},e.injectScript=function(e,r){return n(e,r)},Object.defineProperty(e,"__esModule",{value:!0})})); diff --git a/dist/extension-frames.js b/dist/extension-frames.js index efac85e0a..ec33b632e 100644 --- a/dist/extension-frames.js +++ b/dist/extension-frames.js @@ -1 +1 @@ -!function(){"use strict";const e="single-file-response-fetch";function r(r){return new Promise(((t,a)=>{var s,n,i,d;s=new CustomEvent("single-file-request-fetch",{detail:r}),window.dispatchEvent(s),n=e,i=function s(n){var i,d,o;n.detail?n.detail.url==r&&(i=e,d=s,o=!1,window.removeEventListener(i,d,o),n.detail.response?t({status:n.detail.status,headers:new Map(n.detail.headers),arrayBuffer:async()=>n.detail.response}):a(n.detail.error)):a()},d=!1,window.addEventListener(n,i,d)}))}browser.runtime.onMessage.addListener((e=>{if("singlefile.fetchFrame"==e.method&&window.frameId&&window.frameId==e.frameId)return async function(e){try{let s=await(t=e.url,a={cache:"force-cache",headers:e.headers},window.fetch(t,a));return 401!=s.status&&403!=s.status&&404!=s.status||(s=await Promise.race([r(e.url),new Promise(((e,r)=>setTimeout((()=>r()),5e3)))])),{status:s.status,headers:[...s.headers],array:Array.from(new Uint8Array(await s.arrayBuffer()))}}catch(e){return{error:e&&e.toString()}}var t,a}(e)}))}(); +!function(){"use strict";const e="single-file-response-fetch";let r=new Map;function a(r){return new Promise(((a,t)=>{var s,n,i,d;s=new CustomEvent("single-file-request-fetch",{detail:r}),window.dispatchEvent(s),n=e,i=function s(n){var i,d,o;n.detail?n.detail.url==r&&(i=e,d=s,o=!1,window.removeEventListener(i,d,o),n.detail.response?a({status:n.detail.status,headers:new Map(n.detail.headers),arrayBuffer:async()=>n.detail.response}):t(n.detail.error)):t()},d=!1,window.addEventListener(n,i,d)}))}browser.runtime.onMessage.addListener((e=>"singlefile.fetchFrame"==e.method&&window.frameId&&window.frameId==e.frameId?async function(e){try{let s=await(r=e.url,t={cache:"force-cache",headers:e.headers},window.fetch(r,t));return 401!=s.status&&403!=s.status&&404!=s.status||(s=await Promise.race([a(e.url),new Promise(((e,r)=>setTimeout((()=>r()),5e3)))])),{status:s.status,headers:[...s.headers],array:Array.from(new Uint8Array(await s.arrayBuffer()))}}catch(e){return{error:e&&e.toString()}}var r,t}(e):"singlefile.fetchResponse"==e.method?async function(e){const a=r.get(e.requestId);a&&(e.error?(a.reject(new Error(e.error)),r.delete(e.requestId)):(e.truncated&&(a.array?a.array=a.array.concat(e.array):(a.array=e.array,r.set(e.requestId,a)),e.finished&&(e.array=a.array)),e.truncated&&!e.finished||(a.resolve({status:e.status,headers:{get:r=>e.headers&&e.headers[r]},arrayBuffer:async()=>new Uint8Array(e.array).buffer}),r.delete(e.requestId))));return{}}(e):void 0))}(); diff --git a/dist/extension.js b/dist/extension.js index 158073a8f..6a2fa30c5 100644 --- a/dist/extension.js +++ b/dist/extension.js @@ -1 +1 @@ -!function(){"use strict";const t=33554432;async function e(e,n){if(n.includeInfobar&&await infobar.includeScript(e),n.includeBOM&&(e.content="\ufeff"+e.content),n.backgroundSave||n.openEditor||n.saveToGDrive||n.saveToGitHub||n.saveWithCompanion)for(let o=0;o*tt,r.truncated?(r.finished=(o+1)*t>e.content.length,r.content=e.content.substring(o*t,(o+1)*t)):r.content=e.content,await browser.runtime.sendMessage(r)}else n.saveToClipboard?function(t){const e="copy";function n(e){e.clipboardData.setData("text/html",t.content),e.clipboardData.setData("text/plain",t.content),e.preventDefault()}document.addEventListener(e,n),document.execCommand(e),document.removeEventListener(e,n)}(e):await async function(t){if(t.filename&&t.filename.length){const e=document.createElement("a");e.download=t.filename,e.href=URL.createObjectURL(new Blob([t.content],{type:"text/html"})),e.dispatchEvent(new MouseEvent("click")),URL.revokeObjectURL(e.href)}return new Promise((t=>setTimeout(t,1)))}(e),n.openSavedPage&&open(URL.createObjectURL(new Blob([e.content],{type:"text/html"}))),browser.runtime.sendMessage({method:"ui.processEnd"});await browser.runtime.sendMessage({method:"downloads.end",taskId:n.taskId,hash:e.hash,woleetKey:n.woleetKey})}const n="single-file-response-fetch",o=(t,e)=>window.fetch(t,e);async function r(t){const e=await browser.runtime.sendMessage(t);if(!e||e.error)throw new Error(e&&e.error&&e.error.toString());return e}function a(t){return new Promise(((e,o)=>{var r,a,i,s;r=new CustomEvent("single-file-request-fetch",{detail:t}),window.dispatchEvent(r),a=n,i=function r(a){var i,s,l;a.detail?a.detail.url==t&&(i=n,s=r,l=!1,window.removeEventListener(i,s,l),a.detail.response?e({status:a.detail.status,headers:new Map(a.detail.headers),arrayBuffer:async()=>a.detail.response}):o(a.detail.error)):o()},s=!1,window.addEventListener(a,i,s)}))}browser.runtime.onMessage.addListener((t=>{if("singlefile.fetchFrame"==t.method&&window.frameId&&window.frameId==t.frameId)return async function(t){try{let e=await o(t.url,{cache:"force-cache",headers:t.headers});return 401!=e.status&&403!=e.status&&404!=e.status||(e=await Promise.race([a(t.url),new Promise(((t,e)=>setTimeout((()=>e()),5e3)))])),{status:e.status,headers:[...e.headers],array:Array.from(new Uint8Array(await e.arrayBuffer()))}}catch(t){return{error:t&&t.toString()}}}(t)}));const i=globalThis.singlefile,s=i.helper.SELECTED_CONTENT_ATTRIBUTE_NAME,l="singlefile-mask",c="singlefile-mask-content",d="singlefile-progress-bar",p="singlefile-progress-bar-content",u="single-file-selection-zone",m="singlefile-logs-window",f="singlefile-logs",h="singlefile-logs-line",g="singlefile-logs-line-text",y="singlefile-logs-line-icon",E=i.helper.SINGLE_FILE_UI_ELEMENT_CLASS,b=browser.i18n.getMessage("logPanelDeferredImages"),w=browser.i18n.getMessage("logPanelFrameContents"),A=browser.i18n.getMessage("logPanelStep"),v=browser.i18n.getMessage("logPanelWidth"),C=new Set(Array.from(getComputedStyle(document.documentElement)));let S,x;function I(t,e){return prompt(t,e)}function T(t){if(!document.querySelector(l)&&(t.logsEnabled&&document.body.appendChild(x),t.shadowEnabled)){const e=function(){try{let t=document.querySelector(l);if(!t){t=W(l,document.body);const e=t.attachShadow({mode:"open"}),n=document.createElement("style");n.textContent="\n\t\t\t\t@keyframes single-file-progress { \n\t\t\t\t\t0% { \n\t\t\t\t\t\tleft: -50px;\n\t\t\t\t\t} \n\t\t\t\t\t100% { \n\t\t\t\t\t\tleft: 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t.singlefile-progress-bar {\n\t\t\t\t\tposition: fixed;\n\t\t\t\t\ttop: 0;\n\t\t\t\t\tleft: 0;\n\t\t\t\t\twidth: 0;\n\t\t\t\t\theight: 8px;\n\t\t\t\t\tz-index: 2147483646;\n\t\t\t\t\topacity: .5;\n\t\t\t\t\toverflow: hidden;\t\t\t\t\t\n\t\t\t\t\ttransition: width 200ms ease-in-out;\n\t\t\t\t}\n\t\t\t\t.singlefile-progress-bar-content {\n\t\t\t\t\tposition: absolute;\n\t\t\t\t\tleft: 0;\n\t\t\t\t\tanimation: single-file-progress 3s linear infinite reverse;\n\t\t\t\t\tbackground: \n\t\t\t\t\t\twhite \n\t\t\t\t\t\tlinear-gradient(-45deg, rgba(0, 0, 0, 0.075) 25%, \n\t\t\t\t\t\t\ttransparent 25%, \n\t\t\t\t\t\t\ttransparent 50%, \n\t\t\t\t\t\t\trgba(0, 0, 0, 0.075) 50%, \n\t\t\t\t\t\t\trgba(0, 0, 0, 0.075) 75%, \n\t\t\t\t\t\t\ttransparent 75%, transparent)\n\t\t\t\t\t\trepeat scroll 0% 0% / 50px 50px padding-box border-box;\n\t\t\t\t\twidth: calc(100% + 50px);\n\t\t\t\t\theight: 100%;\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t.singlefile-mask-content {\n\t\t\t\t\tposition: fixed;\n\t\t\t\t\ttop: 0;\n\t\t\t\t\tleft: 0;\n\t\t\t\t\twidth: 100%;\n\t\t\t\t\theight: 100%;\n\t\t\t\t\tz-index: 2147483646;\n\t\t\t\t\topacity: 0;\n\t\t\t\t\tbackground-color: black;\n\t\t\t\t\ttransition: opacity 250ms;\n\t\t\t\t}\n\t\t\t",e.appendChild(n);let o=document.createElement("div");o.classList.add(c),e.appendChild(o),t.offsetWidth,o.style.setProperty("opacity",.3),t.offsetWidth}return t}catch(t){}}();t.progressBarEnabled&&function(t){try{if(!t.shadowRoot.querySelector("."+d)){let e=document.createElement("div");e.classList.add(d),t.shadowRoot.appendChild(e);const n=document.createElement("div");n.classList.add(p),e.appendChild(n)}}catch(t){}}(e)}}function L(){const t=document.querySelector(l);t&&t.remove(),x.remove(),O()}function k(t,e,n){n.shadowEnabled&&n.progressBarEnabled&&function(t,e){try{const n=document.querySelector(l);if(n){const o=n.shadowRoot.querySelector("."+d);if(o&&e){const n=Math.floor(t/e*100)+"%";o.style.getPropertyValue("width")!=n&&(o.style.setProperty("width",n),o.offsetWidth)}}}catch(t){}}(t,e)}function P(){let t;const e=[],n=getSelection();for(let o=0;o{"A"==t.tagName&&t.href&&e.push(n.currentNode.href)}))}}return Array.from(new Set(e))}async function R(t){let e=N();return e||t?e:(e=await new Promise((t=>{let e=[];function n(t){e=[],s(),t.preventDefault()}function o(t){const e=function(t){let e,n=t.target,o=n.getBoundingClientRect();for(e=H("floor",n,t.clientX-o.left,q(n,"left")),e==n&&(e=H("ceil",n,o.left+o.width-t.clientX,q(n,"right"))),e==n&&(e=H("floor",n,t.clientY-o.top,q(n,"top"))),e==n&&(e=H("ceil",n,o.top+o.height-t.clientY,q(n,"bottom"))),n=e;n&&n.clientWidth<=8&&n.clientHeight<=8;)n=n.parentElement;return n}(t);var n;e&&(S=e,n=e,requestAnimationFrame((()=>{const t=M(),e=n.getBoundingClientRect(),o=document.scrollingElement||document.documentElement;t.style.setProperty("top",o.scrollTop+e.top-10+"px"),t.style.setProperty("left",o.scrollLeft+e.left-10+"px"),t.style.setProperty("width",e.width+20+"px"),t.style.setProperty("height",e.height+20+"px")})))}function r(t){t.preventDefault(),t.stopPropagation(),0==t.button?s(S,t.ctrlKey):i()}function a(t){"Escape"==t.key&&i()}function i(){e.length&&getSelection().removeAllRanges(),e=[],c()}function s(t,e){if(t){e||d();const n=document.createRange();n.selectNodeContents(t),l(),getSelection().addRange(n),p(),e||c()}else c()}function l(){const t=getSelection();for(let e=t.rangeCount-1;e>=0;e--){const n=t.getRangeAt(e);n.startOffset==n.endOffset&&(t.removeRange(n),e--)}}function c(){M().remove(),removeEventListener("mousemove",o,!0),removeEventListener("click",r,!0),removeEventListener("keyup",a,!0),S=null,t(Boolean(e.length)),setTimeout((()=>document.removeEventListener("contextmenu",n,!0)),0)}function d(){getSelection().removeAllRanges(),e.forEach((t=>getSelection().addRange(t)))}function p(){e=[];for(let t=0;tD(t)))}}return e}function D(t){(t.nodeType==Node.ELEMENT_NODE?t:t.parentElement).setAttribute(s,"")}function B(t){t.parentElement&&(D(t),B(t.parentElement))}function M(){let t=document.querySelector(u);return t||(t=W(u,document.body),t.style.setProperty("box-sizing","border-box","important"),t.style.setProperty("background-color","#3ea9d7","important"),t.style.setProperty("border","10px solid #0b4892","important"),t.style.setProperty("border-radius","2px","important"),t.style.setProperty("opacity",".25","important"),t.style.setProperty("pointer-events","none","important"),t.style.setProperty("position","absolute","important"),t.style.setProperty("transition","all 100ms","important"),t.style.setProperty("cursor","pointer","important"),t.style.setProperty("z-index","2147483647","important"),t.style.removeProperty("border-inline-end"),t.style.removeProperty("border-inline-start"),t.style.removeProperty("inline-size"),t.style.removeProperty("block-size"),t.style.removeProperty("inset-block-start"),t.style.removeProperty("inset-inline-end"),t.style.removeProperty("inset-block-end"),t.style.removeProperty("inset-inline-start")),t}function O(){try{if(x=document.querySelector(m),!x){x=W(m);const t=x.attachShadow({mode:"open"}),e=document.createElement("style");e.textContent=`\n\t\t\t\t@keyframes single-file-pulse { \n\t\t\t\t\t0% { \n\t\t\t\t\t\topacity: .25;\n\t\t\t\t\t} \n\t\t\t\t\t100% { \n\t\t\t\t\t\topacity: 1;\n\t\t\t\t\t} \n\t\t\t\t}\n\t\t\t\t.singlefile-logs {\n\t\t\t\t\tposition: fixed;\n\t\t\t\t\tbottom: 24px;\n\t\t\t\t\tleft: 8px;\n\t\t\t\t\tz-index: 2147483647;\n\t\t\t\t\topacity: 0.9;\n\t\t\t\t\tpadding: 4px;\n\t\t\t\t\tbackground-color: white;\n\t\t\t\t\tmin-width: ${v}px;\n\t\t\t\t\tmin-height: 16px;\n\t\t\t\t\ttransition: height 100ms;\n\t\t\t\t}\n\t\t\t\t.singlefile-logs-line {\n\t\t\t\t\tdisplay: flex;\n\t\t\t\t\tjustify-content: space-between;\n\t\t\t\t\tpadding: 2px;\n\t\t\t\t\tfont-family: arial, sans-serif;\n\t\t\t\t\tcolor: black;\n\t\t\t\t\tbackground-color: white;\n\t\t\t\t}\n\t\t\t\t.singlefile-logs-line-text {\n\t\t\t\t\tfont-size: 13px;\n\t\t\t\t\topacity: 1;\n\t\t\t\t\ttransition: opacity 200ms;\n\t\t\t\t}\n\t\t\t\t.singlefile-logs-line-icon {\n\t\t\t\t\tfont-size: 11px;\n\t\t\t\t\tmin-width: 15px;\n\t\t\t\t\ttext-align: center;\n\t\t\t\t\tposition: relative;\n\t\t\t\t\ttop: 1px;\n\t\t\t\t}\n\t\t\t`,t.appendChild(e);const n=document.createElement("div");n.classList.add(f),t.appendChild(n)}}catch(t){}}function U(t,e,n,o){try{if(o.logsEnabled){const o=x.shadowRoot.querySelector(".singlefile-logs");let r=o.querySelector("[data-id='"+t+"']");if(!r){r=document.createElement("div"),r.classList.add(h),o.appendChild(r),r.setAttribute("data-id",t);const n=document.createElement("div");n.classList.add(g),r.appendChild(n),n.textContent=e;const a=document.createElement("div");a.classList.add(y),r.appendChild(a)}!function(t,e,n){const o=t.childNodes[0],r=t.childNodes[1];o.textContent=e,r.style.setProperty("color","✓"==n?"#055000":"black"),"✓"==n?(o.style.setProperty("opacity",".5"),r.style.setProperty("opacity",".5"),r.style.setProperty("animation","none")):r.style.setProperty("animation","1s ease-in-out 0s infinite alternate none running single-file-pulse");r.textContent=n}(r,e,n)}}catch(t){}}function q(t,e){let n,o=t,r=[];do{const t=o.getBoundingClientRect();if(o.parentElement){const a=o.parentElement.getBoundingClientRect();n=Math.abs(a[e]-t[e])<=8,n&&(o.parentElement.clientWidth>8&&o.parentElement.clientHeight>8&&(o.parentElement.clientWidth-o.clientWidth>8||o.parentElement.clientHeight-o.clientHeight>8)&&r.push(o.parentElement),o=o.parentElement)}else n=!1}while(n&&o);return r}function H(t,e,n,o){return Math[t](n/8)<=o.length&&(e=o[o.length-Math[t](n/8)-1]),e}function W(t,e){const n=document.createElement(t);return n.className=E,e&&e.appendChild(n),C.forEach((t=>n.style.setProperty(t,"initial","important"))),n}O();const F=globalThis.singlefile,_=F.helper.SINGLE_FILE_UI_ELEMENT_CLASS,G="singlefile-error-bar",z=new Set(Array.from(getComputedStyle(document.documentElement)));let X;function Q(t,e){try{if(console.error("SingleFile",t,e),X=document.querySelector(G),!X){X=function(t,e){const n=document.createElement(t);n.className=_,e&&e.appendChild(n);return z.forEach((t=>n.style.setProperty(t,"initial","important"))),n}(G);const n=X.attachShadow({mode:"open"}),o=document.createElement("style");o.textContent="\n\t\t\t\t.container {\n\t\t\t\t\tbackground-color: #ff6c00;\n\t\t\t\t\tcolor: white;\n\t\t\t\t\tdisplay: flex;\n\t\t\t\t\tposition: fixed;\n\t\t\t\t\ttop: 0px;\n\t\t\t\t\tleft: 0px;\n\t\t\t\t\tright: 0px;\n\t\t\t\t\theight: auto;\n\t\t\t\t\twidth: auto;\n\t\t\t\t\tmin-height: 24px;\n\t\t\t\t\tmin-width: 24px;\t\t\t\t\t\n\t\t\t\t\tz-index: 2147483647;\n\t\t\t\t\tmargin: 0;\n\t\t\t\t\tpadding: 2px;\n\t\t\t\t\tfont-family: Arial;\n\t\t\t\t}\n\t\t\t\t.text {\n\t\t\t\t\tflex: 1;\n\t\t\t\t\tpadding-top: 4px;\n\t\t\t\t\tpadding-bottom: 4px;\n\t\t\t\t\tpadding-left: 8px;\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t.close-button {\n\t\t\t\t\topacity: .7;\n\t\t\t\t\tpadding-top: 4px;\n\t\t\t\t\tpadding-left: 8px;\n\t\t\t\t\tpadding-right: 8px;\n\t\t\t\t\tcursor: pointer;\n\t\t\t\t\ttransition: opacity 250ms;\n\t\t\t\t\theight: 16px;\n\t\t\t\t}\n\t\t\t\ta {\n\t\t\t\t\tcolor: #303036;\n\t\t\t\t}\n\t\t\t\t.close-button:hover {\n\t\t\t\t\topacity: 1;\n\t\t\t\t}\n\t\t\t",n.appendChild(o);const r=document.createElement("div");r.className="container";const a=document.createElement("span");a.classList.add("text");const i=t.split("__DOC_LINK__");if(a.textContent="SingleFile error: "+i[0],e&&2==i.length){const t=document.createElement("a");t.textContent=e,t.href=e,t.target="_blank",a.appendChild(t),a.appendChild(document.createTextNode(i[1]))}r.appendChild(a);const s=document.createElement("img");s.classList.add("close-button"),r.appendChild(s),n.appendChild(r),s.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAABhmlDQ1BJQ0MgcHJvZmlsZQAAKJF9kT1Iw0AYht+mSlUqHewg4hChOogFURFHqWIRLJS2QqsOJpf+CE0akhQXR8G14ODPYtXBxVlXB1dBEPwBcXNzUnSREr9LCi1ivOO4h/e+9+XuO0Col5lqdowDqmYZqXhMzOZWxMAruhGiOYohiZl6Ir2Qgef4uoeP73dRnuVd9+foVfImA3wi8SzTDYt4nXh609I57xOHWUlSiM+Jxwy6IPEj12WX3zgXHRZ4ZtjIpOaIw8RisY3lNmYlQyWeIo4oqkb5QtZlhfMWZ7VcZc178hcG89pymuu0BhHHIhJIQoSMKjZQhoUo7RopJlJ0HvPwDzj+JLlkcm2AkWMeFaiQHD/4H/zurVmYnHCTgjGg88W2P4aBwC7QqNn297FtN04A/zNwpbX8lTow80l6raVFjoDQNnBx3dLkPeByB+h/0iVDciQ/LaFQAN7P6JtyQN8t0LPq9q15jtMHIEO9WroBDg6BkSJlr3m8u6u9b//WNPv3A6mTcr3f/E/sAAAABmJLR0QAigCKAIrj2uckAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAB3RJTUUH5QkPDysvCdPVuwAAABl0RVh0Q29tbWVudABDcmVhdGVkIHdpdGggR0lNUFeBDhcAAAELSURBVHja7ZpLFsIwDAPj3v/OsGHDe1BIa8tKO7Mnlkw+dpoxAAAAAGCfx4ur6Yx/B337UUS4mp/VuWUEcjSfOgO+BXCZCWe0hSqQo/npBLglIUNLdAV2MH84Ad1JyIwdLkK6YoabIHWscBWmihHuAqvHtv+XqmdXOK9TxdKy3axUm2vZkXXGgPJksTuz1bVFeeU2Y6ijsLIpXbtKa1kDs2ews69o7+A+ihJ2lvI+/lcS1G21zUVG18XKNm4OS4BNkGOQQohSmGaIdpgLESvzyiRwKepsXjE2H0ZWMF8Zi4+jK5mviM0DiRXNZ2rhkdTK5jO0xermz2o8dCnq+FS2XNNVH0sDAAAA3JYnre9cH8BZmhEAAAAASUVORK5CYII=",s.onclick=t=>{0===t.button&&X.remove()},document.body.appendChild(X)}}catch(t){}}const Z=globalThis.singlefile,j=globalThis.singlefileBootstrap,V="moz-extension:";let K,J;Z.init({fetch:async function(t,e={}){try{let n=await o(t,{cache:"force-cache",headers:e.headers});return 401!=n.status&&403!=n.status&&404!=n.status||(n=await a(t)),n}catch(n){const o=await r({method:"singlefile.fetch",url:t,referrer:e.referrer,headers:e.headers});return{status:o.status,headers:{get:t=>o.headers&&o.headers[t]},arrayBuffer:async()=>new Uint8Array(o.array).buffer}}},frameFetch:async function(t,e){const n=await r({method:"singlefile.fetchFrame",url:t,frameId:e.frameId,referrer:e.referrer,headers:e.headers});return{status:n.status,headers:new Map(n.headers),arrayBuffer:async()=>new Uint8Array(n.array).buffer}}}),browser.runtime.onMessage.addListener((t=>{if("content.save"==t.method||"content.cancelSave"==t.method||"content.getSelectedLinks"==t.method||"content.error"==t.method)return async function(t){if(!location.href.startsWith(V)){if("content.save"==t.method)return await async function(t){const n=t.options;let o;(n.selected||n.optionallySelected)&&(o=await R(n.optionallySelected));if(!(J||j&&j.pageInfo.processing)){if(n.updatedResources=j?j.pageInfo.updatedResources:{},n.visitDate=j?j.pageInfo.visitDate:new Date,Object.keys(n.updatedResources).forEach((t=>n.updatedResources[t].retrieved=!1)),n.optionallySelected&&o&&(n.selected=!0),!n.selected||o){j&&(j.pageInfo.processing=!0),J=!0;try{const t=await async function(t){const e=Z.processors.frameTree;let n;Z.helper.initDoc(document),T(t),K=new Z.SingleFile(t);const o=[];if(t.insertCanonicalLink=!0,!t.saveRawPage){if(!t.removeFrames&&e&&globalThis.frames&&globalThis.frames.length){let n;n=t.loadDeferredImages?new Promise((n=>setTimeout((()=>n(e.getAsync(t))),t.loadDeferredImagesMaxIdleTime-e.TIMEOUT_INIT_REQUEST_MESSAGE))):e.getAsync(t),function(t){U("load-frames",w,"…",t)}(t),n.then((()=>{K.cancelled||function(t){U("load-frames",w,"✓",t)}(t)})),o.push(n)}if(t.loadDeferredImages){const e=Z.processors.lazy.process(t);!function(t){U("load-deferred-images",b,"…",t)}(t),e.then((()=>{K.cancelled||function(t){U("load-deferred-images",b,"✓",t)}(t)})),o.push(e)}}let r=0,a=0;t.onprogress=e=>{K.cancelled||(e.type==e.RESOURCES_INITIALIZED&&(a=e.detail.max,t.loadDeferredImages&&Z.processors.lazy.resetZoomLevel(t)),e.type==e.RESOURCES_INITIALIZED||e.type==e.RESOURCE_LOADED?(e.type==e.RESOURCE_LOADED&&r++,browser.runtime.sendMessage({method:"ui.processProgress",index:r,maxIndex:a}),k(r,a,t)):e.detail.frame||e.type==e.PAGE_LOADING||e.type==e.PAGE_LOADED||(e.type==e.STAGE_STARTED?e.detail.step<3&&function(t,e){U("step-"+t,`${A} ${t+1} / 3`,"…",e)}(e.detail.step,t):e.type==e.STAGE_ENDED?e.detail.step<3&&function(t,e){U("step-"+t,`${A} ${t+1} / 3`,"✓",e)}(e.detail.step,t):(e.type==e.STAGE_TASK_STARTED||e.type==e.STAGE_TASK_ENDED)&&(e.detail.step,e.detail.task)))},[t.frames]=await new Promise((t=>{const e=Promise.all(o),n=K.cancel.bind(K);K.cancel=function(){n(),t([[]])},e.then((()=>t(e)))})),n=t.frames&&t.frames.sessionId;const i=t.frames&&t.frames.find((t=>t.requestedFrame));t.win=globalThis,i?(t.content=i.content,t.url=i.baseURI,t.canvases=i.canvases,t.fonts=i.fonts,t.stylesheets=i.stylesheets,t.images=i.images,t.posters=i.posters,t.usedFonts=i.usedFonts,t.shadowRoots=i.shadowRoots,t.imports=i.imports):t.doc=document;K.cancelled||await K.run();n&&e.cleanup(n);let l;K.cancelled||(t.confirmInfobarContent&&(t.infobarContent=I("Infobar content",t.infobarContent)||""),l=await K.getPageData(),(t.selected||t.optionallySelected)&&document.querySelectorAll("["+s+"]").forEach((t=>t.removeAttribute(s))),L(),t.displayStats&&(console.log("SingleFile stats"),console.table(l.stats)));return l}(n);t&&((!n.backgroundSave&&!n.saveToClipboard||n.saveToGDrive||n.saveToGitHub||n.saveWithCompanion)&&n.confirmFilename&&(t.filename=I("Save as",t.filename)||t.filename),await e(t,n))}catch(t){K.cancelled||(console.error(t),browser.runtime.sendMessage({method:"ui.processError",error:t}))}}else browser.runtime.sendMessage({method:"ui.processCancelled"});J=!1,j&&(j.pageInfo.processing=!1)}}(t),{};if("content.cancelSave"==t.method)return K&&(K.cancel(),L(),browser.runtime.sendMessage({method:"ui.processCancelled"})),t.options.loadDeferredImages&&Z.processors.lazy.resetZoomLevel(t.options),{};if("content.getSelectedLinks"==t.method)return{urls:P()};"content.error"==t.method&&Q(t.error,t.link)}}(t)}))}(); +!function(){"use strict";const t=33554432;async function e(e,n){if(n.includeInfobar&&await infobar.includeScript(e),n.includeBOM&&(e.content="\ufeff"+e.content),n.backgroundSave||n.openEditor||n.saveToGDrive||n.saveToGitHub||n.saveWithCompanion)for(let o=0;o*tt,r.truncated?(r.finished=(o+1)*t>e.content.length,r.content=e.content.substring(o*t,(o+1)*t)):r.content=e.content,await browser.runtime.sendMessage(r)}else n.saveToClipboard?function(t){const e="copy";function n(e){e.clipboardData.setData("text/html",t.content),e.clipboardData.setData("text/plain",t.content),e.preventDefault()}document.addEventListener(e,n),document.execCommand(e),document.removeEventListener(e,n)}(e):await async function(t){if(t.filename&&t.filename.length){const e=document.createElement("a");e.download=t.filename,e.href=URL.createObjectURL(new Blob([t.content],{type:"text/html"})),e.dispatchEvent(new MouseEvent("click")),URL.revokeObjectURL(e.href)}return new Promise((t=>setTimeout(t,1)))}(e),n.openSavedPage&&open(URL.createObjectURL(new Blob([e.content],{type:"text/html"}))),browser.runtime.sendMessage({method:"ui.processEnd"});await browser.runtime.sendMessage({method:"downloads.end",taskId:n.taskId,hash:e.hash,woleetKey:n.woleetKey})}const n="single-file-response-fetch",o=(t,e)=>window.fetch(t,e);let r=0,a=new Map;async function i(t){const e=await browser.runtime.sendMessage(t);if(!e||e.error)throw new Error(e&&e.error&&e.error.toString());return e}function s(t){return new Promise(((e,o)=>{var r,a,i,s;r=new CustomEvent("single-file-request-fetch",{detail:t}),window.dispatchEvent(r),a=n,i=function r(a){var i,s,l;a.detail?a.detail.url==t&&(i=n,s=r,l=!1,window.removeEventListener(i,s,l),a.detail.response?e({status:a.detail.status,headers:new Map(a.detail.headers),arrayBuffer:async()=>a.detail.response}):o(a.detail.error)):o()},s=!1,window.addEventListener(a,i,s)}))}browser.runtime.onMessage.addListener((t=>"singlefile.fetchFrame"==t.method&&window.frameId&&window.frameId==t.frameId?async function(t){try{let e=await o(t.url,{cache:"force-cache",headers:t.headers});return 401!=e.status&&403!=e.status&&404!=e.status||(e=await Promise.race([s(t.url),new Promise(((t,e)=>setTimeout((()=>e()),5e3)))])),{status:e.status,headers:[...e.headers],array:Array.from(new Uint8Array(await e.arrayBuffer()))}}catch(t){return{error:t&&t.toString()}}}(t):"singlefile.fetchResponse"==t.method?async function(t){const e=a.get(t.requestId);e&&(t.error?(e.reject(new Error(t.error)),a.delete(t.requestId)):(t.truncated&&(e.array?e.array=e.array.concat(t.array):(e.array=t.array,a.set(t.requestId,e)),t.finished&&(t.array=e.array)),t.truncated&&!t.finished||(e.resolve({status:t.status,headers:{get:e=>t.headers&&t.headers[e]},arrayBuffer:async()=>new Uint8Array(t.array).buffer}),a.delete(t.requestId))));return{}}(t):void 0));const l=globalThis.singlefile,c=l.helper.SELECTED_CONTENT_ATTRIBUTE_NAME,d="singlefile-mask",p="singlefile-mask-content",u="singlefile-progress-bar",m="singlefile-progress-bar-content",f="single-file-selection-zone",h="singlefile-logs-window",g="singlefile-logs",y="singlefile-logs-line",w="singlefile-logs-line-text",E="singlefile-logs-line-icon",b=l.helper.SINGLE_FILE_UI_ELEMENT_CLASS,A=browser.i18n.getMessage("logPanelDeferredImages"),v=browser.i18n.getMessage("logPanelFrameContents"),C=browser.i18n.getMessage("logPanelStep"),S=browser.i18n.getMessage("logPanelWidth"),x=new Set(Array.from(getComputedStyle(document.documentElement)));let I,T;function L(t,e){return prompt(t,e)}function P(t){if(!document.querySelector(d)&&(t.logsEnabled&&document.body.appendChild(T),t.shadowEnabled)){const e=function(){try{let t=document.querySelector(d);if(!t){t=_(d,document.body);const e=t.attachShadow({mode:"open"}),n=document.createElement("style");n.textContent="\n\t\t\t\t@keyframes single-file-progress { \n\t\t\t\t\t0% { \n\t\t\t\t\t\tleft: -50px;\n\t\t\t\t\t} \n\t\t\t\t\t100% { \n\t\t\t\t\t\tleft: 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t.singlefile-progress-bar {\n\t\t\t\t\tposition: fixed;\n\t\t\t\t\ttop: 0;\n\t\t\t\t\tleft: 0;\n\t\t\t\t\twidth: 0;\n\t\t\t\t\theight: 8px;\n\t\t\t\t\tz-index: 2147483646;\n\t\t\t\t\topacity: .5;\n\t\t\t\t\toverflow: hidden;\t\t\t\t\t\n\t\t\t\t\ttransition: width 200ms ease-in-out;\n\t\t\t\t}\n\t\t\t\t.singlefile-progress-bar-content {\n\t\t\t\t\tposition: absolute;\n\t\t\t\t\tleft: 0;\n\t\t\t\t\tanimation: single-file-progress 3s linear infinite reverse;\n\t\t\t\t\tbackground: \n\t\t\t\t\t\twhite \n\t\t\t\t\t\tlinear-gradient(-45deg, rgba(0, 0, 0, 0.075) 25%, \n\t\t\t\t\t\t\ttransparent 25%, \n\t\t\t\t\t\t\ttransparent 50%, \n\t\t\t\t\t\t\trgba(0, 0, 0, 0.075) 50%, \n\t\t\t\t\t\t\trgba(0, 0, 0, 0.075) 75%, \n\t\t\t\t\t\t\ttransparent 75%, transparent)\n\t\t\t\t\t\trepeat scroll 0% 0% / 50px 50px padding-box border-box;\n\t\t\t\t\twidth: calc(100% + 50px);\n\t\t\t\t\theight: 100%;\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t.singlefile-mask-content {\n\t\t\t\t\tposition: fixed;\n\t\t\t\t\ttop: 0;\n\t\t\t\t\tleft: 0;\n\t\t\t\t\twidth: 100%;\n\t\t\t\t\theight: 100%;\n\t\t\t\t\tz-index: 2147483646;\n\t\t\t\t\topacity: 0;\n\t\t\t\t\tbackground-color: black;\n\t\t\t\t\ttransition: opacity 250ms;\n\t\t\t\t}\n\t\t\t",e.appendChild(n);let o=document.createElement("div");o.classList.add(p),e.appendChild(o),t.offsetWidth,o.style.setProperty("opacity",.3),t.offsetWidth}return t}catch(t){}}();t.progressBarEnabled&&function(t){try{if(!t.shadowRoot.querySelector("."+u)){let e=document.createElement("div");e.classList.add(u),t.shadowRoot.appendChild(e);const n=document.createElement("div");n.classList.add(m),e.appendChild(n)}}catch(t){}}(e)}}function k(){const t=document.querySelector(d);t&&t.remove(),T.remove(),q()}function R(t,e,n){n.shadowEnabled&&n.progressBarEnabled&&function(t,e){try{const n=document.querySelector(d);if(n){const o=n.shadowRoot.querySelector("."+u);if(o&&e){const n=Math.floor(t/e*100)+"%";o.style.getPropertyValue("width")!=n&&(o.style.setProperty("width",n),o.offsetWidth)}}}catch(t){}}(t,e)}function N(){let t;const e=[],n=getSelection();for(let o=0;o{"A"==t.tagName&&t.href&&e.push(n.currentNode.href)}))}}return Array.from(new Set(e))}async function D(t){let e=B();return e||t?e:(e=await new Promise((t=>{let e=[];function n(t){e=[],s(),t.preventDefault()}function o(t){const e=function(t){let e,n=t.target,o=n.getBoundingClientRect();for(e=F("floor",n,t.clientX-o.left,W(n,"left")),e==n&&(e=F("ceil",n,o.left+o.width-t.clientX,W(n,"right"))),e==n&&(e=F("floor",n,t.clientY-o.top,W(n,"top"))),e==n&&(e=F("ceil",n,o.top+o.height-t.clientY,W(n,"bottom"))),n=e;n&&n.clientWidth<=8&&n.clientHeight<=8;)n=n.parentElement;return n}(t);var n;e&&(I=e,n=e,requestAnimationFrame((()=>{const t=U(),e=n.getBoundingClientRect(),o=document.scrollingElement||document.documentElement;t.style.setProperty("top",o.scrollTop+e.top-10+"px"),t.style.setProperty("left",o.scrollLeft+e.left-10+"px"),t.style.setProperty("width",e.width+20+"px"),t.style.setProperty("height",e.height+20+"px")})))}function r(t){t.preventDefault(),t.stopPropagation(),0==t.button?s(I,t.ctrlKey):i()}function a(t){"Escape"==t.key&&i()}function i(){e.length&&getSelection().removeAllRanges(),e=[],c()}function s(t,e){if(t){e||d();const n=document.createRange();n.selectNodeContents(t),l(),getSelection().addRange(n),p(),e||c()}else c()}function l(){const t=getSelection();for(let e=t.rangeCount-1;e>=0;e--){const n=t.getRangeAt(e);n.startOffset==n.endOffset&&(t.removeRange(n),e--)}}function c(){U().remove(),removeEventListener("mousemove",o,!0),removeEventListener("click",r,!0),removeEventListener("keyup",a,!0),I=null,t(Boolean(e.length)),setTimeout((()=>document.removeEventListener("contextmenu",n,!0)),0)}function d(){getSelection().removeAllRanges(),e.forEach((t=>getSelection().addRange(t)))}function p(){e=[];for(let t=0;tM(t)))}}return e}function M(t){(t.nodeType==Node.ELEMENT_NODE?t:t.parentElement).setAttribute(c,"")}function O(t){t.parentElement&&(M(t),O(t.parentElement))}function U(){let t=document.querySelector(f);return t||(t=_(f,document.body),t.style.setProperty("box-sizing","border-box","important"),t.style.setProperty("background-color","#3ea9d7","important"),t.style.setProperty("border","10px solid #0b4892","important"),t.style.setProperty("border-radius","2px","important"),t.style.setProperty("opacity",".25","important"),t.style.setProperty("pointer-events","none","important"),t.style.setProperty("position","absolute","important"),t.style.setProperty("transition","all 100ms","important"),t.style.setProperty("cursor","pointer","important"),t.style.setProperty("z-index","2147483647","important"),t.style.removeProperty("border-inline-end"),t.style.removeProperty("border-inline-start"),t.style.removeProperty("inline-size"),t.style.removeProperty("block-size"),t.style.removeProperty("inset-block-start"),t.style.removeProperty("inset-inline-end"),t.style.removeProperty("inset-block-end"),t.style.removeProperty("inset-inline-start")),t}function q(){try{if(T=document.querySelector(h),!T){T=_(h);const t=T.attachShadow({mode:"open"}),e=document.createElement("style");e.textContent=`\n\t\t\t\t@keyframes single-file-pulse { \n\t\t\t\t\t0% { \n\t\t\t\t\t\topacity: .25;\n\t\t\t\t\t} \n\t\t\t\t\t100% { \n\t\t\t\t\t\topacity: 1;\n\t\t\t\t\t} \n\t\t\t\t}\n\t\t\t\t.singlefile-logs {\n\t\t\t\t\tposition: fixed;\n\t\t\t\t\tbottom: 24px;\n\t\t\t\t\tleft: 8px;\n\t\t\t\t\tz-index: 2147483647;\n\t\t\t\t\topacity: 0.9;\n\t\t\t\t\tpadding: 4px;\n\t\t\t\t\tbackground-color: white;\n\t\t\t\t\tmin-width: ${S}px;\n\t\t\t\t\tmin-height: 16px;\n\t\t\t\t\ttransition: height 100ms;\n\t\t\t\t}\n\t\t\t\t.singlefile-logs-line {\n\t\t\t\t\tdisplay: flex;\n\t\t\t\t\tjustify-content: space-between;\n\t\t\t\t\tpadding: 2px;\n\t\t\t\t\tfont-family: arial, sans-serif;\n\t\t\t\t\tcolor: black;\n\t\t\t\t\tbackground-color: white;\n\t\t\t\t}\n\t\t\t\t.singlefile-logs-line-text {\n\t\t\t\t\tfont-size: 13px;\n\t\t\t\t\topacity: 1;\n\t\t\t\t\ttransition: opacity 200ms;\n\t\t\t\t}\n\t\t\t\t.singlefile-logs-line-icon {\n\t\t\t\t\tfont-size: 11px;\n\t\t\t\t\tmin-width: 15px;\n\t\t\t\t\ttext-align: center;\n\t\t\t\t\tposition: relative;\n\t\t\t\t\ttop: 1px;\n\t\t\t\t}\n\t\t\t`,t.appendChild(e);const n=document.createElement("div");n.classList.add(g),t.appendChild(n)}}catch(t){}}function H(t,e,n,o){try{if(o.logsEnabled){const o=T.shadowRoot.querySelector(".singlefile-logs");let r=o.querySelector("[data-id='"+t+"']");if(!r){r=document.createElement("div"),r.classList.add(y),o.appendChild(r),r.setAttribute("data-id",t);const n=document.createElement("div");n.classList.add(w),r.appendChild(n),n.textContent=e;const a=document.createElement("div");a.classList.add(E),r.appendChild(a)}!function(t,e,n){const o=t.childNodes[0],r=t.childNodes[1];o.textContent=e,r.style.setProperty("color","✓"==n?"#055000":"black"),"✓"==n?(o.style.setProperty("opacity",".5"),r.style.setProperty("opacity",".5"),r.style.setProperty("animation","none")):r.style.setProperty("animation","1s ease-in-out 0s infinite alternate none running single-file-pulse");r.textContent=n}(r,e,n)}}catch(t){}}function W(t,e){let n,o=t,r=[];do{const t=o.getBoundingClientRect();if(o.parentElement){const a=o.parentElement.getBoundingClientRect();n=Math.abs(a[e]-t[e])<=8,n&&(o.parentElement.clientWidth>8&&o.parentElement.clientHeight>8&&(o.parentElement.clientWidth-o.clientWidth>8||o.parentElement.clientHeight-o.clientHeight>8)&&r.push(o.parentElement),o=o.parentElement)}else n=!1}while(n&&o);return r}function F(t,e,n,o){return Math[t](n/8)<=o.length&&(e=o[o.length-Math[t](n/8)-1]),e}function _(t,e){const n=document.createElement(t);return n.className=b,e&&e.appendChild(n),x.forEach((t=>n.style.setProperty(t,"initial","important"))),n}q();const G=globalThis.singlefile,z=G.helper.SINGLE_FILE_UI_ELEMENT_CLASS,X="singlefile-error-bar",j=new Set(Array.from(getComputedStyle(document.documentElement)));let Q;function Z(t,e){try{if(console.error("SingleFile",t,e),Q=document.querySelector(X),!Q){Q=function(t,e){const n=document.createElement(t);n.className=z,e&&e.appendChild(n);return j.forEach((t=>n.style.setProperty(t,"initial","important"))),n}(X);const n=Q.attachShadow({mode:"open"}),o=document.createElement("style");o.textContent="\n\t\t\t\t.container {\n\t\t\t\t\tbackground-color: #ff6c00;\n\t\t\t\t\tcolor: white;\n\t\t\t\t\tdisplay: flex;\n\t\t\t\t\tposition: fixed;\n\t\t\t\t\ttop: 0px;\n\t\t\t\t\tleft: 0px;\n\t\t\t\t\tright: 0px;\n\t\t\t\t\theight: auto;\n\t\t\t\t\twidth: auto;\n\t\t\t\t\tmin-height: 24px;\n\t\t\t\t\tmin-width: 24px;\t\t\t\t\t\n\t\t\t\t\tz-index: 2147483647;\n\t\t\t\t\tmargin: 0;\n\t\t\t\t\tpadding: 2px;\n\t\t\t\t\tfont-family: Arial;\n\t\t\t\t}\n\t\t\t\t.text {\n\t\t\t\t\tflex: 1;\n\t\t\t\t\tpadding-top: 4px;\n\t\t\t\t\tpadding-bottom: 4px;\n\t\t\t\t\tpadding-left: 8px;\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t.close-button {\n\t\t\t\t\topacity: .7;\n\t\t\t\t\tpadding-top: 4px;\n\t\t\t\t\tpadding-left: 8px;\n\t\t\t\t\tpadding-right: 8px;\n\t\t\t\t\tcursor: pointer;\n\t\t\t\t\ttransition: opacity 250ms;\n\t\t\t\t\theight: 16px;\n\t\t\t\t}\n\t\t\t\ta {\n\t\t\t\t\tcolor: #303036;\n\t\t\t\t}\n\t\t\t\t.close-button:hover {\n\t\t\t\t\topacity: 1;\n\t\t\t\t}\n\t\t\t",n.appendChild(o);const r=document.createElement("div");r.className="container";const a=document.createElement("span");a.classList.add("text");const i=t.split("__DOC_LINK__");if(a.textContent="SingleFile error: "+i[0],e&&2==i.length){const t=document.createElement("a");t.textContent=e,t.href=e,t.target="_blank",a.appendChild(t),a.appendChild(document.createTextNode(i[1]))}r.appendChild(a);const s=document.createElement("img");s.classList.add("close-button"),r.appendChild(s),n.appendChild(r),s.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAABhmlDQ1BJQ0MgcHJvZmlsZQAAKJF9kT1Iw0AYht+mSlUqHewg4hChOogFURFHqWIRLJS2QqsOJpf+CE0akhQXR8G14ODPYtXBxVlXB1dBEPwBcXNzUnSREr9LCi1ivOO4h/e+9+XuO0Col5lqdowDqmYZqXhMzOZWxMAruhGiOYohiZl6Ir2Qgef4uoeP73dRnuVd9+foVfImA3wi8SzTDYt4nXh609I57xOHWUlSiM+Jxwy6IPEj12WX3zgXHRZ4ZtjIpOaIw8RisY3lNmYlQyWeIo4oqkb5QtZlhfMWZ7VcZc178hcG89pymuu0BhHHIhJIQoSMKjZQhoUo7RopJlJ0HvPwDzj+JLlkcm2AkWMeFaiQHD/4H/zurVmYnHCTgjGg88W2P4aBwC7QqNn297FtN04A/zNwpbX8lTow80l6raVFjoDQNnBx3dLkPeByB+h/0iVDciQ/LaFQAN7P6JtyQN8t0LPq9q15jtMHIEO9WroBDg6BkSJlr3m8u6u9b//WNPv3A6mTcr3f/E/sAAAABmJLR0QAigCKAIrj2uckAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAB3RJTUUH5QkPDysvCdPVuwAAABl0RVh0Q29tbWVudABDcmVhdGVkIHdpdGggR0lNUFeBDhcAAAELSURBVHja7ZpLFsIwDAPj3v/OsGHDe1BIa8tKO7Mnlkw+dpoxAAAAAGCfx4ur6Yx/B337UUS4mp/VuWUEcjSfOgO+BXCZCWe0hSqQo/npBLglIUNLdAV2MH84Ad1JyIwdLkK6YoabIHWscBWmihHuAqvHtv+XqmdXOK9TxdKy3axUm2vZkXXGgPJksTuz1bVFeeU2Y6ijsLIpXbtKa1kDs2ews69o7+A+ihJ2lvI+/lcS1G21zUVG18XKNm4OS4BNkGOQQohSmGaIdpgLESvzyiRwKepsXjE2H0ZWMF8Zi4+jK5mviM0DiRXNZ2rhkdTK5jO0xermz2o8dCnq+FS2XNNVH0sDAAAA3JYnre9cH8BZmhEAAAAASUVORK5CYII=",s.onclick=t=>{0===t.button&&Q.remove()},document.body.appendChild(Q)}}catch(t){}}const V=globalThis.singlefile,K=globalThis.singlefileBootstrap,J="moz-extension:";let Y,$;V.init({fetch:async function(t,e={}){try{let n=await o(t,{cache:"force-cache",headers:e.headers});return 401!=n.status&&403!=n.status&&404!=n.status||(n=await s(t)),n}catch(n){r++;const o=new Promise(((t,e)=>a.set(r,{resolve:t,reject:e})));return await i({method:"singlefile.fetch",url:t,requestId:r,referrer:e.referrer,headers:e.headers}),o}},frameFetch:async function(t,e){const n=await i({method:"singlefile.fetchFrame",url:t,frameId:e.frameId,referrer:e.referrer,headers:e.headers});return{status:n.status,headers:new Map(n.headers),arrayBuffer:async()=>new Uint8Array(n.array).buffer}}}),browser.runtime.onMessage.addListener((t=>{if("content.save"==t.method||"content.cancelSave"==t.method||"content.getSelectedLinks"==t.method||"content.error"==t.method)return async function(t){if(!location.href.startsWith(J)){if("content.save"==t.method)return await async function(t){const n=t.options;let o;(n.selected||n.optionallySelected)&&(o=await D(n.optionallySelected));if(!($||K&&K.pageInfo.processing)){if(n.updatedResources=K?K.pageInfo.updatedResources:{},n.visitDate=K?K.pageInfo.visitDate:new Date,Object.keys(n.updatedResources).forEach((t=>n.updatedResources[t].retrieved=!1)),n.optionallySelected&&o&&(n.selected=!0),!n.selected||o){K&&(K.pageInfo.processing=!0),$=!0;try{const t=await async function(t){const e=V.processors.frameTree;let n;V.helper.initDoc(document),P(t),Y=new V.SingleFile(t);const o=[];if(t.insertCanonicalLink=!0,!t.saveRawPage){if(!t.removeFrames&&e&&globalThis.frames&&globalThis.frames.length){let n;n=t.loadDeferredImages?new Promise((n=>setTimeout((()=>n(e.getAsync(t))),t.loadDeferredImagesMaxIdleTime-e.TIMEOUT_INIT_REQUEST_MESSAGE))):e.getAsync(t),function(t){H("load-frames",v,"…",t)}(t),n.then((()=>{Y.cancelled||function(t){H("load-frames",v,"✓",t)}(t)})),o.push(n)}if(t.loadDeferredImages){const e=V.processors.lazy.process(t);!function(t){H("load-deferred-images",A,"…",t)}(t),e.then((()=>{Y.cancelled||function(t){H("load-deferred-images",A,"✓",t)}(t)})),o.push(e)}}let r=0,a=0;t.onprogress=e=>{Y.cancelled||(e.type==e.RESOURCES_INITIALIZED&&(a=e.detail.max,t.loadDeferredImages&&V.processors.lazy.resetZoomLevel(t)),e.type==e.RESOURCES_INITIALIZED||e.type==e.RESOURCE_LOADED?(e.type==e.RESOURCE_LOADED&&r++,browser.runtime.sendMessage({method:"ui.processProgress",index:r,maxIndex:a}),R(r,a,t)):e.detail.frame||e.type==e.PAGE_LOADING||e.type==e.PAGE_LOADED||(e.type==e.STAGE_STARTED?e.detail.step<3&&function(t,e){H("step-"+t,`${C} ${t+1} / 3`,"…",e)}(e.detail.step,t):e.type==e.STAGE_ENDED?e.detail.step<3&&function(t,e){H("step-"+t,`${C} ${t+1} / 3`,"✓",e)}(e.detail.step,t):(e.type==e.STAGE_TASK_STARTED||e.type==e.STAGE_TASK_ENDED)&&(e.detail.step,e.detail.task)))},[t.frames]=await new Promise((t=>{const e=Promise.all(o),n=Y.cancel.bind(Y);Y.cancel=function(){n(),t([[]])},e.then((()=>t(e)))})),n=t.frames&&t.frames.sessionId;const i=t.frames&&t.frames.find((t=>t.requestedFrame));t.win=globalThis,i?(t.content=i.content,t.url=i.baseURI,t.canvases=i.canvases,t.fonts=i.fonts,t.stylesheets=i.stylesheets,t.images=i.images,t.posters=i.posters,t.usedFonts=i.usedFonts,t.shadowRoots=i.shadowRoots,t.imports=i.imports):t.doc=document;Y.cancelled||await Y.run();n&&e.cleanup(n);let s;Y.cancelled||(t.confirmInfobarContent&&(t.infobarContent=L("Infobar content",t.infobarContent)||""),s=await Y.getPageData(),(t.selected||t.optionallySelected)&&document.querySelectorAll("["+c+"]").forEach((t=>t.removeAttribute(c))),k(),t.displayStats&&(console.log("SingleFile stats"),console.table(s.stats)));return s}(n);t&&((!n.backgroundSave&&!n.saveToClipboard||n.saveToGDrive||n.saveToGitHub||n.saveWithCompanion)&&n.confirmFilename&&(t.filename=L("Save as",t.filename)||t.filename),await e(t,n))}catch(t){Y.cancelled||(console.error(t),browser.runtime.sendMessage({method:"ui.processError",error:t}))}}else browser.runtime.sendMessage({method:"ui.processCancelled"});$=!1,K&&(K.pageInfo.processing=!1)}}(t),{};if("content.cancelSave"==t.method)return Y&&(Y.cancel(),k(),browser.runtime.sendMessage({method:"ui.processCancelled"})),t.options.loadDeferredImages&&V.processors.lazy.resetZoomLevel(t.options),{};if("content.getSelectedLinks"==t.method)return{urls:N()};"content.error"==t.method&&Z(t.error,t.link)}}(t)}))}(); diff --git a/dist/single-file-background.js b/dist/single-file-background.js index 6a306517c..8d64c7ef0 100644 --- a/dist/single-file-background.js +++ b/dist/single-file-background.js @@ -1 +1 @@ -!function(){"use strict";const e=new Map;function t(r,s={},n){return new Promise(((a,i)=>{const o=new XMLHttpRequest;if(o.withCredentials=!0,o.responseType="arraybuffer",o.onerror=e=>i(new Error(e.detail)),o.onreadystatechange=()=>{o.readyState==XMLHttpRequest.DONE&&(o.status||o.response.byteLength?401!=o.status&&403!=o.status&&404!=o.status||n?a({array:Array.from(new Uint8Array(o.response)),headers:{"content-type":o.getResponseHeader("Content-Type")},status:o.status}):t(r,s,!0).then(a).catch(i):i())},o.open("GET",r,!0),s.headers)for(const e of Object.entries(s.headers))o.setRequestHeader(e[0],e[1]);if(n){const t=String(Math.random()).substring(2);d=t,f=s.referrer,e.set(d,f),o.setRequestHeader("x-single-file-request-id",t)}var d,f;o.send()}))}browser.runtime.onMessage.addListener(((e,r)=>{if(e.method&&e.method.startsWith("singlefile.fetch"))return new Promise((s=>{(function(e,r){if("singlefile.fetch"==e.method)return t(e.url,{referrer:e.referrer,headers:e.headers});if("singlefile.fetchFrame"==e.method)return browser.tabs.sendMessage(r.tab.id,e)})(e,r).then(s).catch((e=>s({error:e&&e.toString()})))}))})),browser.runtime.onMessage.addListener(((e,t)=>{if("singlefile.frameTree.initResponse"==e.method||"singlefile.frameTree.ackInitRequest"==e.method)return browser.tabs.sendMessage(t.tab.id,e,{frameId:0}),Promise.resolve({})}));const r=new Map;function s(e,t){e.delete(t)}browser.runtime.onMessage.addListener(((e,t)=>{if("singlefile.lazyTimeout.setTimeout"==e.method){let n,a=r.get(t.tab.id);if(a)if(n=a.get(t.frameId),n){const t=n.get(e.type);t&&clearTimeout(t)}else n=new Map;const i=setTimeout((async()=>{try{const n=r.get(t.tab.id),a=n.get(t.frameId);n&&a&&s(a,e.type),await browser.tabs.sendMessage(t.tab.id,{method:"singlefile.lazyTimeout.onTimeout",type:e.type})}catch(e){}}),e.delay);return a||(a=new Map,n=new Map,a.set(t.frameId,n),r.set(t.tab.id,a)),n.set(e.type,i),Promise.resolve({})}if("singlefile.lazyTimeout.clearTimeout"==e.method){let n=r.get(t.tab.id);if(n){const r=n.get(t.frameId);if(r){const t=r.get(e.type);t&&clearTimeout(t),s(r,e.type)}}return Promise.resolve({})}})),browser.tabs.onRemoved.addListener((e=>r.delete(e)))}(); +!function(){"use strict";const e=new Map,t=8388608;async function r(e,r,s){for(let a=0;a*tt,n.truncated?(n.finished=(a+1)*t>s.array.length,n.array=s.array.slice(a*t,(a+1)*t)):n.array=s.array,await browser.tabs.sendMessage(e,n)}return{}}function s(t,r={},a){return new Promise(((n,i)=>{const o=new XMLHttpRequest;if(o.withCredentials=!0,o.responseType="arraybuffer",o.onerror=e=>i(new Error(e.detail)),o.onreadystatechange=()=>{o.readyState==XMLHttpRequest.DONE&&(o.status||o.response.byteLength?401!=o.status&&403!=o.status&&404!=o.status||a?n({array:Array.from(new Uint8Array(o.response)),headers:{"content-type":o.getResponseHeader("Content-Type")},status:o.status}):s(t,r,!0).then(n).catch(i):i())},o.open("GET",t,!0),r.headers)for(const e of Object.entries(r.headers))o.setRequestHeader(e[0],e[1]);if(a){const t=String(Math.random()).substring(2);d=t,u=r.referrer,e.set(d,u),o.setRequestHeader("x-single-file-request-id",t)}var d,u;o.send()}))}browser.runtime.onMessage.addListener(((e,t)=>{if(e.method&&e.method.startsWith("singlefile.fetch"))return new Promise((a=>{(async function(e,t){if("singlefile.fetch"==e.method)try{const a=await s(e.url,{referrer:e.referrer,headers:e.headers});return r(t.tab.id,e.requestId,a)}catch(s){return r(t.tab.id,e.requestId,{error:s.message,arrray:[]})}else if("singlefile.fetchFrame"==e.method)return browser.tabs.sendMessage(t.tab.id,e)})(e,t).then(a).catch((e=>a({error:e&&e.toString()})))}))})),browser.runtime.onMessage.addListener(((e,t)=>{if("singlefile.frameTree.initResponse"==e.method||"singlefile.frameTree.ackInitRequest"==e.method)return browser.tabs.sendMessage(t.tab.id,e,{frameId:0}),Promise.resolve({})}));const a=new Map;function n(e,t){e.delete(t)}browser.runtime.onMessage.addListener(((e,t)=>{if("singlefile.lazyTimeout.setTimeout"==e.method){let r,s=a.get(t.tab.id);if(s)if(r=s.get(t.frameId),r){const t=r.get(e.type);t&&clearTimeout(t)}else r=new Map;const i=setTimeout((async()=>{try{const r=a.get(t.tab.id),s=r.get(t.frameId);r&&s&&n(s,e.type),await browser.tabs.sendMessage(t.tab.id,{method:"singlefile.lazyTimeout.onTimeout",type:e.type})}catch(e){}}),e.delay);return s||(s=new Map,r=new Map,s.set(t.frameId,r),a.set(t.tab.id,s)),r.set(e.type,i),Promise.resolve({})}if("singlefile.lazyTimeout.clearTimeout"==e.method){let r=a.get(t.tab.id);if(r){const s=r.get(t.frameId);if(s){const t=s.get(e.type);t&&clearTimeout(t),n(s,e.type)}}return Promise.resolve({})}})),browser.tabs.onRemoved.addListener((e=>a.delete(e)))}(); diff --git a/manifest.json b/manifest.json index c0676a109..cf3dd9bd9 100644 --- a/manifest.json +++ b/manifest.json @@ -8,7 +8,7 @@ "64": "extension/ui/resources/icon_64.png", "128": "extension/ui/resources/icon_128.png" }, - "version": "1.19.29", + "version": "1.19.30", "description": "__MSG_extensionDescription__", "content_scripts": [ {