@bhavjit/khan-api
Version:
A Khan Academy API client and wrapper
624 lines (623 loc) • 63.9 kB
JavaScript
/**
* Khan API v0.7.4
* https://khan-api.bhavjit.com
* Licensed under MIT license
* Copyright 2025 Bhavjit Chauhan
*/
"use strict";var KhanAPI=(()=>{var wt=Object.create;var Be=Object.defineProperty;var _t=Object.getOwnPropertyDescriptor;var Pt=Object.getOwnPropertyNames;var Rt=Object.getPrototypeOf,St=Object.prototype.hasOwnProperty;var Wr=t=>{throw TypeError(t)};var xt=(t,r)=>()=>(r||t((r={exports:{}}).exports,r),r.exports),fr=(t,r)=>{for(var e in r)Be(t,e,{get:r[e],enumerable:!0})},Yr=(t,r,e,a)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of Pt(r))!St.call(t,s)&&s!==e&&Be(t,s,{get:()=>r[s],enumerable:!(a=_t(r,s))||a.enumerable});return t};var At=(t,r,e)=>(e=t!=null?wt(Rt(t)):{},Yr(r||!t||!t.__esModule?Be(e,"default",{value:t,enumerable:!0}):e,t)),It=t=>Yr(Be({},"__esModule",{value:!0}),t);var gr=(t,r,e)=>r.has(t)||Wr("Cannot "+e);var w=(t,r,e)=>(gr(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),Ne=(t,r,e,a)=>(gr(t,r,"write to private field"),a?a.call(t,e):r.set(t,e),e),m=(t,r,e)=>(gr(t,r,"access private method"),e);var Xr=xt((X,Zr)=>{var $e=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global,Ge=function(){function t(){this.fetch=!1,this.DOMException=$e.DOMException}return t.prototype=$e,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 B(o){if(!o._noBody){if(o.bodyUsed)return Promise.reject(new TypeError("Already read"));o.bodyUsed=!0}}function q(o){return new Promise(function(n,d){o.onload=function(){n(o.result)},o.onerror=function(){d(o.error)}})}function O(o){var n=new FileReader,d=q(n);return n.readAsArrayBuffer(o),d}function y(o){var n=new FileReader,d=q(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 _e(o){if(o.slice)return o.slice(0);var n=new Uint8Array(o.byteLength);return n.set(new Uint8Array(o)),n.buffer}function Hr(){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=_e(o.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(o)||c(o))?this._bodyArrayBuffer=_e(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=B(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=B(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(O);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var o=B(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(ht)}),this.json=function(){return this.text().then(JSON.parse)},this}var ft=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function gt(o){var n=o.toUpperCase();return ft.indexOf(n)>-1?n:o}function Z(o,n){if(!(this instanceof Z))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 Z){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=gt(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()}}}Z.prototype.clone=function(){return new Z(this,{body:this._bodyInit})};function ht(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 bt(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 Ve=P.join(":").trim();try{n.append(p,Ve)}catch(yr){console.warn("Response "+yr.message)}}}),n}Hr.call(Z.prototype);function M(o,n){if(!(this instanceof M))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)}Hr.call(M.prototype),M.prototype.clone=function(){return new M(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new u(this.headers),url:this.url})},M.error=function(){var o=new M(null,{status:200,statusText:""});return o.ok=!1,o.status=0,o.type="error",o};var kt=[301,302,303,307,308];M.redirect=function(o,n){if(kt.indexOf(n)===-1)throw new RangeError("Invalid status code");return new M(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 mr(o,n){return new Promise(function(d,f){var P=new Z(o,n);if(P.signal&&P.signal.aborted)return f(new e.DOMException("Aborted","AbortError"));var p=new XMLHttpRequest;function Ve(){p.abort()}p.onload=function(){var I={statusText:p.statusText,headers:bt(p.getAllResponseHeaders()||"")};P.url.indexOf("file://")===0&&(p.status<200||p.status>599)?I.status=200:I.status=p.status,I.url="responseURL"in p?p.responseURL:I.headers.get("X-Request-URL");var te="response"in p?p.response:p.responseText;setTimeout(function(){d(new M(te,I))},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 yr(I){try{return I===""&&a.location.href?a.location.href:I}catch{return I}}if(p.open(P.method,yr(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 jr=[];Object.getOwnPropertyNames(n.headers).forEach(function(I){jr.push(k(I)),p.setRequestHeader(I,x(n.headers[I]))}),P.headers.forEach(function(I,te){jr.indexOf(te)===-1&&p.setRequestHeader(te,I)})}else P.headers.forEach(function(I,te){p.setRequestHeader(te,I)});P.signal&&(P.signal.addEventListener("abort",Ve),p.onreadystatechange=function(){p.readyState===4&&P.signal.removeEventListener("abort",Ve)}),p.send(typeof P._bodyInit>"u"?null:P._bodyInit)})}return mr.polyfill=!0,a.fetch||(a.fetch=mr,a.Headers=u,a.Request=Z,a.Response=M),e.Headers=u,e.Request=Z,e.Response=M,e.fetch=mr,e}({})})(Ge);Ge.fetch.ponyfill=!0;delete Ge.fetch.polyfill;var me=$e.fetch?$e:Ge;X=me.fetch;X.default=me.fetch;X.fetch=me.fetch;X.Headers=me.Headers;X.Request=me.Request;X.Response=me.Response;Zr.exports=X});var Jt={};fr(Jt,{Answer:()=>pe,BadgeCategory:()=>yt,BaseMessage:()=>W,Client:()=>h,EmailRegex:()=>vr,EmailRegexMatch:()=>Nt,FeedbackFocusKind:()=>lr,FeedbackKeyRegex:()=>Ar,FeedbackKeyRegexMatch:()=>qt,FeedbackSort:()=>Fr,FeedbackType:()=>Le,FeedbackTypename:()=>dt,GoogleIDRegex:()=>xe,GoogleIDRegexMatch:()=>Vt,KaidRegex:()=>Ze,KaidRegexMatch:()=>Ut,ListProgramSortOrder:()=>Cr,MESSAGE_ENCRYPTED_KEY_LENGTHS:()=>Ot,MESSAGE_KEY_LENGTHS:()=>Lt,Message:()=>S,MessageEncryptedKeyRegex:()=>Ir,MessageEncryptedKeyRegexMatch:()=>Mt,MessageType:()=>de,PROGRAM_ID_LENGTHS:()=>ot,PROGRAM_KEY_LENGTHS:()=>st,PROGRAM_URL_PATHS:()=>Rr,Program:()=>C,ProgramEditorType:()=>Dr,ProgramIDRegex:()=>Xe,ProgramIDRegexMatch:()=>Pr,ProgramImagePathRegex:()=>Se,ProgramImagePathRegexMatch:()=>Ft,ProgramKeyRegex:()=>xr,ProgramKeyRegexMatch:()=>Ct,ProgramType:()=>Mr,ProgramURLRegex:()=>se,ProgramURLRegexMatch:()=>Dt,QualarooIDRegex:()=>Ae,QualarooIDRegexMatch:()=>Bt,Question:()=>L,Reply:()=>Y,ServiceErrorCode:()=>nt,ServiceErrorName:()=>it,TipsAndThanks:()=>J,TypeToMessageClass:()=>Gr,URL_LOCALES:()=>_r,URL_TLDS:()=>wr,User:()=>V,UserAccessLevel:()=>lt,UserURLRegex:()=>ge,UserURLRegexMatch:()=>Kt,assertDataResponse:()=>A,avatarNameToSlug:()=>$t,avatarNames:()=>Vr,avatarSlugToName:()=>Gt,avatarSlugs:()=>Br,convertAvatarPNGToSVG:()=>jt,convertAvatarSVGToPNG:()=>Ht,extractAvatarSlug:()=>qe,generateAvatarPNG:()=>ur,generateAvatarSVG:()=>cr,get:()=>vt,getLatestFragment:()=>Et,getLatestMutation:()=>br,getLatestQuery:()=>He,getLatestQueryHash:()=>Tt,graphql:()=>g,hashQuery:()=>et,http:()=>ae,isAnswerSchema:()=>Yt,isDataResponse:()=>pt,isEmail:()=>D,isEncryptedFeedbackKey:()=>K,isFeedbackKey:()=>E,isGoogleID:()=>Er,isInputErrorResponse:()=>ut,isKaid:()=>R,isProgramID:()=>ee,isProgramKey:()=>ne,isProgramURL:()=>Sr,isQualarooID:()=>Tr,isQuestionSchema:()=>$r,isReplySchema:()=>Wt,isServiceErrorsResponse:()=>ct,isTipsAndThanksSchema:()=>Qr,isUserURL:()=>oe,mutations:()=>Kr,post:()=>kr,programIDtoKey:()=>Qt,programKeyToID:()=>Lr,queries:()=>Ur,resolveFeedbackKey:()=>Or,resolveKaid:()=>pr,resolveProgramID:()=>be,resolveUsername:()=>qr});var Ur={};fr(Ur,{AvatarDataForProfile:()=>je,FeedbackQuery:()=>We,GetFeedbackReplies:()=>Ye,GetFeedbackRepliesPage:()=>Je,GetFullUserProfile:()=>er,GetProfileWidgets:()=>rr,GetUserByUsernameOrEmail:()=>tr,GetUserHoverCardProfile:()=>ar,Hotlist:()=>or,ProgramQuery:()=>sr,ProjectsAuthoredByUser:()=>nr,QAExpandKeyInfo:()=>Fe,QaExpandKeyInfo:()=>ir,avatarDataForProfile:()=>Pe,feedbackQuery:()=>ye,getFeedbackReplies:()=>fe,getFeedbackRepliesPage:()=>Re,getFullUserProfile:()=>Ie,getProfileWidgets:()=>Ee,getUserByUsernameOrEmail:()=>Te,getUserHoverCardProfile:()=>ve,hotlist:()=>Ue,programQuery:()=>Ke,projectsAuthoredByUser:()=>De});var b="https://www.khanacademy.org/api/internal/graphql",Qe="https://cdn.jsdelivr.net/gh/bhavjitChauhan/khan-api@safelist",Jr="khan-proxy.bhavjit.com",hr=`bhavjitchauhan/khan-api_${Date.now()}`,zr=4669512406581248;var rt=At(Xr(),1);async function He(t){let r=await ae(`${Qe}/query/${t}`);return r.status===404?null:await r.text()}async function br(t){let r=await ae(`${Qe}/mutation/${t}`);return r.status===404?null:await r.text()}async function Et(t){let r=await ae(`${Qe}/fragment/${t}`);return r.status===404?null:await r.text()}function et(t){let r=5381,e=t.length;for(;e;)r=r*33^t.charCodeAt(--e);return r>>>0}async function Tt(t){let r=await He(t);return r?et(r):null}async function ae(t,r){return await(0,rt.default)(t,r)}async function vt(t,r){return r={method:"get",...r},await ae(t,r)}async function kr(t,r,e){return e={method:"post",body:JSON.stringify(r),...e},await ae(t,e)}async function g(t,r,e={},a){let s={query:r,variables:e};typeof window<"u"&&window.location.hostname!=="khanacademy.org"&&(t=t.replace("www.khanacademy.org",Jr));let i=await kr(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 He(c):await br(c);if(!k)throw new Error(`The query for operation "${c}" was not found in the safelist`);return await kr(t,{...s,query:k},a)}return i}var je;(r=>r.query=`query avatarDataForProfile($kaid: String!) {
user(kaid: $kaid) {
id
avatar {
name
imageSrc
__typename
}
__typename
}
}`)(je||(je={}));function Pe(t,r){return g(`${b}/avatarDataForProfile`,je.query,typeof t=="string"?{kaid:t}:t,r)}var We;(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
}
}`)(We||(We={}));function ye(t,r){return g(`${b}/feedbackQuery`,We.query,t,r)}var Ye;(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
}
}`)(Ye||(Ye={}));function fe(t,r){return g(`${b}/getFeedbackReplies`,Ye.query,typeof t=="string"?{postKey:t}:t,r)}var Je;(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
}
}`)(Je||(Je={}));function Re(t,r){return g(`${b}/getFeedbackRepliesPage`,Je.query,t,r)}function tt(t,r,e="..."){return r=Math.max(0,r),t.length>r?t.slice(0,r-e.length)+e:t}function ze(t){return t.replace(/-/g,"+").replace(/_/g,"/")}function at(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function N(t){return new RegExp(`(${t.source.slice(1,-1)})`)}var wr=["com","org"],_r=["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"],Ze=/^kaid_\d{20,25}$/,Ut=N(Ze),R=t=>Ze.test(t),ge=new RegExp(`^https?:\\/\\/(?:(?:www|${_r.join("|")})\\.)?khanacademy\\.(?:${wr.join("|")})\\/profile\\/((?!kaid_|kaid_\\D)\\w+|(?:${Ze.toString().slice(2,-2)}))(?:\\/.*)?$`,"i"),Kt=N(ge),oe=t=>ge.test(t),ot=[9,10,16],Xe=new RegExp(`^[1-9](?:(?:${ot.map(t=>`\\d{${t-1}}`).join("|")}))$`),Pr=new RegExp(`(?:^|\\D)(${Xe.source.slice(1,-1)})(?:$|\\D)`);function ee(t){return Xe.test(t.toString())}var Rr=["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"],se=new RegExp(`^https?:\\/\\/(?:(?:www|${_r.join("|")})\\.)?khanacademy\\.(?:${wr.join("|")})\\/(?:${Rr.join("|")})\\/[\\w\\d-.~()'!*:@,;]+\\/(${Xe.toString().slice(2,-2)})$`,"i"),Dt=N(se);function Sr(t){return se.test(t)}var Se=new RegExp(`^\\/(?:${Rr.join("|")})\\/[\\w\\d-.~()'!*:@,;]+\\/\\d+\\/(\\d+)\\.png$`),Ft=N(Se),st=[51,54],xr=/^ag5zfmtoYW4tYWNhZGVteXI(?:U|X)CxIKU2NyYXRjaHBhZB(?:i|j)(?=[\w-]*$)(?:.{7}w|.{9}C(?:g|w|A|Q)w)$/,Ct=N(xr);function ne(t){if(st.includes(t.length)||!xr.test(t))return!1;try{return atob(ze(t)),!0}catch{return!1}}var Lt=[106,107,108,110,111],Ar=/^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)$/,qt=N(Ar),E=t=>Ar.test(t),Ot=[301],Ir=/^kaencrypted_[a-z0-9]{32}_[a-z0-9]{256}$/,Mt=N(Ir),K=t=>Ir.test(t),xe=/^http:\/\/googleid\.khanacademy\.org\/(\d+)$/,Vt=N(xe),Er=t=>xe.test(t),Ae=/^_gae_bingo_random:(\w+-\w+-\w+)$/,Bt=N(Ae),Tr=t=>Ae.test(t),vr=/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,Nt=N(vr),D=t=>vr.test(t);var er;(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
}`)(er||(er={}));function Ie(t,r){return g(`${b}/getFullUserProfile`,er.query,typeof t=="string"?R(t)?{kaid:t}:{username:t}:t,r)}var rr;(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
}
}`)(rr||(rr={}));function Ee(t,r){return g(`${b}/getProfileWidgets`,rr.query,typeof t=="string"&&R(t)?{kaid:t}:t,r)}var tr;(r=>r.query=`query getUserByUsernameOrEmail($username: String, $email: String) {
user(username: $username, email: $email) {
id
kaid
__typename
}
}`)(tr||(tr={}));function Te(t,r){return g(`${b}/getUserByUsernameOrEmail`,tr.query,typeof t=="string"?D(t)?{email:t}:{username:t}:t,r)}var ar;(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
}
}`)(ar||(ar={}));function ve(t,r){return g(`${b}/getUserHoverCardProfile`,ar.query,typeof t=="string"?{kaid:t}:t,r)}var or;(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
}
}`)(or||(or={}));function Ue(t,r){return g(`${b}/hotlist`,or.query,t,r)}var sr;(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
}
}`)(sr||(sr={}));function Ke(t,r){return g(`${b}/programQuery`,sr.query,typeof t=="number"?{programId:t.toString()}:typeof t=="string"?{programId:t}:t,r)}var nr;(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
}
}`)(nr||(nr={}));function De(t,r){return g(`${b}/projectsAuthoredByUser`,nr.query,t,r)}var ir;(r=>r.query=`query QAExpandKeyInfo($encryptedKey: String) {
qaExpandKeyInfo(encryptedQaExpandKey: $encryptedKey) {
feedbackType
unencryptedKey
__typename
}
}`)(ir||(ir={}));function Fe(t,r){return g(`${b}/QAExpandKeyInfo`,ir.query,typeof t=="string"?{encryptedKey:t}:t,r)}var Kr={};fr(Kr,{LoginWithPasswordMutation:()=>ie,loginWithPasswordMutation:()=>Ce});var ie;(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={}))})(ie||(ie={}));function Ce(t,r){return g(`${b}/loginWithPasswordMutation`,ie.query,t,{headers:{"x-ka-fkey":hr,Cookie:`fkey=${hr}`},...r})}var H=class{constructor(r,e){return r instanceof h?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 nt=(r=>(r.DOWNSTREAM_SERVICE_ERROR="DOWNSTREAM_SERVICE_ERROR",r))(nt||{}),it=(r=>(r.users="users",r))(it||{}),lt=(e=>(e.COACH="COACH",e.PUBLIC="PUBLIC",e))(lt||{}),Dr=(s=>(s.pjs="pjs",s.webpage="webpage",s.ace_sql="ace_sql",s.unknown="",s))(Dr||{}),lr=(i=>(i.Challenge="Challenge",i.Interactive="Interactive",i.Project="Project",i.Scratchpad="Scratchpad",i.Talkthrough="Talkthrough",i))(lr||{}),Le=(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))(Le||{}),dt=(s=>(s.AnswerFeedback="AnswerFeedback",s.BasicFeedback="BasicFeedback",s.LowQualityFeedback="LowQualityFeedback",s.QuestionFeedback="QuestionFeedback",s))(dt||{}),Fr=(a=>(a[a.TopVoted=1]="TopVoted",a[a.Recent=2]="Recent",a[a.Trending=5]="Trending",a))(Fr||{}),Cr=(l=>(l.TOP="TOP",l.RECENT="RECENT",l.HOT="HOT",l.OFFICIAL="OFFICIAL",l.UPVOTE="UPVOTE",l.OLDEST="OLDEST",l))(Cr||{});var re,he,dr=class dr extends H{constructor(){super(...arguments);U(this,re)}get url(){return this.kaid?`https://www.khanacademy.org/profile/${this.username??this.kaid}`:null}static fromSchema(e){let a=new dr;return a.copyFromSchema(e),a.rawData=e,a}static fromIdentifier(e){return new dr({kaid:R(e)?e:void 0,username:!R(e)&&!D(e)?e:void 0,email:D(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"&&Er(e.userId)?e.userId.match(xe)[1]:typeof e.userId=="string"?null:void 0,qualarooID:typeof e.qualarooId=="string"&&Tr(e.qualarooId)?e.qualarooId.match(Ae)[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 h){let a=await e.getUser(m(this,re,he).call(this));return this.copy(a)}async getAvatar(e=this.client??new h){let a=await e.getUserAvatar(m(this,re,he).call(this));return this.copy({avatar:a}),a}async getStatistics(e=this.client??new h){let a=await e.getUserStatistics(m(this,re,he).call(this));return this.copy({statistics:a})}async*getPrograms(e=this.client??new h,a,s){for await(let i of e.getUserPrograms(m(this,re,he).call(this),a,s))this.programs||this.copy({programs:[]}),this.programs?.push(...i),yield i;return this}async getAllPrograms(e=this.client??new h,a,s){let i=await e.getAllUserPrograms(m(this,re,he).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}};re=new WeakSet,he=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 V=dr;function pt(t){return"data"in t&&!("errors"in t)}function ct(t){return"errors"in t&&Array.isArray(t.errors)&&"data"in t}function ut(t){return"errors"in t&&Array.isArray(t.errors)&&!("data"in t)}function A(t){if(ct(t))throw new Error("Expected data response but got service errors response: "+t.errors.map(r=>r.message).join(", "));if(ut(t))throw new Error("Expected data response but got input errors response: "+t.errors.map(r=>r.message).join(", "));if(!pt(t))throw new Error("Expected data response but got unknown response")}function Lr(t){if(!ne(t))throw new Error("Invalid program key");let r=atob(ze(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 Qt(t){if(!ee(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=at(e),e}async function pr(t){if(R(t))return t;if(R(`kaid_${t}`))return`kaid_${t}`;if(oe(t)){let s=t.match(ge);if(!s)throw new Error("Invalid user URL");if(t=s[1],R(t))return t}let e=await(await Te(t)).json();if(A(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 qr(t){if(!R(t)&&!D(t)&&!oe(t))return t;if(oe(t)){let a=t.match(ge);if(!a)throw new Error("Invalid user URL");if(t=a[1],!R(t)&&!D(t))return t}R(t)||(t=await pr(t));let e=await(await ve(t)).json();if(A(e),!e.data.user)throw new Error("User not found");return e.data.user.username}function be(t){if(typeof t=="number"){if(!ee(t))throw new Error("Invalid program ID");return t}else if(Sr(t)){let r=t.match(se)[1];if(!ee(r))throw new Error("Invalid program URL");return parseInt(r,10)}else if(ne(t)){if(t=Lr(t),!ee(t))throw new Error("Invalid program key");return t}else if(typeof t=="string"){if(!ee(t))throw new Error("Invalid program ID");return parseInt(t,10)}throw new Error("Invalid program identifier")}async function Or(t){if(E(t))return t;if(!K(t))throw new Error("Invalid encrypted message key");let e=await(await Fe(t)).json();if(A(e),!e.data.qaExpandKeyInfo)throw new Error("Message key not found");return e.data.qaExpandKeyInfo.unencryptedKey}var Mr=(s=>(s.ProcessingJS="pjs",s.HTML="webpage",s.SQL="ace_sql",s.Other="",s))(Mr||{}),j,le,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=be(e);return new Q({id:a,key:typeof e=="string"&&ne(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?V.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(se)?.[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&&Se.test(e.imagePath)?parseInt(e.imagePath.match(Se)[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 h){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 h,a){for await(let s of e.getProgramTipsAndThanks(m(this,j,le).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 h,a){let s=await e.getAllProgramTipsAndThanks(m(this,j,le).call(this),a);return this.copy({tipsAndThanks:s})}async*getQuestions(e=this.client??new h,a){for await(let s of e.getProgramQuestions(m(this,j,le).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 h,a){let s=await e.getAllProgramQuestions(m(this,j,le).call(this),a);return this.copy({questions:s})}async*getHelpRequests(e=this.client??new h,a){for await(let s of e.getProgramHelpRequests(m(this,j,le).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 h,a){let s=await e.getAllProgramHelpRequests(m(this,j,le).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,le=function(){if(this.id)return this.id;if(this.key)return this.key;throw new Error("Program has no identifier")},Q.Type=Mr;var C=Q;var Vr=["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"],Br=["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 $t(t){return Br[Vr.indexOf(t)]}function Gt(t){return Vr[Br.indexOf(t)]}function cr(t){return`https://www.khanacademy.org/images/avatars/svg/${t}.svg`}function ur(t){return`https://www.khanacademy.org/images/avatars/${t}.png`}function qe(t){return t.match(/^(?:https:\/\/www\.khanacademy\.org)?\/images\/avatars(?:\/svg)?\/(.*)\.(?:(?:svg)|(?:png))$/)?.[1]??null}function Ht(t){let r=qe(t);return r?ur(r):null}function jt(t){let r=qe(t);return r?cr(r):null}function mt(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 W=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&&V.fromSchema(r.author),program:(()=>{if(r.focus?.kind==="Scratchpad")return new C({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(Pr);return!e||e.length<1?void 0:new C({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 de=(a=>(a[a.TipsAndThanks="COM