scuregpt/chatgpt.min.js

13 lines
53 KiB
JavaScript
Raw Normal View History

2024-06-02 13:38:00 +00:00
/**
* © 20232024 KudoAI & contributors under the MIT license.
* Source: https://github.com/KudoAI/chatgpt.js
* User guide: https://chatgptjs.org/userguide
* Latest minified release: https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js/chatgpt.min.js
*/
const endpoints={assets:"https://cdn.jsdelivr.net/gh/KudoAI/chatgpt.js@a62e2c8069c85aef07794f1b3a17c93b6296f7cb",openAI:{session:"https://chatgpt.com/api/auth/session",chats:"https://chatgpt.com/backend-api/conversations",chat:"https://chatgpt.com/backend-api/conversation",share_create:"https://chatgpt.com/backend-api/share/create",share:"https://chatgpt.com/backend-api/share",instructions:"https://chatgpt.com/backend-api/user_system_messages"}},chatgpt=(localStorage.alertQueue=JSON.stringify([]),localStorage.notifyProps=JSON.stringify({queue:{topRight:[],bottomRight:[],bottomLeft:[],topLeft:[]}}),{openAIaccessToken:{},actAs:function(s){return new Promise((o,r)=>{const a=new XMLHttpRequest;a.open("GET","https://raw.githubusercontent.com/KudoAI/chat-prompts/main/dist/personas.min.json",!0),a.send(),a.onload=()=>{if(200!==a.status)return r("🤖 chatgpt.js >> Request failed. Cannot retrieve prompts data.");var e=JSON.parse(a.responseText).personas;if(s){var t=e.find(e=>e.title.toLowerCase()==s.toLowerCase());if(!t)return r(`🤖 chatgpt.js >> Persona '${s}' was not found!`);chatgpt.send(t.prompt,"click"),console.info(`Loading ${s} persona...`),chatgpt.isIdle().then(()=>{console.info("Persona activated!")})}else{console.log("\n%c🤖 chatgpt.js personas\n","font-family: sans-serif ; font-size: xxx-large ; font-weight: bold");for(const n of e)console.log("%c"+n.title,"font-family: monospace ; font-size: larger ;")}return o()}})},activateDarkMode:function(){document.documentElement.classList.replace("light","dark"),document.documentElement.style.colorScheme="dark",localStorage.setItem("theme","dark")},activateLightMode:function(){document.documentElement.classList.replace("dark","light"),document.documentElement.style.colorScheme="light",localStorage.setItem("theme","light")},alert:function(e,t,n,o,r){const a=chatgpt.isDarkMode()?"dark":"light",s=chatgpt.browser.isMobile(),i=document.createElement("div"),c=(i.id=Math.floor(1e6*chatgpt.randomFloat())+Date.now(),i.classList.add("chatgpt-modal"),document.createElement("div")),l=document.createElement("h2"),u=document.createElement("p");var d=20231203;let g=document.querySelector("#chatgpt-modal-style");(!g||parseInt(g.getAttribute("last-updated"),10)<d)&&(g||((g=document.createElement("style")).id="chatgpt-modal-style",g.setAttribute("last-updated",d.toString()),document.head.append(g)),g.innerText=".chatgpt-modal {position: fixed ; top: 0 ; left: 0 ; width: 100% ; height: 100% ;background-color: rgba(67, 70, 72, 0) ;transition: background-color 0.05s ease ;display: flex ; justify-content: center ; align-items: center ; z-index: 9999 }.chatgpt-modal > div {opacity: 0 ; transform: translateX(-2px) translateY(5px) ; max-width: 75vw ; word-wrap: break-word ;transition: opacity 0.1s cubic-bezier(.165,.84,.44,1), transform 0.2s cubic-bezier(.165,.84,.44,1) ;"+`background-color: ${"dark"==a?"black":"white"} ;`+("dark"!=a?"border: 1px solid rgba(0, 0, 0, 0.3) ;":"")+"padding: 20px ; margin: 12px 23px ; border-radius: 15px ; box-shadow: 0 30px 60px rgba(0, 0, 0, .12) ; -webkit-user-select: none ; -moz-user-select: none ; -ms-user-select: none ; user-select: none ; }.chatgpt-modal h2 { margin-bottom: 9px }"+`.chatgpt-modal a { color: ${"dark"==a?"#00cfff":"#1e9ebb"}}`+".chatgpt-modal.animated > div { opacity: 1 ; transform: translateX(0) translateY(0) }@keyframes alert-zoom-fade-out { 0% { opacity: 1 ; transform: scale(1) }50% { opacity: 0.25 ; transform: scale(1.05) }100% { opacity: 0 ; transform: scale(1.35) }}.modal-buttons { display: flex ; justify-content: flex-end ; margin: 20px -5px -3px 0 ;"+(s?"flex-direction: column-reverse":"")+"}.chatgpt-modal button {"+`margin-left: ${s?0:10}px ; padding: ${s?15:4}px 18px ; border-radius: 15px ;`+(s?"margin-top: 5px ; margin-bottom: 3px ;":"")+`border: 1px solid ${"dark"==a?"white":"black"}}`+".primary-modal-btn {"+`border: 1px solid ${"dark"==a?"white":"black"} ;`+`background: ${"dark"==a?"white":"black"} ;`+`color: ${"dark"==a?"black":"white"}}`+".chatgpt-modal button:hover { color: #3d5d71 ; border-color: #6d9cb9 ;background-color: "+("d
`)+`CHATGPT: ${u.chatgpt}
`}else{s=await(await fetch(await chatgpt.shareChat(e))).text(),i=(new DOMParser).parseFromString(s,"text/html");n=i.querySelector("title").textContent+".html",i.querySelectorAll('link[rel="stylesheet"]').forEach(e=>{var t=e.getAttribute("href");t?.startsWith("/")&&e.setAttribute("href","https://chat.openai.com"+t)}),o=(new XMLSerializer).serializeToString(i)}if(console.info(`Exporting transcript as ${t.toUpperCase()}...`),"pdf"==t){o=o.replace(/<svg.*?<\/svg>/g,e=>{return`<img src="${"data:image/svg+xml,"+encodeURIComponent(e)}">`});const d=window.open("","","toolbar=0, location=0, menubar=0, height=600, width=800");d.document.write(o),setTimeout(()=>{d.print({toPDF:!0})},100)}else{"md"==t&&(c=/<.*(?:<h1(.|\n)*?href=".*?continue[^"]*".*?\/a>.*?)<[^/]/.exec(o)[1],o=c||o,n=n.replace(".html",".md"));r=new Blob([o],{type:"text/"+("html"==t?"html":"md"==t?"markdown":"plain")}),a=document.createElement("a"),e=URL.createObjectURL(r);a.href=e,a.download=n,document.body.append(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(e)}},extractCode:function(){chatgpt.code.extract()},generateRandomIP:function(){var e=Array.from({length:4},()=>Math.floor(256*chatgpt.randomFloat())).join(".");return console.info("IP generated: "+e),e},get:function(e,t=""){if("string"!=typeof e||"string"!=typeof t)throw new TypeError("Invalid arguments. Both arguments must be strings.");if(!targetTypes.includes(e.toLowerCase()))throw new Error("Invalid targetType: "+e+". Valid values are: "+JSON.stringify(targetTypes));var n=[],o=new RegExp("^get(.*)"+e+"$","i");for(const a in chatgpt)"function"==typeof chatgpt[a]&&o.test(a)&&n.push(a.replace(o,"$1").toLowerCase());if(!n.includes(t.toLowerCase()))throw new Error("Invalid targetName: "+t+". "+(0<n.length?"Valid values are: "+JSON.stringify(n):"targetType "+e.toLowerCase()+" does not require additional options."));const r=("get"+t+e).toLowerCase();return this[Object.keys(this).find(e=>e.toLowerCase()==r)]()},getAccessToken:function(){return new Promise((e,t)=>{if(0<Object.keys(chatgpt.openAIaccessToken).length&&0<=Date.parse(chatgpt.openAIaccessToken.expireDate)-Date.parse(new Date))return e(chatgpt.openAIaccessToken.token);const n=new XMLHttpRequest;n.open("GET",endpoints.openAI.session,!0),n.setRequestHeader("Content-Type","application/json"),n.onload=()=>200!==n.status?t("🤖 chatgpt.js >> Request failed. Cannot retrieve access token."):(console.info("Token expiration: "+new Date(JSON.parse(n.responseText).expires).toLocaleString().replace(","," at")),chatgpt.openAIaccessToken={token:JSON.parse(n.responseText).accessToken,expireDate:JSON.parse(n.responseText).expires},e(chatgpt.openAIaccessToken.token)),n.send()})},getAccountDetails:function(...s){var e=["email","id","image","name","picture"];for(const t of s=arguments[0]?Array.isArray(arguments[0])?arguments[0]:Array.from(arguments):e)if(!e.includes(t))return console.error("Invalid detail arg '"+t+"' supplied. Valid details are:\n ["+e+"]");return new Promise((o,r)=>{const a=new XMLHttpRequest;a.open("GET",endpoints.openAI.session,!0),a.setRequestHeader("Content-Type","application/json"),a.onload=()=>{if(200!==a.status)return r("🤖 chatgpt.js >> Request failed. Cannot retrieve account details.");var e=JSON.parse(a.responseText).user,t={};for(const n of s)t[n]=e[n];return o(t)},a.send()})},getChatBox:function(){return document.getElementById("prompt-textarea")},getChatData:function(u=1,o="all",p="all",h="all"){var e=["all","id","title","create_time","update_time","msg"],t=["all","both","user","chatgpt"];u=u?Number.isInteger(u)||/^\d+$/.test(u)?0===parseInt(u,10)?0:parseInt(u,10)-1:u:"active",o=["all",""].includes(o)?e.filter(e=>/^(?!all$|msg$).*/.test(e)):Array.isArray(o)?o:[o],p=p?t.includes(p)?p:"invalid":"all",h=Number.isInteger(h)||/^\d+$/.test(h)?0===parseInt(h,10)?0:parseInt(h,10)-1:["all","latest"].includes(h.toLowerCase())?h.toLowerCase():h?"invalid":"all";for(const n of o)if(!e.includes(n))return console.error("Invalid detail arg '"+n+"' passed. Valid details are:\n ["+e+"]");if("invalid"==p)r
`+o,new Promise(n=>{chatgpt.getAccessToken().then(async e=>{var t=await this.fetchData();return"user"==r?t.about_user_message+=o:"chatgpt"==r&&(t.about_model_message+=o),await this.sendRequest("POST",e,t),n()})})):console.error(`Invalid target ${r}. Valid targets are [${e}]`)):console.error("Please provide a valid target!")):console.error("Please provide an instruction")},clear:function(o){var e=["user","chatgpt"];return o?"string"!=typeof o?console.error("Target must be a string"):(o=o.toLowerCase(),e.includes(o)?new Promise(n=>{chatgpt.getAccessToken().then(async e=>{var t=await this.fetchData();return"user"==o?t.about_user_message="":"chatgpt"==o&&(t.about_model_message=""),await this.sendRequest("POST",e,t),n()})}):console.error(`Invalid target ${o}. Valid targets are [${e}]`)):console.error("Please provide a valid target!")},fetchData:function(){return new Promise(t=>{chatgpt.getAccessToken().then(async e=>t(await this.sendRequest("GET",e)))})},sendRequest:function(r,e,a){for(let e=0;e<arguments.length-1;e++)if("string"!=typeof arguments[e])return console.error(`Argument ${e+1} must be a string`);var t=["POST","GET"];return(r=(r||"").trim().toUpperCase())&&t.includes(r)?e?a&&"object"!=typeof a?console.error(`Invalid body data type. Got ${typeof a}, expected object`):new Promise((t,n)=>{const o=new XMLHttpRequest;o.open(r,endpoints.openAI.instructions,!0),o.setRequestHeader("Accept-Language","en-US"),o.setRequestHeader("Authorization","Bearer "+e),"POST"==r&&o.setRequestHeader("Content-Type","application/json"),o.onload=()=>{var e=JSON.parse(o.responseText);return 422===o.status?n("🤖 chatgpt.js >> Character limit exceeded. Custom instructions can have a maximum length of 1500 characters."):403===o.status&&"content_policy"==e.detail.reason?n("🤖 chatgpt.js >> "+e.detail.description):200!==o.status?n("🤖 chatgpt.js >> Request failed. Cannot contact custom instructions endpoint."):(console.info("Custom instructions successfully contacted with method "+r),t(e||{}))},o.send(JSON.stringify(a)||"")}):console.error("Please provide a valid access token!"):console.error("Valid methods are "+t)},turnOff:function(){return new Promise(n=>{chatgpt.getAccessToken().then(async e=>{var t=await this.fetchData();return t.enabled=!1,await this.sendRequest("POST",e,t),n()})})},turnOn:function(){return new Promise(n=>{chatgpt.getAccessToken().then(async e=>{var t=await this.fetchData();return t.enabled=!0,await this.sendRequest("POST",e,t),n()})})},toggle:function(){return new Promise(t=>{this.fetchData().then(async e=>(await(e.enabled?this.turnOff():this.turnOn()),t()))})}},isChromium:function(){return chatgpt.browser.isChromium()},isDarkMode:function(){return document.documentElement.classList.toString().includes("dark")},isFirefox:function(){return chatgpt.browser.isFirefox()},isFullScreen:function(){return chatgpt.browser.isFullScreen()},isIdle:function(){return new Promise(t=>{!function e(){chatgpt.getRegenerateButton()?t(!0):setTimeout(e,200)}()})},isLoaded:function(){return new Promise(t=>{!function e(){chatgpt.getNewChatButton()?t(!0):setTimeout(e,200)}()})},isLightMode:function(){return document.documentElement.classList.toString().includes("light")},isMobileDevice:function(){return chatgpt.browser.isMobile()},logout:function(){window.location.href="https://chat.openai.com/auth/logout"},menu:{elements:[],addedEvent:!1,append:function(e,t={}){var n=["button","dropdown"];if(!e||"string"!=typeof e)return console.error("🤖 chatgpt.js >> Please supply a valid string element name!");if(e=e.toLowerCase(),!n.includes(e))return console.error(`🤖 chatgpt.js >> Invalid element! Valid elements are [${n}]`);const o=document.createElement("dropdown"==e?"select":"button"==e?"a":e);if(o.id=Math.floor(1e6*chatgpt.randomFloat())+Date.now(),"button"==e){o.textContent=t?.label&&"string"==typeof t.label?t.label:"chatgpt.js button";n=document.createElement("img");n.src=t?.icon&&"string"==typeof t.icon?t.icon:endpoints.assets+"/starters/chrome/extension/icons/icon128.png",n.width=18,o.insertBefore(n,o.firstChild),o.onclick=t?.onclick&&"func