New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

threads-api

Package Overview
Dependencies
Maintainers
1
Versions
34
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

threads-api - npm Package Compare versions

Comparing version 1.5.3 to 1.5.4

build/error.d.ts

1

build/threads-api.d.ts
/// <reference types="node" />
import { AxiosRequestConfig } from 'axios';
import 'dotenv/config';
import { REPLY_CONTROL_OPTIONS } from './constants';

@@ -5,0 +4,0 @@ import { AndroidDevice, Extensions, Thread, ThreadsUser } from './threads-types';

@@ -1,1 +0,1 @@

"use strict";!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(exports,{DEFAULT_DEVICE:function(){return h},ThreadsAPI:function(){return p}});var e=require("axios"),t=require("crypto");require("dotenv/config");var r=require("mrmime"),n=require("uuid"),s=require("./constants"),a=require("./dynamic-data");function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function i(e,t,r,n,s,a,o){try{var i=e[a](o),u=i.value}catch(e){r(e);return}i.done?t(u):Promise.resolve(u).then(n,s)}function u(e){return function(){var t=this,r=arguments;return new Promise(function(n,s){var a=e.apply(t,r);function o(e){i(a,n,s,o,u,"next",e)}function u(e){i(a,n,s,o,u,"throw",e)}o(void 0)})}}function l(){return(l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function c(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return o(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if("Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r)return Array.from(r);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return o(e,t)}}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function d(e,t){var r,n,s,a,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(a){return function(i){return function(a){if(r)throw TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(s=2&a[0]?n.return:a[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,a[1])).done)return s;switch(n=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(s=(s=o.trys).length>0&&s[s.length-1])&&(6===a[0]||2===a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]<s[3])){o.label=a[1];break}if(6===a[0]&&o.label<s[1]){o.label=s[1],s=a;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(a);break}s[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],n=0}finally{r=s=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,i])}}}var h={manufacturer:"OnePlus",model:"ONEPLUS+A3010",os_version:25,os_release:"7.1.1"},p=function(){"use strict";function o(o){var i,p,f,g,v=this;this.verbose=!1,this.token=void 0,this.fbLSDToken=s.DEFAULT_LSD_TOKEN,this.noUpdateToken=!1,this.noUpdateLSD=!1,this.device=h,this.userID=void 0,this.locale=void 0,this.maxRetries=1;var _=this;this.syncLoginExperiments=u(function(){var t,r,a;return d(this,function(o){switch(o.label){case 0:r={id:t=(0,n.v4)(),experiments:s.LOGIN_EXPERIMENTS},o.label=1;case 1:return o.trys.push([1,3,,4]),[4,e.default.post(""+s.BASE_API_URL+"/api/v1/qe/sync/",_.sign(r),{httpAgent:_.httpAgent,httpsAgent:_.httpsAgent,headers:l({},_._getAppHeaders(),{Authorization:void 0,"Sec-Fetch-Site":"same-origin","X-DEVICE-ID":t})})];case 2:return[2,o.sent()];case 3:throw a=o.sent(),_.verbose&&console.log("[SYNC LOGIN EXPERIMENT FAILED]",a.response.data),Error("Sync login experiment failed");case 4:return[2]}})});var b=this;this.encryptPassword=u(function(e){var r,n,s,a,o,i,u,l,c,h,p;return d(this,function(d){switch(d.label){case 0:return r=t.randomBytes(32),n=t.randomBytes(12),[4,b.syncLoginExperiments()];case 1:return s=d.sent().headers,b.verbose&&console.log("[SYNC LOGIN EXPERIMENT HEADERS]",JSON.stringify(s)),a=s["ig-set-password-encryption-key-id"],o=s["ig-set-password-encryption-pub-key"],i=t.publicEncrypt({key:Buffer.from(o||"","base64").toString(),padding:t.constants.RSA_PKCS1_PADDING},r),u=t.createCipheriv("aes-256-gcm",r,n),l=Math.floor(Date.now()/1e3).toString(),u.setAAD(Buffer.from(l)),c=Buffer.concat([u.update(e,"utf8"),u.final()]),(h=Buffer.alloc(2,0)).writeInt16LE(i.byteLength,0),p=u.getAuthTag(),[2,{time:l,password:Buffer.concat([Buffer.from([1,a||0]),n,h,i,p,c]).toString("base64")}]}})});var m=this;this.login=u(function(){var t,r,n,a;return d(this,function(o){switch(o.label){case 0:t=function(){var e;return d(this,function(t){switch(t.label){case 0:return t.trys.push([0,1,,3]),[2,{v:n()}];case 1:return t.sent(),m.verbose&&console.error("[LOGIN] Failed to login, retrying... ("+(r+1)+"/"+m.maxRetries+")"),e=1e3*Math.pow(2,r),[4,new Promise(function(t){return setTimeout(t,e)})];case 2:return t.sent(),r++,[3,3];case 3:return[2]}})},r=0,n=u(function(){var t,r,n,a,o,i,u,l;return d(this,function(c){switch(c.label){case 0:return m.verbose&&console.log("[LOGIN] Logging in..."),[4,m.encryptPassword(m.password)];case 1:return r=encodeURIComponent(JSON.stringify({client_input_params:{password:"#PWD_INSTAGRAM:4:"+(t=c.sent()).time+":"+t.password,contact_point:m.username,device_id:m.deviceID},server_params:{credential_type:"password",device_id:m.deviceID}})),n=encodeURIComponent(JSON.stringify({bloks_version:s.BLOKS_VERSION,styles_id:"instagram"})),a={httpAgent:m.httpAgent,httpsAgent:m.httpsAgent,method:"POST",headers:m._getAppHeaders(),responseType:"text",data:"params="+r+"&bk_client_context="+n+"&bloks_versioning_id="+s.BLOKS_VERSION},[4,(0,e.default)(""+s.BASE_API_URL+"/api/v1/bloks/apps/com.bloks.www.bloks.caa.login.async.send_login_request/",a)];case 2:o=JSON.stringify((o=c.sent().data).replaceAll("\\","")),m.verbose&&console.log("[LOGIN] Cleaned output",o);try{return u=o.split("Bearer IGT:2:")[1].split('"')[0].replaceAll("\\",""),l=null==(i=o.match(/pk_id(.{18})/))?void 0:i[1].replaceAll(/[\\":]/g,""),m.noUpdateToken||(m.verbose&&console.debug("[token] UPDATED",u),m.token=u),m.userID=l,m.verbose&&console.debug("[userID] UPDATED",m.userID),[2,{token:u,userID:l}]}catch(e){throw m.verbose&&console.error("[LOGIN] Failed to login",e),Error("Login Failed")}return[2]}})}),o.label=1;case 1:if(!(r<m.maxRetries))return[3,3];return[5,function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(t())];case 2:var i;if("object"==((i=a=o.sent())&&"undefined"!=typeof Symbol&&i.constructor===Symbol?"symbol":typeof i))return[2,a.v];return[3,1];case 3:throw Error("[LOGIN] Failed to login after "+m.maxRetries+" retries")}})}),this._getUnAuthenticatedHeaders=function(){return{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.199 Safari/537.36","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}},this._getDefaultUserDataHeaders=function(e){return l({},v._getUnAuthenticatedHeaders(),{Host:"www.threads.net",Accept:"*/*","Accept-Language":v.locale,"cache-control":"no-cache",Origin:"https://www.threads.net",Pragma:"no-cache","Sec-Fetch-Site":"same-origin","X-Asbd-id":"129477","X-FB-Friendly-Name":"BarcelonaProfileRootQuery","X-FB-Lsd":v.fbLSDToken,"X-Ig-App-Id":"238260118697367"},e?{Referer:"https://www.threads.net/@"+e}:void 0)},this._getAppHeaders=function(){return l({"User-Agent":"Barcelona "+a.LATEST_ANDROID_APP_VERSION+" Android","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},v.token&&{Authorization:"Bearer IGT:2:"+v.token})},this._getInstaHeaders=function(){return l({},v._getAppHeaders(),{"X-Bloks-Is-Layout-Rtl":"false","X-Bloks-Version-Id":s.BLOKS_VERSION,"X-Ig-Android-Id":v.deviceID,"X-Ig-App-Id":s.IG_APP_ID,"Accept-Language":v.locale||"en-US"},v.userID&&{"Ig-U-Ds-User-Id":v.userID,"Ig-Intended-User-Id":v.userID},v.locale&&{"X-Ig-App-Locale":v.locale.replace("-","_"),"X-Ig-Device-Locale":v.locale.replace("-","_"),"X-Ig-Mapped-Locale":v.locale.replace("-","_")})},this._getDefaultHeaders=function(e){return l({},v._getAppHeaders(),{authority:"www.threads.net",accept:"*/*","accept-language":v.locale,"cache-control":"no-cache",origin:"https://www.threads.net",pragma:"no-cache","Sec-Fetch-Site":"same-origin","x-asbd-id":"129477","x-fb-lsd":v.fbLSDToken,"x-ig-app-id":"238260118697367"},e?{referer:"https://www.threads.net/@"+e}:void 0)};var I=this;this._getCleanedProfileHTML=u(function(t,r,n){return d(this,function(s){switch(s.label){case 0:return[4,e.default.get(""+t+r,l({},n,{httpAgent:I.httpAgent,httpsAgent:I.httpsAgent,headers:l({},I._getDefaultHeaders(r),{accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7","accept-language":"ko,en;q=0.9,ko-KR;q=0.8,ja;q=0.7",Authorization:void 0,referer:"https://www.instagram.com/","sec-fetch-dest":"document","sec-fetch-mode":"navigate","sec-fetch-site":"cross-site","sec-fetch-user":"?1","upgrade-insecure-requests":"1","x-asbd-id":void 0,"x-fb-lsd":void 0,"x-ig-app-id":void 0})}))];case 1:return[2,(0,s.sent().data).replace(/\s/g,"").replace(/\n/g,"")]}})});var D=this;this.getUserIDfromUsernameWithInstagram=u(function(e,t){var r,n,s,a,o;return d(this,function(i){switch(i.label){case 0:return[4,D._getCleanedProfileHTML("https://www.instagram.com/",e,t)];case 1:return a=null==(r=(s=i.sent()).match(/"user_id":"(\d+)",/))?void 0:r[1],o=null==(n=s.match(/"LSD",\[\],{"token":"(\w+)"},\d+\]/))?void 0:n[1],!D.noUpdateLSD&&o&&(D.fbLSDToken=o,D.verbose&&console.debug("[fbLSDToken] UPDATED",D.fbLSDToken)),[2,a]}})});var A=this;this.getUserIDfromUsername=u(function(e,t){var r,n,s,a,o;return d(this,function(i){switch(i.label){case 0:return[4,A._getCleanedProfileHTML("https://www.threads.net/@",e,t)];case 1:if(a=null==(r=(s=i.sent()).match(/"user_id":"(\d+)"/))?void 0:r[1],o=null==(n=s.match(/"LSD",\[\],{"token":"(\w+)"},\d+\]/))?void 0:n[1],!a)return[2,A.getUserIDfromUsernameWithInstagram(e,t)];return!A.noUpdateLSD&&o&&(A.fbLSDToken=o,A.verbose&&console.debug("[fbLSDToken] UPDATED",A.fbLSDToken)),[2,a]}})});var w=this;this.getCurrentUserID=u(function(e){var t;return d(this,function(r){switch(r.label){case 0:if(w.userID)return w.verbose&&console.debug("[userID] USING",w.userID),[2,w.userID];if(!w.username)throw Error("username is not defined");r.label=1;case 1:return r.trys.push([1,3,,5]),[4,w.getUserIDfromUsername(w.username,e)];case 2:return w.userID=r.sent(),w.verbose&&console.debug("[userID] UPDATED",w.userID),[2,w.userID];case 3:return t=r.sent(),w.verbose&&console.error("[userID] Failed to fetch userID, Fallbacking to login",t),[4,w.login()];case 4:return[2,r.sent().userID];case 5:return[2]}})}),this._requestQuery=function(t,r,n){return Object.keys(r).forEach(function(e){return void 0===r[e]&&delete r[e]}),e.default.post(t,new URLSearchParams(r),l({httpAgent:v.httpAgent,httpsAgent:v.httpsAgent,headers:v._getDefaultHeaders()},n))},this._requestUserDataQuery=function(t,r,n){return Object.keys(r).forEach(function(e){return void 0===r[e]&&delete r[e]}),e.default.post(t,new URLSearchParams(r),l({httpAgent:v.httpAgent,httpsAgent:v.httpsAgent,headers:v._getDefaultUserDataHeaders()},n))},this._destructureFromUserIDQuerier=function(e){var t,r;return"string"==typeof e[0]&&"string"==typeof e[1]?(t=e[1],r=e[2]):(t=e[0],r=e[1]),{userID:t,options:r}};var S=this;this.getUserProfile=u(function(){var e,t,r,n,s,a,o,i=arguments;return d(this,function(u){switch(u.label){case 0:for(t=Array(e=i.length),r=0;r<e;r++)t[r]=i[r];return s=(n=S._destructureFromUserIDQuerier(t)).userID,a=n.options,S.verbose&&console.debug("[fbLSDToken] USING",S.fbLSDToken),[4,S._requestUserDataQuery("https://www.threads.net/api/graphql",{lsd:S.fbLSDToken,variables:JSON.stringify({userID:s}),doc_id:"23996318473300828"},a)];case 1:return console.log((o=u.sent()).data),[2,o.data.data.userData.user]}})});var y=this;this.getUserProfileThreads=u(function(){var e,t,r,n,s,a,o,i,u=arguments;return d(this,function(l){switch(l.label){case 0:for(t=Array(e=u.length),r=0;r<e;r++)t[r]=u[r];return o=(a=y._destructureFromUserIDQuerier(t)).userID,i=a.options,y.verbose&&console.debug("[fbLSDToken] USING",y.fbLSDToken),[4,y._requestUserDataQuery("https://www.threads.net/api/graphql",{lsd:y.fbLSDToken,variables:JSON.stringify({userID:o}),doc_id:"6232751443445612"},i)];case 1:return[2,(null==(s=l.sent().data.data)?void 0:null==(n=s.mediaData)?void 0:n.threads)||[]]}})});var L=this;this.getUserProfileThreadsLoggedIn=u(function(t,r,n){var a,o,i,u;return d(this,function(c){switch(c.label){case 0:if(void 0===r&&(r=""),void 0===n&&(n={}),L.token)return[3,2];return[4,L.getToken()];case 1:c.sent(),c.label=2;case 2:if(!L.token)throw Error("Token not found");o=void 0,c.label=3;case 3:return c.trys.push([3,5,,6]),[4,e.default.get(s.BASE_API_URL+"/api/v1/text_feed/"+t+"/profile/"+(r&&"?max_id="+r),l({},n,{headers:l({},L._getInstaHeaders(),null==(i=n)?void 0:i.headers)}))];case 4:return o=c.sent().data,[3,6];case 5:return o=null==(u=c.sent().response)?void 0:u.data,[3,6];case 6:if((null==(a=o)?void 0:a.status)!=="ok")throw L.verbose&&console.log("[USER FEED] Failed to fetch",o),Error("Failed to fetch user feed: "+JSON.stringify(o));return[2,o]}})}),this._getDefaultRepliesHeaders=function(e){return l({},v._getUnAuthenticatedHeaders(),{Host:"www.threads.net",Accept:"*/*","Accept-Language":v.locale,"cache-control":"no-cache",Origin:"https://www.threads.net",Pragma:"no-cache","Sec-Fetch-Site":"same-origin","X-Asbd-id":"129477","X-FB-Friendly-Name":"BarcelonaProfileProfileRepliesTabQuery","X-FB-Lsd":v.fbLSDToken,"X-Ig-App-Id":"238260118697367"},e?{Referer:"https://www.threads.net/@"+e+"/replies"}:void 0)},this._requestRepliesQuery=function(t,r,n){return Object.keys(r).forEach(function(e){return void 0===r[e]&&delete r[e]}),e.default.post(t,new URLSearchParams(r),l({httpAgent:v.httpAgent,httpsAgent:v.httpsAgent,headers:v._getDefaultRepliesHeaders()},n))};var U=this;this.getUserProfileReplies=u(function(){var e,t,r,n,s,a,o,i=arguments;return d(this,function(u){switch(u.label){case 0:for(t=Array(e=i.length),r=0;r<e;r++)t[r]=i[r];return a=(s=U._destructureFromUserIDQuerier(t)).userID,o=s.options,U.verbose&&console.debug("[fbLSDToken] USING",U.fbLSDToken),[4,U._requestRepliesQuery("https://www.threads.net/api/graphql",{lsd:U.fbLSDToken,variables:JSON.stringify({userID:a}),doc_id:"6684830921547925"},o)];case 1:return[2,(null==(n=u.sent().data.data.mediaData)?void 0:n.threads)||[]]}})});var k=this;this.getUserProfileRepliesLoggedIn=u(function(t,r,n){var s,a,o,i;return d(this,function(u){switch(u.label){case 0:if(void 0===r&&(r=""),void 0===n&&(n={}),k.token)return[3,2];return[4,k.getToken()];case 1:u.sent(),u.label=2;case 2:if(!k.token)throw Error("Token not found");a=void 0,u.label=3;case 3:return u.trys.push([3,5,,6]),[4,e.default.get("https://i.instagram.com/api/v1/text_feed/"+t+"/profile/replies/"+(r&&"?max_id="+r),l({},n,{headers:l({},k._getAppHeaders(),null==(o=n)?void 0:o.headers)}))];case 4:return a=u.sent().data,[3,6];case 5:return a=null==(i=u.sent().response)?void 0:i.data,[3,6];case 6:if((null==(s=a)?void 0:s.status)!=="ok")throw k.verbose&&console.log("[USER FEED] Failed to fetch",a),Error("Failed to fetch user feed: "+JSON.stringify(a));return[2,a]}})});var E=this;this.getUserFollowers=u(function(t,r,n){var a,o,i,u,c,h,p,f;return d(this,function(d){switch(d.label){case 0:if(o=(a=void 0===r?{}:r).maxID,i=a.query,E.token)return[3,2];return[4,E.getToken()];case 1:d.sent(),d.label=2;case 2:if(!E.token)throw Error("Token not found");c=void 0,h=new URLSearchParams(s.BASE_FOLLOW_PARAMS),o&&h.append("max_id",o),i&&h.append("query",i),d.label=3;case 3:return d.trys.push([3,5,,6]),[4,e.default.get("https://i.instagram.com/api/v1/friendships/"+t+"/followers/?"+h.toString(),l({},n,{headers:l({},E._getInstaHeaders(),{"X-Ig-Nav-Chain":s.FOLLOW_NAV_CHAIN},null==(p=n)?void 0:p.headers)}))];case 4:return c=d.sent().data,[3,6];case 5:return c=null==(f=d.sent().response)?void 0:f.data,[3,6];case 6:if((null==(u=c)?void 0:u.status)!=="ok")throw E.verbose&&console.log("[USER FOLLOWERS] Failed to fetch",c),Error("Failed to fetch user followers: "+JSON.stringify(c));return[2,c]}})});var T=this;this.getUserFollowings=u(function(t,r,n){var a,o,i,u,c,h,p,f;return d(this,function(d){switch(d.label){case 0:if(o=(a=void 0===r?{}:r).maxID,i=a.query,T.token)return[3,2];return[4,T.getToken()];case 1:d.sent(),d.label=2;case 2:if(!T.token)throw Error("Token not found");c=void 0,h=new URLSearchParams(s.BASE_FOLLOW_PARAMS),o&&h.append("max_id",o),i&&h.append("query",i),d.label=3;case 3:return d.trys.push([3,5,,6]),[4,e.default.get("https://i.instagram.com/api/v1/friendships/"+t+"/following/?"+h.toString(),l({},n,{headers:l({},T._getInstaHeaders(),{"X-Ig-Nav-Chain":s.FOLLOW_NAV_CHAIN},null==(p=n)?void 0:p.headers)}))];case 4:return c=d.sent().data,[3,6];case 5:return c=null==(f=d.sent().response)?void 0:f.data,[3,6];case 6:if((null==(u=c)?void 0:u.status)!=="ok")throw T.verbose&&console.log("[USER FOLLOWING] Failed to fetch",c),Error("Failed to fetch user following: "+JSON.stringify(c));return[2,c]}})}),this.getPostIDfromThreadID=function(e){e=(e=(e=e.split("?")[0]).replace(/\s/g,"")).replace(/\//g,"");for(var t,r=0n,n=c(e);!(t=n()).done;){var s=t.value;r=64n*r+BigInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".indexOf(s))}return r.toString()},this.getPostIDfromURL=function(e){var t,r,n=null==e?void 0:e.split("?")[0];return(null==(t=n)?void 0:t.endsWith("/"))&&(n=n.slice(0,-1)),n=(null==(r=n)?void 0:r.split("/").pop())||"",v.getPostIDfromThreadID(n||"")};var O=this;this.getThreads=u(function(e,t){return d(this,function(r){switch(r.label){case 0:return O.verbose&&console.debug("[fbLSDToken] USING",O.fbLSDToken),[4,O._requestUserDataQuery("https://www.threads.net/api/graphql",{lsd:O.fbLSDToken,variables:JSON.stringify({postID:e}),doc_id:"5587632691339264"},t)];case 1:return[2,r.sent().data.data.data]}})});var P=this;this.getThreadLikers=u(function(e,t){return d(this,function(r){switch(r.label){case 0:return P.verbose&&console.debug("[fbLSDToken] USING",P.fbLSDToken),[4,P._requestUserDataQuery("https://www.threads.net/api/graphql",{lsd:P.fbLSDToken,variables:JSON.stringify({mediaID:e}),doc_id:"9360915773983802"},t)];case 1:return[2,r.sent().data.data.likers]}})});var R=this;this.getTimeline=u(function(e,t){var r;return d(this,function(n){switch(n.label){case 0:if(void 0===e&&(e=""),!R.token&&(!R.username||!R.password))throw Error("Username or password not set");return[4,R.getToken()];case 1:if(!n.sent())throw Error("Token not found");n.label=2;case 2:return n.trys.push([2,4,,5]),[4,R._requestQuery(""+s.BASE_API_URL+"/api/v1/feed/text_post_app_timeline/",{pagination_source:"text_post_feed_threads",max_id:e||void 0},l({},t,{headers:R._getAppHeaders()}))];case 3:return[2,n.sent().data];case 4:throw r=n.sent(),R.verbose&&console.log("[TIMELINE FETCH FAILED]",r.response.data),Error("Failed to fetch timeline");case 5:return[2]}})});var N=this;this._toggleAuthPostRequest=u(function(t,r,n){return d(this,function(s){switch(s.label){case 0:return[4,N.getToken()];case 1:if(!s.sent())throw Error("Token not found");return[4,e.default.post(t,r?new URLSearchParams(r):void 0,l({},n,{httpAgent:N.httpAgent,httpsAgent:N.httpsAgent,headers:N._getDefaultHeaders()}))];case 2:return[2,s.sent()]}})});var x=this;this.like=u(function(e,t){var r;return d(this,function(n){switch(n.label){case 0:return[4,x.getCurrentUserID()];case 1:return r=n.sent(),[4,x._toggleAuthPostRequest(s.BASE_API_URL+"/api/v1/media/"+e+"_"+r+"/like/",void 0,t)];case 2:return[2,"ok"===n.sent().data.status]}})});var F=this;this.unlike=u(function(e,t){var r;return d(this,function(n){switch(n.label){case 0:return[4,F.getCurrentUserID()];case 1:return r=n.sent(),[4,F._toggleAuthPostRequest(s.BASE_API_URL+"/api/v1/media/"+e+"_"+r+"/unlike/",void 0,t)];case 2:return[2,"ok"===n.sent().data.status]}})});var q=this;this.follow=u(function(e,t){var r;return d(this,function(n){switch(n.label){case 0:return[4,q._toggleAuthPostRequest(s.BASE_API_URL+"/api/v1/friendships/create/"+e+"/",void 0,t)];case 1:return r=n.sent(),q.verbose&&console.debug("[FOLLOW]",r.data),[2,r.data]}})});var H=this;this.unfollow=u(function(e,t){var r;return d(this,function(n){switch(n.label){case 0:return[4,H._toggleAuthPostRequest(s.BASE_API_URL+"/api/v1/friendships/destroy/"+e+"/",void 0,t)];case 1:return r=n.sent(),H.verbose&&console.debug("[UNFOLLOW]",r.data),[2,r.data]}})});var B=this;this.repost=u(function(e,t){var r;return d(this,function(n){switch(n.label){case 0:return[4,B._toggleAuthPostRequest(""+s.BASE_API_URL+"api/v1/repost/create_repost/",{media_id:e},t)];case 1:return r=n.sent(),B.verbose&&console.debug("[REPOST]",r.data),[2,r.data]}})});var C=this;this.unrepost=u(function(e,t){var r;return d(this,function(n){switch(n.label){case 0:return[4,C._toggleAuthPostRequest(""+s.BASE_API_URL+"/api/v1/repost/delete_text_app_repost/",{original_media_id:e},t)];case 1:return r=n.sent(),C.verbose&&console.debug("[UNREPOST]",r.data),[2,r.data]}})});var G=this;this.getToken=u(function(){return d(this,function(e){switch(e.label){case 0:if(G.token)return G.verbose&&console.debug("[token] USING",G.token),[2,G.token];if(!G.username||!G.password)throw Error("Username and password are required");return[4,G.login()];case 1:return e.sent(),[2,G.token]}})}),this._lastUploadID=0,this._nextUploadID=function(){var e=Date.now(),t=v._lastUploadID;return(v._lastUploadID=e<t?t+1:e).toString()},this._createUploadMetadata=function(e){var t;return void 0===e&&(e=v._nextUploadID()),{upload_id:e,source_type:"4",timezone_offset:(null!=(t=v._timezoneOffset)?t:v._timezoneOffset=-(60*new Date().getTimezoneOffset())).toString(),device:v.device}};var M=this;this.publish=u(function(t){var r,n,a,o,i,u,h,p,f,g,v,_;return d(this,function(d){switch(d.label){case 0:if(r="string"==typeof t?{text:t}:t,!M.token&&(!M.username||!M.password))throw Error("Username or password not set");return[4,M.getCurrentUserID()];case 1:if(!(n=d.sent()))throw Error("User ID not found");return[4,M.getToken()];case 2:if(!d.sent())throw Error("Token not found");if(o=l({},M._createUploadMetadata(),{text_post_app_info:{reply_control:s.REPLY_CONTROL_OPTIONS[null!=(a=r.replyControl)?a:"everyone"]},_uid:n,device_id:M.deviceID,caption:r.text||""}),i=s.POST_URL,!(u=r.attachment)&&("image"in r&&r.image?u={image:r.image}:"url"in r&&r.url&&(u={url:r.url})),!u)return[3,9];if(!u.url)return[3,3];return o.text_post_app_info.link_attachment_url=u.url,[3,9];case 3:if(!u.image)return[3,5];return i=s.POST_WITH_IMAGE_URL,[4,M.uploadImage(u.image,o.upload_id)];case 4:return d.sent(),o.scene_type=null,o.scene_capture_type="",[3,9];case 5:if(!u.sidecar)return[3,9];i=s.POST_WITH_SIDECAR_URL,o.client_sidecar_id=o.upload_id,o.children_metadata=[],h=c(u.sidecar),d.label=6;case 6:if((p=h()).done)return[3,9];return f=p.value,[4,M.uploadImage(f)];case 7:g=d.sent().upload_id,o.children_metadata.push(l({},M._createUploadMetadata(g),{scene_type:null,scene_capture_type:""})),d.label=8;case 8:return[3,6];case 9:return r.parentPostID&&(o.text_post_app_info.reply_id=r.parentPostID.replace(/_\d+$/,"")),r.quotedPostID&&(o.text_post_app_info.quoted_post_id=r.quotedPostID.replace(/_\d+$/,"")),i===s.POST_URL&&(o.publish_mode="text_post"),v="signed_body=SIGNATURE."+encodeURIComponent(JSON.stringify(o)),[4,e.default.post(i,v,{httpAgent:M.httpAgent,httpsAgent:M.httpsAgent,headers:M._getAppHeaders(),timeout:6e4})];case 10:if(_=d.sent(),M.verbose&&console.debug("[PUBLISH]",_.data),"ok"===_.data.status)return[2,_.data.media.id.replace(/_\d+$/,"")];return[2,void 0]}})});var X=this;this.delete=u(function(t,r){var n,a;return d(this,function(o){switch(o.label){case 0:return n=s.BASE_API_URL+"/api/v1/media/"+t+"/delete/",a="signed_body=SIGNATURE."+encodeURIComponent(JSON.stringify({media_id:t,_uid:X.userID,_uuid:X.deviceID})),[4,e.default.post(n,a,l({httpAgent:X.httpAgent,httpsAgent:X.httpsAgent,headers:X._getAppHeaders(),timeout:6e4},r))];case 1:if("ok"===o.sent().data.status)return[2,!0];return[2,!1]}})});var W=this;this.publishWithImage=u(function(e,t){return d(this,function(r){return[2,W.publish({text:e,image:t})]})});var J=this;if(this.uploadImage=u(function(t,s){var a,o,i,u,c,h,p,f,g,v,_;return d(this,function(d){switch(d.label){case 0:if(void 0===s&&(s=J._nextUploadID()),o="https://www.instagram.com/rupload_igphoto/"+(a=s+"_0_"+Math.floor(9e9*Math.random()+1e9)),!("string"==typeof t||"path"in t))return[3,6];if((c="string"==typeof t?t:t.path).startsWith("http"))return[3,3];return[4,Promise.resolve().then(function(){return require("fs")})];case 1:return[4,d.sent().promises.readFile(c)];case 2:return i=d.sent(),u=r.lookup(c)||"application/octet-stream",[3,5];case 3:return[4,e.default.get(c,{responseType:"arraybuffer"})];case 4:h=d.sent(),i=Buffer.from(h.data,"binary"),u=h.headers["content-type"],d.label=5;case 5:return[3,7];case 6:i=t.data,u=(t.type.includes("/")?t.type:r.lookup(t.type))||"application/octet-stream",d.label=7;case 7:p={upload_id:s,media_type:"1",sticker_burnin_params:JSON.stringify([]),image_compression:JSON.stringify({lib_name:"moz",lib_version:"3.1.m",quality:"80"}),xsharing_user_ids:JSON.stringify([]),retry_context:JSON.stringify({num_step_auto_retry:"0",num_reupload:"0",num_step_manual_retry:"0"}),"IG-FB-Xpost-entry-point-v2":"feed"},f=i.length,g=l({},J._getDefaultHeaders(),{"Content-Type":"application/octet-stream",X_FB_PHOTO_WATERFALL_ID:(0,n.v4)(),"X-Entity-Type":void 0!==u?"image/"+u:"image/jpeg",Offset:"0","X-Instagram-Rupload-Params":JSON.stringify(p),"X-Entity-Name":a,"X-Entity-Length":f.toString(),"Content-Length":f.toString(),"Accept-Encoding":"gzip"}),J.verbose&&console.log("[UPLOAD_IMAGE] Uploading "+f.toLocaleString()+"b as "+s+"..."),d.label=8;case 8:return d.trys.push([8,10,,11]),[4,e.default.post(o,i,{httpAgent:J.httpAgent,headers:g,timeout:6e4})];case 9:return v=d.sent().data,J.verbose&&console.log("[UPLOAD_IMAGE] SUCCESS",v),[2,v];case 10:throw _=d.sent(),J.verbose&&console.log("[UPLOAD_IMAGE] FAILED",_.response.data),Error("Upload image failed");case 11:return[2]}})}),(null==o?void 0:o.token)&&(this.token=o.token),(null==o?void 0:o.fbLSDToken)&&(this.fbLSDToken=o.fbLSDToken),this.noUpdateToken=!!(null==o?void 0:o.noUpdateToken),this.noUpdateLSD=!!(null==o?void 0:o.noUpdateLSD),this.verbose=(null==o?void 0:o.verbose)||!1,this.httpAgent=null==o?void 0:o.httpAgent,this.httpsAgent=null==o?void 0:o.httpsAgent,this.username=null!=(i=null==o?void 0:o.username)?i:process.env.THREADS_USERNAME,this.password=null!=(p=null==o?void 0:o.password)?p:process.env.THREADS_PASSWORD,this.deviceID=null!=(g=null!=(f=null==o?void 0:o.deviceID)?f:process.env.THREADS_DEVICE_ID)?g:"",this.deviceID||(this.deviceID="android-"+(1e24*Math.random()).toString(36),console.warn("⚠️ WARNING: deviceID not provided, automatically generating device id '"+this.deviceID+"'","Please save this device id and use it for future uses to prevent login issues.","You can provide this device id by passing it to the constructor or setting the THREADS_DEVICE_ID environment variable (.env file)")),this.device=null==o?void 0:o.device,this.userID=null==o?void 0:o.userID,null==o?void 0:o.locale)this.locale=o.locale;else{var Q=Intl.DateTimeFormat().resolvedOptions().locale;this.locale=Q}this.maxRetries=(null==o?void 0:o.maxRetries)||this.maxRetries}return o.prototype.sign=function(e){var r="object"==typeof e?JSON.stringify(e):e;return{ig_sig_key_version:4,signed_body:t.createHmac("sha256",s.SIGNATURE_KEY).update(r).digest("hex")+"."+r}},o}();
"use strict";!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(exports,{DEFAULT_DEVICE:function(){return h},ThreadsAPI:function(){return p}});var e=require("axios"),t=require("crypto"),r=require("mrmime"),n=require("uuid"),s=require("./constants"),a=require("./dynamic-data");function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function i(e,t,r,n,s,a,o){try{var i=e[a](o),u=i.value}catch(e){r(e);return}i.done?t(u):Promise.resolve(u).then(n,s)}function u(e){return function(){var t=this,r=arguments;return new Promise(function(n,s){var a=e.apply(t,r);function o(e){i(a,n,s,o,u,"next",e)}function u(e){i(a,n,s,o,u,"throw",e)}o(void 0)})}}function l(){return(l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function c(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return o(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if("Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r)return Array.from(r);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return o(e,t)}}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function d(e,t){var r,n,s,a,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(a){return function(i){return function(a){if(r)throw TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(s=2&a[0]?n.return:a[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,a[1])).done)return s;switch(n=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(s=(s=o.trys).length>0&&s[s.length-1])&&(6===a[0]||2===a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]<s[3])){o.label=a[1];break}if(6===a[0]&&o.label<s[1]){o.label=s[1],s=a;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(a);break}s[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],n=0}finally{r=s=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,i])}}}var h={manufacturer:"OnePlus",model:"ONEPLUS+A3010",os_version:25,os_release:"7.1.1"},p=function(){"use strict";function o(o){var i,p,f,g,v=this;this.verbose=!1,this.token=void 0,this.fbLSDToken=s.DEFAULT_LSD_TOKEN,this.noUpdateToken=!1,this.noUpdateLSD=!1,this.device=h,this.userID=void 0,this.locale=void 0,this.maxRetries=1;var _=this;this.syncLoginExperiments=u(function(){var t,r,a;return d(this,function(o){switch(o.label){case 0:r={id:t=(0,n.v4)(),experiments:s.LOGIN_EXPERIMENTS},o.label=1;case 1:return o.trys.push([1,3,,4]),[4,e.default.post(""+s.BASE_API_URL+"/api/v1/qe/sync/",_.sign(r),{httpAgent:_.httpAgent,httpsAgent:_.httpsAgent,headers:l({},_._getAppHeaders(),{Authorization:void 0,"Sec-Fetch-Site":"same-origin","X-DEVICE-ID":t})})];case 2:return[2,o.sent()];case 3:throw a=o.sent(),_.verbose&&console.log("[SYNC LOGIN EXPERIMENT FAILED]",a.response.data),Error("Sync login experiment failed");case 4:return[2]}})});var b=this;this.encryptPassword=u(function(e){var r,n,s,a,o,i,u,l,c,h,p;return d(this,function(d){switch(d.label){case 0:return r=t.randomBytes(32),n=t.randomBytes(12),[4,b.syncLoginExperiments()];case 1:return s=d.sent().headers,b.verbose&&console.log("[SYNC LOGIN EXPERIMENT HEADERS]",JSON.stringify(s)),a=s["ig-set-password-encryption-key-id"],o=s["ig-set-password-encryption-pub-key"],i=t.publicEncrypt({key:Buffer.from(o||"","base64").toString(),padding:t.constants.RSA_PKCS1_PADDING},r),u=t.createCipheriv("aes-256-gcm",r,n),l=Math.floor(Date.now()/1e3).toString(),u.setAAD(Buffer.from(l)),c=Buffer.concat([u.update(e,"utf8"),u.final()]),(h=Buffer.alloc(2,0)).writeInt16LE(i.byteLength,0),p=u.getAuthTag(),[2,{time:l,password:Buffer.concat([Buffer.from([1,a||0]),n,h,i,p,c]).toString("base64")}]}})});var m=this;this.login=u(function(){var t,r,n,a;return d(this,function(o){switch(o.label){case 0:t=function(){var e;return d(this,function(t){switch(t.label){case 0:return t.trys.push([0,1,,3]),[2,{v:n()}];case 1:return t.sent(),m.verbose&&console.error("[LOGIN] Failed to login, retrying... ("+(r+1)+"/"+m.maxRetries+")"),e=1e3*Math.pow(2,r),[4,new Promise(function(t){return setTimeout(t,e)})];case 2:return t.sent(),r++,[3,3];case 3:return[2]}})},r=0,n=u(function(){var t,r,n,a,o,i,u,l;return d(this,function(c){switch(c.label){case 0:return m.verbose&&console.log("[LOGIN] Logging in..."),[4,m.encryptPassword(m.password)];case 1:return r=encodeURIComponent(JSON.stringify({client_input_params:{password:"#PWD_INSTAGRAM:4:"+(t=c.sent()).time+":"+t.password,contact_point:m.username,device_id:m.deviceID},server_params:{credential_type:"password",device_id:m.deviceID}})),n=encodeURIComponent(JSON.stringify({bloks_version:s.BLOKS_VERSION,styles_id:"instagram"})),a={httpAgent:m.httpAgent,httpsAgent:m.httpsAgent,method:"POST",headers:m._getAppHeaders(),responseType:"text",data:"params="+r+"&bk_client_context="+n+"&bloks_versioning_id="+s.BLOKS_VERSION},[4,(0,e.default)(""+s.BASE_API_URL+"/api/v1/bloks/apps/com.bloks.www.bloks.caa.login.async.send_login_request/",a)];case 2:o=JSON.stringify((o=c.sent().data).replaceAll("\\","")),m.verbose&&console.log("[LOGIN] Cleaned output",o);try{return u=o.split("Bearer IGT:2:")[1].split('"')[0].replaceAll("\\",""),l=null==(i=o.match(/pk_id(.{18})/))?void 0:i[1].replaceAll(/[\\":]/g,""),m.noUpdateToken||(m.verbose&&console.debug("[token] UPDATED",u),m.token=u),m.userID=l,m.verbose&&console.debug("[userID] UPDATED",m.userID),[2,{token:u,userID:l}]}catch(e){throw m.verbose&&console.error("[LOGIN] Failed to login",e),Error("Login Failed")}return[2]}})}),o.label=1;case 1:if(!(r<m.maxRetries))return[3,3];return[5,function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(t())];case 2:var i;if("object"==((i=a=o.sent())&&"undefined"!=typeof Symbol&&i.constructor===Symbol?"symbol":typeof i))return[2,a.v];return[3,1];case 3:throw Error("[LOGIN] Failed to login after "+m.maxRetries+" retries")}})}),this._getUnAuthenticatedHeaders=function(){return{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.199 Safari/537.36","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}},this._getDefaultUserDataHeaders=function(e){return l({},v._getUnAuthenticatedHeaders(),{Host:"www.threads.net",Accept:"*/*","Accept-Language":v.locale,"cache-control":"no-cache",Origin:"https://www.threads.net",Pragma:"no-cache","Sec-Fetch-Site":"same-origin","X-Asbd-id":"129477","X-FB-Friendly-Name":"BarcelonaProfileRootQuery","X-FB-Lsd":v.fbLSDToken,"X-Ig-App-Id":"238260118697367"},e?{Referer:"https://www.threads.net/@"+e}:void 0)},this._getAppHeaders=function(){return l({"User-Agent":"Barcelona "+a.LATEST_ANDROID_APP_VERSION+" Android","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},v.token&&{Authorization:"Bearer IGT:2:"+v.token})},this._getInstaHeaders=function(){return l({},v._getAppHeaders(),{"X-Bloks-Is-Layout-Rtl":"false","X-Bloks-Version-Id":s.BLOKS_VERSION,"X-Ig-Android-Id":v.deviceID,"X-Ig-App-Id":s.IG_APP_ID,"Accept-Language":v.locale||"en-US"},v.userID&&{"Ig-U-Ds-User-Id":v.userID,"Ig-Intended-User-Id":v.userID},v.locale&&{"X-Ig-App-Locale":v.locale.replace("-","_"),"X-Ig-Device-Locale":v.locale.replace("-","_"),"X-Ig-Mapped-Locale":v.locale.replace("-","_")})},this._getDefaultHeaders=function(e){return l({},v._getAppHeaders(),{authority:"www.threads.net",accept:"*/*","accept-language":v.locale,"cache-control":"no-cache",origin:"https://www.threads.net",pragma:"no-cache","Sec-Fetch-Site":"same-origin","x-asbd-id":"129477","x-fb-lsd":v.fbLSDToken,"x-ig-app-id":"238260118697367"},e?{referer:"https://www.threads.net/@"+e}:void 0)};var I=this;this._getCleanedProfileHTML=u(function(t,r,n){return d(this,function(s){switch(s.label){case 0:return[4,e.default.get(""+t+r,l({},n,{httpAgent:I.httpAgent,httpsAgent:I.httpsAgent,headers:l({},I._getDefaultHeaders(r),{accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7","accept-language":"ko,en;q=0.9,ko-KR;q=0.8,ja;q=0.7",Authorization:void 0,referer:"https://www.instagram.com/","sec-fetch-dest":"document","sec-fetch-mode":"navigate","sec-fetch-site":"cross-site","sec-fetch-user":"?1","upgrade-insecure-requests":"1","x-asbd-id":void 0,"x-fb-lsd":void 0,"x-ig-app-id":void 0})}))];case 1:return[2,(0,s.sent().data).replace(/\s/g,"").replace(/\n/g,"")]}})});var D=this;this.getUserIDfromUsernameWithInstagram=u(function(e,t){var r,n,s,a,o;return d(this,function(i){switch(i.label){case 0:return[4,D._getCleanedProfileHTML("https://www.instagram.com/",e,t)];case 1:return a=null==(r=(s=i.sent()).match(/"user_id":"(\d+)",/))?void 0:r[1],o=null==(n=s.match(/"LSD",\[\],{"token":"(\w+)"},\d+\]/))?void 0:n[1],!D.noUpdateLSD&&o&&(D.fbLSDToken=o,D.verbose&&console.debug("[fbLSDToken] UPDATED",D.fbLSDToken)),[2,a]}})});var A=this;this.getUserIDfromUsername=u(function(e,t){var r,n,s,a,o;return d(this,function(i){switch(i.label){case 0:return[4,A._getCleanedProfileHTML("https://www.threads.net/@",e,t)];case 1:if(a=null==(r=(s=i.sent()).match(/"user_id":"(\d+)"/))?void 0:r[1],o=null==(n=s.match(/"LSD",\[\],{"token":"(\w+)"},\d+\]/))?void 0:n[1],!a)return[2,A.getUserIDfromUsernameWithInstagram(e,t)];return!A.noUpdateLSD&&o&&(A.fbLSDToken=o,A.verbose&&console.debug("[fbLSDToken] UPDATED",A.fbLSDToken)),[2,a]}})});var w=this;this.getCurrentUserID=u(function(e){var t;return d(this,function(r){switch(r.label){case 0:if(w.userID)return w.verbose&&console.debug("[userID] USING",w.userID),[2,w.userID];if(!w.username)throw Error("username is not defined");r.label=1;case 1:return r.trys.push([1,3,,5]),[4,w.getUserIDfromUsername(w.username,e)];case 2:return w.userID=r.sent(),w.verbose&&console.debug("[userID] UPDATED",w.userID),[2,w.userID];case 3:return t=r.sent(),w.verbose&&console.error("[userID] Failed to fetch userID, Fallbacking to login",t),[4,w.login()];case 4:return[2,r.sent().userID];case 5:return[2]}})}),this._requestQuery=function(t,r,n){return Object.keys(r).forEach(function(e){return void 0===r[e]&&delete r[e]}),e.default.post(t,new URLSearchParams(r),l({httpAgent:v.httpAgent,httpsAgent:v.httpsAgent,headers:v._getDefaultHeaders()},n))},this._requestUserDataQuery=function(t,r,n){return Object.keys(r).forEach(function(e){return void 0===r[e]&&delete r[e]}),e.default.post(t,new URLSearchParams(r),l({httpAgent:v.httpAgent,httpsAgent:v.httpsAgent,headers:v._getDefaultUserDataHeaders()},n))},this._destructureFromUserIDQuerier=function(e){var t,r;return"string"==typeof e[0]&&"string"==typeof e[1]?(t=e[1],r=e[2]):(t=e[0],r=e[1]),{userID:t,options:r}};var S=this;this.getUserProfile=u(function(){var e,t,r,n,s,a,o=arguments;return d(this,function(i){switch(i.label){case 0:for(t=Array(e=o.length),r=0;r<e;r++)t[r]=o[r];return s=(n=S._destructureFromUserIDQuerier(t)).userID,a=n.options,S.verbose&&console.debug("[fbLSDToken] USING",S.fbLSDToken),[4,S._requestUserDataQuery("https://www.threads.net/api/graphql",{lsd:S.fbLSDToken,variables:JSON.stringify({userID:s}),doc_id:"23996318473300828"},a)];case 1:return[2,i.sent().data.data.userData.user]}})});var y=this;this.getUserProfileThreads=u(function(){var e,t,r,n,s,a,o,i,u=arguments;return d(this,function(l){switch(l.label){case 0:for(t=Array(e=u.length),r=0;r<e;r++)t[r]=u[r];return o=(a=y._destructureFromUserIDQuerier(t)).userID,i=a.options,y.verbose&&console.debug("[fbLSDToken] USING",y.fbLSDToken),[4,y._requestUserDataQuery("https://www.threads.net/api/graphql",{lsd:y.fbLSDToken,variables:JSON.stringify({userID:o}),doc_id:"6232751443445612"},i)];case 1:return[2,(null==(s=l.sent().data.data)?void 0:null==(n=s.mediaData)?void 0:n.threads)||[]]}})});var L=this;this.getUserProfileThreadsLoggedIn=u(function(t,r,n){var a,o,i,u;return d(this,function(c){switch(c.label){case 0:if(void 0===r&&(r=""),void 0===n&&(n={}),L.token)return[3,2];return[4,L.getToken()];case 1:c.sent(),c.label=2;case 2:if(!L.token)throw Error("Token not found");o=void 0,c.label=3;case 3:return c.trys.push([3,5,,6]),[4,e.default.get(s.BASE_API_URL+"/api/v1/text_feed/"+t+"/profile/"+(r&&"?max_id="+r),l({},n,{headers:l({},L._getInstaHeaders(),null==(i=n)?void 0:i.headers)}))];case 4:return o=c.sent().data,[3,6];case 5:return o=null==(u=c.sent().response)?void 0:u.data,[3,6];case 6:if((null==(a=o)?void 0:a.status)!=="ok")throw L.verbose&&console.log("[USER FEED] Failed to fetch",o),Error("Failed to fetch user feed: "+JSON.stringify(o));return[2,o]}})}),this._getDefaultRepliesHeaders=function(e){return l({},v._getUnAuthenticatedHeaders(),{Host:"www.threads.net",Accept:"*/*","Accept-Language":v.locale,"cache-control":"no-cache",Origin:"https://www.threads.net",Pragma:"no-cache","Sec-Fetch-Site":"same-origin","X-Asbd-id":"129477","X-FB-Friendly-Name":"BarcelonaProfileProfileRepliesTabQuery","X-FB-Lsd":v.fbLSDToken,"X-Ig-App-Id":"238260118697367"},e?{Referer:"https://www.threads.net/@"+e+"/replies"}:void 0)},this._requestRepliesQuery=function(t,r,n){return Object.keys(r).forEach(function(e){return void 0===r[e]&&delete r[e]}),e.default.post(t,new URLSearchParams(r),l({httpAgent:v.httpAgent,httpsAgent:v.httpsAgent,headers:v._getDefaultRepliesHeaders()},n))};var U=this;this.getUserProfileReplies=u(function(){var e,t,r,n,s,a,o,i=arguments;return d(this,function(u){switch(u.label){case 0:for(t=Array(e=i.length),r=0;r<e;r++)t[r]=i[r];return a=(s=U._destructureFromUserIDQuerier(t)).userID,o=s.options,U.verbose&&console.debug("[fbLSDToken] USING",U.fbLSDToken),[4,U._requestRepliesQuery("https://www.threads.net/api/graphql",{lsd:U.fbLSDToken,variables:JSON.stringify({userID:a}),doc_id:"6684830921547925"},o)];case 1:return[2,(null==(n=u.sent().data.data.mediaData)?void 0:n.threads)||[]]}})});var k=this;this.getUserProfileRepliesLoggedIn=u(function(t,r,n){var s,a,o,i;return d(this,function(u){switch(u.label){case 0:if(void 0===r&&(r=""),void 0===n&&(n={}),k.token)return[3,2];return[4,k.getToken()];case 1:u.sent(),u.label=2;case 2:if(!k.token)throw Error("Token not found");a=void 0,u.label=3;case 3:return u.trys.push([3,5,,6]),[4,e.default.get("https://i.instagram.com/api/v1/text_feed/"+t+"/profile/replies/"+(r&&"?max_id="+r),l({},n,{headers:l({},k._getAppHeaders(),null==(o=n)?void 0:o.headers)}))];case 4:return a=u.sent().data,[3,6];case 5:return a=null==(i=u.sent().response)?void 0:i.data,[3,6];case 6:if((null==(s=a)?void 0:s.status)!=="ok")throw k.verbose&&console.log("[USER FEED] Failed to fetch",a),Error("Failed to fetch user feed: "+JSON.stringify(a));return[2,a]}})});var E=this;this.getUserFollowers=u(function(t,r,n){var a,o,i,u,c,h,p,f;return d(this,function(d){switch(d.label){case 0:if(o=(a=void 0===r?{}:r).maxID,i=a.query,E.token)return[3,2];return[4,E.getToken()];case 1:d.sent(),d.label=2;case 2:if(!E.token)throw Error("Token not found");c=void 0,h=new URLSearchParams(s.BASE_FOLLOW_PARAMS),o&&h.append("max_id",o),i&&h.append("query",i),d.label=3;case 3:return d.trys.push([3,5,,6]),[4,e.default.get("https://i.instagram.com/api/v1/friendships/"+t+"/followers/?"+h.toString(),l({},n,{headers:l({},E._getInstaHeaders(),{"X-Ig-Nav-Chain":s.FOLLOW_NAV_CHAIN},null==(p=n)?void 0:p.headers)}))];case 4:return c=d.sent().data,[3,6];case 5:return c=null==(f=d.sent().response)?void 0:f.data,[3,6];case 6:if((null==(u=c)?void 0:u.status)!=="ok")throw E.verbose&&console.log("[USER FOLLOWERS] Failed to fetch",c),Error("Failed to fetch user followers: "+JSON.stringify(c));return[2,c]}})});var T=this;this.getUserFollowings=u(function(t,r,n){var a,o,i,u,c,h,p,f;return d(this,function(d){switch(d.label){case 0:if(o=(a=void 0===r?{}:r).maxID,i=a.query,T.token)return[3,2];return[4,T.getToken()];case 1:d.sent(),d.label=2;case 2:if(!T.token)throw Error("Token not found");c=void 0,h=new URLSearchParams(s.BASE_FOLLOW_PARAMS),o&&h.append("max_id",o),i&&h.append("query",i),d.label=3;case 3:return d.trys.push([3,5,,6]),[4,e.default.get("https://i.instagram.com/api/v1/friendships/"+t+"/following/?"+h.toString(),l({},n,{headers:l({},T._getInstaHeaders(),{"X-Ig-Nav-Chain":s.FOLLOW_NAV_CHAIN},null==(p=n)?void 0:p.headers)}))];case 4:return c=d.sent().data,[3,6];case 5:return c=null==(f=d.sent().response)?void 0:f.data,[3,6];case 6:if((null==(u=c)?void 0:u.status)!=="ok")throw T.verbose&&console.log("[USER FOLLOWING] Failed to fetch",c),Error("Failed to fetch user following: "+JSON.stringify(c));return[2,c]}})}),this.getPostIDfromThreadID=function(e){e=(e=(e=e.split("?")[0]).replace(/\s/g,"")).replace(/\//g,"");for(var t,r=0n,n=c(e);!(t=n()).done;){var s=t.value;r=64n*r+BigInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".indexOf(s))}return r.toString()},this.getPostIDfromURL=function(e){var t,r,n=null==e?void 0:e.split("?")[0];return(null==(t=n)?void 0:t.endsWith("/"))&&(n=n.slice(0,-1)),n=(null==(r=n)?void 0:r.split("/").pop())||"",v.getPostIDfromThreadID(n||"")};var O=this;this.getThreads=u(function(e,t){return d(this,function(r){switch(r.label){case 0:return O.verbose&&console.debug("[fbLSDToken] USING",O.fbLSDToken),[4,O._requestUserDataQuery("https://www.threads.net/api/graphql",{lsd:O.fbLSDToken,variables:JSON.stringify({postID:e}),doc_id:"5587632691339264"},t)];case 1:return[2,r.sent().data.data.data]}})});var P=this;this.getThreadLikers=u(function(e,t){return d(this,function(r){switch(r.label){case 0:return P.verbose&&console.debug("[fbLSDToken] USING",P.fbLSDToken),[4,P._requestUserDataQuery("https://www.threads.net/api/graphql",{lsd:P.fbLSDToken,variables:JSON.stringify({mediaID:e}),doc_id:"9360915773983802"},t)];case 1:return[2,r.sent().data.data.likers]}})});var R=this;this.getTimeline=u(function(e,t){var r;return d(this,function(n){switch(n.label){case 0:if(void 0===e&&(e=""),!R.token&&(!R.username||!R.password))throw Error("Username or password not set");return[4,R.getToken()];case 1:if(!n.sent())throw Error("Token not found");n.label=2;case 2:return n.trys.push([2,4,,5]),[4,R._requestQuery(""+s.BASE_API_URL+"/api/v1/feed/text_post_app_timeline/",{pagination_source:"text_post_feed_threads",max_id:e||void 0},l({},t,{headers:R._getAppHeaders()}))];case 3:return[2,n.sent().data];case 4:throw r=n.sent(),R.verbose&&console.log("[TIMELINE FETCH FAILED]",r.response.data),Error("Failed to fetch timeline");case 5:return[2]}})});var N=this;this._toggleAuthPostRequest=u(function(t,r,n){return d(this,function(s){switch(s.label){case 0:return[4,N.getToken()];case 1:if(!s.sent())throw Error("Token not found");return[4,e.default.post(t,r?new URLSearchParams(r):void 0,l({},n,{httpAgent:N.httpAgent,httpsAgent:N.httpsAgent,headers:N._getDefaultHeaders()}))];case 2:return[2,s.sent()]}})});var x=this;this.like=u(function(e,t){var r;return d(this,function(n){switch(n.label){case 0:return[4,x.getCurrentUserID()];case 1:return r=n.sent(),[4,x._toggleAuthPostRequest(s.BASE_API_URL+"/api/v1/media/"+e+"_"+r+"/like/",void 0,t)];case 2:return[2,"ok"===n.sent().data.status]}})});var F=this;this.unlike=u(function(e,t){var r;return d(this,function(n){switch(n.label){case 0:return[4,F.getCurrentUserID()];case 1:return r=n.sent(),[4,F._toggleAuthPostRequest(s.BASE_API_URL+"/api/v1/media/"+e+"_"+r+"/unlike/",void 0,t)];case 2:return[2,"ok"===n.sent().data.status]}})});var q=this;this.follow=u(function(e,t){var r;return d(this,function(n){switch(n.label){case 0:return[4,q._toggleAuthPostRequest(s.BASE_API_URL+"/api/v1/friendships/create/"+e+"/",void 0,t)];case 1:return r=n.sent(),q.verbose&&console.debug("[FOLLOW]",r.data),[2,r.data]}})});var H=this;this.unfollow=u(function(e,t){var r;return d(this,function(n){switch(n.label){case 0:return[4,H._toggleAuthPostRequest(s.BASE_API_URL+"/api/v1/friendships/destroy/"+e+"/",void 0,t)];case 1:return r=n.sent(),H.verbose&&console.debug("[UNFOLLOW]",r.data),[2,r.data]}})});var B=this;this.repost=u(function(e,t){var r;return d(this,function(n){switch(n.label){case 0:return[4,B._toggleAuthPostRequest(""+s.BASE_API_URL+"api/v1/repost/create_repost/",{media_id:e},t)];case 1:return r=n.sent(),B.verbose&&console.debug("[REPOST]",r.data),[2,r.data]}})});var C=this;this.unrepost=u(function(e,t){var r;return d(this,function(n){switch(n.label){case 0:return[4,C._toggleAuthPostRequest(""+s.BASE_API_URL+"/api/v1/repost/delete_text_app_repost/",{original_media_id:e},t)];case 1:return r=n.sent(),C.verbose&&console.debug("[UNREPOST]",r.data),[2,r.data]}})});var G=this;this.getToken=u(function(){return d(this,function(e){switch(e.label){case 0:if(G.token)return G.verbose&&console.debug("[token] USING",G.token),[2,G.token];if(!G.username||!G.password)throw Error("Username and password are required");return[4,G.login()];case 1:return e.sent(),[2,G.token]}})}),this._lastUploadID=0,this._nextUploadID=function(){var e=Date.now(),t=v._lastUploadID;return(v._lastUploadID=e<t?t+1:e).toString()},this._createUploadMetadata=function(e){var t;return void 0===e&&(e=v._nextUploadID()),{upload_id:e,source_type:"4",timezone_offset:(null!=(t=v._timezoneOffset)?t:v._timezoneOffset=-(60*new Date().getTimezoneOffset())).toString(),device:v.device}};var M=this;this.publish=u(function(t){var r,n,a,o,i,u,h,p,f,g,v,_;return d(this,function(d){switch(d.label){case 0:if(r="string"==typeof t?{text:t}:t,!M.token&&(!M.username||!M.password))throw Error("Username or password not set");return[4,M.getCurrentUserID()];case 1:if(!(n=d.sent()))throw Error("User ID not found");return[4,M.getToken()];case 2:if(!d.sent())throw Error("Token not found");if(o=l({},M._createUploadMetadata(),{text_post_app_info:{reply_control:s.REPLY_CONTROL_OPTIONS[null!=(a=r.replyControl)?a:"everyone"]},_uid:n,device_id:M.deviceID,caption:r.text||""}),i=s.POST_URL,!(u=r.attachment)&&("image"in r&&r.image?u={image:r.image}:"url"in r&&r.url&&(u={url:r.url})),!u)return[3,9];if(!u.url)return[3,3];return o.text_post_app_info.link_attachment_url=u.url,[3,9];case 3:if(!u.image)return[3,5];return i=s.POST_WITH_IMAGE_URL,[4,M.uploadImage(u.image,o.upload_id)];case 4:return d.sent(),o.scene_type=null,o.scene_capture_type="",[3,9];case 5:if(!u.sidecar)return[3,9];i=s.POST_WITH_SIDECAR_URL,o.client_sidecar_id=o.upload_id,o.children_metadata=[],h=c(u.sidecar),d.label=6;case 6:if((p=h()).done)return[3,9];return f=p.value,[4,M.uploadImage(f)];case 7:g=d.sent().upload_id,o.children_metadata.push(l({},M._createUploadMetadata(g),{scene_type:null,scene_capture_type:""})),d.label=8;case 8:return[3,6];case 9:return r.parentPostID&&(o.text_post_app_info.reply_id=r.parentPostID.replace(/_\d+$/,"")),r.quotedPostID&&(o.text_post_app_info.quoted_post_id=r.quotedPostID.replace(/_\d+$/,"")),i===s.POST_URL&&(o.publish_mode="text_post"),v="signed_body=SIGNATURE."+encodeURIComponent(JSON.stringify(o)),[4,e.default.post(i,v,{httpAgent:M.httpAgent,httpsAgent:M.httpsAgent,headers:M._getAppHeaders(),timeout:6e4})];case 10:if(_=d.sent(),M.verbose&&console.debug("[PUBLISH]",_.data),"ok"===_.data.status)return[2,_.data.media.id.replace(/_\d+$/,"")];return[2,void 0]}})});var X=this;this.delete=u(function(t,r){var n,a;return d(this,function(o){switch(o.label){case 0:return n=s.BASE_API_URL+"/api/v1/media/"+t+"/delete/",a="signed_body=SIGNATURE."+encodeURIComponent(JSON.stringify({media_id:t,_uid:X.userID,_uuid:X.deviceID})),[4,e.default.post(n,a,l({httpAgent:X.httpAgent,httpsAgent:X.httpsAgent,headers:X._getAppHeaders(),timeout:6e4},r))];case 1:if("ok"===o.sent().data.status)return[2,!0];return[2,!1]}})});var W=this;this.publishWithImage=u(function(e,t){return d(this,function(r){return[2,W.publish({text:e,image:t})]})});var J=this;if(this.uploadImage=u(function(t,s){var a,o,i,u,c,h,p,f,g,v,_;return d(this,function(d){switch(d.label){case 0:if(void 0===s&&(s=J._nextUploadID()),o="https://www.instagram.com/rupload_igphoto/"+(a=s+"_0_"+Math.floor(9e9*Math.random()+1e9)),!("string"==typeof t||"path"in t))return[3,6];if((c="string"==typeof t?t:t.path).startsWith("http"))return[3,3];return[4,Promise.resolve().then(function(){return require("fs")})];case 1:return[4,d.sent().promises.readFile(c)];case 2:return i=d.sent(),u=r.lookup(c)||"application/octet-stream",[3,5];case 3:return[4,e.default.get(c,{responseType:"arraybuffer"})];case 4:h=d.sent(),i=Buffer.from(h.data,"binary"),u=h.headers["content-type"],d.label=5;case 5:return[3,7];case 6:i=t.data,u=(t.type.includes("/")?t.type:r.lookup(t.type))||"application/octet-stream",d.label=7;case 7:p={upload_id:s,media_type:"1",sticker_burnin_params:JSON.stringify([]),image_compression:JSON.stringify({lib_name:"moz",lib_version:"3.1.m",quality:"80"}),xsharing_user_ids:JSON.stringify([]),retry_context:JSON.stringify({num_step_auto_retry:"0",num_reupload:"0",num_step_manual_retry:"0"}),"IG-FB-Xpost-entry-point-v2":"feed"},f=i.length,g=l({},J._getDefaultHeaders(),{"Content-Type":"application/octet-stream",X_FB_PHOTO_WATERFALL_ID:(0,n.v4)(),"X-Entity-Type":void 0!==u?"image/"+u:"image/jpeg",Offset:"0","X-Instagram-Rupload-Params":JSON.stringify(p),"X-Entity-Name":a,"X-Entity-Length":f.toString(),"Content-Length":f.toString(),"Accept-Encoding":"gzip"}),J.verbose&&console.log("[UPLOAD_IMAGE] Uploading "+f.toLocaleString()+"b as "+s+"..."),d.label=8;case 8:return d.trys.push([8,10,,11]),[4,e.default.post(o,i,{httpAgent:J.httpAgent,headers:g,timeout:6e4})];case 9:return v=d.sent().data,J.verbose&&console.log("[UPLOAD_IMAGE] SUCCESS",v),[2,v];case 10:throw _=d.sent(),J.verbose&&console.log("[UPLOAD_IMAGE] FAILED",_.response.data),Error("Upload image failed");case 11:return[2]}})}),(null==o?void 0:o.token)&&(this.token=o.token),(null==o?void 0:o.fbLSDToken)&&(this.fbLSDToken=o.fbLSDToken),this.noUpdateToken=!!(null==o?void 0:o.noUpdateToken),this.noUpdateLSD=!!(null==o?void 0:o.noUpdateLSD),this.verbose=(null==o?void 0:o.verbose)||!1,this.httpAgent=null==o?void 0:o.httpAgent,this.httpsAgent=null==o?void 0:o.httpsAgent,this.username=null!=(i=null==o?void 0:o.username)?i:process.env.THREADS_USERNAME,this.password=null!=(p=null==o?void 0:o.password)?p:process.env.THREADS_PASSWORD,this.deviceID=null!=(g=null!=(f=null==o?void 0:o.deviceID)?f:process.env.THREADS_DEVICE_ID)?g:"",this.deviceID||(this.deviceID="android-"+(1e24*Math.random()).toString(36),console.warn("⚠️ WARNING: deviceID not provided, automatically generating device id '"+this.deviceID+"'","Please save this device id and use it for future uses to prevent login issues.","You can provide this device id by passing it to the constructor or setting the THREADS_DEVICE_ID environment variable (.env file)")),this.device=null==o?void 0:o.device,this.userID=null==o?void 0:o.userID,null==o?void 0:o.locale)this.locale=o.locale;else{var Q=Intl.DateTimeFormat().resolvedOptions().locale;this.locale=Q}this.maxRetries=(null==o?void 0:o.maxRetries)||this.maxRetries}return o.prototype.sign=function(e){var r="object"==typeof e?JSON.stringify(e):e;return{ig_sig_key_version:4,signed_body:t.createHmac("sha256",s.SIGNATURE_KEY).update(r).digest("hex")+"."+r}},o}();
{
"name": "threads-api",
"version": "1.5.3",
"version": "1.5.4",
"description": "Unofficial, Reverse-Engineered Node.js/TypeScript client for Meta's [Threads](https://threads.net).",

@@ -40,2 +40,3 @@ "author": "Junho Yeo <i@junho.io>",

"commander": "^11.0.0",
"dotenv": "^16.3.1",
"jest": "^29.6.1",

@@ -49,3 +50,2 @@ "rimraf": "^5.0.1",

"axios": "^1.4.0",
"dotenv": "^16.3.1",
"mrmime": "^1.0.1",

@@ -52,0 +52,0 @@ "uuid": "^9.0.0"

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc