@bhavjit/khan-api
Version:
A Khan Academy API client and wrapper
624 lines (623 loc) • 63.7 kB
JavaScript
/**
* Khan API v0.7.4
* https://khan-api.bhavjit.com
* Licensed under MIT license
* Copyright 2025 Bhavjit Chauhan
*/
var lt=Object.create;var ir=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var pt=Object.getOwnPropertyNames;var ct=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var wr=t=>{throw TypeError(t)};var mt=(t,r)=>()=>(r||t((r={exports:{}}).exports,r),r.exports),_r=(t,r)=>{for(var e in r)ir(t,e,{get:r[e],enumerable:!0})},yt=(t,r,e,a)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of pt(r))!ut.call(t,s)&&s!==e&&ir(t,s,{get:()=>r[s],enumerable:!(a=dt(r,s))||a.enumerable});return t};var ft=(t,r,e)=>(e=t!=null?lt(ct(t)):{},yt(r||!t||!t.__esModule?ir(e,"default",{value:t,enumerable:!0}):e,t));var lr=(t,r,e)=>r.has(t)||wr("Cannot "+e);var w=(t,r,e)=>(lr(t,r,"read from private field"),e?e.call(t):r.get(t)),U=(t,r,e)=>r.has(t)?wr("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(t):r.set(t,e),Le=(t,r,e,a)=>(lr(t,r,"write to private field"),a?a.call(t,e):r.set(t,e),e),m=(t,r,e)=>(lr(t,r,"access private method"),e);var xr=mt((J,Sr)=>{var Oe=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global,Me=function(){function t(){this.fetch=!1,this.DOMException=Oe.DOMException}return t.prototype=Oe,new t}();(function(t){var r=function(e){var a=typeof t<"u"&&t||typeof self<"u"&&self||typeof global<"u"&&global||{},s={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function i(o){return o&&DataView.prototype.isPrototypeOf(o)}if(s.arrayBuffer)var l=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(o){return o&&l.indexOf(Object.prototype.toString.call(o))>-1};function k(o){if(typeof o!="string"&&(o=String(o)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(o)||o==="")throw new TypeError('Invalid character in header field name: "'+o+'"');return o.toLowerCase()}function x(o){return typeof o!="string"&&(o=String(o)),o}function _(o){var n={next:function(){var d=o.shift();return{done:d===void 0,value:d}}};return s.iterable&&(n[Symbol.iterator]=function(){return n}),n}function u(o){this.map={},o instanceof u?o.forEach(function(n,d){this.append(d,n)},this):Array.isArray(o)?o.forEach(function(n){if(n.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+n.length);this.append(n[0],n[1])},this):o&&Object.getOwnPropertyNames(o).forEach(function(n){this.append(n,o[n])},this)}u.prototype.append=function(o,n){o=k(o),n=x(n);var d=this.map[o];this.map[o]=d?d+", "+n:n},u.prototype.delete=function(o){delete this.map[k(o)]},u.prototype.get=function(o){return o=k(o),this.has(o)?this.map[o]:null},u.prototype.has=function(o){return this.map.hasOwnProperty(k(o))},u.prototype.set=function(o,n){this.map[k(o)]=x(n)},u.prototype.forEach=function(o,n){for(var d in this.map)this.map.hasOwnProperty(d)&&o.call(n,this.map[d],d,this)},u.prototype.keys=function(){var o=[];return this.forEach(function(n,d){o.push(d)}),_(o)},u.prototype.values=function(){var o=[];return this.forEach(function(n){o.push(n)}),_(o)},u.prototype.entries=function(){var o=[];return this.forEach(function(n,d){o.push([d,n])}),_(o)},s.iterable&&(u.prototype[Symbol.iterator]=u.prototype.entries);function V(o){if(!o._noBody){if(o.bodyUsed)return Promise.reject(new TypeError("Already read"));o.bodyUsed=!0}}function C(o){return new Promise(function(n,d){o.onload=function(){n(o.result)},o.onerror=function(){d(o.error)}})}function L(o){var n=new FileReader,d=C(n);return n.readAsArrayBuffer(o),d}function y(o){var n=new FileReader,d=C(n),f=/charset=([A-Za-z0-9_-]+)/.exec(o.type),P=f?f[1]:"utf-8";return n.readAsText(o,P),d}function G(o){for(var n=new Uint8Array(o),d=new Array(n.length),f=0;f<n.length;f++)d[f]=String.fromCharCode(n[f]);return d.join("")}function ke(o){if(o.slice)return o.slice(0);var n=new Uint8Array(o.byteLength);return n.set(new Uint8Array(o)),n.buffer}function br(){return this.bodyUsed=!1,this._initBody=function(o){this.bodyUsed=this.bodyUsed,this._bodyInit=o,o?typeof o=="string"?this._bodyText=o:s.blob&&Blob.prototype.isPrototypeOf(o)?this._bodyBlob=o:s.formData&&FormData.prototype.isPrototypeOf(o)?this._bodyFormData=o:s.searchParams&&URLSearchParams.prototype.isPrototypeOf(o)?this._bodyText=o.toString():s.arrayBuffer&&s.blob&&i(o)?(this._bodyArrayBuffer=ke(o.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(o)||c(o))?this._bodyArrayBuffer=ke(o):this._bodyText=o=Object.prototype.toString.call(o):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof o=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):s.searchParams&&URLSearchParams.prototype.isPrototypeOf(o)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},s.blob&&(this.blob=function(){var o=V(this);if(o)return o;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var o=V(this);return o||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(s.blob)return this.blob().then(L);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var o=V(this);if(o)return o;if(this._bodyBlob)return y(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(G(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},s.formData&&(this.formData=function(){return this.text().then(st)}),this.json=function(){return this.text().then(JSON.parse)},this}var at=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function ot(o){var n=o.toUpperCase();return at.indexOf(n)>-1?n:o}function Y(o,n){if(!(this instanceof Y))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');n=n||{};var d=n.body;if(o instanceof Y){if(o.bodyUsed)throw new TypeError("Already read");this.url=o.url,this.credentials=o.credentials,n.headers||(this.headers=new u(o.headers)),this.method=o.method,this.mode=o.mode,this.signal=o.signal,!d&&o._bodyInit!=null&&(d=o._bodyInit,o.bodyUsed=!0)}else this.url=String(o);if(this.credentials=n.credentials||this.credentials||"same-origin",(n.headers||!this.headers)&&(this.headers=new u(n.headers)),this.method=ot(n.method||this.method||"GET"),this.mode=n.mode||this.mode||null,this.signal=n.signal||this.signal||function(){if("AbortController"in a){var p=new AbortController;return p.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&d)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(d),(this.method==="GET"||this.method==="HEAD")&&(n.cache==="no-store"||n.cache==="no-cache")){var f=/([?&])_=[^&]*/;if(f.test(this.url))this.url=this.url.replace(f,"$1_="+new Date().getTime());else{var P=/\?/;this.url+=(P.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}Y.prototype.clone=function(){return new Y(this,{body:this._bodyInit})};function st(o){var n=new FormData;return o.trim().split("&").forEach(function(d){if(d){var f=d.split("="),P=f.shift().replace(/\+/g," "),p=f.join("=").replace(/\+/g," ");n.append(decodeURIComponent(P),decodeURIComponent(p))}}),n}function nt(o){var n=new u,d=o.replace(/\r?\n[\t ]+/g," ");return d.split("\r").map(function(f){return f.indexOf(`
`)===0?f.substr(1,f.length):f}).forEach(function(f){var P=f.split(":"),p=P.shift().trim();if(p){var Ce=P.join(":").trim();try{n.append(p,Ce)}catch(nr){console.warn("Response "+nr.message)}}}),n}br.call(Y.prototype);function q(o,n){if(!(this instanceof q))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(n||(n={}),this.type="default",this.status=n.status===void 0?200:n.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=n.statusText===void 0?"":""+n.statusText,this.headers=new u(n.headers),this.url=n.url||"",this._initBody(o)}br.call(q.prototype),q.prototype.clone=function(){return new q(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new u(this.headers),url:this.url})},q.error=function(){var o=new q(null,{status:200,statusText:""});return o.ok=!1,o.status=0,o.type="error",o};var it=[301,302,303,307,308];q.redirect=function(o,n){if(it.indexOf(n)===-1)throw new RangeError("Invalid status code");return new q(null,{status:n,headers:{location:o}})},e.DOMException=a.DOMException;try{new e.DOMException}catch{e.DOMException=function(n,d){this.message=n,this.name=d;var f=Error(n);this.stack=f.stack},e.DOMException.prototype=Object.create(Error.prototype),e.DOMException.prototype.constructor=e.DOMException}function sr(o,n){return new Promise(function(d,f){var P=new Y(o,n);if(P.signal&&P.signal.aborted)return f(new e.DOMException("Aborted","AbortError"));var p=new XMLHttpRequest;function Ce(){p.abort()}p.onload=function(){var A={statusText:p.statusText,headers:nt(p.getAllResponseHeaders()||"")};P.url.indexOf("file://")===0&&(p.status<200||p.status>599)?A.status=200:A.status=p.status,A.url="responseURL"in p?p.responseURL:A.headers.get("X-Request-URL");var re="response"in p?p.response:p.responseText;setTimeout(function(){d(new q(re,A))},0)},p.onerror=function(){setTimeout(function(){f(new TypeError("Network request failed"))},0)},p.ontimeout=function(){setTimeout(function(){f(new TypeError("Network request timed out"))},0)},p.onabort=function(){setTimeout(function(){f(new e.DOMException("Aborted","AbortError"))},0)};function nr(A){try{return A===""&&a.location.href?a.location.href:A}catch{return A}}if(p.open(P.method,nr(P.url),!0),P.credentials==="include"?p.withCredentials=!0:P.credentials==="omit"&&(p.withCredentials=!1),"responseType"in p&&(s.blob?p.responseType="blob":s.arrayBuffer&&(p.responseType="arraybuffer")),n&&typeof n.headers=="object"&&!(n.headers instanceof u||a.Headers&&n.headers instanceof a.Headers)){var kr=[];Object.getOwnPropertyNames(n.headers).forEach(function(A){kr.push(k(A)),p.setRequestHeader(A,x(n.headers[A]))}),P.headers.forEach(function(A,re){kr.indexOf(re)===-1&&p.setRequestHeader(re,A)})}else P.headers.forEach(function(A,re){p.setRequestHeader(re,A)});P.signal&&(P.signal.addEventListener("abort",Ce),p.onreadystatechange=function(){p.readyState===4&&P.signal.removeEventListener("abort",Ce)}),p.send(typeof P._bodyInit>"u"?null:P._bodyInit)})}return sr.polyfill=!0,a.fetch||(a.fetch=sr,a.Headers=u,a.Request=Y,a.Response=q),e.Headers=u,e.Request=Y,e.Response=q,e.fetch=sr,e}({})})(Me);Me.fetch.ponyfill=!0;delete Me.fetch.polyfill;var ie=Oe.fetch?Oe:Me;J=ie.fetch;J.default=ie.fetch;J.fetch=ie.fetch;J.Headers=ie.Headers;J.Request=ie.Request;J.Response=ie.Response;Sr.exports=J});var Nr={};_r(Nr,{AvatarDataForProfile:()=>Ve,FeedbackQuery:()=>Be,GetFeedbackReplies:()=>Ne,GetFeedbackRepliesPage:()=>Qe,GetFullUserProfile:()=>We,GetProfileWidgets:()=>Ye,GetUserByUsernameOrEmail:()=>Je,GetUserHoverCardProfile:()=>ze,Hotlist:()=>Ze,ProgramQuery:()=>Xe,ProjectsAuthoredByUser:()=>er,QAExpandKeyInfo:()=>ve,QaExpandKeyInfo:()=>rr,avatarDataForProfile:()=>we,feedbackQuery:()=>de,getFeedbackReplies:()=>pe,getFeedbackRepliesPage:()=>_e,getFullUserProfile:()=>Re,getProfileWidgets:()=>Se,getUserByUsernameOrEmail:()=>xe,getUserHoverCardProfile:()=>Ae,hotlist:()=>Ie,programQuery:()=>Ee,projectsAuthoredByUser:()=>Te});var g="https://www.khanacademy.org/api/internal/graphql",qe="https://cdn.jsdelivr.net/gh/bhavjitChauhan/khan-api@safelist",Pr="khan-proxy.bhavjit.com",dr=`bhavjitchauhan/khan-api_${Date.now()}`,Rr=4669512406581248;var Er=ft(xr(),1);async function pr(t){let r=await le(`${qe}/query/${t}`);return r.status===404?null:await r.text()}async function Ar(t){let r=await le(`${qe}/mutation/${t}`);return r.status===404?null:await r.text()}async function Ut(t){let r=await le(`${qe}/fragment/${t}`);return r.status===404?null:await r.text()}function gt(t){let r=5381,e=t.length;for(;e;)r=r*33^t.charCodeAt(--e);return r>>>0}async function Kt(t){let r=await pr(t);return r?gt(r):null}async function le(t,r){return await(0,Er.default)(t,r)}async function Lt(t,r){return r={method:"get",...r},await le(t,r)}async function Ir(t,r,e){return e={method:"post",body:JSON.stringify(r),...e},await le(t,e)}async function h(t,r,e={},a){let s={query:r,variables:e};typeof window<"u"&&window.location.hostname!=="khanacademy.org"&&(t=t.replace("www.khanacademy.org",Pr));let i=await Ir(t,s,a);if(i.status===403){let l=r.startsWith("query"),c=r.match(/^(?:query|mutation) (\w+)/)?.[1];if(!c)throw new Error("An unknown query is no longer in the safelist");console.warn(`The query for operation "${c}" is no longer in the safelist. Attempting to fetch the latest version from the safelist...`);let k=l?await pr(c):await Ar(c);if(!k)throw new Error(`The query for operation "${c}" was not found in the safelist`);return await Ir(t,{...s,query:k},a)}return i}var Ve;(r=>r.query=`query avatarDataForProfile($kaid: String!) {
user(kaid: $kaid) {
id
avatar {
name
imageSrc
__typename
}
__typename
}
}`)(Ve||(Ve={}));function we(t,r){return h(`${g}/avatarDataForProfile`,Ve.query,typeof t=="string"?{kaid:t}:t,r)}var Be;(r=>r.query=`query feedbackQuery($topicId: String!, $focusKind: String!, $cursor: String, $limit: Int, $feedbackType: FeedbackType!, $currentSort: Int, $qaExpandKey: String) {
feedback(
focusId: $topicId
cursor: $cursor
limit: $limit
feedbackType: $feedbackType
focusKind: $focusKind
sort: $currentSort
qaExpandKey: $qaExpandKey
answersLimit: 1
) {
feedback {
isLocked
isPinned
replyCount
appearsAsDeleted
author {
id
kaid
nickname
avatar {
name
imageSrc
__typename
}
__typename
}
badges {
name
icons {
smallUrl
__typename
}
description
__typename
}
content
date
definitelyNotSpam
deleted
downVoted
expandKey
feedbackType
flaggedBy
flaggedByUser
flags
focusUrl
focus {
kind
id
translatedTitle
relativeUrl
__typename
}
fromVideoAuthor
key
lowQualityScore
notifyOnAnswer
permalink
qualityKind
replyCount
replyExpandKeys
showLowQualityNotice
sumVotesIncremented
upVoted
... on QuestionFeedback {
hasAnswered
answers {
isLocked
isPinned
replyCount
appearsAsDeleted
author {
id
kaid
nickname
avatar {
name
imageSrc
__typename
}
__typename
}
badges {
name
icons {
smallUrl
__typename
}
description
__typename
}
content
date
definitelyNotSpam
deleted
downVoted
expandKey
feedbackType
flaggedBy
flaggedByUser
flags
focusUrl
focus {
kind
id
translatedTitle
relativeUrl
__typename
}
fromVideoAuthor
key
lowQualityScore
notifyOnAnswer
permalink
qualityKind
replyCount
replyExpandKeys
showLowQualityNotice
sumVotesIncremented
upVoted
__typename
}
isOld
answerCount
__typename
}
... on AnswerFeedback {
question {
isLocked
isPinned
replyCount
appearsAsDeleted
author {
id
kaid
nickname
avatar {
name
imageSrc
__typename
}
__typename
}
badges {
name
icons {
smallUrl
__typename
}
description
__typename
}
content
date
definitelyNotSpam
deleted
downVoted
expandKey
feedbackType
flaggedBy
flaggedByUser
flags
focusUrl
focus {
kind
id
translatedTitle
relativeUrl
__typename
}
fromVideoAuthor
key
lowQualityScore
notifyOnAnswer
permalink
qualityKind
replyCount
replyExpandKeys
showLowQualityNotice
sumVotesIncremented
upVoted
__typename
}
__typename
}
__typename
}
cursor
isComplete
sortedByDate
__typename
}
}`)(Be||(Be={}));function de(t,r){return h(`${g}/feedbackQuery`,Be.query,t,r)}var Ne;(r=>r.query=`query getFeedbackReplies($postKey: String!) {
feedbackReplies(feedbackKey: $postKey) {
isLocked
isPinned
expandKey
appearsAsDeleted
author {
id
kaid
nickname
avatar {
name
imageSrc
__typename
}
__typename
}
content
date
definitelyNotSpam
deleted
downVoted
expandKey
feedbackType
flaggedBy
flaggedByUser
flags
focusUrl
fromVideoAuthor
key
lowQualityScore
notifyOnAnswer
permalink
qualityKind
replyCount
replyExpandKeys
showLowQualityNotice
sumVotesIncremented
upVoted
__typename
}
}`)(Ne||(Ne={}));function pe(t,r){return h(`${g}/getFeedbackReplies`,Ne.query,typeof t=="string"?{postKey:t}:t,r)}var Qe;(r=>r.query=`query getFeedbackRepliesPage($postKey: String!, $cursor: String, $limit: Int!) {
feedbackRepliesPaginated(feedbackKey: $postKey, cursor: $cursor, limit: $limit) {
cursor
isComplete
feedback {
isLocked
isPinned
expandKey
appearsAsDeleted
author {
id
kaid
nickname
avatar {
name
imageSrc
__typename
}
__typename
}
content
date
definitelyNotSpam
deleted
downVoted
expandKey
feedbackType
flaggedBy
flaggedByUser
flags
focusUrl
fromVideoAuthor
key
lowQualityScore
notifyOnAnswer
permalink
qualityKind
replyCount
replyExpandKeys
showLowQualityNotice
sumVotesIncremented
upVoted
__typename
}
__typename
}
}`)(Qe||(Qe={}));function _e(t,r){return h(`${g}/getFeedbackRepliesPage`,Qe.query,t,r)}function Tr(t,r,e="..."){return r=Math.max(0,r),t.length>r?t.slice(0,r-e.length)+e:t}function $e(t){return t.replace(/-/g,"+").replace(/_/g,"/")}function vr(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function B(t){return new RegExp(`(${t.source.slice(1,-1)})`)}var Ur=["com","org"],Kr=["as","az","cs","da","el","gu","hu","id","it","lt","ja","kk","kn","ky","lv","mn","mr","my","nl","pt-pt","ru","sv","ta","uz","bg","bn","de","en","es","fr","hi","hy","ka","km","ko","nb","pa","pl","pt","ro","sr","tr","vi","zh-hans","sgn-us"],cr=/^kaid_\d{20,25}$/,ea=B(cr),R=t=>cr.test(t),Pe=new RegExp(`^https?:\\/\\/(?:(?:www|${Kr.join("|")})\\.)?khanacademy\\.(?:${Ur.join("|")})\\/profile\\/((?!kaid_|kaid_\\D)\\w+|(?:${cr.toString().slice(2,-2)}))(?:\\/.*)?$`,"i"),ra=B(Pe),ce=t=>Pe.test(t),ht=[9,10,16],ur=new RegExp(`^[1-9](?:(?:${ht.map(t=>`\\d{${t-1}}`).join("|")}))$`),Dr=new RegExp(`(?:^|\\D)(${ur.source.slice(1,-1)})(?:$|\\D)`);function te(t){return ur.test(t.toString())}var Fr=["computer-programming","cs","pixar","nasa","piab-sandbox","computer-science","hour-of-code","math","differential-equations","electrical-engineering","mcat","apchem-topic","chemistry","art-history-basics","biology"],ue=new RegExp(`^https?:\\/\\/(?:(?:www|${Kr.join("|")})\\.)?khanacademy\\.(?:${Ur.join("|")})\\/(?:${Fr.join("|")})\\/[\\w\\d-.~()'!*:@,;]+\\/(${ur.toString().slice(2,-2)})$`,"i"),ta=B(ue);function Cr(t){return ue.test(t)}var Ge=new RegExp(`^\\/(?:${Fr.join("|")})\\/[\\w\\d-.~()'!*:@,;]+\\/\\d+\\/(\\d+)\\.png$`),aa=B(Ge),bt=[51,54],Lr=/^ag5zfmtoYW4tYWNhZGVteXI(?:U|X)CxIKU2NyYXRjaHBhZB(?:i|j)(?=[\w-]*$)(?:.{7}w|.{9}C(?:g|w|A|Q)w)$/,oa=B(Lr);function me(t){if(bt.includes(t.length)||!Lr.test(t))return!1;try{return atob($e(t)),!0}catch{return!1}}var sa=[106,107,108,110,111],qr=/^ag5zfmtoYW4tYWNhZGVteX(?:I|J)(?:A|B|7|9|-|_)CxIIVXNlckRhdGEi(?:Gm|GG|G2|Hm|HG|HW)thaWRf(?:M|N|O)(?:\w{34}|\w{29,31}|\w{27})(?:LEghGZWVkYmFjaxiAg[I-P](?:O|P|W|X|2|3)|DAsSCEZlZWRiYWNrGICA|MCxIIRmVlZGJhY2sYgI(?:C|D)|wLEghGZWVkYmFjaxiAg|DAsSCEZlZWRiYWNrGICA)(?:[\w-]{5}|[\w-]{7,8})(?:M|DA|C(?:g|w|A|Q)w)$/,na=B(qr),E=t=>qr.test(t),ia=[301],Or=/^kaencrypted_[a-z0-9]{32}_[a-z0-9]{256}$/,la=B(Or),D=t=>Or.test(t),He=/^http:\/\/googleid\.khanacademy\.org\/(\d+)$/,da=B(He),Mr=t=>He.test(t),je=/^_gae_bingo_random:(\w+-\w+-\w+)$/,pa=B(je),Vr=t=>je.test(t),Br=/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,ca=B(Br),F=t=>Br.test(t);var We;(r=>r.query=`query getFullUserProfile($kaid: String, $username: String) {
user(kaid: $kaid, username: $username) {
id
kaid
key
userId
email
username
profileRoot
gaUserId
isPhantom
isDeveloper: hasPermission(name: "can_do_what_only_admins_can_do")
isPublisher: hasPermission(name: "can_publish", scope: ANY_ON_CURRENT_LOCALE)
isModerator: hasPermission(name: "can_moderate_users", scope: GLOBAL)
isParent
isTeacher
isFormalTeacher
isK4dStudent
isKmapStudent
isDataCollectible
isChild
isOrphan
isCoachingLoggedInUser
canModifyCoaches
nickname
hideVisual
joined
points
countVideosCompleted
bio
profile {
accessLevel
__typename
}
soundOn
muteVideos
showCaptions
prefersReducedMotion
noColorInVideos
newNotificationCount
canHellban: hasPermission(name: "can_ban_users", scope: GLOBAL)
canMessageUsers: hasPermission(
name: "can_send_moderator_messages"
scope: GLOBAL
)
isSelf: isActor
hasStudents: hasCoachees
hasClasses
hasChildren
hasCoach
badgeCounts
homepageUrl
isMidsignupPhantom
includesDistrictOwnedData
includesKmapDistrictOwnedData
includesK4dDistrictOwnedData
canAccessDistrictsHomepage
underAgeGate {
parentEmail
daysUntilCutoff
approvalGivenAt
__typename
}
authEmails
signupDataIfUnverified {
email
emailBounced
__typename
}
pendingEmailVerifications {
email
__typename
}
hasAccessToAIGuideCompanionMode
hasAccessToAIGuideLearner
hasAccessToAIGuideDistrictAdmin
hasAccessToAIGuideParent
hasAccessToAIGuideTeacher
tosAccepted
shouldShowAgeCheck
birthMonthYear
lastLoginCountry
region
userDistrictInfos {
id
isKAD
district {
id
region
__typename
}
__typename
}
schoolAffiliation {
id
location
__typename
}
__typename
}
actorIsImpersonatingUser
isAIGuideEnabled
hasAccessToAIGuideDev
}`)(We||(We={}));function Re(t,r){return h(`${g}/getFullUserProfile`,We.query,typeof t=="string"?R(t)?{kaid:t}:{username:t}:t,r)}var Ye;(r=>r.query=`query getProfileWidgets($kaid: String!) {
user(kaid: $kaid) {
id
kaid
badgeCounts
isChild
profile {
programs {
id
authorKaid
authorNickname
deleted
displayableSpinoffCount
imagePath
key
sumVotesIncremented
translatedTitle: title
url
__typename
}
__typename
}
programs(sort: TOP, pageInfo: {itemsPerPage: 2}) {
programs {
id
authorKaid
authorNickname
deleted
displayableSpinoffCount
imagePath
key
sumVotesIncremented
translatedTitle: title
url
__typename
}
__typename
}
__typename
}
userSummary(kaid: $kaid) {
statistics {
answers
comments
flags
projectanswers
projectquestions
questions
replies
votes
__typename
}
__typename
}
}`)(Ye||(Ye={}));function Se(t,r){return h(`${g}/getProfileWidgets`,Ye.query,typeof t=="string"&&R(t)?{kaid:t}:t,r)}var Je;(r=>r.query=`query getUserByUsernameOrEmail($username: String, $email: String) {
user(username: $username, email: $email) {
id
kaid
__typename
}
}`)(Je||(Je={}));function xe(t,r){return h(`${g}/getUserByUsernameOrEmail`,Je.query,typeof t=="string"?F(t)?{email:t}:{username:t}:t,r)}var ze;(r=>r.query=`query getUserHoverCardProfile($kaid: String!) {
user(kaid: $kaid) {
id
nickname
username
bio
avatar {
name
imageSrc
__typename
}
points
isPhantom
isActor
isCoachedByActor
userSummaryIsVisibleToActor
actorHasUserScopedPermission(capability: CAN_VIEW_USER_IDENTITY)
__typename
}
}`)(ze||(ze={}));function Ae(t,r){return h(`${g}/getUserHoverCardProfile`,ze.query,typeof t=="string"?{kaid:t}:t,r)}var Ze;(r=>r.query=`query hotlist($curationNodeId: String, $onlyOfficialProjectSpinoffs: Boolean!, $sort: ListProgramSortOrder, $pageInfo: ListProgramsPageInfo, $userAuthoredContentTypes: [UserAuthoredContentType!]) {
listTopPrograms(
curationNodeId: $curationNodeId
onlyOfficialProjectSpinoffs: $onlyOfficialProjectSpinoffs
sort: $sort
pageInfo: $pageInfo
userAuthoredContentTypes: $userAuthoredContentTypes
) {
complete
cursor
programs {
id
key
authorKaid
authorNickname
displayableSpinoffCount
imagePath
sumVotesIncremented
translatedTitle: title
url
userAuthoredContentType
__typename
}
__typename
}
}`)(Ze||(Ze={}));function Ie(t,r){return h(`${g}/hotlist`,Ze.query,t,r)}var Xe;(r=>r.query=`query programQuery($programId: String!) {
programById(id: $programId) {
byChild
category
created
creatorProfile: author {
id
nickname
profileRoot
profile {
accessLevel
__typename
}
__typename
}
deleted
description
spinoffCount: displayableSpinoffCount
docsUrlPath
flags
flaggedBy: flaggedByKaids
flaggedByUser: isFlaggedByCurrentUser
height
hideFromHotlist
id
imagePath
isProjectOrFork: originIsProject
isOwner
kaid: authorKaid
key
newUrlPath
originScratchpad: originProgram {
deleted
translatedTitle
url
__typename
}
restrictPosting
revision: latestRevision {
id
code
configVersion
created
editorType
folds
__typename
}
slug
sumVotesIncremented
title
topic: parentCurationNode {
id
nodeSlug: slug
relativeUrl
slug
translatedTitle
__typename
}
translatedTitle
url
userAuthoredContentType
upVoted
width
__typename
}
}`)(Xe||(Xe={}));function Ee(t,r){return h(`${g}/programQuery`,Xe.query,typeof t=="number"?{programId:t.toString()}:typeof t=="string"?{programId:t}:t,r)}var er;(r=>r.query=`query projectsAuthoredByUser($kaid: String, $pageInfo: ListProgramsPageInfo, $sort: ListProgramSortOrder) {
user(kaid: $kaid) {
id
programs(pageInfo: $pageInfo, sort: $sort) {
complete
cursor
programs {
id
key
authorKaid
authorNickname
displayableSpinoffCount
imagePath
sumVotesIncremented
translatedTitle: title
url
__typename
}
__typename
}
__typename
}
}`)(er||(er={}));function Te(t,r){return h(`${g}/projectsAuthoredByUser`,er.query,t,r)}var rr;(r=>r.query=`query QAExpandKeyInfo($encryptedKey: String) {
qaExpandKeyInfo(encryptedQaExpandKey: $encryptedKey) {
feedbackType
unencryptedKey
__typename
}
}`)(rr||(rr={}));function ve(t,r){return h(`${g}/QAExpandKeyInfo`,rr.query,typeof t=="string"?{encryptedKey:t}:t,r)}var Qr={};_r(Qr,{LoginWithPasswordMutation:()=>ae,loginWithPasswordMutation:()=>Ue});var ae;(e=>{e.query=`mutation loginWithPasswordMutation($identifier: String!, $password: String!) {
loginWithPassword(identifier: $identifier, password: $password) {
user {
id
kaid
canAccessDistrictsHomepage
isTeacher
hasUnresolvedInvitations
preferredKaLocale {
id
kaLocale
status
__typename
}
__typename
}
isFirstLogin
error {
code
__typename
}
__typename
}
}`;let r;(i=>(i.INVALID_CREDENTIALS="INVALID_CREDENTIALS",i.TOO_MANY_ATTEMPTS="TOO_MANY_ATTEMPTS"))(r=e.ErrorCode||(e.ErrorCode={}))})(ae||(ae={}));function Ue(t,r){return h(`${g}/loginWithPasswordMutation`,ae.query,t,{headers:{"x-ka-fkey":dr,Cookie:`fkey=${dr}`},...r})}var H=class{constructor(r,e){return r instanceof b?this.client=r:e??(e=r),e&&this.copy(e),this}copy(r){return Object.assign(this,r),this}copyFromSchema(r){return this.rawData={...this.rawData,...r},this.copy(this.transformSchema(r))}isSchema(r){return this.is(this.transformSchema(r))}};var kt=(r=>(r.DOWNSTREAM_SERVICE_ERROR="DOWNSTREAM_SERVICE_ERROR",r))(kt||{}),wt=(r=>(r.users="users",r))(wt||{}),_t=(e=>(e.COACH="COACH",e.PUBLIC="PUBLIC",e))(_t||{}),$r=(s=>(s.pjs="pjs",s.webpage="webpage",s.ace_sql="ace_sql",s.unknown="",s))($r||{}),mr=(i=>(i.Challenge="Challenge",i.Interactive="Interactive",i.Project="Project",i.Scratchpad="Scratchpad",i.Talkthrough="Talkthrough",i))(mr||{}),tr=(y=>(y.ALL_PROJECT_ANSWER="ALL_PROJECT_ANSWER",y.ALL_PROJECT_QUESTION="ALL_PROJECT_QUESTION",y.ANSWER="ANSWER",y.COMMENT="COMMENT",y.PROGRAM="PROGRAM",y.PROJECTFEEDBACK="PROJECTFEEDBACK",y.PROJECT_CRITIQUE_ANSWER="PROJECT_CRITIQUE_ANSWER",y.PROJECT_CRITIQUE_QUESTION="PROJECT_CRITIQUE_QUESTION",y.PROJECT_EVAL_ANSWER="PROJECT_EVAL_ANSWER",y.PROJECT_EVAL_QUESTION="PROJECT_EVAL_QUESTION",y.PROJECT_HELP_ANSWER="PROJECT_HELP_ANSWER",y.PROJECT_HELP_QUESTION="PROJECT_HELP_QUESTION",y.QUESTION="QUESTION",y.REPLY="REPLY",y.SUGGESTED_CLARIFICATION="SUGGESTED_CLARIFICATION",y))(tr||{}),Pt=(s=>(s.AnswerFeedback="AnswerFeedback",s.BasicFeedback="BasicFeedback",s.LowQualityFeedback="LowQualityFeedback",s.QuestionFeedback="QuestionFeedback",s))(Pt||{}),Gr=(a=>(a[a.TopVoted=1]="TopVoted",a[a.Recent=2]="Recent",a[a.Trending=5]="Trending",a))(Gr||{}),Hr=(l=>(l.TOP="TOP",l.RECENT="RECENT",l.HOT="HOT",l.OFFICIAL="OFFICIAL",l.UPVOTE="UPVOTE",l.OLDEST="OLDEST",l))(Hr||{});var z,ye,ar=class ar extends H{constructor(){super(...arguments);U(this,z)}get url(){return this.kaid?`https://www.khanacademy.org/profile/${this.username??this.kaid}`:null}static fromSchema(e){let a=new ar;return a.copyFromSchema(e),a.rawData=e,a}static fromIdentifier(e){return new ar({kaid:R(e)?e:void 0,username:!R(e)&&!F(e)?e:void 0,email:F(e)?e:void 0})}transformSchema(e){return{emails:e.authEmails??void 0,badgeCounts:e.badgeCounts?JSON.parse(e.badgeCounts):void 0,bio:e.bio??void 0,canAccessDistrictsHomepage:e.canAccessDistrictsHomepage??void 0,canHellban:e.canHellban??void 0,canMessageUsers:e.canMessageUsers??void 0,canModifyCoaches:e.canModifyCoaches??void 0,completedVideos:e.countVideosCompleted,email:e.email??void 0,hasAccessToAIGuideDev:e.hasAccessToAIGuideDev??void 0,hasAccessToAIGuideTeacher:e.hasAccessToAIGuideTeacher??void 0,hasChildren:e.hasChildren??void 0,hasClasses:e.hasClasses??void 0,hasCoach:e.hasCoach??void 0,hasStudents:e.hasStudents??void 0,child:e.isChild??void 0,creator:e.isCreator??void 0,curator:e.isCurator??void 0,developer:e.isDeveloper??void 0,midsignupPhantom:e.isMidsignupPhantom??void 0,moderator:e.isModerator??void 0,orphan:e.isOrphan??void 0,parent:e.isParent??void 0,phantom:e.isPhantom??void 0,publisher:e.isPublisher??void 0,self:e.isSelf??void 0,teacher:e.isTeacher??void 0,formalTeacher:e.isFormalTeacher??void 0,joined:e.joined?new Date(e.joined):void 0,kaid:typeof e.kaid=="string"&&R(e.kaid)?e.kaid:typeof e.kaid=="string"?null:void 0,key:e.key??void 0,newNotifications:e.newNotificationCount??void 0,nickname:e.nickname??void 0,points:e.points??void 0,accessLevel:e.profile?.accessLevel,googleID:typeof e.userId=="string"&&Mr(e.userId)?e.userId.match(He)[1]:typeof e.userId=="string"?null:void 0,qualarooID:typeof e.qualarooId=="string"&&Vr(e.qualarooId)?e.qualarooId.match(je)[1]:typeof e.qualarooId=="string"?null:void 0,username:e.username??(e.profileRoot?R(e.profileRoot.slice(9,-1))?null:e.profileRoot.slice(9,-1):e.username)}}async get(e=this.client??new b){let a=await e.getUser(m(this,z,ye).call(this));return this.copy(a)}async getAvatar(e=this.client??new b){let a=await e.getUserAvatar(m(this,z,ye).call(this));return this.copy({avatar:a}),a}async getStatistics(e=this.client??new b){let a=await e.getUserStatistics(m(this,z,ye).call(this));return this.copy({statistics:a})}async*getPrograms(e=this.client??new b,a,s){for await(let i of e.getUserPrograms(m(this,z,ye).call(this),a,s))this.programs||this.copy({programs:[]}),this.programs?.push(...i),yield i;return this}async getAllPrograms(e=this.client??new b,a,s){let i=await e.getAllUserPrograms(m(this,z,ye).call(this),a,s);return this.copy({programs:i})}is(e){return!(this.kaid&&e.kaid)&&!(this.email&&e.email)&&!(this.key&&e.key)&&!(this.username&&e.username)&&!(this.googleID&&e.googleID)&&!(this.qualarooID&&e.qualarooID)?(console.warn("Users don't have any identifiers that can be compared"),!1):this.kaid&&e.kaid&&this.kaid===e.kaid||this.email&&e.email&&this.email===e.email||this.key&&e.key&&this.key===e.key||this.username&&e.username&&this.username===e.username||this.googleID&&e.googleID&&this.googleID===e.googleID||this.qualarooID&&e.qualarooID&&this.qualarooID===e.qualarooID||!1}};z=new WeakSet,ye=function(){if(this.kaid)return this.kaid;if(this.username)return this.username;if(this.email)return this.email;throw new Error("User has no identifier")};var N=ar;function Rt(t){return"data"in t&&!("errors"in t)}function St(t){return"errors"in t&&Array.isArray(t.errors)&&"data"in t}function xt(t){return"errors"in t&&Array.isArray(t.errors)&&!("data"in t)}function I(t){if(St(t))throw new Error("Expected data response but got service errors response: "+t.errors.map(r=>r.message).join(", "));if(xt(t))throw new Error("Expected data response but got input errors response: "+t.errors.map(r=>r.message).join(", "));if(!Rt(t))throw new Error("Expected data response but got unknown response")}function jr(t){if(!me(t))throw new Error("Invalid program key");let r=atob($e(t)).split("").map(s=>s.charCodeAt(0)),e=r[17];if(e===20)r=r.slice(32,37);else if(e===23)r=r.slice(34,40);else throw new Error(`Unknown program key version: ${e}`);let a=0n;for(let s=0;s<r.length;s++)a|=BigInt(r[s]&127)<<BigInt(s*7);return Number(e===20?a:a<<14n)}function Do(t){if(!te(t))throw new Error("Invalid program ID");typeof t=="string"&&(t=parseInt(t));let r=t.toString(2).match(/.{1,7}(?=(.{7})*$)/g).map(a=>String.fromCharCode(parseInt(a.length===7?`1${a}`:a,2))).reverse().join(""),e=btoa(`js~khan-academyr${r.length===5?"":""}\v
Scratchpad${r}\f`);return e=vr(e),e}async function yr(t){if(R(t))return t;if(R(`kaid_${t}`))return`kaid_${t}`;if(ce(t)){let s=t.match(Pe);if(!s)throw new Error("Invalid user URL");if(t=s[1],R(t))return t}let e=await(await xe(t)).json();if(I(e),!e.data.user)throw new Error("User not found");let a=e.data.user.kaid;if(!R(a))throw new Error("Invalid KAID");return a}async function Wr(t){if(!R(t)&&!F(t)&&!ce(t))return t;if(ce(t)){let a=t.match(Pe);if(!a)throw new Error("Invalid user URL");if(t=a[1],!R(t)&&!F(t))return t}R(t)||(t=await yr(t));let e=await(await Ae(t)).json();if(I(e),!e.data.user)throw new Error("User not found");return e.data.user.username}function Ke(t){if(typeof t=="number"){if(!te(t))throw new Error("Invalid program ID");return t}else if(Cr(t)){let r=t.match(ue)[1];if(!te(r))throw new Error("Invalid program URL");return parseInt(r,10)}else if(me(t)){if(t=jr(t),!te(t))throw new Error("Invalid program key");return t}else if(typeof t=="string"){if(!te(t))throw new Error("Invalid program ID");return parseInt(t,10)}throw new Error("Invalid program identifier")}async function Yr(t){if(E(t))return t;if(!D(t))throw new Error("Invalid encrypted message key");let e=await(await ve(t)).json();if(I(e),!e.data.qaExpandKeyInfo)throw new Error("Message key not found");return e.data.qaExpandKeyInfo.unencryptedKey}var Jr=(s=>(s.ProcessingJS="pjs",s.HTML="webpage",s.SQL="ace_sql",s.Other="",s))(Jr||{}),j,oe,Q=class Q extends H{constructor(){super(...arguments);U(this,j)}get spinoff(){return typeof this.origin<"u"?!!this.origin:null}get lines(){return this.code?this.code.split(`
`).length:null}get url(){return this.rawData?.url?`https://www.khanacademy.org${this.rawData.url}`:this.id?`https://www.khanacademy.org/computer-programming/-/${this.id}`:null}get shortUrl(){return this.id?`https://khanacademy.org/cs/-/${this.id}`:null}get thumbnailUrl(){return this.rawData?.imagePath?`https://www.khanacademy.org${this.rawData.imagePath}`:this.thumbnailID&&this.url?`${this.url}/${this.thumbnailID}.png`:null}static fromSchema(e){let a=new Q;return a.copyFromSchema(e),a.rawData=e,a}static fromIdentifier(e){let a=Ke(e);return new Q({id:a,key:typeof e=="string"&&me(e)?e:void 0})}transformSchema(e){return{id:e.id?parseInt(e.id,10):void 0,title:e.translatedTitle,author:e.authorKaid||e.authorNickname||e.creatorProfile?N.fromSchema({kaid:e.authorKaid,nickname:e.authorNickname,isChild:e.byChild??void 0,...e.creatorProfile}):void 0,created:(()=>{if(e.created)return e.revision?.created?new Date(Math.min(new Date(e.created).valueOf(),new Date(e.revision.created).valueOf())):new Date(e.created)})(),updated:(()=>{if(e.revision?.created)return e.created&&e.revision.created===e.created?null:new Date(e.revision.created)})(),width:e.width,height:e.height,votes:e.sumVotesIncremented,spinOffCount:e.spinoffCount??e.displayableSpinoffCount,code:e.revision?.code,hidden:e.hideFromHotlist,type:(()=>{switch(e.revision?.editorType){case"pjs":return Q.Type.ProcessingJS;case"webpage":return Q.Type.HTML;case"ace_sql":return Q.Type.SQL;default:return Q.Type.Other}})(),origin:(()=>{if(!e.originScratchpad)return e.originScratchpad;let a=("https://khanacademy.org"+e.originScratchpad.url).match(ue)?.[1];if(!a){console.error(`Failed to parse origin program ID from URL: ${e.originScratchpad.url}`);return}return new Q({id:parseInt(a,10),title:e.originScratchpad.translatedTitle,deleted:e.originScratchpad.deleted})})(),key:e.key,thumbnailID:e.imagePath&&Ge.test(e.imagePath)?parseInt(e.imagePath.match(Ge)[1],10):void 0,description:typeof e.description=="string"?e.description!==""?e.description:null:e.description,deleted:e.deleted??void 0,selfFlagged:e.flaggedByUser,selfVoted:e.upVoted}}async get(e=this.client??new b){if(!this.id&&!this.key)throw new Error("Program is missing ID and key");let a=await e.getProgram(this.id??this.key);return this.copy(a)}async*getTipsAndThanks(e=this.client??new b,a){for await(let s of e.getProgramTipsAndThanks(m(this,j,oe).call(this),a))this.tipsAndThanks||this.copy({tipsAndThanks:[]}),s.forEach(i=>this.tipsAndThanks?.push(i)),yield s;return this}async getAllTipsAndThanks(e=this.client??new b,a){let s=await e.getAllProgramTipsAndThanks(m(this,j,oe).call(this),a);return this.copy({tipsAndThanks:s})}async*getQuestions(e=this.client??new b,a){for await(let s of e.getProgramQuestions(m(this,j,oe).call(this),a))this.questions||this.copy({questions:[]}),s.forEach(i=>this.questions.push(i)),yield s;return this}async getAllQuestions(e=this.client??new b,a){let s=await e.getAllProgramQuestions(m(this,j,oe).call(this),a);return this.copy({questions:s})}async*getHelpRequests(e=this.client??new b,a){for await(let s of e.getProgramHelpRequests(m(this,j,oe).call(this),a))this.helpRequests||this.copy({helpRequests:[]}),s.forEach(i=>this.helpRequests.push(i)),yield s;return this}async getAllHelpRequests(e=this.client??new b,a){let s=await e.getAllProgramHelpRequests(m(this,j,oe).call(this),a);return this.copy({helpRequests:s})}is(e){return!(this.id&&e.id)&&!(this.key&&e.key)?(console.warn("Programs don't have any identifiers that can be compared"),!1):this.id&&e.id&&this.id===e.id||this.key&&e.key&&this.key===e.key||!1}};j=new WeakSet,oe=function(){if(this.id)return this.id;if(this.key)return this.key;throw new Error("Program has no identifier")},Q.Type=Jr;var O=Q;var zr=["blobby_green_style","blobby_yellow_style","blobby_blue_style","blobby_purple_style","area_52_yellow_style","area_52_blue_style","area_52_green_style","area_52_purple_style","eggleston_blue_style","eggleston_yellow_style","eggleston_green_style","eggleston_orange_style","scuttlebug_purple_style","scuttlebug_yellow_style","scuttlebug_blue_style","scuttlebug_green_style","boggle_yellow_style","boggle_blue_style","boggle_green_style","boggle_purple_style","sneak_peak_green_style","sneak_peak_yellow_style","sneak_peak_blue_style","sneak_peak_purple_style","stelly_blue_style","stelly_yellow_style","stelly_green_style","stelly_orange_style","cacteye_purple_style","cacteye_yellow_style","cacteye_blue_style","cacteye_green_style","leaf_green_style","leaf_blue_style","leaf_grey_style","leaf_red_style","leaf_orange_style","leaf_yellow_style","leafers_seed_style","leafers_seedling_style","leafers_sapling_style","leafers_tree_style","leafers_ultimate_style","piceratops_seed_style","piceratops_seedling_style","piceratops_sapling_style","piceratops_tree_style","piceratops_ultimate_style","duskpin_seed_style","duskpin_seedling_style","duskpin_sapling_style","duskpin_tree_style","duskpin_ultimate_style","primosaur_seed_style","primosaur_seedling_style","primosaur_sapling_style","primosaur_tree_style","primosaur_ultimate_style","starky_seed_style","starky_seedling_style","starky_sapling_style","starky_tree_style","starky_ultimate_style","aqualine_seed_style","aqualine_seedling_style","aqualine_sapling_style","aqualine_tree_style","aqualine_ultimate_style","spunky_sam_blue_style","spunky_sam_green_style","spunky_sam_orange_style","spunky_sam_red_style","marcimus_pink_style","marcimus_orange_style","marcimus_red_style","marcimus_purple_style","mr_pink_red_style","mr_pink_green_style","mr_pink_orange_style","female_robot_amelia_style","female_robot_ada_style","female_robot_grace_style","male_robot_johnny_style","male_robot_donald_style","male_robot_hal_style","orange_juice_squid_orange_style","purple_pi_purple_style","purple_pi_pink_style","purple_pi_teal_style","mr_pants_teal_style","mr_pants_green_style","mr_pants_orange_style","mr_pants_pink_style","mr_pants_purple_style","old_spice_man_green_style","old_spice_man_blue_style","winston_default_style","winston_baby_style","ohnoes_default_style","hopper_happy_style","hopper_jumping_style","hopper_cool_style"],Zr=["blobby-green","blobby-yellow","blobby-blue","blobby-purple","area-52-yellow","area-52-blue","area-52-green","area-52-purple","eggleston-blue","eggleston-yellow","eggleston-green","eggleston-orange","scuttlebug-purple","scuttlebug-yellow","scuttlebug-blue","scuttlebug-green","boggle-yellow","boggle-blue","boggle-green","boggle-purple","sneak-peak-green","sneak-peak-yellow","sneak-peak-blue","sneak-peak-purple","stelly-blue","stelly-yellow","stelly-green","stelly-orange","cacteye-purple","cacteye-yellow","cacteye-blue","cacteye-green","leaf-green","leaf-blue","leaf-grey","leaf-red","leaf-orange","leaf-yellow","leafers-seed","leafers-seedling","leafers-sapling","leafers-tree","leafers-ultimate","piceratops-seed","piceratops-seedling","piceratops-sapling","piceratops-tree","piceratops-ultimate","duskpin-seed","duskpin-seedling","duskpin-sapling","duskpin-tree","duskpin-ultimate","primosaur-seed","primosaur-seedling","primosaur-sapling","primosaur-tree","primosaur-ultimate","starky-seed","starky-seedling","starky-sapling","starky-tree","starky-ultimate","aqualine-seed","aqualine-seedling","aqualine-sapling","aqualine-tree","aqualine-ultimate","spunky-sam","spunky-sam-green","spunky-sam-orange","spunky-sam-red","marcimus","marcimus-orange","marcimus-red","marcimus-purple","mr-pink","mr-pink-green","mr-pink-orange","robot_female_1","robot_female_2","robot_female_3","robot_male_1","robot_male_2","robot_male_3","orange-juice-squid","purple-pi","purple-pi-pink","purple-pi-teal","mr-pants","mr-pants-green","mr-pants-orange","mr-pants-pink","mr-pants-purple","old-spice-man","old-spice-man-blue","cs-winston","cs-winston-baby","cs-ohnoes","cs-hopper-happy","cs-hopper-jumping","cs-hopper-cool"];function zo(t){return Zr[zr.indexOf(t)]}function Zo(t){return zr[Zr.indexOf(t)]}function fr(t){return`https://www.khanacademy.org/images/avatars/svg/${t}.svg`}function gr(t){return`https://www.khanacademy.org/images/avatars/${t}.png`}function or(t){return t.match(/^(?:https:\/\/www\.khanacademy\.org)?\/images\/avatars(?:\/svg)?\/(.*)\.(?:(?:svg)|(?:png))$/)?.[1]??null}function Xo(t){let r=or(t);return r?gr(r):null}function es(t){let r=or(t);return r?fr(r):null}function Xr(t){return t.replace(/[a-zA-Z]+, \d\d [A-Za-z0-9]+ \d{4} \d\d:\d\d:\d\d [a-zA-Z]+/g,"").replace(/; (Path|Expires|Max-Age|HttpOnly|Secure|SameSite)[^;,]*/g,"").replace(/,/g,";")}var Z=class extends H{get bySelf(){return this.client?.user?this.byUser(this.client.user):!1}get url(){if(!this.program?.url||!this.encryptedKey)return null;let r={qa_expand_key:this.key??this.encryptedKey,qa_expand_type:this.rawData?.feedbackType?.toLowerCase()},e=new URL(this.program.url);for(let[a,s]of Object.entries(r))s&&e.searchParams.set(a,s);return e.toString()}transformSchema(r){return{text:r.content,author:r.author&&N.fromSchema(r.author),program:(()=>{if(r.focus?.kind==="Scratchpad")return new O({id:typeof r.focus.id=="string"?parseInt(r.focus.id,10):void 0,title:r.focus.translatedTitle});if(r.focusUrl){let e=r.focusUrl.match(Dr);return!e||e.length<1?void 0:new O({id:parseInt(e[1],10)})}})(),created:r.date?new Date(r.date):void 0,key:r.expandKey,encryptedKey:r.key,deleted:r.appearsAsDeleted,locked:r.isLocked,pinned:r.isPinned,verified:r.definitelyNotSpam,score:r.lowQualityScore,byVideoAuthor:r.fromVideoAuthor,selfFlagged:r.flaggedByUser}}byUser(r){return this.author?this.author.is(r):!1}is(r){return!(this.key&&r.key)&&!(this.encryptedKey&&r.encryptedKey)?(console.warn("Messages don't have any identifiers that can be compared"),!1):this.key&&r.key&&this.key===r.key||this.encryptedKey&&r.encryptedKey&&this.encryptedKey===r.encryptedKey||!1}};var fe=(a=>(a[a.TipsAndThanks="COMMENT"]="TipsAndThanks",a[a.Question="QUESTION"]="Question",a[a.HelpRequest="PROJECT_HELP_QUESTION"]="HelpRequest",a))(fe||{}),Fe,hr,De=class De extends Z{constructor(){super(...arguments);U(this,Fe)}get selfVoted(){return this.client?.authenticated===!1?null:this.selfUpvoted?1:this.selfDownvoted?-1:0}static fromSchema(e){let a=new De;return a.copyFromSchema(e),a.rawData=e,a}static fromIdentifier(e){return new De({key:E(e)?e:void 0,encryptedKey:D(e)?e:void 0})}transformSchema(e){return{...super.transformSchema(e),votes:e.sumVotesIncremented,replyCount:e.replyCount,selfUpvoted:e.upVoted,selfDownvoted:e.downVoted}}copy(e){return super.copy(e)}async get(e=this.client??new b){let a=await e.getMessage(m(this,Fe,hr).call(this));return this.copy(a)}async*getReplies(e=this.client??new b,a){for await(let s of e.getMessageReplies(m(this,Fe,hr).call(this),a))this.replies||this.copy({replies:[]}),this.replies?.push(...s),yield s;return this}async getAllReplies(e=this.client??new b){if(!this.key&&!this.encryptedKey)throw new Error("Message does not have a key or encrypted key");let a=await e.getAllMessageReplies(this.key??this.encryptedKey);return this.copy({replies:a})}};Fe=new WeakSet,hr=function(){if(this.key)return this.key;if(this.encryptedKey)return this.encryptedKey;throw new Error("Message does not have a key or encrypted key")},De.Type=fe;var S=De;var ge=class t extends S{static fromSchema(r){let e=new t;return e.copyFromSchema(r),e.rawData=r,e}static fromIdentifier(r){return new t({key:E(r)?r:void 0,encryptedKey:D(r)?r:void 0})}transformSchema(r){return{...super.transformSchema(r),question:r.question?M.fromSchema(r.question):void 0}}copy(r){return super.copy(r)}};var M=class t extends S{static fromSchema(r){let e=new t;return e.copyFromSchema(r),e.rawData=r,e}static fromIdentifier(r){return new t({key:E(r)?r:void 0,encryptedKey:D(r)?r:void 0})}transformSchema(r){return{...super.transformSchema(r),answerCount:r.answerCount,old:r.isOld,answers:(()=>{if(!r.answers)return;let e=r.answers.map(a=>ge.fromSchema(a));return e.forEach(a=>a.copy({question:this})),e})()}}copy(r){return super.copy(r)}};var X=class t extends Z{static fromSchema(r){let e=new t;return e.copyFromSchema(r),e.