UNPKG

@zennomi/mangadex-full-api

Version:

A MangaDex api based around the official API.

6 lines (5 loc) 33.6 kB
"use strict";var O=Object.defineProperty,ue=Object.defineProperties,le=Object.getOwnPropertyDescriptor,he=Object.getOwnPropertyDescriptors,me=Object.getOwnPropertyNames,ee=Object.getOwnPropertySymbols;var ae=Object.prototype.hasOwnProperty,de=Object.prototype.propertyIsEnumerable;var te=(n,s,e)=>s in n?O(n,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[s]=e,w=(n,s)=>{for(var e in s||(s={}))ae.call(s,e)&&te(n,e,s[e]);if(ee)for(var e of ee(s))de.call(s,e)&&te(n,e,s[e]);return n},R=(n,s)=>ue(n,he(s));var ge=(n,s)=>{for(var e in s)O(n,e,{get:s[e],enumerable:!0})},fe=(n,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let a of me(s))!ae.call(n,a)&&a!==e&&O(n,a,{get:()=>s[a],enumerable:!(t=le(s,a))||t.enumerable});return n};var ye=n=>fe(O({},"__esModule",{value:!0}),n);var r=(n,s,e)=>new Promise((t,a)=>{var i=c=>{try{o(e.next(c))}catch(l){a(l)}},p=c=>{try{o(e.throw(c))}catch(l){a(l)}},o=c=>c.done?t(c.value):Promise.resolve(c.value).then(i,p);o((e=e.apply(n,s)).next())});var De={};ge(De,{Author:()=>x,Chapter:()=>b,Cover:()=>v,Group:()=>C,LegacyAuthClient:()=>N,List:()=>M,Manga:()=>m,PersonalAuthClient:()=>k,Tag:()=>E,UploadSession:()=>B,User:()=>$,convertLegacyId:()=>be,getCurrentAuthClient:()=>Ce,login:()=>Pe,loginPersonal:()=>Me,logout:()=>ve,resolveArray:()=>Re,setGlobalLocale:()=>we,useDebugServer:()=>se});module.exports=ye(De);var Z=class{},g=Z;var I=class extends g{constructor(e){super();this.cached=!1;if(this.id=e.id,!(e.type in I.typeMap))throw`Unregistered relationship type: ${e.type}`;if(this.type=e.type,this.related=e.related,e.attributes)try{let t=I.typeMap[this.type],a={attributes:e.attributes,id:this.id,type:this.type,relationships:[]};this.cachedData=Reflect.construct(t,[a]),this.cached=!0}catch(t){}}resolve(){return r(this,null,function*(){return this.cached?this.cachedData:I.typeMap[this.type].get(this.id)})}static resolveAll(e){return r(this,null,function*(){if(e.length===0)return[];let t=I.typeMap[e[0].type];return t!==void 0&&t.getMultiple!==void 0?t.getMultiple(e.map(a=>a.id)):yield Promise.all(e.map(a=>a.resolve()))})}static convertType(e,t){return t.filter(a=>a.type===e).map(a=>new I(a))}static registerTypes(e,t){if(I.typeMapLocked)throw Error(`Cannot add types ${e} because the Relationship type map has been locked.`);e.forEach(a=>I.typeMap[a]=t)}static lockTypeMap(){I.typeMapLocked=!0}static getRegisteredTypes(){return Object.keys(I.typeMap)}},z=I;z.typeMap={},z.typeMapLocked=!1;var h=z;var V=class{constructor(s){for(let e in s)this[e]=s[e]}get localString(){if(V.globalLocale in this)return this[V.globalLocale];if("en"in this)return this.en;for(let s of Object.keys(this))if(typeof this[s]=="string")return this[s];return""}static setGlobalLocale(s){if(s.length<2||s.length>8)throw Error(`Locale "${s}" has an invalid length`);V.globalLocale=s}},H=V;H.globalLocale="en";var L=H;var A=class extends Error{constructor(s){if(typeof s!="string"){let e;"result"in s?e=s.errors:e=s,s=e.map((a,i,p)=>{let o="";return p.length>1&&(o+=`[${i} of ${p.length}] `),o+=`${a.title} (${a.status}, ${a.id}): ${a.detail}. `,o}).join(` `)}s.includes("36 characters")&&(s+=` It looks like MangaDex expected a UUID, but you provided a non-UUID string. If you are using Tags, please use Tag.getByName() instead of the literal name.`),super(s),Object.setPrototypeOf(this,A.prototype),this.name="APIResponseError"}};var T=class extends Error{constructor(s){super(s),Object.setPrototypeOf(this,T.prototype),this.name="AuthError"}};var F=class{};F.useDebugServerValue=!1;function se(n){F.useDebugServerValue=n}function Se(){return F.useDebugServerValue}function Q(n){F.activeClient=n}function re(){F.activeClient=void 0}function ie(){var n;return(n=F.activeClient)!=null?n:null}function u(t,a){return r(this,arguments,function*(n,s,e={}){let i=F.useDebugServerValue?"https://api.mangadex.dev":"https://api.mangadex.org/",p=oe(i,n,s);if(F.activeClient&&!e.noAuth){let d=yield F.activeClient.getSessionToken();e.headers===void 0&&(e.headers={}),e.headers.authorization=`Bearer ${d}`}let o=yield fetch(p,e),c=o.headers.get("content-type");if(!(c!=null&&c.toLowerCase().includes("json"))){let d=`${o.statusText} (${o.status}) Response was an unexpected content type: ${c!=null?c:"Unspecified Type"}.`;try{let y=yield o.text();y.length>128&&(y=y.slice(0,128)),d+=` Start of Body: ${y}`}catch(y){}throw new A(d)}let l=yield o.json();if("result"in l&&l.result!=="ok")throw new A(l);if(o.status>=400)throw new A(`${o.statusText} (${o.status})`);return l})}function S(n,s,e){return r(this,null,function*(){return(yield u(n,s,e)).data})}function f(i){return r(this,arguments,function*(n,s={},e,t=100,a=10){var D,q;let o=Math.min((D=s.limit)!=null?D:a,1e4),c=(q=s.offset)!=null?q:0;if(c>=1e4||o<=0)return[];c>1e4-Math.min(t,o)&&(o=1e4-c);let l=yield u(n,R(w({},s),{limit:Math.min(o,t)}),e);if(o<=t||l.total<=l.data.length+c)return l.data;o=Math.min(o,l.total);let d=[];for(let W=c+t;W<o;W+=t){let pe=Math.min(o-W,t);d.push(S(n,R(w({},s),{limit:pe,offset:W}),e))}let y=yield Promise.all(d);return l.data.concat(...y)})}function G(p,o){return r(this,arguments,function*(n,s,e={},t="ids",a=100,i){let c=s.map(D=>D instanceof g?D.id:D),l=[];for(let D=0;D<c.length;D+=a)l.push(S(n,R(w({},e),{[t]:c.slice(D,D+a),limit:a}),i));let y=(yield Promise.all(l)).flat();return y.sort((D,q)=>c.indexOf(D.id)-c.indexOf(q.id)),y})}function U(i,p,o){return r(this,arguments,function*(n,s,e,t="POST",a={}){let c=a.headers!==void 0?a.headers:{};return c["Content-Type"]="application/json",u(n,e,{body:JSON.stringify(s),method:t,headers:c})})}function P(i,p,o){return r(this,arguments,function*(n,s,e,t="POST",a={}){return(yield U(n,s,e,t,a)).data})}function ne(n,s,e){return r(this,null,function*(){let t=oe("https://api.mangadex.network",n,e),a=yield fetch(t,{body:JSON.stringify(s),method:"POST",headers:{"Content-Type":"application/json"}});if(!a.ok)throw new A(`${a.status} ${a.statusText}`)})}function J(i,p,o){return r(this,arguments,function*(n,s,e,t="POST",a={}){let c=new FormData,l=(d,y)=>{typeof y!="string"&&"data"in y&&"name"in y?c.append(d,y.data,y.name):c.append(d,y)};for(let[d,y]of Object.entries(s))y&&(Array.isArray(y)?y.forEach((D,q)=>l(d+q,D)):l(d,y));return yield u(n,e,R(w({},a),{method:t,body:c}))})}function oe(n,s,e){let t=s?new URL(s,n):new URL(n);if(!e)return t;for(let[a,i]of Object.entries(e))if(Array.isArray(i))for(let p of i)p instanceof g&&(p=p.id),t.searchParams.append(`${a}[]`,p.toString());else if(typeof i=="object")if(i instanceof g)t.searchParams.append(a,i.id.toString());else{let p=Object.entries(i);for(let[o,c]of p)t.searchParams.append(`${a}[${o}]`,c.toString())}else i!==void 0&&t.searchParams.append(a,i.toString());return t}function X(n){return r(this,null,function*(){try{let s;return n!==void 0&&(s={headers:{authorization:`Bearer ${n}`},noAuth:!0}),(yield u("/auth/check",void 0,s)).isAuthenticated}catch(s){if(s instanceof A)return!1;throw s}})}function j(n,s){return r(this,null,function*(){let e=new URLSearchParams;for(let[o,c]of Object.entries(s))e.append(o,c);let t=`https://auth.mangadex.${Se()?"dev":"org"}`,a=new URL(n,t),i=yield fetch(a,{body:e,method:"POST"});if(i.status>=400)throw new T(`${i.statusText} (${i.status})`);return yield i.json()})}var x=class extends g{constructor(e){super();this.id=e.id,this.name=e.attributes.name,this.imageUrl=e.attributes.imageUrl,this.biography=new L(e.attributes.biography),this.twitter=e.attributes.twitter,this.pixiv=e.attributes.pixiv,this.melonBook=e.attributes.melonBook,this.fanBox=e.attributes.fanBox,this.booth=e.attributes.booth,this.nicoVideo=e.attributes.nicoVideo,this.skeb=e.attributes.skeb,this.fantia=e.attributes.fantia,this.tumblr=e.attributes.tumblr,this.youtube=e.attributes.youtube,this.weibo=e.attributes.weibo,this.naver=e.attributes.naver,this.namicomi=e.attributes.namicomi,this.website=e.attributes.website,this.version=e.attributes.version,this.createdAt=new Date(e.attributes.createdAt),this.updatedAt=new Date(e.attributes.updatedAt),this.manga=h.convertType("manga",e.relationships)}static get(e,t){return r(this,null,function*(){return new x(yield S(`/author/${e}`,{includes:t}))})}static search(e){return r(this,null,function*(){return(yield f("/author",e)).map(a=>new x(a))})}static getByQuery(e){return r(this,null,function*(){var a;return(a=(yield this.search(e))[0])!=null?a:null})}static getMultiple(e){return r(this,null,function*(){return(yield G("/author",e)).map(a=>new x(a))})}static create(e){return r(this,null,function*(){return new x(yield P("/author",e))})}static delete(e){return r(this,null,function*(){yield u(`/author/${e}`,void 0,{method:"DELETE"})})}delete(){return r(this,null,function*(){yield x.delete(this.id)})}update(e){return r(this,null,function*(){return new x(yield P(`/author/${this.id}`,R(w({},e),{version:this.version+1}),void 0,"PUT"))})}};var v=class extends g{constructor(e){super();this.id=e.id,this.volume=e.attributes.volume,this.fileName=e.attributes.fileName,this.description=e.attributes.description,this.locale=e.attributes.locale,this.version=e.attributes.version,this.createdAt=new Date(e.attributes.createdAt),this.updatedAt=new Date(e.attributes.updatedAt),this.manga=h.convertType("manga",e.relationships).pop(),this.url=this.manga?`https://mangadex.org/covers/${this.manga.id}/${this.fileName}`:null,this.uploader=h.convertType("user",e.relationships).pop()}static get(e,t){return r(this,null,function*(){return e instanceof g&&(e=e.id),new v(yield S(`/cover/${e}`,{includes:t}))})}static search(e){return r(this,null,function*(){return(yield f("/cover",e)).map(a=>new v(a))})}static getByQuery(e){return r(this,null,function*(){var a;return(a=(yield this.search(e))[0])!=null?a:null})}static getMultiple(e){return r(this,null,function*(){return(yield G("/cover",e)).map(a=>new v(a))})}static getMangaCovers(e,t){return r(this,null,function*(){if(Array.isArray(e)||(e=[typeof e=="string"?e:e.id]),e.length===0)return[];let a=e.map(i=>typeof i=="string"?i:i.id);return v.search({manga:a,includes:t})})}static delete(e){return r(this,null,function*(){yield u(`/cover/${e}`,void 0,{method:"DELETE"})})}delete(){return r(this,null,function*(){yield v.delete(this.id)})}update(e){return r(this,null,function*(){return new v(yield P(`/cover/${this.id}`,R(w({},e),{version:this.version+1}),void 0,"PUT"))})}static create(e,t){return r(this,null,function*(){typeof e!="string"&&(e=e.id);let a=yield J(`/cover/${e}`,t);return new v(a.data)})}};var E=class extends g{constructor(e){super();this.id=e.id,this.name=new L(e.attributes.name),this.description=new L(e.attributes.description),this.group=e.attributes.group,this.version=e.attributes.version}get localName(){return this.name.localString}get localDescription(){return this.description.localString}static getAllTags(){return r(this,null,function*(){if(!E.allTagCache||E.allTagCache.length===0){let e=yield u("/manga/tag");E.allTagCache=e.data.map(t=>new E(t))}return E.allTagCache})}static getByName(e){return r(this,null,function*(){let t=yield this.getAllTags(),a=e.toLowerCase(),i=t.find(p=>Object.values(p.name).some(o=>o.toLowerCase()===a));if(!i)throw new Error(`No tag found with name ${e}`);return i})}static getByNames(e){return r(this,null,function*(){let t=yield this.getAllTags(),a=e.map(i=>i.toLowerCase());return t.filter(i=>Object.values(i.name).some(p=>a.includes(p.toLowerCase())))})}};var _=class{constructor(s){this.anilist=s!=null&&s.al?`https://anilist.co/manga/${s.al}`:void 0,this.animePlanet=s!=null&&s.ap?`https://www.anime-planet.com/manga/${s.ap}`:void 0,this.bookWalker=s!=null&&s.bw?`https://bookwalker.jp/${s.bw}`:void 0,this.mangaUpdates=s!=null&&s.mu?`https://www.mangaupdates.com/series.html?id=${s.mu}`:void 0,this.novelUpdates=s!=null&&s.nu?`https://www.novelupdates.com/series/${s.nu}`:void 0,this.myAnimeList=s!=null&&s.mal?`https://myanimelist.net/manga/${s.mal}`:void 0,(s==null?void 0:s.kt)!==void 0&&(isNaN(parseInt(s.kt))?this.kitsu=`https://kitsu.io/api/edge/manga?filter[slug]=${s.kt}`:this.kitsu=`https://kitsu.io/api/edge/manga/${s.kt}`),this.amazon=s==null?void 0:s.amz,this.eBookJapan=s==null?void 0:s.ebj,this.raw=s==null?void 0:s.raw,this.officialEnglishTranslation=s==null?void 0:s.engtl,this.cdJapan=s==null?void 0:s.cdj}},ce=_;var b=class extends g{constructor(e){super();this.id=e.id,this.title=e.attributes.title,this.volume=e.attributes.volume,this.chapter=e.attributes.chapter,this.pages=e.attributes.pages,this.translatedLanguage=e.attributes.translatedLanguage,this.uploader=h.convertType("user",e.relationships).pop(),this.externalUrl=e.attributes.externalUrl,this.version=e.attributes.version,this.createdAt=new Date(e.attributes.createdAt),this.publishAt=new Date(e.attributes.publishAt),this.updatedAt=new Date(e.attributes.updatedAt),this.readableAt=new Date(e.attributes.readableAt),this.isExternal=e.attributes.externalUrl!==null,this.manga=h.convertType("manga",e.relationships).pop(),this.groups=h.convertType("scanlation_group",e.relationships)}static get(e,t){return r(this,null,function*(){return new b(yield S(`/chapter/${e}`,{includes:t}))})}static getMultiple(e){return r(this,null,function*(){return(yield G("/chapter",e)).map(a=>new b(a))})}static search(e){return r(this,null,function*(){return(yield f("/chapter",e)).map(a=>new b(a))})}static getByQuery(e){return r(this,null,function*(){var a;return(a=(yield this.search(e))[0])!=null?a:null})}update(e){return r(this,null,function*(){return new b(yield P(`/chapter/${this.id}`,R(w({},e),{version:this.version+1}),void 0,"PUT"))})}static delete(e){return r(this,null,function*(){yield u(`/chapter/${e}`,void 0,{method:"DELETE"})})}delete(){return r(this,null,function*(){yield b.delete(this.id)})}getReadablePages(e=!1,t=!1){return r(this,null,function*(){var p,o;if(this.isExternal)throw new Error("Cannot get readable pages for an external chapter.");let a=yield u(`/at-home/server/${this.id}`,{forcePort443:t});return((o=e&&(p=a.chapter.dataSaver)!=null?p:a.chapter.data)!=null?o:[]).map(c=>`${a.baseUrl}/${e?"data-saver":"data"}/${a.chapter.hash}/${c}`)})}static reportPageURL(e){return r(this,null,function*(){yield ne("/report",e)})}static getStatistics(e){return r(this,null,function*(){return(yield u("/statistics/chapter",{chapter:e})).statistics})}getStatistics(){return r(this,null,function*(){return(yield b.getStatistics([this.id]))[this.id]})}};var m=class extends g{constructor(e){super();this.id=e.id,this.altTitles=e.attributes.altTitles.map(t=>new L(t)),this.artists=h.convertType("artist",e.relationships),this.authors=h.convertType("author",e.relationships),this.availableTranslatedLanguages=e.attributes.availableTranslatedLanguages,this.chapterNumbersResetOnNewVolume=e.attributes.chapterNumbersResetOnNewVolume,this.contentRating=e.attributes.contentRating,this.createdAt=new Date(e.attributes.createdAt),this.description=new L(e.attributes.description),this.isLocked=e.attributes.isLocked,this.lastChapter=e.attributes.lastChapter,this.lastVolume=e.attributes.lastVolume,this.latestUploadedChapter=new h({id:e.attributes.latestUploadedChapter,type:"chapter"}),this.links=new ce(e.attributes.links),this.mainCover=h.convertType("cover_art",e.relationships).pop(),this.publicationDemographic=e.attributes.publicationDemographic,this.relatedManga=m.getRelatedManga(e.relationships),this.state=e.attributes.state,this.status=e.attributes.status,this.tags=e.attributes.tags.map(t=>new E(t)),this.title=new L(e.attributes.title),this.updatedAt=new Date(e.attributes.updatedAt),this.version=e.attributes.version,this.year=e.attributes.year,this.originalLanguage=e.attributes.originalLanguage}static getRelatedManga(e){let t={monochrome:[],main_story:[],adapted_from:[],based_on:[],prequel:[],side_story:[],doujinshi:[],same_franchise:[],shared_universe:[],sequel:[],spin_off:[],alternate_story:[],alternate_version:[],preserialization:[],colored:[],serialization:[]};for(let a of e)a.type==="manga"&&t[a.related].push(new h(a));return t}get localTitle(){return this.title.localString}get localAltTitles(){return this.altTitles.map(e=>e.localString)}get localDescription(){return this.description.localString}static get(e,t){return r(this,null,function*(){return new m(yield S(`/manga/${e}`,{includes:t}))})}static search(e){return r(this,null,function*(){return(yield f("/manga",e)).map(a=>new m(a))})}static getMultiple(e,t){return r(this,null,function*(){return(yield G("/manga",e,t)).map(i=>new m(i))})}static getTotalSearchResults(e){return r(this,null,function*(){return(yield u("/manga",R(w({},e),{limit:1,offset:0}))).total})}static getFeed(e,t){return r(this,null,function*(){return(yield f(`/manga/${e}/feed`,t)).map(i=>new b(i))})}getFeed(e){return r(this,null,function*(){return m.getFeed(this.id,e)})}static updateReadChapters(e,t,a=!1){return r(this,null,function*(){var p,o,c,l;if(!t.read&&!t.unread)return[];let i={chapterIdsRead:(o=(p=t.read)==null?void 0:p.map(d=>typeof d=="string"?d:d.id))!=null?o:[],chapterIdsUnread:(l=(c=t.unread)==null?void 0:c.map(d=>typeof d=="string"?d:d.id))!=null?l:[]};yield U(`/manga/${e}/read`,i,{updateHistory:a})})}updateReadChapters(e,t=!1){return r(this,null,function*(){return m.updateReadChapters(this.id,e,t)})}static getReadChapters(e){return r(this,null,function*(){let t={};for(let p=0;p<e.length;p+=100){let o=yield S("/manga/read",{ids:e.slice(p,p+100),grouped:!0});if(Array.isArray(o))if(e.length===1)o={[typeof e[0]=="string"?e[0]:e[0].id]:o};else throw new A("MangaDex did not respond with a grouped body.");for(let[c,l]of Object.entries(o))c in t?t[c].push(...l):t[c]=l}let a=yield b.getMultiple(Object.values(t).flat()),i={};for(let p in t)i[p]=a.filter(o=>t[p].includes(o.id));return i})}getReadChapters(){return r(this,null,function*(){let e=yield S(`/manga/${this.id}/read`);return yield b.getMultiple(e)})}static getRandom(e){return r(this,null,function*(){let t=yield S("/manga/random",e);return new m(t)})}static getByQuery(e){return r(this,null,function*(){var a;return(a=(yield this.search(e))[0])!=null?a:null})}getCovers(){return r(this,null,function*(){return v.getMangaCovers(this.id)})}static getFollowedManga(){return r(this,arguments,function*(e={limit:1/0,offset:0}){return(yield f("/user/follows/manga",e)).map(a=>new m(a))})}static getUserRatings(e){return r(this,null,function*(){let t=yield u("/rating",{manga:e}),a={};for(let i of e)typeof i!="string"&&(i=i.id),i in t.ratings?a[i]={rating:t.ratings[i].rating,createdAt:new Date(t.ratings[i].createdAt)}:a[i]=null;return a})}getUserRating(){return r(this,null,function*(){var t,a;return(a=(t=(yield m.getUserRatings([this.id]))[this.id])==null?void 0:t.rating)!=null?a:null})}static giveRating(e,t){return r(this,null,function*(){if(t>10||t<1)throw new Error("Rating must be in the range of 1-10 (inclusive).");yield U(`/rating/${e}`,{rating:t})})}giveRating(e){return r(this,null,function*(){yield m.giveRating(this.id,e)})}static removeRating(e){return r(this,null,function*(){yield u(`/rating/${e}`,void 0,{method:"DELETE"})})}removeRating(){return r(this,null,function*(){yield m.removeRating(this.id)})}static getFollowedFeed(e){return r(this,null,function*(){return(yield f("/user/follows/manga/feed",e)).map(a=>new b(a))})}static convertLegacyId(e,t){return r(this,null,function*(){let a=yield P("/legacy/mapping",{type:e,ids:t});return Object.fromEntries(a.map(i=>[i.attributes.legacyId,i.attributes.newId]))})}static getAllReadingStatus(e){return r(this,null,function*(){return(yield u("/manga/status",{status:e})).statuses})}static getReadingStatus(e){return r(this,null,function*(){return(yield u(`/manga/${e}/status`)).status})}getReadingStatus(){return r(this,null,function*(){return yield m.getReadingStatus(this.id)})}static setReadingStatus(e,t){return r(this,null,function*(){yield U(`/manga/${e}/status`,{status:t})})}setReadingStatus(e){return r(this,null,function*(){yield m.setReadingStatus(this.id,e)})}static getRelations(e,t=!1){return r(this,null,function*(){let i=(yield S(`/manga/${e}/relation`,{includes:t?["manga"]:void 0})).flatMap(p=>p.relationships.map(o=>R(w({},o),{related:p.attributes.relation})));return m.getRelatedManga(i)})}getRelations(e=!1){return r(this,null,function*(){return yield m.getRelations(this.id,e)})}static addRelation(e,t,a){return r(this,null,function*(){yield P(`/manga/${e}/relation`,{targetManga:t,relation:a})})}addRelation(e,t){return r(this,null,function*(){yield m.addRelation(this.id,e,t)})}static removeRelation(e,t){return r(this,null,function*(){yield u(`/manga/${e}/relation/${t}`,void 0,{method:"DELETE"})})}removeRelation(e){return r(this,null,function*(){yield m.removeRelation(this.id,e)})}static getStatistics(e){return r(this,null,function*(){return(yield u("/statistics/manga",{manga:e})).statistics})}getStatistics(){return r(this,null,function*(){return(yield m.getStatistics([this.id]))[this.id]})}static getDraft(e,t){return r(this,null,function*(){return new m(yield S(`/manga/draft/${e}`,{includes:t}))})}static searchDrafts(e){return r(this,null,function*(){return(yield f("/manga/draft",e)).map(a=>new m(a))})}static commitDraft(e,t){return r(this,null,function*(){let a=yield P(`/manga/draft/${e}/commit`,t);return new m(a)})}static create(e){return r(this,null,function*(){return new m(yield P("/manga",e))})}static delete(e){return r(this,null,function*(){yield u(`/manga/${e}`,void 0,{method:"DELETE"})})}delete(){return r(this,null,function*(){yield m.delete(this.id)})}update(e){return r(this,null,function*(){return new m(yield P(`/author/${this.id}`,R(w({},e),{version:this.version+1}),void 0,"PUT"))})}static getAggregate(e,t,a){return r(this,null,function*(){return(yield u(`/manga/${e}/aggregate`,{groups:t,translatedLanguage:a})).volumes})}getAggregate(e,t){return r(this,null,function*(){return m.getAggregate(this.id,e,t)})}static changeFollowship(e,t=!0){return r(this,null,function*(){yield u(`/manga/${e}/follow`,void 0,{method:t?"POST":"DELETE"})})}changeFollowship(e=!0){return r(this,null,function*(){yield m.changeFollowship(this.id,e)})}};var $=class extends g{constructor(e){super();this.id=e.id,this.username=e.attributes.username,this.roles=e.attributes.roles,this.version=e.attributes.version,this.groups=h.convertType("scanlation_group",e.relationships)}static get(e){return r(this,null,function*(){return new $(yield S(`/user/${e}`))})}static search(e){return r(this,null,function*(){return(yield f("/user",e)).map(a=>new $(a))})}static getMultiple(e){return r(this,null,function*(){return(yield G("/user",e)).map(a=>new $(a))})}static getByQuery(e){return r(this,null,function*(){var a;return(a=(yield this.search(e))[0])!=null?a:null})}static getLoggedInUser(){return r(this,null,function*(){return new $(yield S("/user/me"))})}static getFollowedUsers(){return r(this,arguments,function*(e={limit:1/0,offset:0}){return(yield f("/user/follows/user",e)).map(a=>new $(a))})}};var C=class extends g{constructor(e){var t;super();this.id=e.id,this.name=e.attributes.name,this.altNames=e.attributes.altNames.map(a=>new L(a)),this.website=e.attributes.website,this.ircServer=e.attributes.ircServer,this.ircChannel=e.attributes.ircChannel,this.discord=e.attributes.discord,this.contactEmail=e.attributes.contactEmail,this.description=e.attributes.description,this.twitter=e.attributes.twitter,this.mangaUpdates=e.attributes.mangaUpdates,this.focusedLanguage=e.attributes.focusedLanguage,this.locked=e.attributes.locked,this.official=e.attributes.official,this.inactive=e.attributes.inactive,this.publishDelay=e.attributes.publishDelay,this.version=e.attributes.version,this.createdAt=new Date(e.attributes.createdAt),this.updatedAt=new Date(e.attributes.updatedAt),this.leader=(t=h.convertType("leader",e.relationships).pop())!=null?t:null,this.members=h.convertType("member",e.relationships),this.exLicensed=e.attributes.exLicensed,this.verified=e.attributes.verified}static get(e){return r(this,null,function*(){return new C(yield S(`/group/${e}`))})}static search(e){return r(this,null,function*(){return(yield f("/group",e)).map(a=>new C(a))})}static getMultiple(e){return r(this,null,function*(){return(yield G("/group",e)).map(a=>new C(a))})}static getByQuery(e){return r(this,null,function*(){var a;return(a=(yield this.search(e))[0])!=null?a:null})}static create(e){return r(this,null,function*(){return new C(yield P("/group",e))})}static delete(e){return r(this,null,function*(){yield u(`/group/${e}`,void 0,{method:"DELETE"})})}delete(){return r(this,null,function*(){yield C.delete(this.id)})}update(e){return r(this,null,function*(){return new C(yield P(`/group/${this.id}`,R(w({},e),{version:this.version+1}),void 0,"PUT"))})}static changeFollowship(e,t=!0){return r(this,null,function*(){yield u(`/group/${e}/follow`,void 0,{method:t?"POST":"DELETE"})})}changeFollowship(e=!0){return r(this,null,function*(){yield C.changeFollowship(this.id,e)})}static getStatistics(e){return r(this,null,function*(){return(yield u("/statistics/group",{group:e})).statistics})}getStatistics(){return r(this,null,function*(){return(yield C.getStatistics([this.id]))[this.id]})}static getFollowedGroups(){return r(this,arguments,function*(e={limit:1/0,offset:0}){return(yield f("/user/follows/group",e)).map(a=>new C(a))})}};var B=class extends g{constructor(e){super();this.updateData(e)}updateData(e){"data"in e&&(e=e.data),this.id=e.id,this.isCommitted=e.attributes.isCommitted,this.isProcessed=e.attributes.isProcessed,this.isDeleted=e.attributes.isDeleted,this.version=e.attributes.version,this.createdAt=new Date(e.attributes.createdAt),this.updatedAt=new Date(e.attributes.updatedAt),this.uploader=h.convertType("user",e.relationships).pop(),this.manga=h.convertType("manga",e.relationships).pop(),this.groups=h.convertType("scanlation_group",e.relationships),this.pages=e.relationships.filter(t=>t.type==="upload_session_file").map(t=>{if(!t.attributes)throw new Error("MangaDex did not return session file attributes in a relationship. Did you forget a reference expansion (ie includes[])?");return new K({id:t.id,attributes:t.attributes,type:"upload_session_file"})}),this.pages.sort((t,a)=>t.num-a.num)}static begin(i){return r(this,arguments,function*(e,t=[],a=!1){return a&&(yield B.cancelCurrentSession()),new B(yield U("/upload/begin",{manga:typeof e=="string"?e:e.id,groups:t.map(p=>typeof p=="string"?p:p.id)},{includes:["upload_session_file"]}))})}static beginChapterEdit(e,t=!1){return r(this,null,function*(){return t&&(yield B.cancelCurrentSession()),new B(yield U(`/upload/begin/${e.id}`,{version:e.version},{includes:["upload_session_file"]}))})}static getCurrentSession(){return r(this,null,function*(){return new B(yield u("/upload",{includes:["upload_session_file"]}))})}static cancelCurrentSession(){return r(this,null,function*(){let e;try{e=yield B.getCurrentSession()}catch(t){}e&&(yield e.close())})}close(){return r(this,null,function*(){yield u(`/upload/${this.id}`,void 0,{method:"DELETE"}),this.isDeleted=!0})}commit(e,t){return r(this,null,function*(){t?t=t.map(a=>typeof a=="string"?a:a.id):t=this.pages.map(a=>a.id),this.updateData(yield U(`/upload/${this.id}/commit`,{chapterDraft:e,pageOrder:t},{includes:["upload_session_file"]}))})}uploadPages(e){return r(this,null,function*(){let t=Math.max(...this.pages.map(l=>l.num),0),a=e.map((l,d)=>({data:l,name:(d+t).toString()})),i=[];for(;a.length>0;)i.push(J(`/upload/${this.id}`,{files:a.splice(0,10)}));let p=yield Promise.all(i),o=p.flatMap(l=>{var d;return(d=l.errors)!=null?d:[]});if(o.length>0)throw new A(o);let c=p.flatMap(l=>{var d;return(d=l.data)!=null?d:[]}).map(l=>new K(l));c.sort((l,d)=>l.num-d.num),this.pages.push(...c)})}deletePages(e){return r(this,null,function*(){let t=e.map(a=>typeof a=="string"?a:a.id);yield U(`/upload/${this.id}/batch`,t,void 0,"DELETE"),this.pages=this.pages.filter(a=>!t.includes(a.id))})}},K=class extends g{constructor(e){super();this.id=e.id,this.originalFileName=e.attributes.originalFileName,this.fileHash=e.attributes.fileHash,this.fileSize=e.attributes.fileSize,this.mimeType=e.attributes.mimeType,this.source=e.attributes.source,this.version=e.attributes.version,this.num=parseInt(this.originalFileName),isNaN(this.num)&&(this.num=parseInt(this.fileHash,16)),isNaN(this.num)&&(this.num=1e3)}};var k=class{constructor(s){this.data=s}getSessionToken(){return r(this,null,function*(){if(Date.now()>this.data.refreshExpiration)throw new T("Refresh token has expired. Please login again.");if(Date.now()>this.data.accessExpiration&&(yield this.refreshTokens(),!(yield X(this.data.accessToken))))throw new T("Failed to validate auth token. Please login again.");return this.data.accessToken})}refreshTokens(){return r(this,null,function*(){let s=yield j("/realms/mangadex/protocol/openid-connect/token",{grant_type:"refresh_token",refresh_token:this.data.refreshToken,client_id:this.data.clientId,client_secret:this.data.clientSecret});this.data.accessToken=s.access_token,this.data.accessExpiration=Y(s.expires_in),this.data.refreshToken=s.refresh_token,this.data.refreshExpiration=Y(s.refresh_expires_in)})}static login(s,e=!0){return r(this,null,function*(){let t=yield j("/realms/mangadex/protocol/openid-connect/token",{grant_type:"password",username:s.username,password:s.password,client_id:s.clientId,client_secret:s.clientSecret}),a=new k(R(w({},s),{accessToken:t.access_token,accessExpiration:Y(t.expires_in),refreshToken:t.refresh_token,refreshExpiration:Y(t.refresh_expires_in)}));return e&&Q(a),a})}};function Y(n){return n*1e3+Date.now()-5e3}var N=class{constructor(s){this.data=s}getSessionToken(){return r(this,null,function*(){if(Date.now()-this.data.timestamp>=894e3&&(yield this.refreshTokens(),!(yield this.checkSessionToken())))throw new T("Failed to validate auth token. Please login again.");return this.data.session})}setActive(){Q(this)}static login(s,e){return r(this,null,function*(){let t=yield U("/auth/login",{username:s,password:e}),a=t.token.session,i=t.token.refresh;if(!a||!i)throw new T("MangaDex did not return auth tokens.");let p=new N({session:a,refresh:i,timestamp:Date.now()});return p.setActive(),p})}refreshTokens(){return r(this,null,function*(){let s=yield U("/auth/refresh",{token:this.data.refresh},void 0,"POST",{noAuth:!0});if(!s.token)throw new T(`Failed to refresh auth tokens, MangaDex did not return any. ${s.message}`);let e=s.token.session,t=s.token.refresh;if(!e||!t)throw new T(`MangaDex did not return auth tokens. ${s.message}`);this.data={session:e,refresh:t,timestamp:Date.now()}})}checkSessionToken(){return X(this.data.session)}};var M=class extends g{constructor(e){super();this.id=e.id,this.name=e.attributes.name,this.visibility=e.attributes.visibility,this.version=e.attributes.version,this.creator=h.convertType("user",e.relationships).pop(),this.manga=h.convertType("manga",e.relationships)}static get(e){return r(this,null,function*(){return new M(yield S(`/list/${e}`))})}static create(e){return r(this,null,function*(){return new M(yield P("/list",e))})}static delete(e){return r(this,null,function*(){yield u(`/list/${e}`,void 0,{method:"DELETE"})})}delete(){return r(this,null,function*(){yield M.delete(this.id)})}update(e){return r(this,null,function*(){var t;return new M(yield P(`/list/${this.id}`,R(w({},e),{name:(t=e.name)!=null?t:this.name,version:this.version+1}),void 0,"PUT"))})}static follow(e){return r(this,null,function*(){yield u(`/list/${e}/follow`,void 0,{method:"POST"})})}follow(){return r(this,null,function*(){yield M.follow(this.id)})}static unfollow(e){return r(this,null,function*(){yield u(`/list/${e}/follow`,void 0,{method:"DELETE"})})}unfollow(){return r(this,null,function*(){yield M.unfollow(this.id)})}static addManga(e,t){return r(this,null,function*(){typeof t!="string"&&(t=t.id),yield u(`/manga/${t}/list/${e}`,void 0,{method:"POST"})})}addManga(e){return r(this,null,function*(){yield M.addManga(this.id,e)})}static removeManga(e,t){return r(this,null,function*(){typeof t!="string"&&(t=t.id),yield u(`/manga/${t}/list/${e}`,void 0,{method:"DELETE"})})}removeManga(e){return r(this,null,function*(){yield M.removeManga(this.id,e)})}static getLoggedInUserLists(e=1/0,t=0){return r(this,null,function*(){return(yield f("/user/list",{limit:e,offset:t})).map(i=>new M(i))})}static getUserLists(e,t=1/0,a=0){return r(this,null,function*(){return typeof e!="string"&&(e=e.id),(yield f(`/user/${e}/list`,{limit:t,offset:a})).map(p=>new M(p))})}static getFeed(e,t){return r(this,null,function*(){return(yield f(`/list/${e}/feed`,t)).map(i=>new b(i))})}getFeed(e){return r(this,null,function*(){return yield M.getFeed(this.id,e)})}static getFollowedLists(e=1/0,t=0){return r(this,null,function*(){return(yield f("/user/follows/list",{limit:e,offset:t})).map(i=>new M(i))})}changeVisibility(e){return r(this,null,function*(){return yield this.update({visibility:e})})}rename(e){return r(this,null,function*(){return yield this.update({name:e})})}updateMangaList(e){return r(this,null,function*(){return e=e.map(t=>typeof t=="string"?t:t.id),yield this.update({manga:e})})}};h.getRegisteredTypes().length===0&&(h.registerTypes(["manga"],m),h.registerTypes(["author","artist"],x),h.registerTypes(["cover_art"],v),h.registerTypes(["chapter"],b),h.registerTypes(["user","member","leader"],$),h.registerTypes(["scanlation_group"],C),h.lockTypeMap());var we=L.setGlobalLocale,Re=h.resolveAll,be=m.convertLegacyId,Pe=N.login,Me=k.login,ve=re,Ce=ie;0&&(module.exports={Author,Chapter,Cover,Group,LegacyAuthClient,List,Manga,PersonalAuthClient,Tag,UploadSession,User,convertLegacyId,getCurrentAuthClient,login,loginPersonal,logout,resolveArray,setGlobalLocale,useDebugServer}); //# sourceMappingURL=index.js.map