@stacksjs/socials 0.75.770 → 0.75.775

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -60,7 +60,7 @@ export declare class MastodonApiError extends SocialApiError {
60
60
  */
61
61
  export declare class MastodonPublishingDriver implements SocialPublishingDriver, SocialDeletionDriver, SocialMetricsDriver {
62
62
  readonly provider: 'mastodon';
63
- characterLimit: unknown;
63
+ characterLimit: number;
64
64
  fetchImage: unknown;
65
65
  private limits;
66
66
  instanceLimits(identity: SocialIdentityCredentials): Promise<MastodonLimits>;
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- var ht=import.meta.require;import{Buffer as V}from"buffer";class k{clientId;clientSecret;redirectUrl;parameters={};_scopes=[];scopeSeparator=",";_stateless=!1;_usesPKCE=!1;_codeVerifier=null;_state=null;user=null;constructor(e){this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.redirectUrl=e.redirectUrl}async getCodeFields(e=null){let t={client_id:this.clientId,redirect_uri:this.redirectUrl,scope:this.formatScopes(this.getScopes(),this.scopeSeparator),response_type:"code"};if(this.usesState())t.state=e;return{...t,...await this.pkceFields(),...this.parameters}}formatScopes(e,t){return e.join(t)}async userFromToken(e){return{...await this.getUserByToken(e),token:e}}scopes(e){let t=Array.isArray(e)?e:[e];return this._scopes=[...new Set([...this._scopes,...t])],this}setScopes(e){let t=Array.isArray(e)?e:[e];return this._scopes=[...new Set(t)],this}getScopes(){return this._scopes}setRedirectUrl(e){if(typeof e!=="string"||e.length===0)throw Error("[socials] setRedirectUrl requires a non-empty string");let t;try{t=new URL(e)}catch{throw Error(`[socials] setRedirectUrl: invalid URL: ${e}`)}if(t.protocol!=="https:"&&t.protocol!=="http:")throw Error(`[socials] setRedirectUrl protocol must be http(s)://, got ${t.protocol}`);return this.redirectUrl=e,this}withState(e){if(typeof e!=="string"||e.length===0)throw Error("[socials] withState requires a non-empty string");return this._state=e,this}resolveState(){return this._state??this.getState()}usesState(){return!this._stateless}validateState(e,t){if(typeof e!=="string"||typeof t!=="string")return!1;if(e.length===0||t.length===0)return!1;if(e.length!==t.length)return!1;try{let{timingSafeEqual:r}=ht("crypto");return r(V.from(e,"utf8"),V.from(t,"utf8"))}catch{let r=0;for(let i=0;i<e.length;i++)r|=e.charCodeAt(i)^t.charCodeAt(i);return r===0}}isStateless(){return this._stateless}stateless(){return this._stateless=!0,this}getState(){let e=new Uint8Array(32);return crypto.getRandomValues(e),Array.from(e).map((t)=>t.toString(16).padStart(2,"0")).join("")}usesPKCE(){return this._usesPKCE}enablePKCE(){return this._usesPKCE=!0,this}getCodeVerifier(){if(this._codeVerifier===null){let e=new Uint8Array(32);crypto.getRandomValues(e),this._codeVerifier=V.from(e).toString("base64url")}return this._codeVerifier}getPkceVerifier(){return this._codeVerifier}withCodeVerifier(e){if(!e)throw Error("A PKCE code verifier must be a non-empty string");return this._usesPKCE=!0,this._codeVerifier=e,this}async pkceFields(){if(!this.usesPKCE())return{};return{code_challenge:await this.getCodeChallenge(),code_challenge_method:this.getCodeChallengeMethod()}}pkceTokenFields(){if(!this.usesPKCE())return{};if(this._codeVerifier===null)throw Error("PKCE is enabled but no code verifier is known for this exchange. Pass the one from getPkceVerifier() back with withCodeVerifier().");return{code_verifier:this._codeVerifier}}async getCodeChallenge(){let t=new TextEncoder().encode(this.getCodeVerifier()),r=await crypto.subtle.digest("SHA-256",t);return V.from(new Uint8Array(r)).toString("base64url")}getCodeChallengeMethod(){return"S256"}with(e){return this.parameters=e,this}async buildAuthUrlFromBase(e,t){let r=new URLSearchParams(await this.getCodeFields(t));return`${e}?${r.toString()}`}}import{Buffer as Ce}from"buffer";import{createPrivateKey as yt,sign as kt}from"crypto";import{config as R}from"@stacksjs/config";class gt extends Error{constructor(e="Invalid state"){super(e);this.name="InvalidStateException"}}class g extends Error{constructor(e){super(e);this.name="ConfigException"}}import{Buffer as ce}from"buffer";var Re=new Map,mt=600000,ft=60000;async function Te(e,t){let r=await fetch(e);if(!r.ok)throw Error(`id_token verification failed: could not fetch signing keys from ${e} (HTTP ${r.status})`);let i=await r.json(),n=Array.isArray(i.keys)?i.keys:[];return Re.set(e,{keys:n,fetchedAt:t}),n}async function wt(e,t,r){let i=Re.get(e),n=i!==void 0&&r-i.fetchedAt<mt,s=n?i.keys:await Te(e,r),o=s.find((a)=>a.kid===t);if(!o&&n&&r-i.fetchedAt>=ft)s=await Te(e,r),o=s.find((a)=>a.kid===t);if(!o)throw Error(`id_token verification failed: no signing key matches kid "${t}"`);if(o.kty!=="RSA")throw Error(`id_token verification failed: signing key "${t}" is ${o.kty}, expected RSA`);return o}function Ae(e,t){try{return JSON.parse(ce.from(e,"base64url").toString("utf8"))}catch{throw Error(`id_token verification failed: ${t} is not valid JSON`)}}async function j(e,t){let r=e.split(".");if(r.length!==3)throw Error("id_token verification failed: malformed token");let[i,n,s]=r,o=Ae(i,"header");if(o.alg!=="RS256")throw Error(`id_token verification failed: unsupported algorithm ${JSON.stringify(o.alg)}, expected RS256`);if(typeof o.kid!=="string"||o.kid==="")throw Error("id_token verification failed: header has no kid");let a=t.now??Date.now(),c=await wt(t.jwksUrl,o.kid,a),u=await crypto.subtle.importKey("jwk",{kty:"RSA",n:c.n,e:c.e,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);if(!await crypto.subtle.verify("RSASSA-PKCS1-v1_5",u,ce.from(s,"base64url"),ce.from(`${i}.${n}`)))throw Error("id_token verification failed: signature does not match the issuer's key");let d=Ae(n,"payload"),p=(t.clockSkewSeconds??60)*1000,h=Array.isArray(t.issuer)?t.issuer:[t.issuer];if(!h.includes(d.iss))throw Error(`id_token verification failed: issuer is ${JSON.stringify(d.iss)}, expected ${h.map((ae)=>JSON.stringify(ae)).join(" or ")}`);let m=Array.isArray(t.audience)?t.audience:[t.audience];if(!(Array.isArray(d.aud)?d.aud:[d.aud]).some((ae)=>m.includes(ae)))throw Error("id_token verification failed: token is addressed to a different client");if(typeof d.exp!=="number"||d.exp*1000+p<=a)throw Error("id_token verification failed: token has expired");if(typeof d.iat==="number"&&d.iat*1000-p>a)throw Error("id_token verification failed: token was issued in the future");if(typeof d.nbf==="number"&&d.nbf*1000-p>a)throw Error("id_token verification failed: token is not valid yet");if(t.nonce!==void 0&&d.nonce!==t.nonce)throw Error("id_token verification failed: nonce does not match");if(typeof d.sub!=="string"||d.sub==="")throw Error("id_token verification failed: token has no subject");return d}class de extends k{baseUrl="https://appleid.apple.com";teamId="";keyId="";privateKey="";native=!1;constructor(e){super(e);this.teamId=e.teamId??"",this.keyId=e.keyId??"",this.privateKey=e.privateKey??"",this.native=e.native===!0}getConfig(){let e={clientId:this.clientId||(R.services.apple?.clientId??""),teamId:this.teamId||(R.services.apple?.teamId??""),keyId:this.keyId||(R.services.apple?.keyId??""),privateKey:(this.privateKey||(R.services.apple?.privateKey??"")).replace(/\\n/g,`
3
- `),redirectUrl:this.native?"":this.redirectUrl||(R.services.apple?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:R.services.apple?.scopes??["name","email"]};return this.setScopes(e.scopes),e}async getAuthUrl(){if(this.native)throw new g("A native Apple provider redeems the app's codes; the web flow needs the Service ID");let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();this.validateConfig();let n={client_id:t,redirect_uri:r,scope:i.join(" "),state:e,response_type:"code",...this.parameters};if(i.length>0)n.response_mode="form_post";return`${this.baseUrl}/auth/authorize?${new URLSearchParams(n).toString()}`}async getAccessToken(e){let{clientId:t,redirectUrl:r}=this.getConfig();this.validateConfig();let i=await fetch(`${this.baseUrl}/auth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,...this.native?{}:{redirect_uri:r},client_id:t,client_secret:this.generateClientSecret()})}),n=await i.json();if(!i.ok||n.error)throw Error(`Apple OAuth error: ${n.error_description??n.error??`HTTP ${i.status}`}`);if(!n.id_token)throw Error("Apple OAuth error: token response contained no id_token");return n.id_token}async getUserByToken(e,t={}){let{clientId:r}=this.getConfig(),i;try{i=await j(e,{jwksUrl:`${this.baseUrl}/auth/keys`,issuer:this.baseUrl,audience:r,nonce:t.nonce})}catch(o){throw Error(`Apple OAuth error: ${o instanceof Error?o.message:String(o)}`)}let n=typeof i.email==="string"?i.email:null,s=null;if(i.email_verified===!0||i.email_verified==="true")s=!0;else if(i.email_verified===!1||i.email_verified==="false")s=!1;return{id:String(i.sub),nickname:null,name:"",email:n,emailVerified:s,avatar:null,token:e,raw:i}}generateClientSecret(){let{clientId:e,teamId:t,keyId:r,privateKey:i}=this.getConfig(),n=Math.floor(Date.now()/1000),s={alg:"ES256",kid:r,typ:"JWT"},o={iss:t,iat:n,exp:n+3600,aud:this.baseUrl,sub:e},a=`${this.base64urlJson(s)}.${this.base64urlJson(o)}`,c;try{c=yt(i)}catch(l){throw new g(`Apple private key could not be parsed: ${l instanceof Error?l.message:String(l)}`)}let u=kt("sha256",Ce.from(a),{key:c,dsaEncoding:"ieee-p1363"});return`${a}.${u.toString("base64url")}`}base64urlJson(e){return Ce.from(JSON.stringify(e)).toString("base64url")}validateConfig(){let{clientId:e,teamId:t,keyId:r,privateKey:i,redirectUrl:n}=this.getConfig();if(!e)throw new g(this.native?"Apple client ID (the app's bundle ID) not provided":"Apple client ID (Service ID) not provided");if(!t)throw new g("Apple team ID not provided");if(!r)throw new g("Apple key ID not provided");if(!i)throw new g("Apple private key not provided");if(!n&&!this.native)throw new g("Apple redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/auth/token`}}import{fetchPublicUrl as Rt}from"@stacksjs/security";import{fetchPublicUrl as bt}from"@stacksjs/security";var St=10485760;function le(e){if(e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255)return"image/jpeg";if(e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71)return"image/png";if(e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56)return"image/gif";if(e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80)return"image/webp";return null}function Ue(e){let t=le(e);if(!t)return;let r=new DataView(e.buffer,e.byteOffset,e.byteLength);if(t==="image/png"&&e.length>=24){let i=r.getUint32(16),n=r.getUint32(20);return i>0&&n>0?{width:i,height:n}:void 0}if(t==="image/gif"&&e.length>=10){let i=r.getUint16(6,!0),n=r.getUint16(8,!0);return i>0&&n>0?{width:i,height:n}:void 0}if(t==="image/webp"&&e.length>=30){let i=String.fromCharCode(e[12],e[13],e[14],e[15]);if(i==="VP8X"&&e.length>=30){let n=1+(e[24]|e[25]<<8|e[26]<<16),s=1+(e[27]|e[28]<<8|e[29]<<16);return n>0&&s>0?{width:n,height:s}:void 0}if(i==="VP8 "&&e.length>=30&&e[23]===157&&e[24]===1&&e[25]===42){let n=r.getUint16(26,!0)&16383,s=r.getUint16(28,!0)&16383;return n>0&&s>0?{width:n,height:s}:void 0}if(i==="VP8L"&&e.length>=25&&e[20]===47){let n=r.getUint32(21,!0),s=(n&16383)+1,o=(n>>14&16383)+1;return s>0&&o>0?{width:s,height:o}:void 0}return}if(t==="image/jpeg"){let i=2;while(i+4<=e.length){if(e[i]!==255)break;while(i<e.length&&e[i]===255)i++;if(i>=e.length)break;let n=e[i];if(i++,n===216||n===217||n===1||n>=208&&n<=215)continue;if(i+2>e.length)break;let s=r.getUint16(i);if(s<2||i+s>e.length)break;if((n>=192&&n<=195||n>=197&&n<=199||n>=201&&n<=203||n>=205&&n<=207)&&s>=7){let a=r.getUint16(i+3),c=r.getUint16(i+5);return c>0&&a>0?{width:c,height:a}:void 0}i+=s}}return}async function C(e,t={}){try{let r=await bt(e,{},{allowHttp:!0,timeoutMs:15000,maxBytes:St,...t});if(!r.ok)return null;let i=new Uint8Array(await r.arrayBuffer()),n=le(i);return n?{bytes:i,mimeType:n}:null}catch{return null}}class Ee extends Error{url;status=422;body="";constructor(e){super(`Could not read the image at ${e}.`);this.url=e;this.name="PostImageError"}}async function U(e,t){if(e.bytes?.length)return{bytes:e.bytes,mimeType:e.mimeType||le(e.bytes)||"image/jpeg"};if(!e.url)return;let r=await t(e.url);if(!r)throw new Ee(e.url);return r}function H(e,t){if(t?.length)throw Error("A video cannot be attached together with images.");if(e.mimeType!=="video/mp4"||!e.bytes.length)throw Error("Attach a non-empty MP4 video.");let r=e.aspectRatio;if(r&&![r.width,r.height].every((i)=>Number.isSafeInteger(i)&&i>0))throw Error("Video width and height must be positive integers.")}function _(e,t){if(e.video)throw Error(`Video publishing to ${t} is unavailable.`)}var ei=23,Pt=/\bhttps?:\/\/[^\s<>]+|(?<![@\w.-])(?:[a-z0-9-]+\.)+(?:com|org|net|io|dev|app|co|social|blog|ai|me|info|xyz|tv|fm|us|uk|de|fr|jp|ca|au|nl|ch|se|no|es|it)\b(?:\/[^\s<>]*)?/gi,vt=/[.,;:!?)\]}'"]+$/,$e;function Le(){return $e??=new Intl.Segmenter(void 0,{granularity:"grapheme"}),$e}function J(e){let t=0;for(let r of Le().segment(e))t++;return t}function Oe(e){let t=[],r=0;for(let i of e.matchAll(Pt)){let n=i[0].replace(vt,"");if(!n)continue;let s=i.index;if(s>r)t.push({link:!1,value:e.slice(r,s)});t.push({link:!0,value:n}),r=s+n.length}if(r<e.length)t.push({link:!1,value:e.slice(r)});return t}function xt(e){return e<=4351||e>=8192&&e<=8205||e>=8208&&e<=8223||e>=8242&&e<=8247}function _t(e){let t=0;for(let{segment:r}of Le().segment(e.normalize("NFC"))){if(/\p{Extended_Pictographic}|\p{Regional_Indicator}/u.test(r)){t+=2;continue}for(let i of r)t+=xt(i.codePointAt(0))?1:2}return t}function It(e,t,r={}){let i=String(t??"");switch(e){case"twitter":return Oe(i).reduce((n,s)=>n+(s.link?23:_t(s.value)),0);case"mastodon":{let n=r.linkLength??23;return Oe(i).reduce((s,o)=>{if(o.link)return s+n;return s+J(o.value.replace(/(^|[^\w/])(@[\w.-]+)@[\w.-]+\.[a-z]{2,}/gi,"$1$2"))},0)}case"bluesky":case"threads":return J(i);default:return i.length}}function S(e,t,r,i={}){return r>0&&It(e,t,i)>r}function G(e){let t;try{t=typeof e==="string"?JSON.parse(e):e}catch{return""}if(!t||typeof t!=="object")return"";let r=Array.isArray(t.errors)?t.errors[0]:void 0,i=[t.detail,t.error?.error_user_msg,t.error?.message,t.message,t.error_description,t.error_message,r?.detail,r?.message,typeof t.error==="string"?t.error:void 0];for(let n of i){let s=typeof n==="string"?n.replace(/\s+/g," ").trim():"";if(s&&s.length<=200&&s.includes(" ")&&!/[{}<>]/.test(s))return s.replace(/[.!]+$/,"")}return""}function Tt(e,t){let r=(i)=>i.test(t);if(e===429||r(/rate.?limit|too many requests|usage cap|throttl|request limit reached/i))return"rate-limited";if(r(/duplicate|already (?:posted|published|exists)|DUPLICATE_POST/i))return"duplicate";if(e===401||r(/invalid.?token|expired.?token|token (?:has )?(?:expired|been revoked)|session has (?:expired|been invalidated)|OAuthException.*(?:expired|invalid)|REVOKED_ACCESS_TOKEN/i))return"expired";if(e===413||r(/media|image|video|attachment|aspect ratio|file size|unsupported (?:format|type)|blob/i))return"media";if(e===403||r(/permission|scope|not (?:allowed|authorized|permitted)|forbidden|ACCESS_DENIED|insufficient/i))return"permission";if(e===408||e>=500)return"temporary";if(e===400||e===404||e===409||e===422)return"content";if(r(/fetch failed|network|ENOTFOUND|ECONNREFUSED|ECONNRESET|EAI_AGAIN|timed? ?out|socket|aborted/i))return"temporary";return"unknown"}function K(e){let t=e??{},r=Number(t.status)||0,i=String(t.message??e??""),n=G(t.body),s=typeof t.body==="string"?t.body.slice(0,2000):"";return{kind:Tt(r,`${n} ${s} ${r?"":i}`),status:r,reason:n}}function ri(e){return K(e).kind==="expired"}class w extends Error{network;status;body;retryAfterMs;constructor(e,t,r,i,n={}){super(t);this.network=e;this.status=r;this.body=i;if(this.name="SocialApiError",n.retryAfterMs!==void 0)this.retryAfterMs=n.retryAfterMs}get kind(){return K(this).kind}get reason(){return G(this.body)}}function Me(e,t){let r=e.trim();if(!r)return;if(/^\d+(?:\.\d+)?$/.test(r)){let n=Number(r);return n>1e9?Math.max(0,Math.round(n*1000-t)):Math.round(n*1000)}let i=Date.parse(r);return Number.isNaN(i)?void 0:Math.max(0,i-t)}function At(e,t){let r=t.now??Date.now(),i=e.get("retry-after");if(i){let s=Me(i,r);if(s!==void 0)return s}if(!t.rateLimited)return;for(let s of["x-rate-limit-reset","ratelimit-reset","x-ratelimit-reset"]){let o=e.get(s),a=o?Me(o,r):void 0;if(a!==void 0)return a}let n=0;for(let s of["x-business-use-case-usage","x-app-usage"]){let o=e.get(s);if(!o)continue;try{let a=JSON.parse(o),c=Array.isArray(a)?a:Object.values(a??{}).flat();for(let u of[a,...c]){let l=Number(u?.estimated_time_to_regain_access);if(Number.isFinite(l)&&l>n)n=l}}catch{}}return n>0?n*60000:void 0}function f(e,t,r){let i=G(r)||t.statusText||"no reason given",n=At(t.headers,{rateLimited:K({status:t.status,body:r}).kind==="rate-limited"});return[`${e} failed (${t.status}): ${i}`,t.status,r,n===void 0?{}:{retryAfterMs:n}]}var E="app.bsky.feed.post";function pe(e){let t=/^at:\/\/([^/]+)\/([^/]+)\/([^/]+)$/.exec(String(e||"").trim());if(!t)throw Error(`"${e}" is not a Bluesky post URI.`);return{repo:t[1],collection:t[2],rkey:t[3]}}class O extends w{constructor(e,t,r,i={}){super("bluesky",e,t,r,i);this.name="BlueskyApiError"}get isAuthError(){if(this.status===401||this.status===403)return!0;if(this.status!==400)return!1;try{return Ct.includes(String(JSON.parse(this.body)?.error))}catch{return!1}}}var Ct=["ExpiredToken","InvalidToken"],Be=1e6,De=300000000,Ne="https://video.bsky.app",Ut=90000;function Ve(e,t){if(e?.id!==t)return;let r=e.service?.find((n)=>(n?.id==="#atproto_pds"||n?.id===`${t}#atproto_pds`)&&n.type==="AtprotoPersonalDataServer"),i=typeof r?.serviceEndpoint==="string"?URL.parse(r.serviceEndpoint):null;if(!i||i.protocol!=="https:"||i.username||i.password||i.search||i.hash)return;return i.href.replace(/\/+$/,"")}var Et=4,$t=3,ze=200;function li(e){return e instanceof O&&e.isAuthError}var Ot=new TextEncoder;function I(e){return Ot.encode(e).length}function Lt(e){let t=e;while(t.length>0){let r=t[t.length-1];if(r===")"||r==="]"){let i=r===")"?"(":"[",n=0;for(let s of t)if(s===i)n++;else if(s===r)n--;if(n>=0)break;t=t.slice(0,-1);continue}if(/[.,;!?:'"\u201D\u2019]/.test(r)){t=t.slice(0,-1);continue}break}return t}function Mt(e){let t=[],r=/https?:\/\/[^\s<>"']+/g;for(let o of e.matchAll(r)){let a=Lt(o[0]);if(!a)continue;t.push({byteStart:I(e.slice(0,o.index)),byteEnd:I(e.slice(0,o.index))+I(a),type:"link",value:a})}let i=(o,a)=>t.some((c)=>c.type==="link"&&o<c.byteEnd&&a>c.byteStart),n=/(^|[\s(["'\u201C\u2018])([#\uFF03])([^\s\u00AD\u2060\u200A-\u200D\u20E2]+)/gu;for(let o of e.matchAll(n)){let a=o[1],c=o[2],u=o[3];if(a===void 0||c===void 0||u===void 0)continue;let l=u.replace(/\p{P}+$/u,"");if(!l||!/[^\d\p{P}]/u.test(l)||[...l].length>64)continue;let d=(o.index??0)+a.length,p=I(e.slice(0,d)),h=p+I(c+l);if(i(p,h))continue;t.push({byteStart:p,byteEnd:h,type:"tag",value:l})}let s=/(^|[\s(["'\u201C\u2018])(@[a-z0-9][a-z0-9.-]*\.[a-z]{2,})/gi;for(let o of e.matchAll(s)){let a=o[1],c=o[2];if(a===void 0||c===void 0)continue;let u=(o.index??0)+a.length,l=I(e.slice(0,u)),d=l+I(c);if(i(l,d))continue;t.push({byteStart:l,byteEnd:d,type:"mention",value:c.slice(1).replace(/\.+$/,"")})}return t.sort((o,a)=>o.byteStart-a.byteStart)}async function qe(e,t={}){let r=(t.entryway??"https://bsky.social").replace(/\/+$/,""),i=(t.directory??"https://plc.directory").replace(/\/+$/,""),n=t.fetchJson??(async(s)=>{let a=s.startsWith(`${r}/`)||s.startsWith(`${i}/`)?await fetch(s,{redirect:"error",signal:AbortSignal.timeout(1e4)}):await Rt(s,{},{maxRedirects:0,timeoutMs:1e4,maxBytes:262144});if(!a.ok)throw Error(`${a.status}`);return await a.json()});try{let s=e.trim(),o=s.startsWith("did:")?void 0:s.replace(/^@/,"").toLowerCase();if(o!==void 0){let l=await n(`${r}/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(o)}`);if(typeof l?.did!=="string")return;s=l.did}let a;if(/^did:plc:[a-z0-9]+$/i.test(s))a=`${i}/${s}`;else if(/^did:web:[a-z0-9.-]+$/i.test(s))a=`https://${s.slice(8)}/.well-known/did.json`;else return;let c=await n(a),u=c?.alsoKnownAs?.find((l)=>typeof l==="string"&&l.startsWith("at://"));if(o!==void 0&&u!==`at://${o}`)return;return Ve(c,s)}catch{return}}var D=/^did:[a-z]+:[A-Za-z0-9._:%-]+$/,Bt=/^[A-Za-z0-9._:~-]{1,512}$/,ue=/^[A-Za-z0-9]{1,256}$/;function Fe(e){let t,r;if(e.startsWith("at://")){let i=pe(e);if(i.collection===E)({repo:t,rkey:r}=i)}else{let i=URL.parse(e);if(i?.origin==="https://bsky.app"&&!i.username&&!i.password){let[,n,s]=/^\/profile\/([^/]+)\/post\/([^/]+)\/?$/.exec(i.pathname)??[];try{if(n&&s)t=decodeURIComponent(n),r=decodeURIComponent(s)}catch{}}}if(!t||!D.test(t)&&!/^(?:[A-Za-z0-9-]+\.)+[A-Za-z]+$/.test(t)||!r||!Bt.test(r)||r==="."||r==="..")throw Error("Choose a valid Bluesky post link.");return{repo:t,rkey:r}}function Dt(e){if(!Array.isArray(e)||e.some((r)=>typeof r!=="string"||r.length>128||!/^!?[a-z]+(?:-[a-z]+)*$/.test(r)))throw Error("Bluesky content labels must be lowercase label names.");let t=[...new Set(e)].map((r)=>({val:r}));if(t.length>10)throw Error("Bluesky supports up to 10 self-labels per post.");return t}var Nt="234567abcdefghijklmnopqrstuvwxyz";function ui(e=Date.now(),t=Math.floor(Math.random()*1024)){let r=BigInt(Math.floor(e))*1000n<<10n|BigInt(t&1023),i="";for(let n=0;n<13;n++)i=Nt[Number(r&31n)]+i,r>>=5n;return i}class X{provider="bluesky";characterLimit=300;service;configuredService;fetcher;constructor(e={}){this.service=e.service||"https://bsky.social",this.configuredService=Boolean(e.service),this.fetcher=e.fetcher}async createSession(e){let t=e.identifier.trim(),r=e.password.trim();if(!t)throw Error("Bluesky identifier is required.");if(!r)throw Error("Bluesky app password is required.");let i=await this.signIn(t,r),n=await this.getProfile({did:i.did,handle:i.handle,accessToken:i.accessJwt,refreshToken:i.refreshJwt}).catch(()=>{return});return{did:i.did,handle:i.handle,displayName:n?.displayName,accessJwt:i.accessJwt,refreshJwt:i.refreshJwt,service:this.service}}async signIn(e,t){let r=()=>this.post("/xrpc/com.atproto.server.createSession",{identifier:e,password:t});try{return await r()}catch(i){if(!(i instanceof O&&(i.status===400||i.status===401))||this.configuredService)throw i;let s=await qe(e,{entryway:this.service});if(!s||s===this.service)throw i;return this.service=s,await r()}}async refreshSession(e){if(!e)throw Error("Bluesky refresh token is required.");let t=await this.post("/xrpc/com.atproto.server.refreshSession",void 0,{authorization:`Bearer ${e}`});return{did:t.did,handle:t.handle,accessJwt:t.accessJwt,refreshJwt:t.refreshJwt}}async resolveQuote(e,t){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let{repo:r,rkey:i}=Fe(t.trim()),n=D.test(r)?r:await this.resolveHandle(r);if(!n||!D.test(n))throw Error("Could not resolve the author of this Bluesky post.");let s=`at://${n}/${E}/${i}`,o=new URL(`${this.service}/xrpc/app.bsky.feed.getPosts`);o.searchParams.set("uris",s);let c=(await this.request(o,{headers:{authorization:`Bearer ${e.accessToken}`},redirect:"error",signal:AbortSignal.timeout(15000)})).posts?.find((u)=>u.uri===s);if(!c||typeof c.cid!=="string"||!ue.test(c.cid))throw Error("Could not find the Bluesky post at this link.");if(c.viewer?.embeddingDisabled)throw Error("The author has disabled quoting this Bluesky post.");return{uri:s,cid:c.cid}}async publish(e,t,r={}){let i=e.did||e.handle;if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(!i)throw Error("Bluesky identity DID or handle is required.");if(S("bluesky",t.text,this.characterLimit))throw Error(`Bluesky posts must be ${this.characterLimit} characters or fewer.`);if(t.video){if(H(t.video,t.media),t.video.bytes.length>De)throw Error("Bluesky video must be 300 MB or smaller.")}let n=r.quote;if(n){let d=Fe(n.uri);if(n.uri!==`at://${d.repo}/${E}/${d.rkey}`||!D.test(d.repo)||typeof n.cid!=="string"||!ue.test(n.cid))throw Error("Resolve the Bluesky post before quoting it.")}let s=r.selfLabels===void 0?[]:Dt(r.selfLabels),o={$type:"app.bsky.feed.post",text:t.text,createdAt:t.scheduledAt||new Date().toISOString()};if(t.langs?.length)o.langs=t.langs.slice(0,$t);if(t.reply)o.reply=t.reply;if(s.length)o.labels={$type:"com.atproto.label.defs#selfLabels",values:s};let a=t.facets??await this.buildFacets(t.text);if(a.length)o.facets=a;let c=[],u=(t.media||[]).filter((d)=>d.bytes?.length).slice(0,Et);if(t.video){if(o.embed={$type:"app.bsky.embed.video",video:await this.uploadVideo(e,t.video),...t.video.altText&&{alt:t.video.altText},...t.video.aspectRatio&&{aspectRatio:t.video.aspectRatio}},t.external)c.push("A Bluesky post holds one attachment, so the video went out and the link card did not. The link in the text still works.")}else if(u.length){let d=[];for(let p of u){let h=await this.uploadBlob(e,p.bytes,p.mimeType||"image/jpeg"),m=Ue(p.bytes);d.push({image:h,alt:p.altText||"",...m?{aspectRatio:m}:{}})}if(o.embed={$type:"app.bsky.embed.images",images:d},t.external)c.push("A Bluesky post holds one attachment, so the images went out and the link card did not. The link in the text still works.")}else if(t.external){let d={uri:t.external.uri,title:t.external.title,description:t.external.description||""},p=t.external.thumb;if(p?.bytes?.length)if(p.bytes.length>Be)c.push("The link card's picture is larger than Bluesky takes, so the card went out without it.");else try{d.thumb=await this.uploadBlob(e,p.bytes,p.mimeType)}catch{c.push("Bluesky did not take the link card's picture, so the card went out without it.")}o.embed={$type:"app.bsky.embed.external",external:d}}if(n){let d={$type:"app.bsky.embed.record",record:{uri:n.uri,cid:n.cid}};o.embed=o.embed?{$type:"app.bsky.embed.recordWithMedia",record:d,media:o.embed}:d}let l=await this.createPostRecord(e,i,o,r.rkey);return{provider:this.provider,uri:l.uri,cid:l.cid,url:this.toPostUrl(e.handle,l.uri),...c.length?{warnings:c}:{}}}async metrics(e,t){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let r=[];for(let i=0;i<t.length;i+=25){let n=new URL(`${this.service}/xrpc/app.bsky.feed.getPosts`);for(let o of t.slice(i,i+25))n.searchParams.append("uris",o);let s=await this.request(n,{headers:{authorization:`Bearer ${e.accessToken}`}});for(let o of s.posts||[])r.push({uri:o.uri,likes:o.likeCount??0,reposts:o.repostCount??0,replies:o.replyCount??0,quotes:o.quoteCount??0})}return r}async postMetrics(e,t){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(t.length===0)return[];let r=new URL(`${this.service}/xrpc/app.bsky.feed.getPosts`);for(let n of t.slice(0,25))r.searchParams.append("uris",n);return((await this.request(r,{headers:{authorization:`Bearer ${e.accessToken}`}})).posts||[]).map((n)=>({uri:n.uri,likeCount:n.likeCount||0,repostCount:n.repostCount||0,replyCount:n.replyCount||0}))}async timeline(e,t={}){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let r=new URL(`${this.service}/xrpc/app.bsky.feed.getTimeline`);if(r.searchParams.set("limit",String(Math.min(Math.max(t.limit||30,1),100))),t.cursor)r.searchParams.set("cursor",t.cursor);let i=await this.request(r,{headers:{authorization:`Bearer ${e.accessToken}`}});return{cursor:i.cursor,items:(i.feed||[]).flatMap((n)=>{let s=n.post;if(!s?.uri||!s.author?.handle)return[];return[{uri:s.uri,authorHandle:s.author.handle,authorName:s.author.displayName,authorAvatar:s.author.avatar,postUrl:this.toPostUrl(s.author.handle,s.uri),body:s.record?.text||"",postedAt:s.record?.createdAt||new Date().toISOString(),likeCount:s.likeCount||0,repostCount:s.repostCount||0,replyCount:s.replyCount||0}]})}}async getProfile(e){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let t=e.did||e.handle;if(!t)throw Error("Bluesky identity DID or handle is required.");let r=new URL(`${this.service}/xrpc/app.bsky.actor.getProfile`);return r.searchParams.set("actor",t),await this.request(r,{headers:{authorization:`Bearer ${e.accessToken}`}})}async buildFacets(e){let t=[];for(let r of Mt(e)){let i=null;if(r.type==="link")i={$type:"app.bsky.richtext.facet#link",uri:r.value};else if(r.type==="tag")i={$type:"app.bsky.richtext.facet#tag",tag:r.value};else if(r.type==="mention"){let n=await this.resolveHandle(r.value);if(n)i={$type:"app.bsky.richtext.facet#mention",did:n}}if(i)t.push({index:{byteStart:r.byteStart,byteEnd:r.byteEnd},features:[i]})}return t}async resolveHandle(e){try{let t=new URL(`${this.service}/xrpc/com.atproto.identity.resolveHandle`);return t.searchParams.set("handle",e),(await this.request(t,{})).did||null}catch{return null}}async uploadVideo(e,t){let r={authorization:`Bearer ${e.accessToken}`},i=await this.request(new URL(`${this.service}/xrpc/com.atproto.server.getSession`),{headers:r,signal:AbortSignal.timeout(15000)});if(!D.test(i.did)||e.did&&i.did!==e.did)throw Error("Bluesky could not verify the account for this video.");let n=Ve(i.didDoc,i.did)??await qe(i.did);if(!n)throw Error("Bluesky could not find the account\u2019s data server for this video.");let s=new URL(`${this.service}/xrpc/com.atproto.server.getServiceAuth`);s.searchParams.set("aud",`did:web:${new URL(n).host.replace(":","%3A")}`),s.searchParams.set("lxm","com.atproto.repo.uploadBlob"),s.searchParams.set("exp",String(Math.floor(Date.now()/1000)+1800));let{token:o}=await this.request(s,{headers:r,signal:AbortSignal.timeout(15000)});if(typeof o!=="string"||!o)throw Error("Bluesky did not authorize the video upload.");let a=new URL("/xrpc/app.bsky.video.uploadVideo",Ne);a.searchParams.set("did",i.did),a.searchParams.set("name","upload.mp4");let c=await(this.fetcher??fetch)(a,{method:"POST",headers:{authorization:`Bearer ${o}`,"content-type":t.mimeType,"content-length":String(t.bytes.length)},body:new Uint8Array(t.bytes),redirect:"error",signal:AbortSignal.timeout(120000)}),u=await c.text(),l;try{l=JSON.parse(u)}catch{}let d=l?.jobStatus??l??{};if(d.error==="unconfirmed_email")throw Error("Verify your Bluesky account email before uploading video.");if(!c.ok&&!(c.status===409&&d.error==="already_exists"))throw new w("bluesky",...f("Bluesky video service",c,u));if(d.did!==i.did||typeof d.jobId!=="string"||!d.jobId||d.jobId.length>200)throw Error("Bluesky did not return a video processing job for this account.");let p=new URL("/xrpc/app.bsky.video.getJobStatus",Ne);p.searchParams.set("jobId",d.jobId);let h=AbortSignal.timeout(Ut);for(;;){let m=d.blob;if(m){if(m.$type!=="blob"||m.mimeType!==t.mimeType||typeof m.ref?.$link!=="string"||!ue.test(m.ref.$link)||typeof m.size!=="number"||!Number.isSafeInteger(m.size)||m.size<=0||m.size>De)throw Error("Bluesky did not return a valid processed video attachment.");return m}if(d.state==="JOB_STATE_FAILED")throw new w("bluesky",d.message||"Bluesky could not process the video.",422,JSON.stringify({message:d.message,error:d.failureCode}));if(h.aborted)throw new O("Bluesky took too long to process the attachment.",503,"");let A=await this.request(p,{signal:h});if(A.jobStatus?.jobId!==d.jobId||A.jobStatus?.did!==i.did)throw Error("Bluesky returned a different video processing job.");if(d=A.jobStatus,!d.blob&&d.state!=="JOB_STATE_FAILED")await Bun.sleep(1000)}}async uploadBlob(e,t,r){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(t.length>Be)throw Error("Bluesky images must be 1MB or smaller.");return(await this.request(new URL(`${this.service}/xrpc/com.atproto.repo.uploadBlob`),{method:"POST",headers:{"content-type":r,authorization:`Bearer ${e.accessToken}`},body:new Uint8Array(t)})).blob}async listAuthoredPosts(e,t={}){let r=e.did||e.handle;if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(!r)throw Error("Bluesky identity DID or handle is required.");let i=new URL(`${this.service}/xrpc/com.atproto.repo.listRecords`);if(i.searchParams.set("repo",r),i.searchParams.set("collection",E),i.searchParams.set("limit",String(Math.min(Math.max(t.limit||100,1),100))),t.cursor)i.searchParams.set("cursor",t.cursor);let n=await this.request(i,{headers:{authorization:`Bearer ${e.accessToken}`}});return{cursor:n.cursor,posts:(n.records||[]).filter((s)=>s?.uri).map((s)=>({uri:s.uri,cid:s.cid,text:s.value?.text,postedAt:s.value?.createdAt,url:e.handle?this.toPostUrl(e.handle,s.uri):void 0}))}}async createPostRecord(e,t,r,i){let n=`Bearer ${e.accessToken}`;try{return await this.post("/xrpc/com.atproto.repo.createRecord",{repo:t,collection:E,...i?{rkey:i}:{},record:r},{authorization:n})}catch(s){if(!i||!(s instanceof O)||s.status>=500)throw s;let o=new URL(`${this.service}/xrpc/com.atproto.repo.getRecord`);o.searchParams.set("repo",t),o.searchParams.set("collection",E),o.searchParams.set("rkey",i);let a=await this.request(o,{headers:{authorization:n}}).catch(()=>{return});if(a?.uri&&a.cid&&a.value?.text===r.text)return{uri:a.uri,cid:a.cid};throw s}}async deletePost(e,t){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let{repo:r,collection:i,rkey:n}=pe(t.uri);await this.post("/xrpc/com.atproto.repo.deleteRecord",{repo:r,collection:i,rkey:n},{authorization:`Bearer ${e.accessToken}`})}async deletePosts(e,t){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(!t.length)return;let r=new Map;for(let n of t){let{repo:s,collection:o,rkey:a}=pe(n.uri),c=r.get(s)??[];c.push({collection:o,rkey:a}),r.set(s,c)}let i={authorization:`Bearer ${e.accessToken}`};for(let[n,s]of r)for(let o=0;o<s.length;o+=ze){let a=s.slice(o,o+ze);await this.post("/xrpc/com.atproto.repo.applyWrites",{repo:n,writes:a.map(({collection:c,rkey:u})=>({$type:"com.atproto.repo.applyWrites#delete",collection:c,rkey:u}))},i)}}async post(e,t,r={}){return await this.request(new URL(`${this.service}${e}`),{method:"POST",headers:{...t===void 0?{}:{"content-type":"application/json"},...r},...t===void 0?{}:{body:JSON.stringify(t)}})}async request(e,t){let r=await(this.fetcher??fetch)(e,{...t,redirect:"error",signal:t.signal??AbortSignal.timeout(30000)}),i=await r.text();if(!r.ok)throw new O(...f("Bluesky API",r,i));return i?JSON.parse(i):{}}toPostUrl(e,t){let r=t.split("/").pop();return`https://bsky.app/profile/${e}/post/${r}`}}import{fetcher as je}from"@stacksjs/api";import{config as N}from"@stacksjs/config";var Q="v24.0";function W(e){try{let t=JSON.parse(String(e?.body??""));return t.error?.code===100&&/does not exist/i.test(String(t.error.message))}catch{return!1}}class he extends k{baseUrl="https://www.facebook.com";apiUrl="https://graph.facebook.com";get graphVersion(){return N.services.facebook?.graphVersion??Q}getConfig(){let e={clientId:this.clientId||(N.services.facebook?.clientId??""),clientSecret:this.clientSecret||(N.services.facebook?.clientSecret??""),redirectUrl:this.redirectUrl||(N.services.facebook?.redirectUrl??""),scopes:N.services.facebook?.scopes??["email","public_profile"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/${this.graphVersion}/dialog/oauth?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(","),response_type:"code",...await this.pkceFields(),...this.parameters,state:e}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let n=await je.get(`${this.apiUrl}/${this.graphVersion}/oauth/access_token?${new URLSearchParams({client_id:t,client_secret:r,redirect_uri:i,code:e,...this.pkceTokenFields()}).toString()}`);if(n.data.error)throw Error(`Facebook OAuth error: ${n.data.error.message}`);return n.data.access_token}async getUserByToken(e){let t=await je.withHeaders({Authorization:`Bearer ${e}`}).get(`${this.apiUrl}/${this.graphVersion}/me?${new URLSearchParams({fields:"id,name,email,picture"}).toString()}`);return{id:t.data.id,nickname:null,name:t.data.name,email:t.data.email??null,avatar:t.data.picture?.data.url??null,token:e,raw:t.data}}validateConfig(){let{clientId:e,clientSecret:t,redirectUrl:r}=this.getConfig();if(!e)throw new g("Facebook client ID not provided");if(!t)throw new g("Facebook client secret not provided");if(!r)throw new g("Facebook redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/${this.graphVersion}/oauth/access_token`}}import{fetcher as ge}from"@stacksjs/api";import{config as Y}from"@stacksjs/config";class me extends k{baseUrl="https://github.com";apiUrl="https://api.github.com";getConfig(){let e={clientId:this.clientId||(Y.services.github?.clientId??""),clientSecret:this.clientSecret||(Y.services.github?.clientSecret??""),redirectUrl:this.redirectUrl||(Y.services.github?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:Y.services.github?.scopes??["read:user","user:email"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/login/oauth/authorize?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(" "),state:e,response_type:"code",...await this.pkceFields(),...this.parameters}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let n=await ge.post(`${this.baseUrl}/login/oauth/access_token`,{client_id:t,client_secret:r,code:e,redirect_uri:i,...this.pkceTokenFields()});if(n.data.error)throw Error(`GitHub OAuth error: ${n.data.error_description}`);return n.data.access_token}async getUserByToken(e){let[t,r]=await Promise.all([ge.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${e}`}).get(`${this.apiUrl}/user`),ge.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${e}`}).get(`${this.apiUrl}/user/emails`)]),i=this.pickEmail(r.data);return{id:t.data.id.toString(),nickname:t.data.login,name:t.data.name??t.data.login,email:i?.email??t.data.email??null,emailVerified:i?i.verified:null,avatar:t.data.avatar_url,token:e,raw:t.data}}pickEmail(e){if(!Array.isArray(e)||e.length===0)return null;let t=e.find((i)=>i.primary&&i.verified),r=e.find((i)=>i.verified);return t??r??e.find((i)=>i.primary)??e[0]??null}getEmail(e){return this.pickEmail(e)?.email??null}validateConfig(){let{clientId:e,clientSecret:t,redirectUrl:r}=this.getConfig();if(!e)throw new g("GitHub client ID not provided");if(!t)throw new g("GitHub client secret not provided");if(!r)throw new g("GitHub redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/login/oauth/access_token`}}import{fetcher as He}from"@stacksjs/api";import{config as Z}from"@stacksjs/config";class fe extends k{baseUrl="https://accounts.google.com";apiUrl="https://www.googleapis.com";tokenUrl="https://oauth2.googleapis.com/token";tokenInfoUrl="https://oauth2.googleapis.com/tokeninfo";certsUrl="https://www.googleapis.com/oauth2/v3/certs";issuers=["https://accounts.google.com","accounts.google.com"];getConfig(){let e={clientId:this.clientId||(Z.services.google?.clientId??""),clientSecret:this.clientSecret||(Z.services.google?.clientSecret??""),redirectUrl:this.redirectUrl||(Z.services.google?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:Z.services.google?.scopes??["openid","email"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/o/oauth2/v2/auth?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(" "),state:e,response_type:"code",access_type:"offline",prompt:"consent",...await this.pkceFields(),...this.parameters}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let n=await He.post(this.tokenUrl,{client_id:t,client_secret:r,code:e,redirect_uri:i,grant_type:"authorization_code",...this.pkceTokenFields()});if(n.data.error)throw Error(`Google OAuth error: ${n.data.error_description}`);return n.data.access_token}async getUserByToken(e){await this.assertTokenWasIssuedToUs(e);let t=await He.withHeaders({Authorization:`Bearer ${e}`}).get(`${this.apiUrl}/oauth2/v2/userinfo`);return{id:t.data.id,nickname:t.data.given_name,name:t.data.name,email:t.data.email,emailVerified:typeof t.data.verified_email==="boolean"?t.data.verified_email:null,avatar:t.data.picture,token:e,raw:t.data}}async getUserByIdToken(e,t={}){let{clientId:r}=this.getConfig(),i;try{i=await j(e,{jwksUrl:this.certsUrl,issuer:this.issuers,audience:r,nonce:t.nonce})}catch(s){throw Error(`Google OAuth error: ${s instanceof Error?s.message:String(s)}`)}let n=typeof i.email==="string"?i.email:"";return{id:String(i.sub),nickname:typeof i.given_name==="string"?i.given_name:null,name:typeof i.name==="string"?i.name:"",email:n,emailVerified:typeof i.email_verified==="boolean"?i.email_verified:i.email_verified==="true"?!0:i.email_verified==="false"?!1:null,avatar:typeof i.picture==="string"?i.picture:null,token:e,raw:i}}async assertTokenWasIssuedToUs(e){let{clientId:t}=this.getConfig(),r=await fetch(`${this.tokenInfoUrl}?access_token=${encodeURIComponent(e)}`);if(!r.ok)throw Error(`Google OAuth error: access token was not accepted by tokeninfo (HTTP ${r.status})`);let i=await r.json();if(i.error)throw Error(`Google OAuth error: ${i.error_description??i.error}`);let n=i.aud??i.audience;if(!n)throw Error("Google OAuth error: tokeninfo did not report an audience for the access token");if(n!==t)throw Error("Google OAuth error: access token was issued to a different client")}validateConfig(){let{clientId:e,clientSecret:t,redirectUrl:r}=this.getConfig();if(!e)throw new g("Google client ID not provided");if(!t)throw new g("Google client secret not provided");if(!r)throw new g("Google redirect URL not provided")}getTokenUrl(){return this.tokenUrl}}var zt=10,qt=1000,Ft=20,Je={likes:"likes",comments:"replies",shares:"shares",saved:"saves",reach:"reach",views:"views"};class b extends w{constructor(e,t,r,i={}){super("instagram",e,t,r,i);this.name="InstagramApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class we{provider="instagram";characterLimit=2200;maxImages=zt;containerTimeoutMs=300000;graphVersion;authBase;graphBase;constructor(e={}){this.graphVersion=e.graphVersion||Q,this.authBase=e.authBase||"https://www.facebook.com",this.graphBase=e.graphBase||"https://graph.facebook.com"}getAuthUrl(e){let t=new URLSearchParams({client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(","),state:e.state,response_type:"code"});return`${this.authBase}/${this.graphVersion}/dialog/oauth?${t.toString()}`}async exchangeCode(e){let t=await this.graph("/oauth/access_token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,redirect_uri:e.redirectUrl,code:e.code}).toString()});if(!t.access_token)throw new b("Facebook did not return an access token.",400,JSON.stringify(t));return{accessToken:t.access_token,expiresIn:t.expires_in}}async resolveAccount(e){for await(let t of this.pageAccounts(e))return{igUserId:t.igUserId,username:t.username,pageAccessToken:t.pageAccessToken};throw new b("No Instagram Business account is linked to your Facebook Pages.",400,"")}async listAccounts(e){let t=new Map;for await(let r of this.pageAccounts(e))if(r.pageId&&!t.has(r.pageId))t.set(r.pageId,{...r,pageId:r.pageId});return[...t.values()]}async*pageAccounts(e){let r=`/me/accounts?${new URLSearchParams({fields:"id,name,access_token,instagram_business_account{id,username}"}).toString()}`;for(let i=0;r&&i<Ft;i++){let n=await this.graph(r,{method:"GET"},e);for(let s of n.data??[]){let o=s.instagram_business_account;if(o?.id&&s.access_token)yield{pageId:s.id,pageName:s.name,igUserId:o.id,username:o.username,pageAccessToken:s.access_token}}r=n.paging?.next}}async exchangeLongLivedUserToken(e,t,r){let i=await this.graph("/oauth/access_token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"fb_exchange_token",client_id:e,client_secret:t,fb_exchange_token:r}).toString()});if(!i.access_token)throw new b("Facebook did not return a long-lived token.",400,JSON.stringify(i));return{accessToken:i.access_token,expiresIn:i.expires_in}}async publish(e,t){if(_(t,"Instagram"),!e.accessToken)throw Error("Instagram access token is missing for this identity.");let r=e.did;if(!r)throw Error("Instagram account id is required to publish.");let i=(t.media??[]).slice(0,this.maxImages);if(!i.length)throw Error("Instagram requires an image to post.");if(i.some((l)=>!l.url))throw new b("Instagram fetches images from a public address, and this image has none.",422,"");if(i.some((l)=>l.mimeType&&!/^image\/jpe?g$/i.test(l.mimeType)))throw new b("Instagram only publishes JPEG images, and this image is not one.",422,"");if(S("instagram",t.text,this.characterLimit))throw Error(`Instagram captions must be ${this.characterLimit} characters or fewer.`);let n=e.accessToken,s=async(l)=>{let d=await this.graph(`/${r}/media`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(l).toString()},n);if(!d.id)throw new b("Instagram did not return a media container id.",400,JSON.stringify(d));return d.id},o=(l)=>({image_url:l.url,...l.altText?.trim()?{alt_text:l.altText.trim().slice(0,qt)}:{}}),a;if(i.length>1){let l=[];for(let d of i)l.push(await s({...o(d),is_carousel_item:"true"}));a=await s({media_type:"CAROUSEL",children:l.join(","),caption:t.text})}else a=await s({...o(i[0]),caption:t.text});await this.waitForContainer(a,n);let c=await this.graph(`/${r}/media_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:a}).toString()},n);if(!c.id)throw new b("Instagram did not return a published post id.",400,JSON.stringify(c));let u=await this.graph(`/${c.id}?fields=permalink`,{method:"GET"},n).catch(()=>{return});return{provider:this.provider,uri:c.id,url:u?.permalink}}async createComment(e,t,r){let i=e.accessToken;if(!i)throw Error("Instagram access token is missing for this identity.");let n=t.trim();if(!/^[0-9]{1,32}$/.test(n))throw Error("An Instagram published media ID is required to comment.");let s=r.trim();if(!s)throw Error("Instagram comment text is required.");let o=await this.graph(`/${n}/comments?${new URLSearchParams({message:s})}`,{method:"POST",redirect:"error",signal:AbortSignal.timeout(15000)},i);return typeof o?.id==="string"&&/^[0-9]{1,32}$/.test(o.id)?o.id:null}async waitForContainer(e,t){let r=0,i=1000;for(;;){let n=await this.graph(`/${e}?fields=status_code,status`,{method:"GET"},t),s=n.status_code;if(s==="FINISHED"||s==="PUBLISHED"||s===void 0)return;if(s==="ERROR"||s==="EXPIRED")throw new b(`Instagram could not prepare this post (${s}${n.status?`: ${n.status}`:""}).`,422,JSON.stringify(n));if(r>=this.containerTimeoutMs)throw new b(`Instagram was still processing this post after ${Math.round(r/1000)} seconds, so it was not published.`,504,JSON.stringify(n));let o=Math.min(i,60000,Math.max(this.containerTimeoutMs-r,0));await this.sleep(o),r+=o,i*=2}}sleep(e){return new Promise((t)=>setTimeout(t,e))}async timeline(e,t={}){return{items:[]}}async metrics(e,t){let r=e.accessToken;if(!r)throw Error("Instagram access token is missing for this identity.");let i=[];for(let n of t){let s=String(n||"").trim();if(!s)continue;let o;try{o=await this.graph(`/${encodeURIComponent(s)}/insights?metric=${Object.keys(Je).join(",")}`,{method:"GET"},r)}catch(c){if(c instanceof b&&W(c))continue;throw c}let a={uri:n};for(let c of o.data||[]){let u=Je[String(c.name)],l=Number(c.values?.[0]?.value);if(u&&Number.isFinite(l))a[u]=l}i.push(a)}return i}graphUrl(e){if(!/^https?:\/\//i.test(e))return`${this.graphBase}/${this.graphVersion}${e}`;let t=new URL(e);if(t.origin!==new URL(this.graphBase).origin||t.username||t.password)throw new b("Instagram returned a paging address on another host, so it was not followed.",502,"");return t.searchParams.delete("access_token"),t.href}async graph(e,t,r){let i=new Headers(t.headers);if(r)i.set("authorization",`Bearer ${r}`);let n=await fetch(this.graphUrl(e),{...t,headers:i,signal:t.signal??AbortSignal.timeout(30000)}),s=await n.text(),o={};try{o=s?JSON.parse(s):{}}catch{o={}}if(!n.ok||o?.error)throw new b(...f("Instagram API",n,s));return o}}function Ge(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ee(){let e=Ge(crypto.getRandomValues(new Uint8Array(32))),t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return{codeVerifier:e,codeChallenge:Ge(new Uint8Array(t))}}var Ke="202611";function Vt(e){let t=Number(e.slice(0,4)),r=Number(e.slice(4,6));return new Date(Date.UTC(t+1,r-1,15))}function jt(e,t=Date.now()){let r=String(e??"").trim();if(!/^\d{6}$/.test(r))return Ke;return Vt(r).getTime()>t?r:Ke}var Ht=20,Jt=4086,Gt=["ADMINISTRATOR","DIRECT_SPONSORED_CONTENT_POSTER","CONTENT_ADMINISTRATOR","CONTENT_ADMIN"],T="2.0.0";class y extends w{constructor(e,t,r,i={}){super("linkedin",e,t,r,i);this.name="LinkedInApiError"}get isAuthError(){return this.status===401||this.status===403}}function Xe(e){return new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(" "),state:e.state})}function Qe(e){let t=/^https?:\/\/(?:127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?]|$)/i,r=URL.parse(e);if(!r||r.port==="0"||!t.test(e)||/[\s#\\]/.test(e))throw Error("LinkedIn native OAuth requires an HTTP or HTTPS loopback redirect on 127.0.0.1 or [::1].")}class ye{provider="linkedin";characterLimit=3000;maxImages=Ht;fetchImage=C;organizationPageSize=100;apiVersion;authBase;apiBase;constructor(e={}){this.apiVersion=jt(e.apiVersion),this.authBase=e.authBase||"https://www.linkedin.com",this.apiBase=e.apiBase||"https://api.linkedin.com"}getAuthUrl(e){return`${this.authBase}/oauth/v2/authorization?${Xe(e)}`}async createNativeAuthorization(e){Qe(e.redirectUrl);let{codeVerifier:t,codeChallenge:r}=await ee(),i=Xe(e);return i.set("code_challenge",r),i.set("code_challenge_method","S256"),{url:`${this.authBase}/oauth/native-pkce/authorization?${i}`,codeVerifier:t}}async exchangeCode(e){let t=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:e.redirectUrl,client_id:e.clientId,client_secret:e.clientSecret});return this.tokenRequest(t,"LinkedIn did not return an access token.")}async exchangeNativeCode(e){if(Qe(e.redirectUrl),!/^[A-Z0-9._~-]{43,128}$/i.test(e.codeVerifier))throw Error("LinkedIn native OAuth requires the original PKCE code verifier.");if(!e.code.trim())throw Error("LinkedIn did not return an authorization code.");return this.tokenRequest(new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:e.redirectUrl,client_id:e.clientId,code_verifier:e.codeVerifier}),"LinkedIn did not return an access token.")}async refreshAccessToken(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId});if(e.clientSecret)t.set("client_secret",e.clientSecret);return this.tokenRequest(t,"LinkedIn did not return a refreshed access token.")}async tokenRequest(e,t){let r=await this.request(`${this.authBase}/oauth/v2/accessToken`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:e.toString()});if(!r.access_token)throw new y(t,400,JSON.stringify(r));return{accessToken:r.access_token,expiresIn:r.expires_in,scope:r.scope,refreshToken:r.refresh_token,refreshTokenExpiresIn:r.refresh_token_expires_in}}async getProfile(e){if(!e)throw Error("LinkedIn access token is required.");let t=await this.request(`${this.apiBase}/v2/userinfo`,{headers:{authorization:`Bearer ${e}`}});if(!t.sub)throw new y("LinkedIn profile is missing a subject id.",400,JSON.stringify(t));return{sub:t.sub,name:t.name,picture:t.picture}}async uploadImage(e,t,r,i){let n=await this.request(`${this.apiBase}/rest/images?action=initializeUpload`,{method:"POST",headers:{authorization:`Bearer ${e}`,"content-type":"application/json","linkedin-version":this.apiVersion,"x-restli-protocol-version":T},body:JSON.stringify({initializeUploadRequest:{owner:t}})}),s=n.value?.uploadUrl,o=n.value?.image;if(!s||!o)throw new y("LinkedIn did not return an image upload URL.",400,JSON.stringify(n));let a=await fetch(s,{method:"PUT",headers:{authorization:`Bearer ${e}`,"content-type":i||"image/jpeg"},body:new Uint8Array(r),signal:AbortSignal.timeout(60000)});if(!a.ok){let c=await a.text().catch(()=>"");throw new y(...f("LinkedIn image upload",a,c))}return o}async publish(e,t){if(_(t,"LinkedIn"),!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let r=e.did;if(!r)throw Error("LinkedIn author URN is required to publish.");if(S("linkedin",t.text,this.characterLimit))throw Error(`LinkedIn posts must be ${this.characterLimit} characters or fewer.`);let i=[];for(let u of(t.media??[]).slice(0,this.maxImages)){let l=await U(u,(h)=>this.fetchImage(h));if(!l)continue;let d=await this.uploadImage(e.accessToken,r,l.bytes,l.mimeType),p=u.altText?.trim();i.push({id:d,...p?{altText:p.slice(0,Jt)}:{}})}let n={author:r,commentary:Kt(t.text),visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1},s=[];if(i.length===1)n.content={media:i[0]};else if(i.length>1)n.content={multiImage:{images:i}};else if(t.external){let u={source:t.external.uri,title:t.external.title,description:t.external.description||""};if(t.external.thumb?.bytes?.length)try{u.thumbnail=await this.uploadImage(e.accessToken,r,t.external.thumb.bytes,t.external.thumb.mimeType)}catch{s.push("LinkedIn did not take the link card's picture, so the card went out without it.")}n.content={article:u}}let o=await fetch(`${this.apiBase}/rest/posts`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json","linkedin-version":this.apiVersion,"x-restli-protocol-version":T},body:JSON.stringify(n),signal:AbortSignal.timeout(30000)}),a=await o.text();if(!o.ok)throw new y(...f("LinkedIn API",o,a));let c=o.headers.get("x-restli-id")||o.headers.get("x-linkedin-id")||"";return{provider:this.provider,uri:c,url:c?`https://www.linkedin.com/feed/update/${c}`:void 0,...s.length?{warnings:s}:{}}}async createComment(e,t,r){if(!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let i=e.did;if(!i||!/^urn:li:(?:person:[\w-]{1,128}|organization(?:Brand)?:[0-9]{1,32})$/.test(i))throw Error("A LinkedIn author URN for a member or organization is required to comment.");let n=t.trim();if(!/^urn:li:(?:share|ugcPost):[0-9]{1,32}$/.test(n))throw Error("A LinkedIn share or UGC post URN is required to comment.");let s=r.trim();if(!s)throw Error("LinkedIn comment text is required.");let o=await fetch(`${this.apiBase}/rest/socialActions/${encodeURIComponent(n)}/comments`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json","linkedin-version":this.apiVersion,"x-restli-protocol-version":T},body:JSON.stringify({actor:i,object:n,message:{text:s}}),redirect:"error",signal:AbortSignal.timeout(15000)});if(!o.ok)throw new y(...f("LinkedIn comment",o,await o.text().catch(()=>"")));let a=o.headers.get("x-restli-id");if(a&&/^[0-9]{1,32}$/.test(a))return await o.body?.cancel().catch(()=>{}),a;let c=await o.json().catch(()=>null);return typeof c?.id==="string"&&/^[0-9]{1,32}$/.test(c.id)?c.id:null}async timeline(e,t={}){return{items:[]}}async listAuthoredPosts(e,t={}){if(!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let r=e.did;if(!r)throw Error("LinkedIn author URN is required to list posts.");let i=r.startsWith("urn:li:organization:")?"r_organization_social":"r_member_social",n=Math.min(Math.max(t.limit||50,1),100),s=Number(t.cursor||0)||0,o=new URL(`${this.apiBase}/rest/posts`);o.searchParams.set("q","author"),o.searchParams.set("author",r),o.searchParams.set("count",String(n)),o.searchParams.set("start",String(s));let a;try{a=await this.request(o.toString(),{headers:{authorization:`Bearer ${e.accessToken}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":T}})}catch(p){if(p instanceof y&&(p.status===401||p.status===403))throw new y(`LinkedIn will not list this account's posts - the Posts author finder needs the ${i} permission, which this app does not hold.`,p.status,p.body,p.retryAfterMs===void 0?{}:{retryAfterMs:p.retryAfterMs});throw p}let c=a.elements||[],u=c.filter((p)=>p?.id).map((p)=>({uri:String(p.id),text:p.commentary,postedAt:p.createdAt?new Date(p.createdAt).toISOString():void 0,url:`https://www.linkedin.com/feed/update/${p.id}`})),l=a.paging?.total;return{cursor:c.length===n&&(typeof l!=="number"||s+n<l)?String(s+n):void 0,posts:u}}async metrics(e,t){if(!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let r=String(e.did||"").startsWith("urn:li:organization:")?"r_organization_social_feed":"r_member_social_feed",i=[...new Set(t.map((s)=>String(s||"").trim()).filter(Boolean))],n=[];for(let s=0;s<i.length;s+=20){let o=i.slice(s,s+20),a=`${this.apiBase}/rest/socialMetadata?ids=List(${o.map((l)=>encodeURIComponent(l)).join(",")})`,c;try{c=await this.request(a,{headers:{authorization:`Bearer ${e.accessToken}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":T}})}catch(l){if(l instanceof y&&l.status===403)throw new y(`LinkedIn will not show this account's reactions and comments - that needs the ${r} permission, which this app does not hold.`,l.status,l.body,l.retryAfterMs===void 0?{}:{retryAfterMs:l.retryAfterMs});throw l}let u=c.results||{};for(let l of o){let d=u[l]??u[encodeURIComponent(l)];if(!d)continue;let p=Object.values(d.reactionSummaries||{}).reduce((h,m)=>h+(Number(m?.count)||0),0);n.push({uri:l,likes:p,...typeof d.commentSummary?.count==="number"?{replies:d.commentSummary.count}:{}})}}return n}async listOrganizations(e){if(!e)throw Error("LinkedIn access token is required to list organizations.");let t={authorization:`Bearer ${e}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":T},r=new Map,i=Math.max(1,this.organizationPageSize);for(let s=0,o=0;o<50;s+=i,o++){let a=new URL(`${this.apiBase}/rest/organizationAcls`);a.searchParams.set("q","roleAssignee"),a.searchParams.set("state","APPROVED"),a.searchParams.set("start",String(s)),a.searchParams.set("count",String(i));let c;try{c=await this.request(a.toString(),{headers:t})}catch(d){if(d instanceof y&&(d.status===401||d.status===403))throw new y("LinkedIn will not list this member's Pages - that needs the rw_organization_admin (or r_organization_admin) permission, which this token does not hold.",d.status,d.body);throw d}let u=c.elements||[];for(let d of u){let p=d.organizationTarget||d.organization,h=d.role||"";if(!p?.startsWith("urn:li:organization:")||!Gt.includes(h)||r.has(p))continue;r.set(p,{urn:p,id:p.slice(20),role:h})}let l=c.paging?.total;if(u.length<i||typeof l==="number"&&s+i>=l)break}let n=[...r.values()];for(let s of n){let o=await this.request(`${this.apiBase}/rest/organizations/${encodeURIComponent(s.id)}`,{headers:t}).then((a)=>a.localizedName,()=>{return});if(o)s.name=o}return n}async deletePost(e,t){if(!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let r=String(t.uri||"").trim();if(!r)throw Error("A LinkedIn post URN is required to delete a post.");let i=await fetch(`${this.apiBase}/rest/posts/${encodeURIComponent(r)}`,{method:"DELETE",headers:{authorization:`Bearer ${e.accessToken}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":T},signal:AbortSignal.timeout(30000)});if(!i.ok&&i.status!==404){let n=await i.text().catch(()=>"");throw new y(...f("LinkedIn API",i,n))}}async request(e,t){let r=await fetch(e,{...t,signal:t.signal??AbortSignal.timeout(30000)}),i=await r.text();if(!r.ok)throw new y(...f("LinkedIn API",r,i));return i?JSON.parse(i):{}}}function Kt(e){return e.replace(/[\\|{}@[\]()<>#*_~]/g,(t,r)=>{if(t==="#"&&Xt(e,r))return t;return`\\${t}`})}function Xt(e,t){let r=t===0?"":e[t-1];if(r&&/[\p{L}\p{N}_#&/]/u.test(r))return!1;let i=/^[\p{L}\p{N}_]+/u.exec(e.slice(t+1))?.[0];return Boolean(i&&/\p{L}/u.test(i))}import{fetchPublicUrl as We}from"@stacksjs/security";function Ye(e){return e instanceof te&&e.status===404}class te extends w{constructor(e,t,r,i={}){super("mastodon",e,t,r,i);this.name="MastodonApiError"}get isAuthError(){return this.status===401||this.status===403}}var L={characters:500,charactersPerUrl:23,mediaAttachments:4},Qt=3600000,Wt=60000,Yt=60000;function Zt(e){if(!e)return null;let t=Number(e.max_options),r=Number(e.max_characters_per_option),i=Number(e.min_expiration),n=Number(e.max_expiration);if(![t,r,i,n].every((s)=>Number.isSafeInteger(s)&&s>0)||t<2||n<i)return null;return{maxOptions:t,maxCharactersPerOption:r,minExpiration:i,maxExpiration:n}}function er(e,t){if(!t)throw Error("The Mastodon instance did not report its poll limits.");if(!Array.isArray(e.options)||e.options.some((i)=>typeof i!=="string"||!i.trim()))throw Error("Each poll option needs text.");let r=e.options.map((i)=>i.trim());if(r.length<2||r.length>t.maxOptions)throw Error(`This Mastodon instance allows between 2 and ${t.maxOptions} poll options.`);if(r.some((i)=>J(i)>t.maxCharactersPerOption))throw Error(`Each poll option can have up to ${t.maxCharactersPerOption} characters.`);if(new Set(r).size!==r.length)throw Error("Poll options must be distinct.");if(!Number.isSafeInteger(e.expiresIn)||e.expiresIn<t.minExpiration||e.expiresIn>t.maxExpiration)throw Error(`This Mastodon instance allows poll durations between ${t.minExpiration} and ${t.maxExpiration} seconds.`);return{options:r,expires_in:e.expiresIn,multiple:e.multiple===!0,hide_totals:e.hideTotals===!0}}function ke(e){let t=typeof e==="string"?URL.parse(e):null;if(!t||t.protocol!=="https:"||t.username||t.password)return null;return t.hash="",t.href}function tr(e){let t=String(e||"").trim().replace(/\/+$/,"");if(!t)throw Error("Mastodon instance URL is required.");if(/\s/.test(t))throw Error("Mastodon instance URL is invalid.");if(/^[a-z][a-z0-9+.-]*:/i.test(t)&&!/^https?:\/\//i.test(t))throw Error("Mastodon instance URL must use https:// or http://.");let r=/^https?:\/\//i.test(t)?t:`https://${t}`,i;try{i=new URL(r)}catch{throw Error("Mastodon instance URL is invalid.")}if(i.username||i.password)throw Error("Mastodon instance URL must not contain credentials.");if(!i.hostname)throw Error("Mastodon instance URL is invalid.");return`${i.protocol}//${i.host}`}class be{provider="mastodon";characterLimit=L.characters;fetchImage=C;limits=new Map;async instanceLimits(e){let t=this.instanceOf(e),r=this.limits.get(t);if(r&&Date.now()<r.expires)return r.value;try{let i=await We(`${t}/api/v2/instance`,{},{maxRedirects:0,timeoutMs:5000});if(!i.ok)throw Error(`HTTP ${i.status}`);let n=await i.json(),s=n.configuration?.statuses??{},o=(m,A)=>Number(m)>0?Math.floor(Number(m)):A,a=Zt(n.configuration?.polls),c=n.configuration?.media_attachments,u=Number(c?.video_size_limit),l=Number.isSafeInteger(u)&&u>0,d=c?.supported_mime_types,p=Number(n.api_versions?.mastodon)>=7,h={...a&&{poll:a},...p&&{quotePosts:!0},...l&&{videoSizeLimit:u},...Array.isArray(d)&&{supportsMp4:d.includes("video/mp4")},characters:o(s.max_characters,L.characters),charactersPerUrl:o(s.characters_reserved_per_url,L.charactersPerUrl),mediaAttachments:o(s.max_media_attachments,L.mediaAttachments)};return this.limits.set(t,{value:h,expires:Date.now()+Qt}),h}catch{return this.limits.set(t,{value:L,expires:Date.now()+Wt}),L}}instanceOf(e){return tr(e.did||"")}tokenOf(e){if(!e.accessToken)throw Error("Mastodon access token is missing for this identity.");return e.accessToken}async verifyCredentials(e){let t=await this.request(`${this.instanceOf(e)}/api/v1/accounts/verify_credentials`,{headers:{authorization:`Bearer ${this.tokenOf(e)}`}});return{accountId:t.id,username:t.username,displayName:t.display_name||void 0,url:t.url}}async resolvePostId(e,t){let r=ke(t);if(!r)throw Error("Enter an HTTPS link to a Mastodon post.");let i=new URL("/api/v2/search",this.instanceOf(e));i.search=new URLSearchParams({q:r,type:"statuses",resolve:"true",limit:"1"}).toString();let s=(await this.request(i.href,{headers:{authorization:`Bearer ${this.tokenOf(e)}`},redirect:"error",signal:AbortSignal.timeout(15000)})).statuses?.find((o)=>ke(o.url)===r||ke(o.uri)===r);if(!s||!/^[0-9]{1,32}$/.test(s.id))throw Error("The Mastodon instance could not find the post at this link.");return s.id}async uploadMedia(e,t,r,i){return(await this.createMediaAttachment(e,t,r,i)).id}async createMediaAttachment(e,t,r,i,n){let s=new FormData,o=r==="video/mp4"?"upload.mp4":"upload";if(s.set("file",new Blob([new Uint8Array(t)],{type:r||"image/jpeg"}),o),i?.trim())s.set("description",i.trim().slice(0,1500));return await this.request(`${this.instanceOf(e)}/api/v2/media`,{method:"POST",headers:{authorization:`Bearer ${this.tokenOf(e)}`},body:s,redirect:"error",signal:n})}async uploadVideo(e,t){let r=await this.createMediaAttachment(e,t.bytes,t.mimeType,t.altText,AbortSignal.timeout(60000));if(typeof r.id!=="string"||!/^[a-z0-9_-]{1,128}$/i.test(r.id))throw Error("Mastodon did not return a valid video attachment ID.");let i=`${this.instanceOf(e)}/api/v1/media/${r.id}`,n={authorization:`Bearer ${this.tokenOf(e)}`},s=AbortSignal.timeout(Yt),o=r;while(!o.url){if(s.aborted)throw new te("Mastodon took too long to process the attachment.",503,"");if(o=await this.request(i,{headers:n,signal:s,redirect:"error"}),!o.url)await Bun.sleep(1000)}if(o.id!==r.id||typeof o.url!=="string"||o.type!=="video"&&o.type!=="gifv")throw Error("Mastodon did not return a processed video attachment.");return r.id}async publish(e,t,r={}){let i=this.instanceOf(e),n=this.tokenOf(e),s=await this.instanceLimits(e);if(S("mastodon",t.text,s.characters,{linkLength:s.charactersPerUrl}))throw Error(`Mastodon posts on this instance must be ${s.characters} characters or fewer.`);if((r.poll||r.quotedStatusId!==void 0)&&t.media?.length)throw Error("Mastodon does not allow images with a poll or a quote.");if(t.video){if(H(t.video,t.media),r.poll||r.quotedStatusId!==void 0)throw Error("Mastodon does not allow a video with a poll or a quote.");if(s.supportsMp4===!1)throw Error("This Mastodon instance does not accept MP4 video.");if(s.videoSizeLimit&&t.video.bytes.length>s.videoSizeLimit)throw Error(`Video exceeds this Mastodon instance\u2019s ${s.videoSizeLimit}-byte limit.`)}if(r.poll&&r.quotedStatusId!==void 0)throw Error("Choose a poll or a quoted post on Mastodon.");if(r.quotedStatusId!==void 0){if(!s.quotePosts)throw Error("This Mastodon instance does not advertise quote posts.");if(!/^[0-9]{1,32}$/.test(r.quotedStatusId))throw Error("Choose a valid Mastodon status to quote.")}let o=r.poll?er(r.poll,s.poll):void 0,a=[];if(t.video)a.push(await this.uploadVideo(e,t.video));for(let p of(t.media||[]).slice(0,s.mediaAttachments)){let h=await U(p,(m)=>this.fetchImage(m));if(h)a.push(await this.uploadMedia(e,h.bytes,h.mimeType,p.altText))}let c={status:t.text,visibility:r.visibility??"public"};if(a.length)c.media_ids=a;if(o)c.poll=o;if(r.quotedStatusId!==void 0)c.quoted_status_id=r.quotedStatusId;if(t.reply?.parent?.uri)c.in_reply_to_id=t.reply.parent.uri;if(r.spoilerText?.trim())c.spoiler_text=r.spoilerText.trim();let u=r.language??t.langs?.[0];if(u)c.language=u;let l={authorization:`Bearer ${n}`,"content-type":"application/json"};if(r.idempotencyKey)l["idempotency-key"]=r.idempotencyKey;let d=await this.request(`${i}/api/v1/statuses`,{method:"POST",headers:l,body:JSON.stringify(c)});return{provider:this.provider,uri:d.id,cid:d.id,url:d.url||d.uri}}async timeline(e,t={}){return{items:[]}}async listAuthoredPosts(e,t={}){let r=this.instanceOf(e),{accountId:i}=await this.verifyCredentials(e),n=new URL(`${r}/api/v1/accounts/${encodeURIComponent(i)}/statuses`);if(n.searchParams.set("limit",String(Math.min(Math.max(t.limit||40,1),40))),n.searchParams.set("exclude_reblogs","true"),t.cursor)n.searchParams.set("max_id",t.cursor);let o=(await this.request(n.toString(),{headers:{authorization:`Bearer ${this.tokenOf(e)}`}})||[]).filter((a)=>a?.id).map((a)=>({uri:a.id,cid:a.id,text:a.content,postedAt:a.created_at,url:a.url}));return{cursor:o.length?o[o.length-1]?.uri:void 0,posts:o}}async deletePost(e,t){let r=String(t.cid||Ze(t.uri)||"").trim();if(!r)throw Error("A status id is required to delete a post.");await this.request(`${this.instanceOf(e)}/api/v1/statuses/${encodeURIComponent(r)}`,{method:"DELETE",headers:{authorization:`Bearer ${this.tokenOf(e)}`}})}async metrics(e,t){let r=this.instanceOf(e),i={authorization:`Bearer ${this.tokenOf(e)}`},n=new Map;for(let a of t){let c=String(Ze(a)||"").trim();if(c)n.set(c,a)}let s=[...n.keys()],o=[];for(let a=0;a<s.length;a+=40){let c=s.slice(a,a+40);try{o.push(...await this.request(`${r}/api/v1/statuses?${c.map((u)=>`id[]=${encodeURIComponent(u)}`).join("&")}`,{headers:i}))}catch(u){if(!Ye(u))throw u;for(let l of c)try{o.push(await this.request(`${r}/api/v1/statuses/${encodeURIComponent(l)}`,{headers:i}))}catch(d){if(!Ye(d))throw d}}}return o.flatMap((a)=>{let c=n.get(String(a.id));if(c===void 0)return[];let u={likes:a.favourites_count,reposts:a.reblogs_count,replies:a.replies_count,quotes:a.quotes_count},l=Object.entries(u).filter(([,d])=>typeof d==="number"&&Number.isSafeInteger(d)&&d>=0);return[{uri:c,...Object.fromEntries(l)}]})}async request(e,t){let r=await We(e,t,{maxRedirects:0,timeoutMs:60000}),i=await r.text();if(!r.ok)throw new te(...f("Mastodon API",r,i));return i?JSON.parse(i):{}}}function Ze(e){return String(e||"").replace(/\/+$/,"").split("/").pop()||""}var rr=20,ir=1000,et={views:"views",likes:"likes",replies:"replies",reposts:"reposts",quotes:"quotes",shares:"shares"},nr=Object.keys(et);class v extends w{constructor(e,t,r,i={}){super("threads",e,t,r,i);this.name="ThreadsApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class Se{provider="threads";characterLimit=500;maxImages=rr;containerTimeoutMs=300000;graphVersion;authBase;graphBase;constructor(e={}){this.graphVersion=e.graphVersion||"v1.0",this.authBase=e.authBase||"https://threads.net",this.graphBase=e.graphBase||"https://graph.threads.net"}getAuthUrl(e){let t=new URLSearchParams({client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(","),response_type:"code",state:e.state});return`${this.authBase}/oauth/authorize?${t.toString()}`}async exchangeCode(e){let t=await fetch(`${this.graphBase}/oauth/access_token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,grant_type:"authorization_code",redirect_uri:e.redirectUrl,code:e.code}).toString(),signal:AbortSignal.timeout(30000)}),r=await t.text(),i={};try{i=r?JSON.parse(r):{}}catch{i={}}if(!t.ok||i?.error||!i?.access_token)throw new v(...f("Threads token exchange",t,r));return{accessToken:i.access_token,userId:i.user_id!=null?String(i.user_id):void 0,expiresIn:i.expires_in}}async resolveAccount(e){let t=new URLSearchParams({fields:"id,username"}),r=await this.graph(`/me?${t.toString()}`,{method:"GET"},e);if(!r.id)throw new v("Could not resolve the Threads account for this token.",400,JSON.stringify(r));return{threadsUserId:r.id,username:r.username,accessToken:e}}async exchangeLongLivedToken(e,t){return this.tokenRequest("/access_token",new URLSearchParams({grant_type:"th_exchange_token",client_secret:e,access_token:t}))}async refreshLongLivedToken(e){return this.tokenRequest("/refresh_access_token",new URLSearchParams({grant_type:"th_refresh_token",access_token:e}))}async publish(e,t){if(_(t,"Threads"),!e.accessToken)throw Error("Threads access token is missing for this identity.");let r=e.did;if(!r)throw Error("Threads account id is required to publish.");if(S("threads",t.text,this.characterLimit))throw Error(`Threads posts must be ${this.characterLimit} characters or fewer.`);let i=(t.media??[]).slice(0,this.maxImages);if(i.some((p)=>!p.url))throw new v("Threads fetches images from a public address, and this image has none.",422,"");let n=e.accessToken,s=async(p)=>{let h=await this.graph(`/${r}/threads`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(p).toString()},n);if(!h.id)throw new v("Threads did not return a media container id.",400,JSON.stringify(h));return h.id},o=t.reply?.parent?.uri,a={text:t.text,...o?{reply_to_id:o}:{}},c=(p)=>({media_type:"IMAGE",image_url:p.url,...p.altText?.trim()?{alt_text:p.altText.trim().slice(0,ir)}:{}}),u;if(i.length>1){let p=[];for(let h of i)p.push(await s({...c(h),is_carousel_item:"true"}));u=await s({media_type:"CAROUSEL",children:p.join(","),...a})}else if(i.length===1)u=await s({...c(i[0]),...a});else u=await s({media_type:"TEXT",...a});if(i.length>0)await this.waitForContainer(u,n);let l=await this.graph(`/${r}/threads_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:u}).toString()},n);if(!l.id)throw new v("Threads did not return a published post id.",400,JSON.stringify(l));let d=await this.graph(`/${l.id}?fields=permalink`,{method:"GET"},n).catch(()=>{return});return{provider:this.provider,uri:l.id,cid:l.id,url:d?.permalink}}async waitForContainer(e,t){let r=0,i=1000;for(;;){let n=await this.graph(`/${e}?fields=status,error_message`,{method:"GET"},t),s=n.status;if(s==="FINISHED"||s==="PUBLISHED"||s===void 0)return;if(s==="ERROR"||s==="EXPIRED")throw new v(`Threads could not prepare this post (${s}${n.error_message?`: ${n.error_message}`:""}).`,422,JSON.stringify(n));if(r>=this.containerTimeoutMs)throw new v(`Threads was still processing this post after ${Math.round(r/1000)} seconds, so it was not published.`,504,JSON.stringify(n));let o=Math.min(i,60000,Math.max(this.containerTimeoutMs-r,0));await this.sleep(o),r+=o,i*=2}}sleep(e){return new Promise((t)=>setTimeout(t,e))}async deletePost(e,t){if(!e.accessToken)throw Error("Threads access token is missing for this identity.");if(!/^\w+$/.test(t.uri))throw Error(`Threads post id "${t.uri}" is not an id.`);await this.graph(`/${t.uri}`,{method:"DELETE"},e.accessToken)}async timeline(e,t={}){return{items:[]}}async tokenRequest(e,t){let r=await fetch(`${this.graphBase}${e}`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:t.toString(),signal:AbortSignal.timeout(30000)}),i=await r.text(),n={};try{n=i?JSON.parse(i):{}}catch{n={}}if(!r.ok||n?.error||!n?.access_token)throw new v(...f("Threads token request",r,i));return{accessToken:n.access_token,expiresIn:n.expires_in}}async metrics(e,t){let r=e.accessToken;if(!r)throw Error("Threads access token is missing for this identity.");let i=[];for(let n of t){let s=String(n||"").trim();if(!s)continue;let o;try{o=await this.graph(`/${encodeURIComponent(s)}/insights?metric=${nr.join(",")}`,{method:"GET"},r)}catch(c){if(c instanceof v&&W(c))continue;throw c}let a={uri:n};for(let c of o.data||[]){let u=et[String(c.name)],l=Number(c.values?.[0]?.value);if(u&&Number.isFinite(l))a[u]=l}i.push(a)}return i}async graph(e,t,r){let i=new Headers(t.headers);if(r)i.set("authorization",`Bearer ${r}`);let n=await fetch(`${this.graphBase}/${this.graphVersion}${e}`,{...t,headers:i,signal:t.signal??AbortSignal.timeout(30000)}),s=await n.text(),o={};try{o=s?JSON.parse(s):{}}catch{o={}}if(!n.ok||o?.error)throw new v(...f("Threads API",n,s));return o}}import{Buffer as sr}from"buffer";import{fetcher as tt}from"@stacksjs/api";import{config as re}from"@stacksjs/config";class Pe extends k{baseUrl="https://twitter.com";apiUrl="https://api.twitter.com";_usesPKCE=!0;getConfig(){let e={clientId:this.clientId||(re.services.twitter?.clientId??""),clientSecret:this.clientSecret||(re.services.twitter?.clientSecret??""),redirectUrl:this.redirectUrl||(re.services.twitter?.redirectUrl??""),scopes:re.services.twitter?.scopes??["users.read","tweet.read"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/i/oauth2/authorize?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(" "),response_type:"code",...this.parameters,...await this.pkceFields(),state:e}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let n=this.pkceTokenFields(),s=sr.from(`${t}:${r}`).toString("base64"),o=await tt.asForm().withHeaders({Authorization:`Basic ${s}`}).post(`${this.apiUrl}/2/oauth2/token`,{code:e,grant_type:"authorization_code",redirect_uri:i,...n});if(o.data.error)throw Error(`Twitter OAuth error: ${o.data.error_description}`);return o.data.access_token}async getUserByToken(e){let t=await tt.withHeaders({Authorization:`Bearer ${e}`}).get(`${this.apiUrl}/2/users/me?user.fields=profile_image_url`);return{id:t.data.id,nickname:t.data.username,name:t.data.name,email:t.data.email??null,avatar:t.data.profile_image_url??null,token:e,raw:t.data}}validateConfig(){let{clientId:e,clientSecret:t,redirectUrl:r}=this.getConfig();if(!e)throw new g("Twitter client ID not provided");if(!t)throw new g("Twitter client secret not provided");if(!r)throw new g("Twitter redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/2/oauth2/token`}}class x extends w{constructor(e,t,r,i={}){super("twitter",e,t,r,i);this.name="TwitterApiError"}get isAuthError(){return this.kind==="expired"}}var or=4,ar=1000;function rt(e){if(!/^\d{1,19}(?:-\d{1,19})?$/.test(e))throw Error("An X direct-message conversation id is required.");return e}class M{provider="twitter";characterLimit=280;maxImages=or;fetchImage=C;apiBase;authorizeBase;constructor(e={}){this.apiBase=e.apiBase||"https://api.twitter.com",this.authorizeBase=e.authorizeBase||"https://twitter.com"}async createAuthorization(e){let{codeVerifier:t,codeChallenge:r}=await ee(),i=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(" "),state:e.state,code_challenge:r,code_challenge_method:"S256"});return{url:`${this.authorizeBase}/i/oauth2/authorize?${i.toString()}`,codeVerifier:t}}async exchangeCode(e){return this.tokenRequest(new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:e.redirectUrl,code_verifier:e.codeVerifier,client_id:e.clientId}),e.clientId,e.clientSecret)}async refreshAccessToken(e){return this.tokenRequest(new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId}),e.clientId,e.clientSecret)}async getProfile(e){let t=await this.request(`${this.apiBase}/2/users/me?user.fields=username,name,profile_image_url`,{headers:{authorization:`Bearer ${e}`}});if(!t.data?.id||!t.data.username)throw new x("Twitter did not return the authenticated user.",400,JSON.stringify(t));return{id:t.data.id,username:t.data.username,name:t.data.name,...t.data.profile_image_url?{avatar:t.data.profile_image_url}:{}}}async uploadMedia(e,t,r){let i=new FormData;i.set("media",new Blob([new Uint8Array(t)],{type:r||"image/jpeg"})),i.set("media_category","tweet_image");let n=await this.request(`${this.apiBase}/2/media/upload`,{method:"POST",headers:{authorization:`Bearer ${e}`},body:i}),s=n.data?.id||n.media_id_string||n.id;if(!s)throw new x("Twitter did not return a media id.",400,JSON.stringify(n));return s}async describeMedia(e,t,r){try{return await this.request(`${this.apiBase}/2/media/metadata`,{method:"POST",headers:{authorization:`Bearer ${e}`,"content-type":"application/json"},body:JSON.stringify({id:t,metadata:{alt_text:{text:r.slice(0,ar)}}})}),!0}catch{return!1}}async publish(e,t){if(_(t,"X"),!e.accessToken)throw Error("Twitter access token is missing for this identity.");if(S("twitter",t.text,this.characterLimit))throw Error(`Twitter posts must be ${this.characterLimit} characters or fewer.`);let r=[],i=[];for(let a of(t.media??[]).slice(0,this.maxImages)){let c=await U(a,(d)=>this.fetchImage(d));if(!c)continue;let u=await this.uploadMedia(e.accessToken,c.bytes,c.mimeType),l=a.altText?.trim();if(l&&!await this.describeMedia(e.accessToken,u,l))i.push(`X did not take the description for image ${r.length+1}.`);r.push(u)}let n={text:t.text};if(r.length)n.media={media_ids:r};if(t.reply?.parent?.uri)n.reply={in_reply_to_tweet_id:t.reply.parent.uri};let s=await this.request(`${this.apiBase}/2/tweets`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json"},body:JSON.stringify(n)}),o=s.data?.id;if(!o)throw new x("Twitter did not return a tweet id.",400,JSON.stringify(s));return{provider:this.provider,uri:o,cid:o,url:e.handle?`https://x.com/${e.handle}/status/${o}`:`https://x.com/i/web/status/${o}`,...i.length?{warnings:i}:{}}}async timeline(e,t={}){return{items:[]}}async listAuthoredPosts(e,t={}){if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");let r=e.did;if(!r)throw Error("Twitter user id is required to list posts.");let i=new URL(`${this.apiBase}/2/users/${encodeURIComponent(r)}/tweets`);if(i.searchParams.set("max_results",String(Math.min(Math.max(t.limit||100,5),100))),i.searchParams.set("tweet.fields","created_at"),t.cursor)i.searchParams.set("pagination_token",t.cursor);let n=await this.request(i.toString(),{headers:{authorization:`Bearer ${e.accessToken}`}});return{cursor:n.meta?.next_token,posts:(n.data||[]).filter((s)=>s?.id).map((s)=>({uri:s.id,cid:s.id,text:s.text,postedAt:s.created_at,url:`https://x.com/i/web/status/${s.id}`}))}}async listDirectMessageEvents(e,t={}){if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");let r=t.conversationId===void 0?"/2/dm_events":`/2/dm_conversations/${rt(t.conversationId)}/dm_events`,i=new URL(`${this.apiBase}${r}`),n=t.limit??50,s=Number.isFinite(n)?Math.max(1,Math.min(100,Math.trunc(n))):50;if(i.searchParams.set("max_results",String(s)),i.searchParams.set("event_types","MessageCreate"),i.searchParams.set("dm_event.fields","attachments,created_at,dm_conversation_id,sender_id,text"),i.searchParams.set("expansions","sender_id"),i.searchParams.set("user.fields","profile_image_url"),t.cursor)i.searchParams.set("pagination_token",t.cursor);let o=await this.request(i.toString(),{headers:{authorization:`Bearer ${e.accessToken}`},signal:AbortSignal.timeout(15000)});if(!o.data?.length&&o.errors?.length)throw new x("X did not return the requested direct messages.",502,JSON.stringify(o));return{events:o.data??[],users:o.includes?.users??[],cursor:o.meta?.next_token}}async sendDirectMessage(e,t,r){if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");if(!r.trim())throw Error("Write a message before sending.");let i=rt(t),n=await this.request(`${this.apiBase}/2/dm_conversations/${i}/messages`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json"},body:JSON.stringify({text:r}),signal:AbortSignal.timeout(15000)}),s=n.data?.dm_event_id;if(n.data?.dm_conversation_id!==i||!s||!/^\d{1,19}$/.test(s))throw new x("X did not confirm the reply. Refresh the conversation before sending again.",502,JSON.stringify(n));return{conversationId:i,eventId:s}}async metrics(e,t){let r=[...new Set(t.filter((s)=>/^[0-9]{1,19}$/.test(s)))];if(!r.length)return[];if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");let i=[],n={authorization:`Bearer ${e.accessToken}`};for(let s=0;s<r.length;s+=100){let o=r.slice(s,s+100),a=new URLSearchParams({ids:o.join(","),"tweet.fields":"public_metrics"}),c=await this.request(`${this.apiBase}/2/tweets?${a}`,{headers:n}),u=new Set(o);for(let l of c.data??[]){let d=l.public_metrics;if(!d||!u.delete(l.id))continue;let p={likes:d.like_count,replies:d.reply_count,reposts:d.repost_count??d.retweet_count,quotes:d.quote_count,views:d.impression_count,saves:d.bookmark_count},h=Object.entries(p).filter(([,m])=>typeof m==="number"&&Number.isSafeInteger(m)&&m>=0);if(h.length)i.push({uri:l.id,...Object.fromEntries(h)})}}return i}async deletePost(e,t){if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");let r=String(t.uri||"").trim();if(!r)throw Error("A tweet id is required to delete a post.");let i=await fetch(`${this.apiBase}/2/tweets/${encodeURIComponent(r)}`,{method:"DELETE",headers:{authorization:`Bearer ${e.accessToken}`},signal:AbortSignal.timeout(30000)});if(i.status===404)return;let n=await i.text();if(!i.ok)throw new x(...f("Twitter API",i,n));let s=n?JSON.parse(n):{};if(s.data&&s.data.deleted===!1)throw new x(`X refused to delete tweet ${r}.`,400,JSON.stringify(s))}async tokenRequest(e,t,r){let i={"content-type":"application/x-www-form-urlencoded"};if(r)i.authorization=`Basic ${btoa(`${t}:${r}`)}`;let n=await this.request(`${this.apiBase}/2/oauth2/token`,{method:"POST",headers:i,body:e.toString()});if(!n.access_token)throw new x("Twitter did not return an access token.",400,JSON.stringify(n));return{accessToken:n.access_token,refreshToken:n.refresh_token,expiresIn:n.expires_in,scope:n.scope}}async request(e,t){let r=await fetch(e,{...t,signal:t.signal??AbortSignal.timeout(30000)}),i=await r.text();if(!r.ok)throw new x(...f("Twitter API",r,i));return i?JSON.parse(i):{}}}import{Buffer as cr}from"buffer";class z extends Error{code;status;constructor(e,t){super(`Stacks issuer refused the request: ${e}`);this.code=e;this.status=t;this.name="StacksIssuerError"}}class dr extends k{scopeSeparator=" ";settings;constructor(e){super(e);this.settings=e,this._scopes=e.scopes?.length?[...e.scopes]:[],this._usesPKCE=!0}endpoint(e){return(e==="authorize"?this.settings.authorizeUrl:e==="token"?this.settings.tokenUrl:this.settings.revokeUrl)||`${this.settings.issuer.replace(/\/+$/,"")}/${e}`}resources(){let e=this.settings.resource;return e==null?[]:Array.isArray(e)?e:[e]}validateConfig(){if(!this.settings.issuer)throw new g("Stacks issuer not provided");if(!this.clientId)throw new g("Stacks issuer client ID not provided");if(!this.clientSecret)throw new g("Stacks issuer client secret not provided");if(!this.redirectUrl)throw new g("Stacks issuer redirect URL not provided");if(!this.settings.userInfoUrl)throw new g("Stacks issuer userinfo URL not provided")}getTokenUrl(){return this.endpoint("token")}async getAuthUrl(){this.validateConfig();let e=new URLSearchParams({client_id:this.clientId,redirect_uri:this.redirectUrl,response_type:"code",scope:this.formatScopes(this.getScopes(),this.scopeSeparator),state:this.resolveState(),...await this.pkceFields()});for(let t of this.resources())e.append("resource",t);for(let[t,r]of Object.entries(this.parameters))e.set(t,String(r));return`${this.endpoint("authorize")}?${e.toString()}`}async post(e,t){let r=await fetch(e,{method:"POST",headers:{Authorization:`Basic ${cr.from(`${encodeURIComponent(this.clientId)}:${encodeURIComponent(this.clientSecret)}`).toString("base64")}`,"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:t.toString()}),i=await r.json().catch(()=>({}));if(!r.ok)throw new z(typeof i.error==="string"?i.error:"server_error",r.status);return i}tokens(e){if(typeof e.access_token!=="string"||!e.access_token)throw new z("invalid_token_response",502);return{accessToken:e.access_token,refreshToken:typeof e.refresh_token==="string"?e.refresh_token:null,expiresIn:typeof e.expires_in==="number"?e.expires_in:null,scopes:typeof e.scope==="string"?e.scope.split(" ").filter(Boolean):[]}}async getTokens(e){this.validateConfig();let t=new URLSearchParams({grant_type:"authorization_code",code:e,redirect_uri:this.redirectUrl,...this.pkceTokenFields()});for(let r of this.resources())t.append("resource",r);return this.tokens(await this.post(this.endpoint("token"),t))}async getAccessToken(e){return(await this.getTokens(e)).accessToken}async refreshTokens(e){this.validateConfig();let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e});for(let r of this.resources())t.append("resource",r);return this.tokens(await this.post(this.endpoint("token"),t))}async revokeToken(e,t="refresh_token"){this.validateConfig(),await this.post(this.endpoint("revoke"),new URLSearchParams({token:e,token_type_hint:t}))}async getClaims(e){this.validateConfig();let t=await fetch(this.settings.userInfoUrl,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}}),r=await t.json().catch(()=>({}));if(!t.ok)throw new z(typeof r.error==="string"?r.error:"invalid_token",t.status);if(typeof r.sub!=="string"||!r.sub)throw new z("invalid_userinfo",502);return r}async getUserByToken(e){let t=await this.getClaims(e),r=typeof t.email==="string"?t.email:null;return{id:String(t.sub),nickname:typeof t.preferred_username==="string"?t.preferred_username:null,name:typeof t.name==="string"&&t.name?t.name:r??"",email:r,emailVerified:typeof t.email_verified==="boolean"?t.email_verified:null,avatar:typeof t.picture==="string"?t.picture:null,token:e,raw:t}}}import{config as lr}from"@stacksjs/config";var ie=["clientId","clientSecret","redirectUrl"],q=Object.freeze({google:{name:"google",label:"Google",driver:fe,required:ie,postCallback:!1,pkce:!1,nonce:!1},github:{name:"github",label:"GitHub",driver:me,required:ie,postCallback:!1,pkce:!1,nonce:!1},facebook:{name:"facebook",label:"Facebook",driver:he,required:ie,postCallback:!1,pkce:!1,nonce:!1},twitter:{name:"twitter",label:"X",driver:Pe,required:ie,postCallback:!1,pkce:!0,nonce:!1},apple:{name:"apple",label:"Apple",driver:de,required:["clientId","teamId","keyId","privateKey","redirectUrl"],postCallback:!0,pkce:!1,nonce:!0}});function it(e){return lr?.services?.[e]}function ur(e){return typeof e==="string"&&e in q}function nt(e){if(!ur(e))return!1;let t=it(e);if(!t)return!1;return q[e].required.every((r)=>Boolean(t[r]))}function mn(){return Object.keys(q).filter(nt).map((e)=>q[e])}function fn(e){if(!nt(e))return null;let t=q[e],r=it(e)??{};return new t.driver({clientSecret:"",...r,clientId:String(r.clientId??""),redirectUrl:String(r.redirectUrl??"")})}class pr{accessToken;refreshToken;expiresIn;approvedScopes;constructor(e,t=null,r=null,i=[]){this.accessToken=e;this.refreshToken=t;this.expiresIn=r;this.approvedScopes=i}}function kn(e){return typeof e?.metrics==="function"}function bn(e){return typeof e?.deletePost==="function"}function Sn(e){return typeof e?.listAuthoredPosts==="function"}import{buildSessionHandoffCodeUrl as hr,buildSessionHandoffUrl as gr}from"@stacksjs/composables";function ve(e,t=[]){if(!e)return!1;if(/[\\\u0000-\u001F\u007F]/.test(e))return!1;if(e.startsWith("//"))return!1;if(e.startsWith("/"))try{return new URL(e,"https://stacks.invalid").origin==="https://stacks.invalid"}catch{return!1}try{let r=new URL(e);if(r.protocol!=="http:"&&r.protocol!=="https:")return!1;return t.includes(r.host)}catch{return!1}}function xn(e,t={}){let r=t.redirectTo??"/";if(!ve(r,t.allowedHosts??[]))throw Error(`[socials] refusing to hand a session to ${r}: relative paths are always allowed; an absolute URL needs its host in allowedHosts.`);return new Response(null,{status:302,headers:{Location:gr(r,e),"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function _n(e,t={}){let r=t.redirectTo??"/";if(!ve(r,t.allowedHosts??[]))throw Error(`[socials] refusing to hand a session to ${r}: relative paths are always allowed; an absolute URL needs its host in allowedHosts.`);return new Response(null,{status:302,headers:{Location:hr(r,e),"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function In(e,t={}){let r=t.redirectTo??"/login";if(!ve(r,t.allowedHosts??[]))throw Error(`[socials] refusing to redirect to ${r}`);let i=r.indexOf("#"),n=i>=0?r.slice(0,i):r,s=i>=0?r.slice(i):"",o=n.includes("?")?"&":"?",a=`${n}${o}social_error=${encodeURIComponent(e)}${s}`;return new Response(null,{status:302,headers:{Location:a,"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}import{Buffer as st}from"buffer";import{createHash as mr,randomBytes as fr,timingSafeEqual as wr}from"crypto";function F(e){return mr("sha256").update(e).digest("hex")}var yr=/^[a-f0-9]{64}$/,kr=/^[a-f0-9]{64}$/,br=/^[\w.:-]{1,64}$/,Sr=3600000,ot=null;function Cn(e){ot=e}function at(){return ot??xr()}function xe(e=32){return fr(e).toString("hex")}function Pr(e,t){if(e.length!==t.length)return!1;return wr(st.from(e,"utf8"),st.from(t,"utf8"))}function _e(e){return`stacks_oauth_${F(e).slice(0,24)}`}async function vr(){try{let{config:e}=await import("@stacksjs/config");return String(e.app?.url??"").startsWith("https:")}catch{return!1}}function ct(e,t,r,i){return[`${e}=${t}`,`Path=${i.path}`,"HttpOnly",`SameSite=${i.sameSite}`,`Max-Age=${Math.max(0,Math.floor(r))}`,...i.secure?["Secure"]:[]].join("; ")}async function dt(e={}){let t=e.sameSite??"Lax",r=t==="None"?!0:e.secure??await vr();return{path:e.path??"/",sameSite:t,secure:r}}async function Un(e){if(!br.test(e.purpose??""))throw TypeError("[socials] issueOAuthFlow needs a purpose of 1-64 word characters, dots, colons or dashes.");if(!Number.isFinite(e.ttlMs)||e.ttlMs<=0)throw TypeError("[socials] issueOAuthFlow needs a positive ttlMs.");if(e.challenge!==void 0&&!kr.test(e.challenge))throw TypeError("[socials] issueOAuthFlow challenge must be the lowercase hex SHA-256 of the verifier.");if(e.userId!=null&&(!Number.isSafeInteger(e.userId)||e.userId<=0))throw TypeError("[socials] issueOAuthFlow userId must be a positive integer.");let t=Math.min(e.ttlMs,Sr),r=xe(),n=(e.challenge?!1:e.bindBrowser!==!1)?xe():null,s=e.nonce===!0?xe():typeof e.nonce==="string"&&e.nonce?e.nonce:void 0,o=new Date,a=new Date(o.getTime()+t),c=at();try{await c.prune(o)}catch{}await c.insert({stateDigest:F(r),purpose:e.purpose,browserDigest:e.challenge??(n?F(n):null),userId:e.userId??null,nonce:s??null,data:e.data??null,expiresAt:a});let u=n?ct(_e(r),n,t/1000,await dt(e.cookie)):null;return{state:r,cookie:u,secret:n,...s!==void 0&&{nonce:s},expiresAt:a}}async function En(e,t){if(typeof e!=="string"||!yr.test(e))return null;let r=at(),i=F(e),n=await r.find(i);if(!n)return null;if(n.expiresAt.getTime()<=Date.now())return await r.take(i).catch(()=>!1),null;if(n.purpose!==t.purpose)return null;if(n.browserDigest!==null){let s=t.browserSecret;if(typeof s!=="string"||s.length===0||s.length>512)return null;if(!Pr(F(s),n.browserDigest))return null}if(!await r.take(i))return null;return{purpose:n.purpose,userId:n.userId,nonce:n.nonce,data:n.data,expiresAt:n.expiresAt}}function $n(e,t){if(!e||!t)return"";let r=_e(t);for(let i of e.split(";")){let n=i.trim();if(n.startsWith(`${r}=`))return n.slice(r.length+1)}return""}async function On(e,t={}){return ct(_e(e),"",0,await dt(t))}function Ln(){let e=new Map;return{records:e,async insert(t){e.set(t.stateDigest,{...t})},async find(t){let r=e.get(t);return r?{...r}:void 0},async take(t){return e.delete(t)},async prune(t){for(let[r,i]of e)if(i.expiresAt.getTime()<=t.getTime())e.delete(r)}}}var ne="oauth_flows";function xr(){let e=()=>import("@stacksjs/database/runtime");return{async insert(t){let{db:r,sqlDateTime:i}=await e();await r.insertInto(ne).values({state_digest:t.stateDigest,purpose:t.purpose,browser_digest:t.browserDigest,user_id:t.userId,nonce:t.nonce,data:t.data?JSON.stringify(t.data):null,expires_at:i(t.expiresAt),created_at:i(new Date)}).execute()},async find(t){let{db:r,parseSqlDateTime:i}=await e(),n=await r.primary.selectFrom(ne).where("state_digest","=",t).selectAll().executeTakeFirst();if(!n)return;let s=null;if(typeof n.data==="string"&&n.data)try{let o=JSON.parse(n.data);s=o&&typeof o==="object"?o:null}catch{s=null}return{stateDigest:String(n.state_digest),purpose:String(n.purpose),browserDigest:typeof n.browser_digest==="string"&&n.browser_digest?n.browser_digest:null,userId:n.user_id==null?null:Number(n.user_id),nonce:typeof n.nonce==="string"&&n.nonce?n.nonce:null,data:s,expiresAt:i(n.expires_at)??new Date(0)}},async take(t){let{db:r,mutationCount:i}=await e(),n=await r.deleteFrom(ne).where("state_digest","=",t).execute();return i(n)===1},async prune(t){let{db:r,sqlDateTime:i}=await e();await r.deleteFrom(ne).where("expires_at","<",i(t)).execute()}}}var _r={bluesky:["identifier","password","service"],twitter:["clientId","clientSecret","accessToken","refreshToken"],linkedin:["accessToken","memberUrn","clientId","clientSecret","apiVersion"],mastodon:["accessToken","instanceUrl"],instagram:["accessToken","accountId","clientId","clientSecret"],threads:["accessToken","userId","clientId","clientSecret"]},Ir={bluesky:["identifier","password"],twitter:["clientId","clientSecret","accessToken"],linkedin:["accessToken","memberUrn"],mastodon:["accessToken","instanceUrl"],instagram:["accessToken","accountId"],threads:["accessToken","userId"]};function Tr(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function se(e,t,r){let i=r.replace(/[A-Z]/g,(n)=>`_${n}`).toUpperCase();return`SOCIALS_${Tr(e)}_${t.toUpperCase()}_${i}`}class P extends Error{constructor(e){super(e);this.name="SocialIdentityError"}}async function oe(){let{config:e,overridesReady:t}=await import("@stacksjs/config");return await t,e.socials??{}}function lt(e,t){let r=Object.keys(e.identities??{});if(t){if(!r.includes(t))throw new P(`Unknown social identity '${t}'. config/socials.ts declares: ${r.length?r.join(", "):"none"}.`);return t}if(e.default){if(!r.includes(e.default))throw new P(`config/socials.ts sets default: '${e.default}', which is not one of its identities: ${r.length?r.join(", "):"none"}.`);return e.default}if(r.length===1)return r[0];if(r.length===0)throw new P("config/socials.ts declares no identities, so there is no account to post as.");throw new P(`config/socials.ts declares ${r.length} identities (${r.join(", ")}) and no default, so a call has to name one.`)}function Ar(e,t,r,i=process.env){let s=(e.identities?.[r]??{}).credentials?.[t]??{},o={};for(let a of _r[t]){let c=(s[a]??i[se(r,t,a)]??"").trim();if(c)o[a]=c}return o}function Ie(e,t,r,i=process.env){let n=lt(e,r),s=Ar(e,t,n,i),o=Ir[t].filter((a)=>!s[a]);if(o.length){let a=o.map((c)=>se(n,t,c)).join(", ");throw new P(`Identity '${n}' is not configured for ${t}: ${o.join(", ")} ${o.length===1?"is":"are"} missing. Set ${a}, or supply them inline in config/socials.ts.`)}return s}async function ut(e){return lt(await oe(),e)}async function B(e,t,r){return Ie(await oe(),e,t,r)}function Bn(e,t){return B("bluesky",e,t)}function Dn(e,t){return B("twitter",e,t)}function Nn(e,t){return B("linkedin",e,t)}function zn(e,t){return B("mastodon",e,t)}function qn(e,t){return B("instagram",e,t)}function Fn(e,t){return B("threads",e,t)}import{randomBytes as Rr}from"crypto";function Gn(e){return e==="twitter"}var Cr=["tweet.read","tweet.write","users.read","offline.access"],Ur="127.0.0.1",pt="/callback";function Kn(e){if(!Number.isInteger(e)||e<1||e>65535)throw new P(`${e} is not a port a redirect can listen on.`);return`http://${Ur}:${e}${pt}`}function Xn(){return Rr(16).toString("hex")}function Qn(e,t){let r;try{r=new URL(e)}catch{return{ok:!1,reason:"not-the-callback",message:`Not a URL: ${e}`}}if(r.pathname!==pt)return{ok:!1,reason:"not-the-callback",message:`Ignoring a request for ${r.pathname}.`};let i=r.searchParams.get("error");if(i){let o=r.searchParams.get("error_description");return{ok:!1,reason:"declined",message:o?`${i}: ${o}`:i}}let n=r.searchParams.get("state")??"";if(!t||n!==t)return{ok:!1,reason:"state-mismatch",message:"The redirect carried the wrong state, so it did not come from this run."};let s=r.searchParams.get("code")??"";if(!s)return{ok:!1,reason:"no-code",message:"The redirect carried no authorization code."};return{ok:!0,code:s}}function Wn(e,t,r){let i=[];for(let[n,s]of Object.entries(r)){if(!s)continue;i.push(`${se(e,t,n)}=${s}`)}return i}async function Yn(e){let t=new M,r=await t.exchangeCode(e);if(!r.accessToken)throw new P("X returned no access token for that code.");let i=Boolean(r.refreshToken),n=await t.getProfile(r.accessToken);return{handle:n.username,accountId:n.id,accessToken:r.accessToken,refreshToken:r.refreshToken,expiresIn:r.expiresIn,scope:r.scope,renewable:i}}async function Zn(e){return new M().createAuthorization({clientId:e.clientId,redirectUrl:e.redirectUrl,scopes:[...Cr],state:e.state})}function es(e,t){let r=(i)=>i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${r(e)}</title><style>body{font:16px/1.5 system-ui,sans-serif;margin:0;display:grid;place-items:center;min-height:100vh;color:#111}main{max-width:28rem;padding:2rem;text-align:center}h1{font-size:1.25rem;margin:0 0 .5rem}p{margin:0;color:#555}@media(prefers-color-scheme:dark){body{background:#111;color:#eee}p{color:#aaa}}</style></head><body><main><h1>${r(e)}</h1><p>${r(t)}</p></main></body></html>`}var Er={bluesky:null,twitter:null,linkedin:"memberUrn",mastodon:"instanceUrl",instagram:"accountId",threads:"userId"};function $r(e,t){if(e==="bluesky")return t.service?{service:t.service}:{};if(e==="linkedin")return t.apiVersion?{apiVersion:t.apiVersion}:{};return{}}function Or(e,t){if(e.service||!t.service)return e;return{...e,service:t.service}}function Lr(e,t={}){switch(e){case"bluesky":return new X(t);case"linkedin":return new ye(t);case"twitter":return new M;case"mastodon":return new be;case"instagram":return new we;case"threads":return new Se;default:throw new P(`No publishing driver for '${String(e)}'.`)}}function Mr(e,t,r){let i=Er[e],n={handle:(t??"").trim()};if(r.accessToken)n.accessToken=r.accessToken;if(r.refreshToken)n.refreshToken=r.refreshToken;if(i&&r[i])n.did=r[i];return n}function Br(e,t,r){if(!r)return;if(r.includes(t))return;throw new P(`Identity '${e}' is not set up for ${t}. config/socials.ts lists: ${r.length?r.join(", "):"none"}.`)}async function Dr(e,t,r){let i=await oe(),n=await ut(t),s=i.identities?.[n]??{};Br(n,e,s.platforms);let o=Ie(i,e,n,r),a=$r(e,o);if(e==="bluesky"){let c=await new X(a).createSession({identifier:o.identifier,password:o.password});return{name:n,platform:e,identity:{handle:c.handle,did:c.did,accessToken:c.accessJwt,refreshToken:c.refreshJwt},options:Or(a,c)}}return{name:n,platform:e,identity:Mr(e,s.handle??"",o),options:a}}async function ns(e,t,r,i){let n=await Dr(e,r,i);return Lr(n.platform,n.options).publish(n.identity,t)}export{Ur as AUTHORIZE_HOST,pt as AUTHORIZE_PATH,k as AbstractProvider,de as AppleProvider,ze as BLUESKY_MAX_BATCH_WRITES,Be as BLUESKY_MAX_BLOB_BYTES,Et as BLUESKY_MAX_IMAGES,$t as BLUESKY_MAX_LANGS,De as BLUESKY_MAX_VIDEO_BYTES,O as BlueskyApiError,X as BlueskyPublishingDriver,g as ConfigException,Er as DRIVER_DID_FIELD,he as FacebookProvider,me as GitHubProvider,fe as GoogleProvider,qt as INSTAGRAM_MAX_ALT_TEXT,zt as INSTAGRAM_MAX_IMAGES,b as InstagramApiError,we as InstagramPublishingDriver,gt as InvalidStateException,Ke as LINKEDIN_API_VERSION,Jt as LINKEDIN_MAX_ALT_TEXT,Ht as LINKEDIN_MAX_IMAGES,Gt as LINKEDIN_POSTING_ROLES,ei as LINK_LENGTH,y as LinkedInApiError,ye as LinkedInPublishingDriver,L as MASTODON_DEFAULT_LIMITS,St as MAX_POST_IMAGE_BYTES,Q as META_GRAPH_VERSION,te as MastodonApiError,be as MastodonPublishingDriver,Ee as PostImageError,Ir as REQUIRED_SOCIAL_CREDENTIALS,_r as SOCIAL_CREDENTIAL_FIELDS,q as SOCIAL_PROVIDERS,w as SocialApiError,P as SocialIdentityError,z as StacksIssuerError,dr as StacksIssuerProvider,ir as THREADS_MAX_ALT_TEXT,rr as THREADS_MAX_IMAGES,Cr as TWITTER_PUBLISH_SCOPES,v as ThreadsApiError,Se as ThreadsPublishingDriver,pr as Token,x as TwitterApiError,Pe as TwitterProvider,M as TwitterPublishingDriver,ar as X_MAX_ALT_TEXT,or as X_MAX_IMAGES,f as apiFailure,Br as assertPlatformDeclared,ui as blueskyRecordKey,Or as blueskyTargetOptions,es as callbackPage,Kn as callbackUri,K as classifySocialError,On as clearOAuthFlowCookie,Yn as completeTwitterAuthorization,mn as configuredSocialProviders,En as consumeOAuthFlow,It as countText,xr as databaseOAuthFlowStore,Mt as detectFacetCandidates,$r as driverOptions,Wn as envLines,se as envName,Tr as envSegment,Kt as escapeLinkedInText,S as exceedsLimit,C as fetchPostImage,J as graphemes,Gn as isAuthorizablePlatform,li as isBlueskySessionError,ri as isExpiredSignIn,W as isMissingGraphObject,ve as isSafeHandoffTarget,nt as isSocialProviderConfigured,ur as isSocialProviderName,Un as issueOAuthFlow,Vt as linkedInVersionSunset,Ln as memoryOAuthFlowStore,G as networkReason,Xn as newState,tr as normalizeInstance,_e as oauthFlowCookieName,F as oauthFlowDigest,pe as parseAtUri,Ie as pickCredentials,lt as pickIdentity,ns as publishAs,Lr as publishingDriver,Qn as readCallback,Ar as readCredentials,Ue as readImageDimensions,$n as readOAuthFlowCookie,_ as rejectPostVideo,Bn as resolveBlueskyCredentials,qe as resolveBlueskyService,ut as resolveIdentityName,qn as resolveInstagramCredentials,Nn as resolveLinkedInCredentials,jt as resolveLinkedInVersion,zn as resolveMastodonCredentials,U as resolvePostImage,B as resolveSocialCredentials,Fn as resolveThreadsCredentials,Dn as resolveTwitterCredentials,At as retryAfterMs,le as sniffImageType,_n as socialHandoffCodeRedirect,In as socialHandoffFailureRedirect,xn as socialHandoffRedirect,fn as socialProvider,Dr as socialPublishTarget,oe as socialsConfig,Zn as startTwitterAuthorization,bn as supportsDeletion,Sn as supportsEnumeration,kn as supportsMetrics,Mr as toDriverIdentity,Cn as useOAuthFlowStore,H as validatePostVideo};
2
+ var gt=import.meta.require;import{Buffer as H}from"buffer";class y{clientId;clientSecret;redirectUrl;parameters={};_scopes=[];scopeSeparator=",";_stateless=!1;_usesPKCE=!1;_codeVerifier=null;_state=null;user=null;constructor(e){this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.redirectUrl=e.redirectUrl}async getCodeFields(e=null){let t={client_id:this.clientId,redirect_uri:this.redirectUrl,scope:this.formatScopes(this.getScopes(),this.scopeSeparator),response_type:"code"};if(this.usesState())t.state=e;return{...t,...await this.pkceFields(),...this.parameters}}formatScopes(e,t){return e.join(t)}async userFromToken(e){return{...await this.getUserByToken(e),token:e}}scopes(e){let t=Array.isArray(e)?e:[e];return this._scopes=[...new Set([...this._scopes,...t])],this}setScopes(e){let t=Array.isArray(e)?e:[e];return this._scopes=[...new Set(t)],this}getScopes(){return this._scopes}setRedirectUrl(e){if(typeof e!=="string"||e.length===0)throw Error("[socials] setRedirectUrl requires a non-empty string");let t;try{t=new URL(e)}catch{throw Error(`[socials] setRedirectUrl: invalid URL: ${e}`)}if(t.protocol!=="https:"&&t.protocol!=="http:")throw Error(`[socials] setRedirectUrl protocol must be http(s)://, got ${t.protocol}`);return this.redirectUrl=e,this}withState(e){if(typeof e!=="string"||e.length===0)throw Error("[socials] withState requires a non-empty string");return this._state=e,this}resolveState(){return this._state??this.getState()}usesState(){return!this._stateless}validateState(e,t){if(typeof e!=="string"||typeof t!=="string")return!1;if(e.length===0||t.length===0)return!1;if(e.length!==t.length)return!1;try{let{timingSafeEqual:r}=gt("crypto");return r(H.from(e,"utf8"),H.from(t,"utf8"))}catch{let r=0;for(let i=0;i<e.length;i++)r|=e.charCodeAt(i)^t.charCodeAt(i);return r===0}}isStateless(){return this._stateless}stateless(){return this._stateless=!0,this}getState(){let e=new Uint8Array(32);return crypto.getRandomValues(e),Array.from(e).map((t)=>t.toString(16).padStart(2,"0")).join("")}usesPKCE(){return this._usesPKCE}enablePKCE(){return this._usesPKCE=!0,this}getCodeVerifier(){if(this._codeVerifier===null){let e=new Uint8Array(32);crypto.getRandomValues(e),this._codeVerifier=H.from(e).toString("base64url")}return this._codeVerifier}getPkceVerifier(){return this._codeVerifier}withCodeVerifier(e){if(!e)throw Error("A PKCE code verifier must be a non-empty string");return this._usesPKCE=!0,this._codeVerifier=e,this}async pkceFields(){if(!this.usesPKCE())return{};return{code_challenge:await this.getCodeChallenge(),code_challenge_method:this.getCodeChallengeMethod()}}pkceTokenFields(){if(!this.usesPKCE())return{};if(this._codeVerifier===null)throw Error("PKCE is enabled but no code verifier is known for this exchange. Pass the one from getPkceVerifier() back with withCodeVerifier().");return{code_verifier:this._codeVerifier}}async getCodeChallenge(){let t=new TextEncoder().encode(this.getCodeVerifier()),r=await crypto.subtle.digest("SHA-256",t);return H.from(new Uint8Array(r)).toString("base64url")}getCodeChallengeMethod(){return"S256"}with(e){return this.parameters=e,this}async buildAuthUrlFromBase(e,t){let r=new URLSearchParams(await this.getCodeFields(t));return`${e}?${r.toString()}`}}import{Buffer as Re}from"buffer";import{createPrivateKey as kt,sign as bt}from"crypto";import{config as R}from"@stacksjs/config";class mt extends Error{constructor(e="Invalid state"){super(e);this.name="InvalidStateException"}}class g extends Error{constructor(e){super(e);this.name="ConfigException"}}import{Buffer as ce}from"buffer";var Ue=new Map,ft=600000,wt=60000;async function Te(e,t){let r=await fetch(e,{redirect:"error",signal:AbortSignal.timeout(15000)});if(!r.ok)throw Error(`id_token verification failed: could not fetch signing keys from ${e} (HTTP ${r.status})`);let i=await r.json(),n=Array.isArray(i.keys)?i.keys:[];return Ue.set(e,{keys:n,fetchedAt:t}),n}async function yt(e,t,r){let i=Ue.get(e),n=i!==void 0&&r-i.fetchedAt<ft,s=n?i.keys:await Te(e,r),o=s.find((a)=>a.kid===t);if(!o&&n&&r-i.fetchedAt>=wt)s=await Te(e,r),o=s.find((a)=>a.kid===t);if(!o)throw Error(`id_token verification failed: no signing key matches kid "${t}"`);if(o.kty!=="RSA")throw Error(`id_token verification failed: signing key "${t}" is ${o.kty}, expected RSA`);return o}function Ae(e,t){try{let r=JSON.parse(ce.from(e,"base64url").toString("utf8"));if(!r||typeof r!=="object"||Array.isArray(r))throw Error("not an object");return r}catch{throw Error(`id_token verification failed: ${t} is not valid JSON`)}}async function J(e,t){let r=e.split(".");if(r.length!==3)throw Error("id_token verification failed: malformed token");let[i,n,s]=r,o=Ae(i,"header");if(o.alg!=="RS256")throw Error(`id_token verification failed: unsupported algorithm ${JSON.stringify(o.alg)}, expected RS256`);if(typeof o.kid!=="string"||o.kid==="")throw Error("id_token verification failed: header has no kid");let a=t.now??Date.now(),c=await yt(t.jwksUrl,o.kid,a),u=await crypto.subtle.importKey("jwk",{kty:"RSA",n:c.n,e:c.e,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);if(!await crypto.subtle.verify("RSASSA-PKCS1-v1_5",u,ce.from(s,"base64url"),ce.from(`${i}.${n}`)))throw Error("id_token verification failed: signature does not match the issuer's key");let d=Ae(n,"payload"),h=(t.clockSkewSeconds??60)*1000,p=Array.isArray(t.issuer)?t.issuer:[t.issuer];if(!p.includes(d.iss))throw Error(`id_token verification failed: issuer is ${JSON.stringify(d.iss)}, expected ${p.map((D)=>JSON.stringify(D)).join(" or ")}`);let m=Array.isArray(t.audience)?t.audience:[t.audience];if(!(Array.isArray(d.aud)?d.aud:[d.aud]).some((D)=>m.includes(D)))throw Error("id_token verification failed: token is addressed to a different client");if(typeof d.exp!=="number"||d.exp*1000+h<=a)throw Error("id_token verification failed: token has expired");if(typeof d.iat==="number"&&d.iat*1000-h>a)throw Error("id_token verification failed: token was issued in the future");if(typeof d.nbf==="number"&&d.nbf*1000-h>a)throw Error("id_token verification failed: token is not valid yet");if(t.nonce!==void 0&&d.nonce!==t.nonce)throw Error("id_token verification failed: nonce does not match");if(typeof d.sub!=="string"||d.sub==="")throw Error("id_token verification failed: token has no subject");return d}class de extends y{baseUrl="https://appleid.apple.com";teamId="";keyId="";privateKey="";native=!1;constructor(e){super(e);this.teamId=e.teamId??"",this.keyId=e.keyId??"",this.privateKey=e.privateKey??"",this.native=e.native===!0}getConfig(){let e={clientId:this.clientId||(R.services.apple?.clientId??""),teamId:this.teamId||(R.services.apple?.teamId??""),keyId:this.keyId||(R.services.apple?.keyId??""),privateKey:(this.privateKey||(R.services.apple?.privateKey??"")).replace(/\\n/g,`
3
+ `),redirectUrl:this.native?"":this.redirectUrl||(R.services.apple?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:R.services.apple?.scopes??["name","email"]};return this.setScopes(e.scopes),e}async getAuthUrl(){if(this.native)throw new g("A native Apple provider redeems the app's codes; the web flow needs the Service ID");let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();this.validateConfig();let n={client_id:t,redirect_uri:r,scope:i.join(" "),state:e,response_type:"code",...this.parameters};if(i.length>0)n.response_mode="form_post";return`${this.baseUrl}/auth/authorize?${new URLSearchParams(n).toString()}`}async getAccessToken(e){let{clientId:t,redirectUrl:r}=this.getConfig();this.validateConfig();let i=await fetch(`${this.baseUrl}/auth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,...this.native?{}:{redirect_uri:r},client_id:t,client_secret:this.generateClientSecret()})}),n=await i.json();if(!i.ok||n.error)throw Error(`Apple OAuth error: ${n.error_description??n.error??`HTTP ${i.status}`}`);if(!n.id_token)throw Error("Apple OAuth error: token response contained no id_token");return n.id_token}async getUserByToken(e,t={}){let{clientId:r}=this.getConfig(),i;try{i=await J(e,{jwksUrl:`${this.baseUrl}/auth/keys`,issuer:this.baseUrl,audience:r,nonce:t.nonce})}catch(o){throw Error(`Apple OAuth error: ${o instanceof Error?o.message:String(o)}`)}let n=typeof i.email==="string"?i.email:null,s=null;if(i.email_verified===!0||i.email_verified==="true")s=!0;else if(i.email_verified===!1||i.email_verified==="false")s=!1;return{id:String(i.sub),nickname:null,name:"",email:n,emailVerified:s,avatar:null,token:e,raw:i}}generateClientSecret(){let{clientId:e,teamId:t,keyId:r,privateKey:i}=this.getConfig(),n=Math.floor(Date.now()/1000),s={alg:"ES256",kid:r,typ:"JWT"},o={iss:t,iat:n,exp:n+3600,aud:this.baseUrl,sub:e},a=`${this.base64urlJson(s)}.${this.base64urlJson(o)}`,c;try{c=kt(i)}catch(l){throw new g(`Apple private key could not be parsed: ${l instanceof Error?l.message:String(l)}`)}let u=bt("sha256",Re.from(a),{key:c,dsaEncoding:"ieee-p1363"});return`${a}.${u.toString("base64url")}`}base64urlJson(e){return Re.from(JSON.stringify(e)).toString("base64url")}validateConfig(){let{clientId:e,teamId:t,keyId:r,privateKey:i,redirectUrl:n}=this.getConfig();if(!e)throw new g(this.native?"Apple client ID (the app's bundle ID) not provided":"Apple client ID (Service ID) not provided");if(!t)throw new g("Apple team ID not provided");if(!r)throw new g("Apple key ID not provided");if(!i)throw new g("Apple private key not provided");if(!n&&!this.native)throw new g("Apple redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/auth/token`}}import{fetchPublicUrl as Rt,outboundUrlProblem as Ct}from"@stacksjs/security";import{fetchPublicUrl as St}from"@stacksjs/security";var Pt=10485760;function le(e){if(e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255)return"image/jpeg";if(e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71)return"image/png";if(e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56)return"image/gif";if(e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80)return"image/webp";return null}function Ce(e){let t=le(e);if(!t)return;let r=new DataView(e.buffer,e.byteOffset,e.byteLength);if(t==="image/png"&&e.length>=24){let i=r.getUint32(16),n=r.getUint32(20);return i>0&&n>0?{width:i,height:n}:void 0}if(t==="image/gif"&&e.length>=10){let i=r.getUint16(6,!0),n=r.getUint16(8,!0);return i>0&&n>0?{width:i,height:n}:void 0}if(t==="image/webp"&&e.length>=30){let i=String.fromCharCode(e[12],e[13],e[14],e[15]);if(i==="VP8X"&&e.length>=30){let n=1+(e[24]|e[25]<<8|e[26]<<16),s=1+(e[27]|e[28]<<8|e[29]<<16);return n>0&&s>0?{width:n,height:s}:void 0}if(i==="VP8 "&&e.length>=30&&e[23]===157&&e[24]===1&&e[25]===42){let n=r.getUint16(26,!0)&16383,s=r.getUint16(28,!0)&16383;return n>0&&s>0?{width:n,height:s}:void 0}if(i==="VP8L"&&e.length>=25&&e[20]===47){let n=r.getUint32(21,!0),s=(n&16383)+1,o=(n>>14&16383)+1;return s>0&&o>0?{width:s,height:o}:void 0}return}if(t==="image/jpeg"){let i=2;while(i+4<=e.length){if(e[i]!==255)break;while(i<e.length&&e[i]===255)i++;if(i>=e.length)break;let n=e[i];if(i++,n===216||n===217||n===1||n>=208&&n<=215)continue;if(i+2>e.length)break;let s=r.getUint16(i);if(s<2||i+s>e.length)break;if((n>=192&&n<=195||n>=197&&n<=199||n>=201&&n<=203||n>=205&&n<=207)&&s>=7){let a=r.getUint16(i+3),c=r.getUint16(i+5);return c>0&&a>0?{width:c,height:a}:void 0}i+=s}}return}async function C(e,t={}){try{let r=await St(e,{},{allowHttp:!0,timeoutMs:15000,maxBytes:Pt,...t});if(!r.ok)return null;let i=new Uint8Array(await r.arrayBuffer()),n=le(i);return n?{bytes:i,mimeType:n}:null}catch{return null}}class Ee extends Error{url;status=422;body="";constructor(e){super(`Could not read the image at ${e}.`);this.url=e;this.name="PostImageError"}}async function E(e,t){if(e.bytes?.length)return{bytes:e.bytes,mimeType:e.mimeType||le(e.bytes)||"image/jpeg"};if(!e.url)return;let r=await t(e.url);if(!r)throw new Ee(e.url);return r}function G(e,t){if(t?.length)throw Error("A video cannot be attached together with images.");if(e.mimeType!=="video/mp4"||!e.bytes.length)throw Error("Attach a non-empty MP4 video.");let r=e.aspectRatio;if(r&&![r.width,r.height].every((i)=>Number.isSafeInteger(i)&&i>0))throw Error("Video width and height must be positive integers.")}function I(e,t){if(e.video)throw Error(`Video publishing to ${t} is unavailable.`)}var ni=23,vt=/\bhttps?:\/\/[^\s<>]+|(?<![@\w.-])(?:[a-z0-9-]+\.)+(?:com|org|net|io|dev|app|co|social|blog|ai|me|info|xyz|tv|fm|us|uk|de|fr|jp|ca|au|nl|ch|se|no|es|it)\b(?:\/[^\s<>]*)?/gi,xt=/[.,;:!?)\]}'"]+$/,$e;function Le(){return $e??=new Intl.Segmenter(void 0,{granularity:"grapheme"}),$e}function K(e){let t=0;for(let r of Le().segment(e))t++;return t}function Oe(e){let t=[],r=0;for(let i of e.matchAll(vt)){let n=i[0].replace(xt,"");if(!n)continue;let s=i.index;if(s>r)t.push({link:!1,value:e.slice(r,s)});t.push({link:!0,value:n}),r=s+n.length}if(r<e.length)t.push({link:!1,value:e.slice(r)});return t}function _t(e){return e<=4351||e>=8192&&e<=8205||e>=8208&&e<=8223||e>=8242&&e<=8247}function It(e){let t=0;for(let{segment:r}of Le().segment(e.normalize("NFC"))){if(/\p{Extended_Pictographic}|\p{Regional_Indicator}/u.test(r)){t+=2;continue}for(let i of r)t+=_t(i.codePointAt(0))?1:2}return t}function Tt(e,t,r={}){let i=String(t??"");switch(e){case"twitter":return Oe(i).reduce((n,s)=>n+(s.link?23:It(s.value)),0);case"mastodon":{let n=r.linkLength??23;return Oe(i).reduce((s,o)=>{if(o.link)return s+n;return s+K(o.value.replace(/(^|[^\w/])(@[\w.-]+)@[\w.-]+\.[a-z]{2,}/gi,"$1$2"))},0)}case"bluesky":case"threads":return K(i);default:return i.length}}function P(e,t,r,i={}){return r>0&&Tt(e,t,i)>r}function X(e){let t;try{t=typeof e==="string"?JSON.parse(e):e}catch{return""}if(!t||typeof t!=="object")return"";let r=Array.isArray(t.errors)?t.errors[0]:void 0,i=[t.detail,t.error?.error_user_msg,t.error?.message,t.message,t.error_description,t.error_message,r?.detail,r?.message,typeof t.error==="string"?t.error:void 0];for(let n of i){let s=typeof n==="string"?n.replace(/\s+/g," ").trim():"";if(s&&s.length<=200&&s.includes(" ")&&!/[{}<>]/.test(s))return s.replace(/[.!]+$/,"")}return""}function At(e,t){let r=(i)=>i.test(t);if(e===429||r(/rate.?limit|too many requests|usage cap|throttl|request limit reached/i))return"rate-limited";if(r(/duplicate|already (?:posted|published|exists)|DUPLICATE_POST/i))return"duplicate";if(e===401||r(/invalid.?token|expired.?token|token (?:has )?(?:expired|been revoked)|session has (?:expired|been invalidated)|OAuthException.*(?:expired|invalid)|REVOKED_ACCESS_TOKEN/i))return"expired";if(e===408||e>=500)return"temporary";if(e===403)return"permission";if(e===413||r(/media|image|video|attachment|aspect ratio|file size|unsupported (?:format|type)|blob/i))return"media";if(r(/permission|scope|not (?:allowed|authorized|permitted)|forbidden|ACCESS_DENIED|insufficient/i))return"permission";if(e===400||e===404||e===409||e===422)return"content";if(r(/fetch failed|network|ENOTFOUND|ECONNREFUSED|ECONNRESET|EAI_AGAIN|timed? ?out|socket|aborted/i))return"temporary";return"unknown"}function Q(e){let t=e??{},r=Number(t.status)||0,i=String(t.message??e??""),n=X(t.body),s=typeof t.body==="string"?t.body.slice(0,2000):"";return{kind:At(r,`${n} ${s} ${r?"":i}`),status:r,reason:n}}function oi(e){return Q(e).kind==="expired"}class k extends Error{network;status;body;retryAfterMs;constructor(e,t,r,i,n={}){super(t);this.network=e;this.status=r;this.body=i;if(this.name="SocialApiError",n.retryAfterMs!==void 0)this.retryAfterMs=n.retryAfterMs}get kind(){return Q(this).kind}get reason(){return X(this.body)}}function Be(e,t){let r=e.trim();if(!r)return;if(/^\d+(?:\.\d+)?$/.test(r)){let n=Number(r);if(!Number.isFinite(n))return;return n>1e9?Math.max(0,Math.round(n*1000-t)):Math.round(n*1000)}let i=Date.parse(r);return Number.isNaN(i)?void 0:Math.max(0,i-t)}function Ut(e,t){let r=t.now??Date.now(),i=e.get("retry-after");if(i){let s=Be(i,r);if(s!==void 0)return s}if(!t.rateLimited)return;for(let s of["x-rate-limit-reset","ratelimit-reset","x-ratelimit-reset"]){let o=e.get(s),a=o?Be(o,r):void 0;if(a!==void 0)return a}let n=0;for(let s of["x-business-use-case-usage","x-app-usage"]){let o=e.get(s);if(!o)continue;try{let a=JSON.parse(o),c=Array.isArray(a)?a:Object.values(a??{}).flat();for(let u of[a,...c]){let l=Number(u?.estimated_time_to_regain_access);if(Number.isFinite(l)&&l>n)n=l}}catch{}}return n>0?n*60000:void 0}function f(e,t,r){let i=X(r)||t.statusText||"no reason given",n=Ut(t.headers,{rateLimited:Q({status:t.status,body:r}).kind==="rate-limited"});return[`${e} failed (${t.status}): ${i}`,t.status,r,n===void 0?{}:{retryAfterMs:n}]}var O="app.bsky.feed.post";function he(e){let t=/^at:\/\/([^/]+)\/([^/]+)\/([^/]+)$/.exec(String(e||"").trim());if(!t)throw Error(`"${e}" is not a Bluesky post URI.`);return{repo:t[1],collection:t[2],rkey:t[3]}}class _ extends k{constructor(e,t,r,i={}){super("bluesky",e,t,r,i);this.name="BlueskyApiError"}get isAuthError(){if(this.status===401||this.status===403)return!0;if(this.status!==400)return!1;try{return Et.includes(String(JSON.parse(this.body)?.error))}catch{return!1}}}var Et=["ExpiredToken","InvalidToken"],Me=1e6,De=300000000,Ne="https://video.bsky.app",$t=90000;function Ve(e,t){if(e?.id!==t)return;let r=e.service?.find((n)=>(n?.id==="#atproto_pds"||n?.id===`${t}#atproto_pds`)&&n.type==="AtprotoPersonalDataServer"),i=typeof r?.serviceEndpoint==="string"?URL.parse(r.serviceEndpoint):null;if(!i||i.protocol!=="https:"||i.username||i.password||i.search||i.hash)return;if(Ct(i.href))return;return i.href.replace(/\/+$/,"")}var Ot=4,Lt=3,ze=200;function gi(e){return e instanceof _&&e.isAuthError}var Bt=new TextEncoder;function A(e){return Bt.encode(e).length}function Mt(e){let t=e;while(t.length>0){let r=t[t.length-1];if(r===")"||r==="]"){let i=r===")"?"(":"[",n=0;for(let s of t)if(s===i)n++;else if(s===r)n--;if(n>=0)break;t=t.slice(0,-1);continue}if(/[.,;!?:'"\u201D\u2019]/.test(r)){t=t.slice(0,-1);continue}break}return t}function Dt(e){let t=[],r=/https?:\/\/[^\s<>"']+/g;for(let o of e.matchAll(r)){let a=Mt(o[0]);if(!a)continue;t.push({byteStart:A(e.slice(0,o.index)),byteEnd:A(e.slice(0,o.index))+A(a),type:"link",value:a})}let i=(o,a)=>t.some((c)=>c.type==="link"&&o<c.byteEnd&&a>c.byteStart),n=/(^|[\s(["'\u201C\u2018])([#\uFF03])([^\s\u00AD\u2060\u200A-\u200D\u20E2]+)/gu;for(let o of e.matchAll(n)){let a=o[1],c=o[2],u=o[3];if(a===void 0||c===void 0||u===void 0)continue;let l=u.replace(/\p{P}+$/u,"");if(!l||!/[^\d\p{P}]/u.test(l)||[...l].length>64)continue;let d=(o.index??0)+a.length,h=A(e.slice(0,d)),p=h+A(c+l);if(i(h,p))continue;t.push({byteStart:h,byteEnd:p,type:"tag",value:l})}let s=/(^|[\s(["'\u201C\u2018])(@[a-z0-9][a-z0-9.-]*\.[a-z]{2,})/gi;for(let o of e.matchAll(s)){let a=o[1],c=o[2];if(a===void 0||c===void 0)continue;let u=(o.index??0)+a.length,l=A(e.slice(0,u)),d=l+A(c);if(i(l,d))continue;t.push({byteStart:l,byteEnd:d,type:"mention",value:c.slice(1).replace(/\.+$/,"")})}return t.sort((o,a)=>o.byteStart-a.byteStart)}async function qe(e,t={}){let r=(t.entryway??"https://bsky.social").replace(/\/+$/,""),i=(t.directory??"https://plc.directory").replace(/\/+$/,""),n=t.fetchJson??(async(s)=>{let a=s.startsWith(`${r}/`)||s.startsWith(`${i}/`)?await fetch(s,{redirect:"error",signal:AbortSignal.timeout(1e4)}):await Rt(s,{},{maxRedirects:0,timeoutMs:1e4,maxBytes:262144});if(!a.ok)throw Error(`${a.status}`);return await a.json()});try{let s=e.trim(),o=s.startsWith("did:")?void 0:s.replace(/^@/,"").toLowerCase();if(o!==void 0){let l=await n(`${r}/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(o)}`);if(typeof l?.did!=="string")return;s=l.did}let a;if(/^did:plc:[a-z0-9]+$/i.test(s))a=`${i}/${s}`;else if(/^did:web:[a-z0-9.-]+$/i.test(s))a=`https://${s.slice(8)}/.well-known/did.json`;else return;let c=await n(a),u=c?.alsoKnownAs?.find((l)=>typeof l==="string"&&l.startsWith("at://"));if(o!==void 0&&typeof u==="string"?u.toLowerCase()!==`at://${o}`:o!==void 0)return;return Ve(c,s)}catch{return}}var N=/^did:[a-z]+:[A-Za-z0-9._:%-]+$/,Nt=/^[A-Za-z0-9._:~-]{1,512}$/,ue=/^[A-Za-z0-9]{1,256}$/;function zt(e){let t=e.split(".");return t.length>=2&&t.every((r)=>/^[A-Za-z0-9-]+$/.test(r))&&/^[A-Za-z]+$/.test(t[t.length-1])}function qt(e){if(e.length>128)return!1;return(e.startsWith("!")?e.slice(1):e).split("-").every((r)=>/^[a-z]+$/.test(r))}function Fe(e){let t,r;if(e.startsWith("at://")){let i=he(e);if(i.collection===O)({repo:t,rkey:r}=i)}else{let i=URL.parse(e);if(i?.origin==="https://bsky.app"&&!i.username&&!i.password){let[,n,s]=/^\/profile\/([^/]+)\/post\/([^/]+)\/?$/.exec(i.pathname)??[];try{if(n&&s)t=decodeURIComponent(n),r=decodeURIComponent(s)}catch{}}}if(!t||!N.test(t)&&!zt(t)||!r||!Nt.test(r)||r==="."||r==="..")throw Error("Choose a valid Bluesky post link.");return{repo:t,rkey:r}}function Ft(e){if(!Array.isArray(e)||e.some((r)=>typeof r!=="string"||!qt(r)))throw Error("Bluesky content labels must be lowercase label names.");let t=[...new Set(e)].map((r)=>({val:r}));if(t.length>10)throw Error("Bluesky supports up to 10 self-labels per post.");return t}var Vt="234567abcdefghijklmnopqrstuvwxyz";function mi(e=Date.now(),t=Math.floor(Math.random()*1024)){let r=BigInt(Math.floor(e))*1000n<<10n|BigInt(t&1023),i="";for(let n=0;n<13;n++)i=Vt[Number(r&31n)]+i,r>>=5n;return i}class W{provider="bluesky";characterLimit=300;service;configuredService;fetcher;constructor(e={}){this.service=e.service||"https://bsky.social",this.configuredService=Boolean(e.service),this.fetcher=e.fetcher}async createSession(e){let t=e.identifier.trim(),r=e.password.trim();if(!t)throw Error("Bluesky identifier is required.");if(!r)throw Error("Bluesky app password is required.");let i=await this.signIn(t,r),n=await this.getProfile({did:i.did,handle:i.handle,accessToken:i.accessJwt,refreshToken:i.refreshJwt}).catch(()=>{return});return{did:i.did,handle:i.handle,displayName:n?.displayName,accessJwt:i.accessJwt,refreshJwt:i.refreshJwt,service:this.service}}async signIn(e,t){let r=()=>this.post("/xrpc/com.atproto.server.createSession",{identifier:e,password:t});try{return await r()}catch(i){if(!(i instanceof _&&(i.status===400||i.status===401))||this.configuredService)throw i;let s=await qe(e,{entryway:this.service});if(!s||s===this.service)throw i;let o=this.service;this.service=s;try{return await r()}catch(a){throw this.service=o,a}}}async refreshSession(e){if(!e)throw Error("Bluesky refresh token is required.");let t=await this.post("/xrpc/com.atproto.server.refreshSession",void 0,{authorization:`Bearer ${e}`});return{did:t.did,handle:t.handle,accessJwt:t.accessJwt,refreshJwt:t.refreshJwt}}async resolveQuote(e,t){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let{repo:r,rkey:i}=Fe(t.trim()),n=N.test(r)?r:await this.resolveHandle(r);if(!n||!N.test(n))throw Error("Could not resolve the author of this Bluesky post.");let s=`at://${n}/${O}/${i}`,o=new URL(`${this.service}/xrpc/app.bsky.feed.getPosts`);o.searchParams.set("uris",s);let c=(await this.request(o,{headers:{authorization:`Bearer ${e.accessToken}`},redirect:"error",signal:AbortSignal.timeout(15000)})).posts?.find((u)=>u.uri===s);if(!c||typeof c.cid!=="string"||!ue.test(c.cid))throw Error("Could not find the Bluesky post at this link.");if(c.viewer?.embeddingDisabled)throw Error("The author has disabled quoting this Bluesky post.");return{uri:s,cid:c.cid}}async publish(e,t,r={}){let i=e.did||e.handle;if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(!i)throw Error("Bluesky identity DID or handle is required.");if(P("bluesky",t.text,this.characterLimit))throw Error(`Bluesky posts must be ${this.characterLimit} characters or fewer.`);if(t.video){if(G(t.video,t.media),t.video.bytes.length>De)throw Error("Bluesky video must be 300 MB or smaller.")}let n=r.quote;if(n){let d=Fe(n.uri);if(n.uri!==`at://${d.repo}/${O}/${d.rkey}`||!N.test(d.repo)||typeof n.cid!=="string"||!ue.test(n.cid))throw Error("Resolve the Bluesky post before quoting it.")}let s=r.selfLabels===void 0?[]:Ft(r.selfLabels),o={$type:"app.bsky.feed.post",text:t.text,createdAt:t.scheduledAt||new Date().toISOString()};if(t.langs?.length)o.langs=t.langs.slice(0,Lt);if(t.reply)o.reply=t.reply;if(s.length)o.labels={$type:"com.atproto.label.defs#selfLabels",values:s};let a=t.facets??await this.buildFacets(t.text);if(a.length)o.facets=a;let c=[],u=(t.media||[]).filter((d)=>d.bytes?.length).slice(0,Ot);if(t.video){if(o.embed={$type:"app.bsky.embed.video",video:await this.uploadVideo(e,t.video),...t.video.altText&&{alt:t.video.altText},...t.video.aspectRatio&&{aspectRatio:t.video.aspectRatio}},t.external)c.push("A Bluesky post holds one attachment, so the video went out and the link card did not. The link in the text still works.")}else if(u.length){let d=[];for(let h of u){let p=await this.uploadBlob(e,h.bytes,h.mimeType||"image/jpeg"),m=Ce(h.bytes);d.push({image:p,alt:h.altText||"",...m?{aspectRatio:m}:{}})}if(o.embed={$type:"app.bsky.embed.images",images:d},t.external)c.push("A Bluesky post holds one attachment, so the images went out and the link card did not. The link in the text still works.")}else if(t.external){let d={uri:t.external.uri,title:t.external.title,description:t.external.description||""},h=t.external.thumb;if(h?.bytes?.length)if(h.bytes.length>Me)c.push("The link card's picture is larger than Bluesky takes, so the card went out without it.");else try{d.thumb=await this.uploadBlob(e,h.bytes,h.mimeType)}catch{c.push("Bluesky did not take the link card's picture, so the card went out without it.")}o.embed={$type:"app.bsky.embed.external",external:d}}if(n){let d={$type:"app.bsky.embed.record",record:{uri:n.uri,cid:n.cid}};o.embed=o.embed?{$type:"app.bsky.embed.recordWithMedia",record:d,media:o.embed}:d}let l=await this.createPostRecord(e,i,o,r.rkey);return{provider:this.provider,uri:l.uri,cid:l.cid,url:this.toPostUrl(e.handle,l.uri),...c.length?{warnings:c}:{}}}async metrics(e,t){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let r=[];for(let i=0;i<t.length;i+=25){let n=new URL(`${this.service}/xrpc/app.bsky.feed.getPosts`);for(let o of t.slice(i,i+25))n.searchParams.append("uris",o);let s=await this.request(n,{headers:{authorization:`Bearer ${e.accessToken}`}});for(let o of s.posts||[])r.push({uri:o.uri,likes:o.likeCount??0,reposts:o.repostCount??0,replies:o.replyCount??0,quotes:o.quoteCount??0})}return r}async postMetrics(e,t){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(t.length===0)return[];let r=new URL(`${this.service}/xrpc/app.bsky.feed.getPosts`);for(let n of t.slice(0,25))r.searchParams.append("uris",n);return((await this.request(r,{headers:{authorization:`Bearer ${e.accessToken}`}})).posts||[]).map((n)=>({uri:n.uri,likeCount:n.likeCount||0,repostCount:n.repostCount||0,replyCount:n.replyCount||0}))}async timeline(e,t={}){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let r=new URL(`${this.service}/xrpc/app.bsky.feed.getTimeline`);if(r.searchParams.set("limit",String(Math.min(Math.max(t.limit||30,1),100))),t.cursor)r.searchParams.set("cursor",t.cursor);let i=await this.request(r,{headers:{authorization:`Bearer ${e.accessToken}`}});return{cursor:i.cursor,items:(i.feed||[]).flatMap((n)=>{let s=n.post;if(!s?.uri||!s.author?.handle)return[];return[{uri:s.uri,authorHandle:s.author.handle,authorName:s.author.displayName,authorAvatar:s.author.avatar,postUrl:this.toPostUrl(s.author.handle,s.uri),body:s.record?.text||"",postedAt:s.record?.createdAt||new Date().toISOString(),likeCount:s.likeCount||0,repostCount:s.repostCount||0,replyCount:s.replyCount||0}]})}}async getProfile(e){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let t=e.did||e.handle;if(!t)throw Error("Bluesky identity DID or handle is required.");let r=new URL(`${this.service}/xrpc/app.bsky.actor.getProfile`);return r.searchParams.set("actor",t),await this.request(r,{headers:{authorization:`Bearer ${e.accessToken}`}})}async buildFacets(e){let t=[];for(let r of Dt(e)){let i=null;if(r.type==="link")i={$type:"app.bsky.richtext.facet#link",uri:r.value};else if(r.type==="tag")i={$type:"app.bsky.richtext.facet#tag",tag:r.value};else if(r.type==="mention"){let n=await this.resolveHandle(r.value);if(n)i={$type:"app.bsky.richtext.facet#mention",did:n}}if(i)t.push({index:{byteStart:r.byteStart,byteEnd:r.byteEnd},features:[i]})}return t}async resolveHandle(e){try{let t=new URL(`${this.service}/xrpc/com.atproto.identity.resolveHandle`);return t.searchParams.set("handle",e),(await this.request(t,{})).did||null}catch{return null}}async uploadVideo(e,t){let r={authorization:`Bearer ${e.accessToken}`},i=await this.request(new URL(`${this.service}/xrpc/com.atproto.server.getSession`),{headers:r,signal:AbortSignal.timeout(15000)});if(!N.test(i.did)||e.did&&i.did!==e.did)throw Error("Bluesky could not verify the account for this video.");let n=Ve(i.didDoc,i.did)??await qe(i.did);if(!n)throw Error("Bluesky could not find the account\u2019s data server for this video.");let s=new URL(`${this.service}/xrpc/com.atproto.server.getServiceAuth`);s.searchParams.set("aud",`did:web:${new URL(n).host.replace(":","%3A")}`),s.searchParams.set("lxm","com.atproto.repo.uploadBlob"),s.searchParams.set("exp",String(Math.floor(Date.now()/1000)+1800));let{token:o}=await this.request(s,{headers:r,signal:AbortSignal.timeout(15000)});if(typeof o!=="string"||!o)throw Error("Bluesky did not authorize the video upload.");let a=new URL("/xrpc/app.bsky.video.uploadVideo",Ne);a.searchParams.set("did",i.did),a.searchParams.set("name","upload.mp4");let c=await(this.fetcher??fetch)(a,{method:"POST",headers:{authorization:`Bearer ${o}`,"content-type":t.mimeType,"content-length":String(t.bytes.length)},body:new Uint8Array(t.bytes),redirect:"error",signal:AbortSignal.timeout(120000)}),u=await c.text(),l;try{l=JSON.parse(u)}catch{}let d=l?.jobStatus??l??{};if(d.error==="unconfirmed_email")throw Error("Verify your Bluesky account email before uploading video.");if(!c.ok&&!(c.status===409&&d.error==="already_exists"))throw new _(...f("Bluesky video service",c,u));if(d.did!==i.did||typeof d.jobId!=="string"||!d.jobId||d.jobId.length>200)throw Error("Bluesky did not return a video processing job for this account.");let h=new URL("/xrpc/app.bsky.video.getJobStatus",Ne);h.searchParams.set("jobId",d.jobId);let p=AbortSignal.timeout($t);for(;;){let m=d.blob;if(m){if(m.$type!=="blob"||m.mimeType!==t.mimeType||typeof m.ref?.$link!=="string"||!ue.test(m.ref.$link)||typeof m.size!=="number"||!Number.isSafeInteger(m.size)||m.size<=0||m.size>De)throw Error("Bluesky did not return a valid processed video attachment.");return m}if(d.state==="JOB_STATE_FAILED")throw new _(d.message||"Bluesky could not process the video.",422,JSON.stringify({message:d.message,error:d.failureCode}));if(p.aborted)throw new _("Bluesky took too long to process the attachment.",503,"");let T;try{T=await this.request(h,{signal:p})}catch(D){if(p.aborted)throw new _("Bluesky took too long to process the attachment.",503,"");throw D}if(T.jobStatus?.jobId!==d.jobId||T.jobStatus?.did!==i.did)throw Error("Bluesky returned a different video processing job.");if(d=T.jobStatus,!d.blob&&d.state!=="JOB_STATE_FAILED")await Bun.sleep(1000)}}async uploadBlob(e,t,r){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(t.length>Me)throw Error("Bluesky images must be 1MB or smaller.");return(await this.request(new URL(`${this.service}/xrpc/com.atproto.repo.uploadBlob`),{method:"POST",headers:{"content-type":r,authorization:`Bearer ${e.accessToken}`},body:new Uint8Array(t)})).blob}async listAuthoredPosts(e,t={}){let r=e.did||e.handle;if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(!r)throw Error("Bluesky identity DID or handle is required.");let i=new URL(`${this.service}/xrpc/com.atproto.repo.listRecords`);if(i.searchParams.set("repo",r),i.searchParams.set("collection",O),i.searchParams.set("limit",String(Math.min(Math.max(t.limit||100,1),100))),t.cursor)i.searchParams.set("cursor",t.cursor);let n=await this.request(i,{headers:{authorization:`Bearer ${e.accessToken}`}});return{cursor:n.cursor,posts:(n.records||[]).filter((s)=>s?.uri).map((s)=>({uri:s.uri,cid:s.cid,text:s.value?.text,postedAt:s.value?.createdAt,url:e.handle?this.toPostUrl(e.handle,s.uri):void 0}))}}async createPostRecord(e,t,r,i){let n=`Bearer ${e.accessToken}`;try{return await this.post("/xrpc/com.atproto.repo.createRecord",{repo:t,collection:O,...i?{rkey:i}:{},record:r},{authorization:n})}catch(s){if(!i||!(s instanceof _)||s.status>=500)throw s;let o=new URL(`${this.service}/xrpc/com.atproto.repo.getRecord`);o.searchParams.set("repo",t),o.searchParams.set("collection",O),o.searchParams.set("rkey",i);let a=await this.request(o,{headers:{authorization:n}}).catch(()=>{return});if(a?.uri&&a.cid&&a.value?.text===r.text)return{uri:a.uri,cid:a.cid};throw s}}async deletePost(e,t){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let{repo:r,collection:i,rkey:n}=he(t.uri);await this.post("/xrpc/com.atproto.repo.deleteRecord",{repo:r,collection:i,rkey:n},{authorization:`Bearer ${e.accessToken}`})}async deletePosts(e,t){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(!t.length)return;let r=new Map;for(let n of t){let{repo:s,collection:o,rkey:a}=he(n.uri),c=r.get(s)??[];c.push({collection:o,rkey:a}),r.set(s,c)}let i={authorization:`Bearer ${e.accessToken}`};for(let[n,s]of r)for(let o=0;o<s.length;o+=ze){let a=s.slice(o,o+ze);await this.post("/xrpc/com.atproto.repo.applyWrites",{repo:n,writes:a.map(({collection:c,rkey:u})=>({$type:"com.atproto.repo.applyWrites#delete",collection:c,rkey:u}))},i)}}async post(e,t,r={}){return await this.request(new URL(`${this.service}${e}`),{method:"POST",headers:{...t===void 0?{}:{"content-type":"application/json"},...r},...t===void 0?{}:{body:JSON.stringify(t)}})}async request(e,t){let r=await(this.fetcher??fetch)(e,{...t,redirect:"error",signal:t.signal??AbortSignal.timeout(30000)}),i=await r.text();if(!r.ok)throw new _(...f("Bluesky API",r,i));return i?JSON.parse(i):{}}toPostUrl(e,t){let r=t.split("/").pop();return`https://bsky.app/profile/${e}/post/${r}`}}import{fetcher as je}from"@stacksjs/api";import{config as z}from"@stacksjs/config";var Y="v24.0";function Z(e){try{let t=JSON.parse(String(e?.body??""));return t.error?.code===100&&/does not exist/i.test(String(t.error.message))}catch{return!1}}class pe extends y{baseUrl="https://www.facebook.com";apiUrl="https://graph.facebook.com";get graphVersion(){return z.services.facebook?.graphVersion??Y}getConfig(){let e={clientId:this.clientId||(z.services.facebook?.clientId??""),clientSecret:this.clientSecret||(z.services.facebook?.clientSecret??""),redirectUrl:this.redirectUrl||(z.services.facebook?.redirectUrl??""),scopes:z.services.facebook?.scopes??["email","public_profile"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/${this.graphVersion}/dialog/oauth?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(","),response_type:"code",...await this.pkceFields(),...this.parameters,state:e}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let n=await je.get(`${this.apiUrl}/${this.graphVersion}/oauth/access_token?${new URLSearchParams({client_id:t,client_secret:r,redirect_uri:i,code:e,...this.pkceTokenFields()}).toString()}`);if(n.data.error)throw Error(`Facebook OAuth error: ${n.data.error.message}`);return n.data.access_token}async getUserByToken(e){let t=await je.withHeaders({Authorization:`Bearer ${e}`}).get(`${this.apiUrl}/${this.graphVersion}/me?${new URLSearchParams({fields:"id,name,email,picture"}).toString()}`);return{id:t.data.id,nickname:null,name:t.data.name,email:t.data.email??null,avatar:t.data.picture?.data.url??null,token:e,raw:t.data}}validateConfig(){let{clientId:e,clientSecret:t,redirectUrl:r}=this.getConfig();if(!e)throw new g("Facebook client ID not provided");if(!t)throw new g("Facebook client secret not provided");if(!r)throw new g("Facebook redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/${this.graphVersion}/oauth/access_token`}}import{fetcher as ge}from"@stacksjs/api";import{config as ee}from"@stacksjs/config";class me extends y{baseUrl="https://github.com";apiUrl="https://api.github.com";getConfig(){let e={clientId:this.clientId||(ee.services.github?.clientId??""),clientSecret:this.clientSecret||(ee.services.github?.clientSecret??""),redirectUrl:this.redirectUrl||(ee.services.github?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:ee.services.github?.scopes??["read:user","user:email"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/login/oauth/authorize?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(" "),state:e,response_type:"code",...await this.pkceFields(),...this.parameters}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let n=await ge.post(`${this.baseUrl}/login/oauth/access_token`,{client_id:t,client_secret:r,code:e,redirect_uri:i,...this.pkceTokenFields()});if(n.data.error)throw Error(`GitHub OAuth error: ${n.data.error_description}`);return n.data.access_token}async getUserByToken(e){let[t,r]=await Promise.all([ge.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${e}`}).get(`${this.apiUrl}/user`),ge.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${e}`}).get(`${this.apiUrl}/user/emails`)]),i=this.pickEmail(r.data);return{id:t.data.id.toString(),nickname:t.data.login,name:t.data.name??t.data.login,email:i?.email??t.data.email??null,emailVerified:i?i.verified:null,avatar:t.data.avatar_url,token:e,raw:t.data}}pickEmail(e){if(!Array.isArray(e)||e.length===0)return null;let t=e.find((i)=>i.primary&&i.verified),r=e.find((i)=>i.verified);return t??r??e.find((i)=>i.primary)??e[0]??null}getEmail(e){return this.pickEmail(e)?.email??null}validateConfig(){let{clientId:e,clientSecret:t,redirectUrl:r}=this.getConfig();if(!e)throw new g("GitHub client ID not provided");if(!t)throw new g("GitHub client secret not provided");if(!r)throw new g("GitHub redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/login/oauth/access_token`}}import{fetcher as He}from"@stacksjs/api";import{config as te}from"@stacksjs/config";class fe extends y{baseUrl="https://accounts.google.com";apiUrl="https://www.googleapis.com";tokenUrl="https://oauth2.googleapis.com/token";tokenInfoUrl="https://oauth2.googleapis.com/tokeninfo";certsUrl="https://www.googleapis.com/oauth2/v3/certs";issuers=["https://accounts.google.com","accounts.google.com"];getConfig(){let e={clientId:this.clientId||(te.services.google?.clientId??""),clientSecret:this.clientSecret||(te.services.google?.clientSecret??""),redirectUrl:this.redirectUrl||(te.services.google?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:te.services.google?.scopes??["openid","email"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/o/oauth2/v2/auth?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(" "),state:e,response_type:"code",access_type:"offline",prompt:"consent",...await this.pkceFields(),...this.parameters}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let n=await He.post(this.tokenUrl,{client_id:t,client_secret:r,code:e,redirect_uri:i,grant_type:"authorization_code",...this.pkceTokenFields()});if(n.data.error)throw Error(`Google OAuth error: ${n.data.error_description}`);return n.data.access_token}async getUserByToken(e){await this.assertTokenWasIssuedToUs(e);let t=await He.withHeaders({Authorization:`Bearer ${e}`}).get(`${this.apiUrl}/oauth2/v2/userinfo`);return{id:t.data.id,nickname:t.data.given_name,name:t.data.name,email:t.data.email,emailVerified:typeof t.data.verified_email==="boolean"?t.data.verified_email:null,avatar:t.data.picture,token:e,raw:t.data}}async getUserByIdToken(e,t={}){let{clientId:r}=this.getConfig(),i;try{i=await J(e,{jwksUrl:this.certsUrl,issuer:this.issuers,audience:r,nonce:t.nonce})}catch(s){throw Error(`Google OAuth error: ${s instanceof Error?s.message:String(s)}`)}let n=typeof i.email==="string"?i.email:"";return{id:String(i.sub),nickname:typeof i.given_name==="string"?i.given_name:null,name:typeof i.name==="string"?i.name:"",email:n,emailVerified:typeof i.email_verified==="boolean"?i.email_verified:i.email_verified==="true"?!0:i.email_verified==="false"?!1:null,avatar:typeof i.picture==="string"?i.picture:null,token:e,raw:i}}async assertTokenWasIssuedToUs(e){let{clientId:t}=this.getConfig(),r=await fetch(`${this.tokenInfoUrl}?access_token=${encodeURIComponent(e)}`);if(!r.ok)throw Error(`Google OAuth error: access token was not accepted by tokeninfo (HTTP ${r.status})`);let i=await r.json();if(i.error)throw Error(`Google OAuth error: ${i.error_description??i.error}`);let n=i.aud??i.audience;if(!n)throw Error("Google OAuth error: tokeninfo did not report an audience for the access token");if(n!==t)throw Error("Google OAuth error: access token was issued to a different client")}validateConfig(){let{clientId:e,clientSecret:t,redirectUrl:r}=this.getConfig();if(!e)throw new g("Google client ID not provided");if(!t)throw new g("Google client secret not provided");if(!r)throw new g("Google redirect URL not provided")}getTokenUrl(){return this.tokenUrl}}var jt=10,Ht=1000,Jt=20,Je={likes:"likes",comments:"replies",shares:"shares",saved:"saves",reach:"reach",views:"views"};class b extends k{constructor(e,t,r,i={}){super("instagram",e,t,r,i);this.name="InstagramApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class we{provider="instagram";characterLimit=2200;maxImages=jt;containerTimeoutMs=300000;graphVersion;authBase;graphBase;constructor(e={}){this.graphVersion=e.graphVersion||Y,this.authBase=e.authBase||"https://www.facebook.com",this.graphBase=e.graphBase||"https://graph.facebook.com"}getAuthUrl(e){let t=new URLSearchParams({client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(","),state:e.state,response_type:"code"});return`${this.authBase}/${this.graphVersion}/dialog/oauth?${t.toString()}`}async exchangeCode(e){let t=await this.graph("/oauth/access_token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,redirect_uri:e.redirectUrl,code:e.code}).toString()});if(!t.access_token)throw new b("Facebook did not return an access token.",400,JSON.stringify(t));return{accessToken:t.access_token,expiresIn:t.expires_in}}async resolveAccount(e){for await(let t of this.pageAccounts(e))return{igUserId:t.igUserId,username:t.username,pageAccessToken:t.pageAccessToken};throw new b("No Instagram Business account is linked to your Facebook Pages.",400,"")}async listAccounts(e){let t=new Map;for await(let r of this.pageAccounts(e))if(r.pageId&&!t.has(r.pageId))t.set(r.pageId,{...r,pageId:r.pageId});return[...t.values()]}async*pageAccounts(e){let r=`/me/accounts?${new URLSearchParams({fields:"id,name,access_token,instagram_business_account{id,username}"}).toString()}`;for(let i=0;r&&i<Jt;i++){let n=await this.graph(r,{method:"GET"},e);for(let s of n.data??[]){let o=s.instagram_business_account;if(o?.id&&s.access_token)yield{pageId:s.id,pageName:s.name,igUserId:o.id,username:o.username,pageAccessToken:s.access_token}}r=n.paging?.next}}async exchangeLongLivedUserToken(e,t,r){let i=await this.graph("/oauth/access_token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"fb_exchange_token",client_id:e,client_secret:t,fb_exchange_token:r}).toString()});if(!i.access_token)throw new b("Facebook did not return a long-lived token.",400,JSON.stringify(i));return{accessToken:i.access_token,expiresIn:i.expires_in}}async publish(e,t){if(I(t,"Instagram"),!e.accessToken)throw Error("Instagram access token is missing for this identity.");let r=e.did;if(!r)throw Error("Instagram account id is required to publish.");let i=(t.media??[]).slice(0,this.maxImages);if(!i.length)throw Error("Instagram requires an image to post.");if(i.some((l)=>!l.url))throw new b("Instagram fetches images from a public address, and this image has none.",422,"");if(i.some((l)=>l.mimeType&&!/^image\/jpe?g$/i.test(l.mimeType)))throw new b("Instagram only publishes JPEG images, and this image is not one.",422,"");if(P("instagram",t.text,this.characterLimit))throw Error(`Instagram captions must be ${this.characterLimit} characters or fewer.`);let n=e.accessToken,s=async(l)=>{let d=await this.graph(`/${encodeURIComponent(r)}/media`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(l).toString()},n);if(!d.id)throw new b("Instagram did not return a media container id.",400,JSON.stringify(d));return d.id},o=(l)=>({image_url:l.url,...l.altText?.trim()?{alt_text:l.altText.trim().slice(0,Ht)}:{}}),a;if(i.length>1){let l=[];for(let d of i)l.push(await s({...o(d),is_carousel_item:"true"}));a=await s({media_type:"CAROUSEL",children:l.join(","),caption:t.text})}else a=await s({...o(i[0]),caption:t.text});await this.waitForContainer(a,n);let c=await this.graph(`/${encodeURIComponent(r)}/media_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:a}).toString()},n);if(!c.id)throw new b("Instagram did not return a published post id.",400,JSON.stringify(c));let u=await this.graph(`/${encodeURIComponent(c.id)}?fields=permalink`,{method:"GET"},n).catch(()=>{return});return{provider:this.provider,uri:c.id,url:u?.permalink}}async createComment(e,t,r){let i=e.accessToken;if(!i)throw Error("Instagram access token is missing for this identity.");let n=t.trim();if(!/^[0-9]{1,32}$/.test(n))throw Error("An Instagram published media ID is required to comment.");let s=r.trim();if(!s)throw Error("Instagram comment text is required.");let o=await this.graph(`/${n}/comments?${new URLSearchParams({message:s})}`,{method:"POST",redirect:"error",signal:AbortSignal.timeout(15000)},i);return typeof o?.id==="string"&&/^[0-9]{1,32}$/.test(o.id)?o.id:null}async waitForContainer(e,t){let r=0,i=1000;for(;;){let n=await this.graph(`/${encodeURIComponent(e)}?fields=status_code,status`,{method:"GET"},t),s=n.status_code;if(s==="FINISHED"||s==="PUBLISHED"||s===void 0)return;if(s==="ERROR"||s==="EXPIRED")throw new b(`Instagram could not prepare this post (${s}${n.status?`: ${n.status}`:""}).`,422,JSON.stringify(n));if(r>=this.containerTimeoutMs)throw new b(`Instagram was still processing this post after ${Math.round(r/1000)} seconds, so it was not published.`,504,JSON.stringify(n));let o=Math.min(i,60000,Math.max(this.containerTimeoutMs-r,0));await this.sleep(o),r+=o,i*=2}}sleep(e){return new Promise((t)=>setTimeout(t,e))}async timeline(e,t={}){return{items:[]}}async metrics(e,t){let r=e.accessToken;if(!r)throw Error("Instagram access token is missing for this identity.");let i=[];for(let n of t){let s=String(n||"").trim();if(!s)continue;let o;try{o=await this.graph(`/${encodeURIComponent(s)}/insights?metric=${Object.keys(Je).join(",")}`,{method:"GET"},r)}catch(c){if(c instanceof b&&Z(c))continue;throw c}let a={uri:n};for(let c of o.data||[]){let u=Je[String(c.name)],l=Number(c.values?.[0]?.value);if(u&&Number.isFinite(l))a[u]=l}i.push(a)}return i}graphUrl(e){if(!/^https?:\/\//i.test(e))return`${this.graphBase}/${this.graphVersion}${e}`;let t=new URL(e);if(t.origin!==new URL(this.graphBase).origin||t.username||t.password)throw new b("Instagram returned a paging address on another host, so it was not followed.",502,"");return t.searchParams.delete("access_token"),t.href}async graph(e,t,r){let i=new Headers(t.headers);if(r)i.set("authorization",`Bearer ${r}`);let n=await fetch(this.graphUrl(e),{redirect:"error",...t,headers:i,signal:t.signal??AbortSignal.timeout(30000)}),s=await n.text(),o={};try{o=s?JSON.parse(s):{}}catch{o={}}if(!n.ok||o?.error)throw new b(...f("Instagram API",n,s));return o}}import{outboundUrlProblem as Gt}from"@stacksjs/security";function Ge(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function re(){let e=Ge(crypto.getRandomValues(new Uint8Array(32))),t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return{codeVerifier:e,codeChallenge:Ge(new Uint8Array(t))}}var Ke="202611";function Kt(e){let t=Number(e.slice(0,4)),r=Number(e.slice(4,6));return new Date(Date.UTC(t+1,r-1,15))}function Xt(e,t=Date.now()){let r=String(e??"").trim();if(!/^\d{6}$/.test(r))return Ke;return Kt(r).getTime()>t?r:Ke}var Qt=20,Wt=4086,Yt=["ADMINISTRATOR","DIRECT_SPONSORED_CONTENT_POSTER","CONTENT_ADMINISTRATOR","CONTENT_ADMIN"],U="2.0.0";class w extends k{constructor(e,t,r,i={}){super("linkedin",e,t,r,i);this.name="LinkedInApiError"}get isAuthError(){return this.status===401||this.status===403}}function Xe(e){return new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(" "),state:e.state})}function Qe(e){let t=/^https?:\/\/(?:127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?]|$)/i,r=URL.parse(e);if(!r||r.port==="0"||!t.test(e)||/[\s#\\]/.test(e))throw Error("LinkedIn native OAuth requires an HTTP or HTTPS loopback redirect on 127.0.0.1 or [::1].")}class ye{provider="linkedin";characterLimit=3000;maxImages=Qt;fetchImage=C;organizationPageSize=100;apiVersion;authBase;apiBase;constructor(e={}){this.apiVersion=Xt(e.apiVersion),this.authBase=e.authBase||"https://www.linkedin.com",this.apiBase=e.apiBase||"https://api.linkedin.com"}getAuthUrl(e){return`${this.authBase}/oauth/v2/authorization?${Xe(e)}`}async createNativeAuthorization(e){Qe(e.redirectUrl);let{codeVerifier:t,codeChallenge:r}=await re(),i=Xe(e);return i.set("code_challenge",r),i.set("code_challenge_method","S256"),{url:`${this.authBase}/oauth/native-pkce/authorization?${i}`,codeVerifier:t}}async exchangeCode(e){let t=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:e.redirectUrl,client_id:e.clientId,client_secret:e.clientSecret});return this.tokenRequest(t,"LinkedIn did not return an access token.")}async exchangeNativeCode(e){if(Qe(e.redirectUrl),!/^[A-Z0-9._~-]{43,128}$/i.test(e.codeVerifier))throw Error("LinkedIn native OAuth requires the original PKCE code verifier.");if(!e.code.trim())throw Error("LinkedIn did not return an authorization code.");return this.tokenRequest(new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:e.redirectUrl,client_id:e.clientId,code_verifier:e.codeVerifier}),"LinkedIn did not return an access token.")}async refreshAccessToken(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId});if(e.clientSecret)t.set("client_secret",e.clientSecret);return this.tokenRequest(t,"LinkedIn did not return a refreshed access token.")}async tokenRequest(e,t){let r=await this.request(`${this.authBase}/oauth/v2/accessToken`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:e.toString()});if(!r.access_token)throw new w(t,400,JSON.stringify(r));return{accessToken:r.access_token,expiresIn:r.expires_in,scope:r.scope,refreshToken:r.refresh_token,refreshTokenExpiresIn:r.refresh_token_expires_in}}async getProfile(e){if(!e)throw Error("LinkedIn access token is required.");let t=await this.request(`${this.apiBase}/v2/userinfo`,{headers:{authorization:`Bearer ${e}`}});if(!t.sub)throw new w("LinkedIn profile is missing a subject id.",400,JSON.stringify(t));return{sub:t.sub,name:t.name,picture:t.picture}}async uploadImage(e,t,r,i){let n=await this.request(`${this.apiBase}/rest/images?action=initializeUpload`,{method:"POST",headers:{authorization:`Bearer ${e}`,"content-type":"application/json","linkedin-version":this.apiVersion,"x-restli-protocol-version":U},body:JSON.stringify({initializeUploadRequest:{owner:t}})}),s=n.value?.uploadUrl,o=n.value?.image;if(!s||!o)throw new w("LinkedIn did not return an image upload URL.",400,JSON.stringify(n));let a=URL.parse(s),c=URL.parse(this.apiBase)?.origin,u=Boolean(a&&c&&a.origin===c);if(!a||a.username||a.password||!u&&Gt(s))throw new w("LinkedIn returned an unsafe image upload URL.",502,JSON.stringify(n));let l=await fetch(s,{method:"PUT",headers:{authorization:`Bearer ${e}`,"content-type":i||"image/jpeg"},body:new Uint8Array(r),redirect:"error",signal:AbortSignal.timeout(60000)});if(!l.ok){let d=await l.text().catch(()=>"");throw new w(...f("LinkedIn image upload",l,d))}return o}async publish(e,t){if(I(t,"LinkedIn"),!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let r=e.did;if(!r)throw Error("LinkedIn author URN is required to publish.");if(P("linkedin",t.text,this.characterLimit))throw Error(`LinkedIn posts must be ${this.characterLimit} characters or fewer.`);let i=[];for(let u of(t.media??[]).slice(0,this.maxImages)){let l=await E(u,(p)=>this.fetchImage(p));if(!l)continue;let d=await this.uploadImage(e.accessToken,r,l.bytes,l.mimeType),h=u.altText?.trim();i.push({id:d,...h?{altText:h.slice(0,Wt)}:{}})}let n={author:r,commentary:Zt(t.text),visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1},s=[];if(i.length===1)n.content={media:i[0]};else if(i.length>1)n.content={multiImage:{images:i}};else if(t.external){let u={source:t.external.uri,title:t.external.title,description:t.external.description||""};if(t.external.thumb?.bytes?.length)try{u.thumbnail=await this.uploadImage(e.accessToken,r,t.external.thumb.bytes,t.external.thumb.mimeType)}catch{s.push("LinkedIn did not take the link card's picture, so the card went out without it.")}n.content={article:u}}let o=await fetch(`${this.apiBase}/rest/posts`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json","linkedin-version":this.apiVersion,"x-restli-protocol-version":U},body:JSON.stringify(n),redirect:"error",signal:AbortSignal.timeout(30000)}),a=await o.text();if(!o.ok)throw new w(...f("LinkedIn API",o,a));let c=o.headers.get("x-restli-id")||o.headers.get("x-linkedin-id")||"";return{provider:this.provider,uri:c,url:c?`https://www.linkedin.com/feed/update/${c}`:void 0,...s.length?{warnings:s}:{}}}async createComment(e,t,r){if(!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let i=e.did;if(!i||!/^urn:li:(?:person:[\w-]{1,128}|organization(?:Brand)?:[0-9]{1,32})$/.test(i))throw Error("A LinkedIn author URN for a member or organization is required to comment.");let n=t.trim();if(!/^urn:li:(?:share|ugcPost):[0-9]{1,32}$/.test(n))throw Error("A LinkedIn share or UGC post URN is required to comment.");let s=r.trim();if(!s)throw Error("LinkedIn comment text is required.");let o=await fetch(`${this.apiBase}/rest/socialActions/${encodeURIComponent(n)}/comments`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json","linkedin-version":this.apiVersion,"x-restli-protocol-version":U},body:JSON.stringify({actor:i,object:n,message:{text:s}}),redirect:"error",signal:AbortSignal.timeout(15000)});if(!o.ok)throw new w(...f("LinkedIn comment",o,await o.text().catch(()=>"")));let a=o.headers.get("x-restli-id");if(a&&/^[0-9]{1,32}$/.test(a))return await o.body?.cancel().catch(()=>{}),a;let c=await o.json().catch(()=>null);return typeof c?.id==="string"&&/^[0-9]{1,32}$/.test(c.id)?c.id:null}async timeline(e,t={}){return{items:[]}}async listAuthoredPosts(e,t={}){if(!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let r=e.did;if(!r)throw Error("LinkedIn author URN is required to list posts.");let i=r.startsWith("urn:li:organization:")?"r_organization_social":"r_member_social",n=Math.min(Math.max(t.limit||50,1),100),s=Number(t.cursor||0)||0,o=new URL(`${this.apiBase}/rest/posts`);o.searchParams.set("q","author"),o.searchParams.set("author",r),o.searchParams.set("count",String(n)),o.searchParams.set("start",String(s));let a;try{a=await this.request(o.toString(),{headers:{authorization:`Bearer ${e.accessToken}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":U}})}catch(h){if(h instanceof w&&(h.status===401||h.status===403))throw new w(`LinkedIn will not list this account's posts - the Posts author finder needs the ${i} permission, which this app does not hold.`,h.status,h.body,h.retryAfterMs===void 0?{}:{retryAfterMs:h.retryAfterMs});throw h}let c=a.elements||[],u=c.filter((h)=>h?.id).map((h)=>({uri:String(h.id),text:h.commentary,postedAt:h.createdAt?new Date(h.createdAt).toISOString():void 0,url:`https://www.linkedin.com/feed/update/${h.id}`})),l=a.paging?.total;return{cursor:c.length===n&&(typeof l!=="number"||s+n<l)?String(s+n):void 0,posts:u}}async metrics(e,t){if(!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let r=String(e.did||"").startsWith("urn:li:organization:")?"r_organization_social_feed":"r_member_social_feed",i=[...new Set(t.map((s)=>String(s||"").trim()).filter(Boolean))],n=[];for(let s=0;s<i.length;s+=20){let o=i.slice(s,s+20),a=`${this.apiBase}/rest/socialMetadata?ids=List(${o.map((l)=>encodeURIComponent(l)).join(",")})`,c;try{c=await this.request(a,{headers:{authorization:`Bearer ${e.accessToken}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":U}})}catch(l){if(l instanceof w&&l.status===403)throw new w(`LinkedIn will not show this account's reactions and comments - that needs the ${r} permission, which this app does not hold.`,l.status,l.body,l.retryAfterMs===void 0?{}:{retryAfterMs:l.retryAfterMs});throw l}let u=c.results||{};for(let l of o){let d=u[l]??u[encodeURIComponent(l)];if(!d)continue;let h=Object.values(d.reactionSummaries||{}).reduce((p,m)=>p+(Number(m?.count)||0),0);n.push({uri:l,likes:h,...typeof d.commentSummary?.count==="number"?{replies:d.commentSummary.count}:{}})}}return n}async listOrganizations(e){if(!e)throw Error("LinkedIn access token is required to list organizations.");let t={authorization:`Bearer ${e}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":U},r=new Map,i=Math.max(1,this.organizationPageSize);for(let s=0,o=0;o<50;s+=i,o++){let a=new URL(`${this.apiBase}/rest/organizationAcls`);a.searchParams.set("q","roleAssignee"),a.searchParams.set("state","APPROVED"),a.searchParams.set("start",String(s)),a.searchParams.set("count",String(i));let c;try{c=await this.request(a.toString(),{headers:t})}catch(d){if(d instanceof w&&(d.status===401||d.status===403))throw new w("LinkedIn will not list this member's Pages - that needs the rw_organization_admin (or r_organization_admin) permission, which this token does not hold.",d.status,d.body);throw d}let u=c.elements||[];for(let d of u){let h=d.organizationTarget||d.organization,p=d.role||"";if(!h?.startsWith("urn:li:organization:")||!Yt.includes(p)||r.has(h))continue;r.set(h,{urn:h,id:h.slice(20),role:p})}let l=c.paging?.total;if(u.length<i||typeof l==="number"&&s+i>=l)break}let n=[...r.values()];for(let s of n){let o=await this.request(`${this.apiBase}/rest/organizations/${encodeURIComponent(s.id)}`,{headers:t}).then((a)=>a.localizedName,()=>{return});if(o)s.name=o}return n}async deletePost(e,t){if(!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let r=String(t.uri||"").trim();if(!r)throw Error("A LinkedIn post URN is required to delete a post.");let i=await fetch(`${this.apiBase}/rest/posts/${encodeURIComponent(r)}`,{method:"DELETE",headers:{authorization:`Bearer ${e.accessToken}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":U},redirect:"error",signal:AbortSignal.timeout(30000)});if(!i.ok&&i.status!==404){let n=await i.text().catch(()=>"");throw new w(...f("LinkedIn API",i,n))}}async request(e,t){let r=await fetch(e,{redirect:"error",...t,signal:t.signal??AbortSignal.timeout(30000)}),i=await r.text();if(!r.ok)throw new w(...f("LinkedIn API",r,i));return i?JSON.parse(i):{}}}function Zt(e){return e.replace(/[\\|{}@[\]()<>#*_~]/g,(t,r)=>{if(t==="#"&&er(e,r))return t;return`\\${t}`})}function er(e,t){let r=t===0?"":e[t-1];if(r&&/[\p{L}\p{N}_#&/]/u.test(r))return!1;let i=/^[\p{L}\p{N}_]+/u.exec(e.slice(t+1))?.[0];return Boolean(i&&/\p{L}/u.test(i))}import{fetchPublicUrl as We}from"@stacksjs/security";function Ye(e){return e instanceof q&&e.status===404}class q extends k{constructor(e,t,r,i={}){super("mastodon",e,t,r,i);this.name="MastodonApiError"}get isAuthError(){return this.status===401||this.status===403}}var L={characters:500,charactersPerUrl:23,mediaAttachments:4},tr=3600000,rr=60000,ir=60000;function nr(e){if(!e)return null;let t=Number(e.max_options),r=Number(e.max_characters_per_option),i=Number(e.min_expiration),n=Number(e.max_expiration);if(![t,r,i,n].every((s)=>Number.isSafeInteger(s)&&s>0)||t<2||n<i)return null;return{maxOptions:t,maxCharactersPerOption:r,minExpiration:i,maxExpiration:n}}function sr(e,t){if(!t)throw Error("The Mastodon instance did not report its poll limits.");if(!Array.isArray(e.options)||e.options.some((i)=>typeof i!=="string"||!i.trim()))throw Error("Each poll option needs text.");let r=e.options.map((i)=>i.trim());if(r.length<2||r.length>t.maxOptions)throw Error(`This Mastodon instance allows between 2 and ${t.maxOptions} poll options.`);if(r.some((i)=>K(i)>t.maxCharactersPerOption))throw Error(`Each poll option can have up to ${t.maxCharactersPerOption} characters.`);if(new Set(r).size!==r.length)throw Error("Poll options must be distinct.");if(!Number.isSafeInteger(e.expiresIn)||e.expiresIn<t.minExpiration||e.expiresIn>t.maxExpiration)throw Error(`This Mastodon instance allows poll durations between ${t.minExpiration} and ${t.maxExpiration} seconds.`);return{options:r,expires_in:e.expiresIn,multiple:e.multiple===!0,hide_totals:e.hideTotals===!0}}function ke(e){let t=typeof e==="string"?URL.parse(e):null;if(!t||t.protocol!=="https:"||t.username||t.password)return null;return t.hash="",t.href}function or(e){let t=String(e||"").trim().replace(/\/+$/,"");if(!t)throw Error("Mastodon instance URL is required.");if(/\s/.test(t))throw Error("Mastodon instance URL is invalid.");if(/^[a-z][a-z0-9+.-]*:/i.test(t)&&!/^https?:\/\//i.test(t))throw Error("Mastodon instance URL must use https:// or http://.");let r=/^https?:\/\//i.test(t)?t:`https://${t}`,i;try{i=new URL(r)}catch{throw Error("Mastodon instance URL is invalid.")}if(i.username||i.password)throw Error("Mastodon instance URL must not contain credentials.");if(!i.hostname)throw Error("Mastodon instance URL is invalid.");return`${i.protocol}//${i.host}`}class be{provider="mastodon";characterLimit=L.characters;fetchImage=C;limits=new Map;async instanceLimits(e){let t=this.instanceOf(e),r=this.limits.get(t);if(r&&Date.now()<r.expires)return r.value;try{let i=await We(`${t}/api/v2/instance`,{},{maxRedirects:0,timeoutMs:5000});if(!i.ok)throw Error(`HTTP ${i.status}`);let n=await i.json(),s=n.configuration?.statuses??{},o=(m,T)=>Number(m)>0?Math.floor(Number(m)):T,a=nr(n.configuration?.polls),c=n.configuration?.media_attachments,u=Number(c?.video_size_limit),l=Number.isSafeInteger(u)&&u>0,d=c?.supported_mime_types,h=Number(n.api_versions?.mastodon)>=7,p={...a&&{poll:a},...h&&{quotePosts:!0},...l&&{videoSizeLimit:u},...Array.isArray(d)&&{supportsMp4:d.includes("video/mp4")},characters:o(s.max_characters,L.characters),charactersPerUrl:o(s.characters_reserved_per_url,L.charactersPerUrl),mediaAttachments:o(s.max_media_attachments,L.mediaAttachments)};return this.limits.set(t,{value:p,expires:Date.now()+tr}),p}catch{return this.limits.set(t,{value:L,expires:Date.now()+rr}),L}}instanceOf(e){return or(e.did||"")}tokenOf(e){if(!e.accessToken)throw Error("Mastodon access token is missing for this identity.");return e.accessToken}async verifyCredentials(e){let t=await this.request(`${this.instanceOf(e)}/api/v1/accounts/verify_credentials`,{headers:{authorization:`Bearer ${this.tokenOf(e)}`}});return{accountId:t.id,username:t.username,displayName:t.display_name||void 0,url:t.url}}async resolvePostId(e,t){let r=ke(t);if(!r)throw Error("Enter an HTTPS link to a Mastodon post.");let i=new URL("/api/v2/search",this.instanceOf(e));i.search=new URLSearchParams({q:r,type:"statuses",resolve:"true",limit:"1"}).toString();let s=(await this.request(i.href,{headers:{authorization:`Bearer ${this.tokenOf(e)}`},redirect:"error",signal:AbortSignal.timeout(15000)})).statuses?.find((o)=>ke(o.url)===r||ke(o.uri)===r);if(!s||!/^[0-9]{1,32}$/.test(s.id))throw Error("The Mastodon instance could not find the post at this link.");return s.id}async uploadMedia(e,t,r,i){return(await this.createMediaAttachment(e,t,r,i)).id}async createMediaAttachment(e,t,r,i,n){let s=new FormData,o=r==="video/mp4"?"upload.mp4":"upload";if(s.set("file",new Blob([new Uint8Array(t)],{type:r||"image/jpeg"}),o),i?.trim())s.set("description",i.trim().slice(0,1500));return await this.request(`${this.instanceOf(e)}/api/v2/media`,{method:"POST",headers:{authorization:`Bearer ${this.tokenOf(e)}`},body:s,redirect:"error",signal:n})}async uploadVideo(e,t){let r=await this.createMediaAttachment(e,t.bytes,t.mimeType,t.altText,AbortSignal.timeout(60000));if(typeof r.id!=="string"||!/^[a-z0-9_-]{1,128}$/i.test(r.id))throw Error("Mastodon did not return a valid video attachment ID.");let i=`${this.instanceOf(e)}/api/v1/media/${r.id}`,n={authorization:`Bearer ${this.tokenOf(e)}`},s=AbortSignal.timeout(ir),o=r;while(!o.url){if(s.aborted)throw new q("Mastodon took too long to process the attachment.",503,"");try{o=await this.request(i,{headers:n,signal:s,redirect:"error"})}catch(a){if(s.aborted)throw new q("Mastodon took too long to process the attachment.",503,"");throw a}if(!o.url)await Bun.sleep(1000)}if(o.id!==r.id||typeof o.url!=="string"||o.type!=="video"&&o.type!=="gifv")throw Error("Mastodon did not return a processed video attachment.");return r.id}async publish(e,t,r={}){let i=this.instanceOf(e),n=this.tokenOf(e),s=await this.instanceLimits(e);if(P("mastodon",t.text,s.characters,{linkLength:s.charactersPerUrl}))throw Error(`Mastodon posts on this instance must be ${s.characters} characters or fewer.`);if((r.poll||r.quotedStatusId!==void 0)&&t.media?.length)throw Error("Mastodon does not allow images with a poll or a quote.");if(t.video){if(G(t.video,t.media),r.poll||r.quotedStatusId!==void 0)throw Error("Mastodon does not allow a video with a poll or a quote.");if(s.supportsMp4===!1)throw Error("This Mastodon instance does not accept MP4 video.");if(s.videoSizeLimit&&t.video.bytes.length>s.videoSizeLimit)throw Error(`Video exceeds this Mastodon instance\u2019s ${s.videoSizeLimit}-byte limit.`)}if(r.poll&&r.quotedStatusId!==void 0)throw Error("Choose a poll or a quoted post on Mastodon.");if(r.quotedStatusId!==void 0){if(!s.quotePosts)throw Error("This Mastodon instance does not advertise quote posts.");if(!/^[0-9]{1,32}$/.test(r.quotedStatusId))throw Error("Choose a valid Mastodon status to quote.")}let o=r.poll?sr(r.poll,s.poll):void 0,a=[];if(t.video)a.push(await this.uploadVideo(e,t.video));for(let h of(t.media||[]).slice(0,s.mediaAttachments)){let p=await E(h,(m)=>this.fetchImage(m));if(p)a.push(await this.uploadMedia(e,p.bytes,p.mimeType,h.altText))}let c={status:t.text,visibility:r.visibility??"public"};if(a.length)c.media_ids=a;if(o)c.poll=o;if(r.quotedStatusId!==void 0)c.quoted_status_id=r.quotedStatusId;if(t.reply?.parent?.uri)c.in_reply_to_id=t.reply.parent.uri;if(r.spoilerText?.trim())c.spoiler_text=r.spoilerText.trim();let u=r.language??t.langs?.[0];if(u)c.language=u;let l={authorization:`Bearer ${n}`,"content-type":"application/json"};if(r.idempotencyKey)l["idempotency-key"]=r.idempotencyKey;let d=await this.request(`${i}/api/v1/statuses`,{method:"POST",headers:l,body:JSON.stringify(c)});return{provider:this.provider,uri:d.id,cid:d.id,url:d.url||d.uri}}async timeline(e,t={}){return{items:[]}}async listAuthoredPosts(e,t={}){let r=this.instanceOf(e),{accountId:i}=await this.verifyCredentials(e),n=new URL(`${r}/api/v1/accounts/${encodeURIComponent(i)}/statuses`);if(n.searchParams.set("limit",String(Math.min(Math.max(t.limit||40,1),40))),n.searchParams.set("exclude_reblogs","true"),t.cursor)n.searchParams.set("max_id",t.cursor);let o=(await this.request(n.toString(),{headers:{authorization:`Bearer ${this.tokenOf(e)}`}})||[]).filter((a)=>a?.id).map((a)=>({uri:a.id,cid:a.id,text:a.content,postedAt:a.created_at,url:a.url}));return{cursor:o.length?o[o.length-1]?.uri:void 0,posts:o}}async deletePost(e,t){let r=String(t.cid||Ze(t.uri)||"").trim();if(!r)throw Error("A status id is required to delete a post.");await this.request(`${this.instanceOf(e)}/api/v1/statuses/${encodeURIComponent(r)}`,{method:"DELETE",headers:{authorization:`Bearer ${this.tokenOf(e)}`}})}async metrics(e,t){let r=this.instanceOf(e),i={authorization:`Bearer ${this.tokenOf(e)}`},n=new Map;for(let a of t){let c=String(Ze(a)||"").trim();if(c)n.set(c,a)}let s=[...n.keys()],o=[];for(let a=0;a<s.length;a+=40){let c=s.slice(a,a+40);try{o.push(...await this.request(`${r}/api/v1/statuses?${c.map((u)=>`id[]=${encodeURIComponent(u)}`).join("&")}`,{headers:i}))}catch(u){if(!Ye(u))throw u;for(let l of c)try{o.push(await this.request(`${r}/api/v1/statuses/${encodeURIComponent(l)}`,{headers:i}))}catch(d){if(!Ye(d))throw d}}}return o.flatMap((a)=>{let c=n.get(String(a.id));if(c===void 0)return[];let u={likes:a.favourites_count,reposts:a.reblogs_count,replies:a.replies_count,quotes:a.quotes_count},l=Object.entries(u).filter(([,d])=>typeof d==="number"&&Number.isSafeInteger(d)&&d>=0);return[{uri:c,...Object.fromEntries(l)}]})}async request(e,t){let r=await We(e,t,{maxRedirects:0,timeoutMs:60000}),i=await r.text();if(!r.ok)throw new q(...f("Mastodon API",r,i));return i?JSON.parse(i):{}}}function Ze(e){return String(e||"").replace(/\/+$/,"").split("/").pop()||""}var ar=20,cr=1000,et={views:"views",likes:"likes",replies:"replies",reposts:"reposts",quotes:"quotes",shares:"shares"},dr=Object.keys(et);class v extends k{constructor(e,t,r,i={}){super("threads",e,t,r,i);this.name="ThreadsApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class Se{provider="threads";characterLimit=500;maxImages=ar;containerTimeoutMs=300000;graphVersion;authBase;graphBase;constructor(e={}){this.graphVersion=e.graphVersion||"v1.0",this.authBase=e.authBase||"https://threads.net",this.graphBase=e.graphBase||"https://graph.threads.net"}getAuthUrl(e){let t=new URLSearchParams({client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(","),response_type:"code",state:e.state});return`${this.authBase}/oauth/authorize?${t.toString()}`}async exchangeCode(e){let t=await fetch(`${this.graphBase}/oauth/access_token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,grant_type:"authorization_code",redirect_uri:e.redirectUrl,code:e.code}).toString(),redirect:"error",signal:AbortSignal.timeout(30000)}),r=await t.text(),i={};try{i=r?JSON.parse(r):{}}catch{i={}}if(!t.ok||i?.error||!i?.access_token)throw new v(...f("Threads token exchange",t,r));return{accessToken:i.access_token,userId:i.user_id!=null?String(i.user_id):void 0,expiresIn:i.expires_in}}async resolveAccount(e){let t=new URLSearchParams({fields:"id,username"}),r=await this.graph(`/me?${t.toString()}`,{method:"GET"},e);if(!r.id)throw new v("Could not resolve the Threads account for this token.",400,JSON.stringify(r));return{threadsUserId:r.id,username:r.username,accessToken:e}}async exchangeLongLivedToken(e,t){return this.tokenRequest("/access_token",new URLSearchParams({grant_type:"th_exchange_token",client_secret:e,access_token:t}))}async refreshLongLivedToken(e){return this.tokenRequest("/refresh_access_token",new URLSearchParams({grant_type:"th_refresh_token",access_token:e}))}async publish(e,t){if(I(t,"Threads"),!e.accessToken)throw Error("Threads access token is missing for this identity.");let r=e.did;if(!r)throw Error("Threads account id is required to publish.");if(P("threads",t.text,this.characterLimit))throw Error(`Threads posts must be ${this.characterLimit} characters or fewer.`);let i=(t.media??[]).slice(0,this.maxImages);if(i.some((h)=>!h.url))throw new v("Threads fetches images from a public address, and this image has none.",422,"");let n=e.accessToken,s=async(h)=>{let p=await this.graph(`/${encodeURIComponent(r)}/threads`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(h).toString()},n);if(!p.id)throw new v("Threads did not return a media container id.",400,JSON.stringify(p));return p.id},o=t.reply?.parent?.uri,a={text:t.text,...o?{reply_to_id:o}:{}},c=(h)=>({media_type:"IMAGE",image_url:h.url,...h.altText?.trim()?{alt_text:h.altText.trim().slice(0,cr)}:{}}),u;if(i.length>1){let h=[];for(let p of i)h.push(await s({...c(p),is_carousel_item:"true"}));u=await s({media_type:"CAROUSEL",children:h.join(","),...a})}else if(i.length===1)u=await s({...c(i[0]),...a});else u=await s({media_type:"TEXT",...a});if(i.length>0)await this.waitForContainer(u,n);let l=await this.graph(`/${encodeURIComponent(r)}/threads_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:u}).toString()},n);if(!l.id)throw new v("Threads did not return a published post id.",400,JSON.stringify(l));let d=await this.graph(`/${encodeURIComponent(l.id)}?fields=permalink`,{method:"GET"},n).catch(()=>{return});return{provider:this.provider,uri:l.id,cid:l.id,url:d?.permalink}}async waitForContainer(e,t){let r=0,i=1000;for(;;){let n=await this.graph(`/${encodeURIComponent(e)}?fields=status,error_message`,{method:"GET"},t),s=n.status;if(s==="FINISHED"||s==="PUBLISHED"||s===void 0)return;if(s==="ERROR"||s==="EXPIRED")throw new v(`Threads could not prepare this post (${s}${n.error_message?`: ${n.error_message}`:""}).`,422,JSON.stringify(n));if(r>=this.containerTimeoutMs)throw new v(`Threads was still processing this post after ${Math.round(r/1000)} seconds, so it was not published.`,504,JSON.stringify(n));let o=Math.min(i,60000,Math.max(this.containerTimeoutMs-r,0));await this.sleep(o),r+=o,i*=2}}sleep(e){return new Promise((t)=>setTimeout(t,e))}async deletePost(e,t){if(!e.accessToken)throw Error("Threads access token is missing for this identity.");if(!/^\w+$/.test(t.uri))throw Error(`Threads post id "${t.uri}" is not an id.`);await this.graph(`/${t.uri}`,{method:"DELETE"},e.accessToken)}async timeline(e,t={}){return{items:[]}}async tokenRequest(e,t){let r=await fetch(`${this.graphBase}${e}`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:t.toString(),redirect:"error",signal:AbortSignal.timeout(30000)}),i=await r.text(),n={};try{n=i?JSON.parse(i):{}}catch{n={}}if(!r.ok||n?.error||!n?.access_token)throw new v(...f("Threads token request",r,i));return{accessToken:n.access_token,expiresIn:n.expires_in}}async metrics(e,t){let r=e.accessToken;if(!r)throw Error("Threads access token is missing for this identity.");let i=[];for(let n of t){let s=String(n||"").trim();if(!s)continue;let o;try{o=await this.graph(`/${encodeURIComponent(s)}/insights?metric=${dr.join(",")}`,{method:"GET"},r)}catch(c){if(c instanceof v&&Z(c))continue;throw c}let a={uri:n};for(let c of o.data||[]){let u=et[String(c.name)],l=Number(c.values?.[0]?.value);if(u&&Number.isFinite(l))a[u]=l}i.push(a)}return i}async graph(e,t,r){let i=new Headers(t.headers);if(r)i.set("authorization",`Bearer ${r}`);let n=await fetch(`${this.graphBase}/${this.graphVersion}${e}`,{redirect:"error",...t,headers:i,signal:t.signal??AbortSignal.timeout(30000)}),s=await n.text(),o={};try{o=s?JSON.parse(s):{}}catch{o={}}if(!n.ok||o?.error)throw new v(...f("Threads API",n,s));return o}}import{Buffer as it}from"buffer";import{fetcher as tt}from"@stacksjs/api";import{config as ie}from"@stacksjs/config";class Pe extends y{baseUrl="https://twitter.com";apiUrl="https://api.twitter.com";_usesPKCE=!0;getConfig(){let e={clientId:this.clientId||(ie.services.twitter?.clientId??""),clientSecret:this.clientSecret||(ie.services.twitter?.clientSecret??""),redirectUrl:this.redirectUrl||(ie.services.twitter?.redirectUrl??""),scopes:ie.services.twitter?.scopes??["users.read","tweet.read"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/i/oauth2/authorize?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(" "),response_type:"code",...this.parameters,...await this.pkceFields(),state:e}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let n=this.pkceTokenFields(),s=it.from(`${t}:${r}`).toString("base64"),o=await tt.asForm().withHeaders({Authorization:`Basic ${s}`}).post(`${this.apiUrl}/2/oauth2/token`,{code:e,grant_type:"authorization_code",redirect_uri:i,...n});if(o.data.error)throw Error(`Twitter OAuth error: ${o.data.error_description}`);return o.data.access_token}async getUserByToken(e){let r=(await tt.withHeaders({Authorization:`Bearer ${e}`}).get(`${this.apiUrl}/2/users/me?user.fields=profile_image_url`)).data,i=r&&typeof r==="object"&&"data"in r&&r.data?r.data:r;return{id:i.id,nickname:i.username,name:i.name,email:i.email??null,avatar:i.profile_image_url??null,token:e,raw:i}}validateConfig(){let{clientId:e,clientSecret:t,redirectUrl:r}=this.getConfig();if(!e)throw new g("Twitter client ID not provided");if(!t)throw new g("Twitter client secret not provided");if(!r)throw new g("Twitter redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/2/oauth2/token`}}class x extends k{constructor(e,t,r,i={}){super("twitter",e,t,r,i);this.name="TwitterApiError"}get isAuthError(){return this.kind==="expired"}}var lr=4,ur=1000;function rt(e){if(!/^\d{1,19}(?:-\d{1,19})?$/.test(e))throw Error("An X direct-message conversation id is required.");return e}class B{provider="twitter";characterLimit=280;maxImages=lr;fetchImage=C;apiBase;authorizeBase;constructor(e={}){this.apiBase=e.apiBase||"https://api.twitter.com",this.authorizeBase=e.authorizeBase||"https://twitter.com"}async createAuthorization(e){let{codeVerifier:t,codeChallenge:r}=await re(),i=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(" "),state:e.state,code_challenge:r,code_challenge_method:"S256"});return{url:`${this.authorizeBase}/i/oauth2/authorize?${i.toString()}`,codeVerifier:t}}async exchangeCode(e){return this.tokenRequest(new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:e.redirectUrl,code_verifier:e.codeVerifier,client_id:e.clientId}),e.clientId,e.clientSecret)}async refreshAccessToken(e){return this.tokenRequest(new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId}),e.clientId,e.clientSecret)}async getProfile(e){let t=await this.request(`${this.apiBase}/2/users/me?user.fields=username,name,profile_image_url`,{headers:{authorization:`Bearer ${e}`}});if(!t.data?.id||!t.data.username)throw new x("Twitter did not return the authenticated user.",400,JSON.stringify(t));return{id:t.data.id,username:t.data.username,name:t.data.name,...t.data.profile_image_url?{avatar:t.data.profile_image_url}:{}}}async uploadMedia(e,t,r){let i=new FormData;i.set("media",new Blob([new Uint8Array(t)],{type:r||"image/jpeg"})),i.set("media_category","tweet_image");let n=await this.request(`${this.apiBase}/2/media/upload`,{method:"POST",headers:{authorization:`Bearer ${e}`},body:i}),s=n.data?.id||n.media_id_string||n.id;if(!s)throw new x("Twitter did not return a media id.",400,JSON.stringify(n));return s}async describeMedia(e,t,r){try{return await this.request(`${this.apiBase}/2/media/metadata`,{method:"POST",headers:{authorization:`Bearer ${e}`,"content-type":"application/json"},body:JSON.stringify({id:t,metadata:{alt_text:{text:r.slice(0,ur)}}})}),!0}catch{return!1}}async publish(e,t){if(I(t,"X"),!e.accessToken)throw Error("Twitter access token is missing for this identity.");if(P("twitter",t.text,this.characterLimit))throw Error(`Twitter posts must be ${this.characterLimit} characters or fewer.`);let r=[],i=[];for(let a of(t.media??[]).slice(0,this.maxImages)){let c=await E(a,(d)=>this.fetchImage(d));if(!c)continue;let u=await this.uploadMedia(e.accessToken,c.bytes,c.mimeType),l=a.altText?.trim();if(l&&!await this.describeMedia(e.accessToken,u,l))i.push(`X did not take the description for image ${r.length+1}.`);r.push(u)}let n={text:t.text};if(r.length)n.media={media_ids:r};if(t.reply?.parent?.uri)n.reply={in_reply_to_tweet_id:t.reply.parent.uri};let s=await this.request(`${this.apiBase}/2/tweets`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json"},body:JSON.stringify(n)}),o=s.data?.id;if(!o)throw new x("Twitter did not return a tweet id.",400,JSON.stringify(s));return{provider:this.provider,uri:o,cid:o,url:e.handle?`https://x.com/${e.handle}/status/${o}`:`https://x.com/i/web/status/${o}`,...i.length?{warnings:i}:{}}}async timeline(e,t={}){return{items:[]}}async listAuthoredPosts(e,t={}){if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");let r=e.did;if(!r)throw Error("Twitter user id is required to list posts.");let i=new URL(`${this.apiBase}/2/users/${encodeURIComponent(r)}/tweets`);if(i.searchParams.set("max_results",String(Math.min(Math.max(t.limit||100,5),100))),i.searchParams.set("tweet.fields","created_at"),t.cursor)i.searchParams.set("pagination_token",t.cursor);let n=await this.request(i.toString(),{headers:{authorization:`Bearer ${e.accessToken}`}});return{cursor:n.meta?.next_token,posts:(n.data||[]).filter((s)=>s?.id).map((s)=>({uri:s.id,cid:s.id,text:s.text,postedAt:s.created_at,url:`https://x.com/i/web/status/${s.id}`}))}}async listDirectMessageEvents(e,t={}){if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");let r=t.conversationId===void 0?"/2/dm_events":`/2/dm_conversations/${rt(t.conversationId)}/dm_events`,i=new URL(`${this.apiBase}${r}`),n=t.limit??50,s=Number.isFinite(n)?Math.max(1,Math.min(100,Math.trunc(n))):50;if(i.searchParams.set("max_results",String(s)),i.searchParams.set("event_types","MessageCreate"),i.searchParams.set("dm_event.fields","attachments,created_at,dm_conversation_id,sender_id,text"),i.searchParams.set("expansions","sender_id"),i.searchParams.set("user.fields","profile_image_url"),t.cursor)i.searchParams.set("pagination_token",t.cursor);let o=await this.request(i.toString(),{headers:{authorization:`Bearer ${e.accessToken}`},signal:AbortSignal.timeout(15000)});if(!o.data?.length&&o.errors?.length)throw new x("X did not return the requested direct messages.",502,JSON.stringify(o));return{events:o.data??[],users:o.includes?.users??[],cursor:o.meta?.next_token}}async sendDirectMessage(e,t,r){if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");if(!r.trim())throw Error("Write a message before sending.");let i=rt(t),n=await this.request(`${this.apiBase}/2/dm_conversations/${i}/messages`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json"},body:JSON.stringify({text:r}),signal:AbortSignal.timeout(15000)}),s=n.data?.dm_event_id;if(n.data?.dm_conversation_id!==i||!s||!/^\d{1,19}$/.test(s))throw new x("X did not confirm the reply. Refresh the conversation before sending again.",502,JSON.stringify(n));return{conversationId:i,eventId:s}}async metrics(e,t){let r=[...new Set(t.filter((s)=>/^[0-9]{1,19}$/.test(s)))];if(!r.length)return[];if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");let i=[],n={authorization:`Bearer ${e.accessToken}`};for(let s=0;s<r.length;s+=100){let o=r.slice(s,s+100),a=new URLSearchParams({ids:o.join(","),"tweet.fields":"public_metrics"}),c=await this.request(`${this.apiBase}/2/tweets?${a}`,{headers:n}),u=new Set(o);for(let l of c.data??[]){let d=l.public_metrics;if(!d||!u.delete(l.id))continue;let h={likes:d.like_count,replies:d.reply_count,reposts:d.repost_count??d.retweet_count,quotes:d.quote_count,views:d.impression_count,saves:d.bookmark_count},p=Object.entries(h).filter(([,m])=>typeof m==="number"&&Number.isSafeInteger(m)&&m>=0);if(p.length)i.push({uri:l.id,...Object.fromEntries(p)})}}return i}async deletePost(e,t){if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");let r=String(t.uri||"").trim();if(!r)throw Error("A tweet id is required to delete a post.");let i=await fetch(`${this.apiBase}/2/tweets/${encodeURIComponent(r)}`,{method:"DELETE",headers:{authorization:`Bearer ${e.accessToken}`},redirect:"error",signal:AbortSignal.timeout(30000)});if(i.status===404)return;let n=await i.text();if(!i.ok)throw new x(...f("Twitter API",i,n));let s=n?JSON.parse(n):{};if(s.data&&s.data.deleted===!1)throw new x(`X refused to delete tweet ${r}.`,400,JSON.stringify(s))}async tokenRequest(e,t,r){let i={"content-type":"application/x-www-form-urlencoded"};if(r)i.authorization=`Basic ${it.from(`${t}:${r}`,"utf8").toString("base64")}`;let n=await this.request(`${this.apiBase}/2/oauth2/token`,{method:"POST",headers:i,body:e.toString()});if(!n.access_token)throw new x("Twitter did not return an access token.",400,JSON.stringify(n));return{accessToken:n.access_token,refreshToken:n.refresh_token,expiresIn:n.expires_in,scope:n.scope}}async request(e,t){let r=await fetch(e,{redirect:"error",...t,signal:t.signal??AbortSignal.timeout(30000)}),i=await r.text();if(!r.ok)throw new x(...f("Twitter API",r,i));return i?JSON.parse(i):{}}}import{Buffer as hr}from"buffer";class F extends Error{code;status;constructor(e,t){super(`Stacks issuer refused the request: ${e}`);this.code=e;this.status=t;this.name="StacksIssuerError"}}class pr extends y{scopeSeparator=" ";settings;constructor(e){super(e);this.settings=e,this._scopes=e.scopes?.length?[...e.scopes]:[],this._usesPKCE=!0}endpoint(e){return(e==="authorize"?this.settings.authorizeUrl:e==="token"?this.settings.tokenUrl:this.settings.revokeUrl)||`${this.settings.issuer.replace(/\/+$/,"")}/${e}`}resources(){let e=this.settings.resource;return e==null?[]:Array.isArray(e)?e:[e]}validateConfig(){if(!this.settings.issuer)throw new g("Stacks issuer not provided");if(!this.clientId)throw new g("Stacks issuer client ID not provided");if(!this.clientSecret)throw new g("Stacks issuer client secret not provided");if(!this.redirectUrl)throw new g("Stacks issuer redirect URL not provided");if(!this.settings.userInfoUrl)throw new g("Stacks issuer userinfo URL not provided")}getTokenUrl(){return this.endpoint("token")}async getAuthUrl(){this.validateConfig();let e=new URLSearchParams({client_id:this.clientId,redirect_uri:this.redirectUrl,response_type:"code",scope:this.formatScopes(this.getScopes(),this.scopeSeparator),state:this.resolveState(),...await this.pkceFields()});for(let t of this.resources())e.append("resource",t);for(let[t,r]of Object.entries(this.parameters))e.set(t,String(r));return`${this.endpoint("authorize")}?${e.toString()}`}async post(e,t){let r=await fetch(e,{method:"POST",headers:{Authorization:`Basic ${hr.from(`${encodeURIComponent(this.clientId)}:${encodeURIComponent(this.clientSecret)}`).toString("base64")}`,"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:t.toString()}),i=await r.json().catch(()=>({}));if(!r.ok)throw new F(typeof i.error==="string"?i.error:"server_error",r.status);return i}tokens(e){if(typeof e.access_token!=="string"||!e.access_token)throw new F("invalid_token_response",502);return{accessToken:e.access_token,refreshToken:typeof e.refresh_token==="string"?e.refresh_token:null,expiresIn:typeof e.expires_in==="number"?e.expires_in:null,scopes:typeof e.scope==="string"?e.scope.split(" ").filter(Boolean):[]}}async getTokens(e){this.validateConfig();let t=new URLSearchParams({grant_type:"authorization_code",code:e,redirect_uri:this.redirectUrl,...this.pkceTokenFields()});for(let r of this.resources())t.append("resource",r);return this.tokens(await this.post(this.endpoint("token"),t))}async getAccessToken(e){return(await this.getTokens(e)).accessToken}async refreshTokens(e){this.validateConfig();let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e});for(let r of this.resources())t.append("resource",r);return this.tokens(await this.post(this.endpoint("token"),t))}async revokeToken(e,t="refresh_token"){this.validateConfig(),await this.post(this.endpoint("revoke"),new URLSearchParams({token:e,token_type_hint:t}))}async getClaims(e){this.validateConfig();let t=await fetch(this.settings.userInfoUrl,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}}),r=await t.json().catch(()=>({}));if(!t.ok)throw new F(typeof r.error==="string"?r.error:"invalid_token",t.status);if(typeof r.sub!=="string"||!r.sub)throw new F("invalid_userinfo",502);return r}async getUserByToken(e){let t=await this.getClaims(e),r=typeof t.email==="string"?t.email:null;return{id:String(t.sub),nickname:typeof t.preferred_username==="string"?t.preferred_username:null,name:typeof t.name==="string"&&t.name?t.name:r??"",email:r,emailVerified:typeof t.email_verified==="boolean"?t.email_verified:null,avatar:typeof t.picture==="string"?t.picture:null,token:e,raw:t}}}import{config as gr}from"@stacksjs/config";var ne=["clientId","clientSecret","redirectUrl"],V=Object.freeze({google:{name:"google",label:"Google",driver:fe,required:ne,postCallback:!1,pkce:!1,nonce:!1},github:{name:"github",label:"GitHub",driver:me,required:ne,postCallback:!1,pkce:!1,nonce:!1},facebook:{name:"facebook",label:"Facebook",driver:pe,required:ne,postCallback:!1,pkce:!1,nonce:!1},twitter:{name:"twitter",label:"X",driver:Pe,required:ne,postCallback:!1,pkce:!0,nonce:!1},apple:{name:"apple",label:"Apple",driver:de,required:["clientId","teamId","keyId","privateKey","redirectUrl"],postCallback:!0,pkce:!1,nonce:!0}});function nt(e){return gr?.services?.[e]}function mr(e){return typeof e==="string"&&e in V}function st(e){if(!mr(e))return!1;let t=nt(e);if(!t)return!1;return V[e].required.every((r)=>Boolean(t[r]))}function bn(){return Object.keys(V).filter(st).map((e)=>V[e])}function Sn(e){if(!st(e))return null;let t=V[e],r=nt(e)??{};return new t.driver({clientSecret:"",...r,clientId:String(r.clientId??""),redirectUrl:String(r.redirectUrl??"")})}class fr{accessToken;refreshToken;expiresIn;approvedScopes;constructor(e,t=null,r=null,i=[]){this.accessToken=e;this.refreshToken=t;this.expiresIn=r;this.approvedScopes=i}}function xn(e){return typeof e?.metrics==="function"}function _n(e){return typeof e?.deletePost==="function"}function In(e){return typeof e?.listAuthoredPosts==="function"}import{buildSessionHandoffCodeUrl as wr,buildSessionHandoffUrl as yr}from"@stacksjs/composables";function ve(e,t=[]){if(!e)return!1;if(/[\\\u0000-\u001F\u007F]/.test(e))return!1;if(e.startsWith("//"))return!1;if(e.startsWith("/"))try{return new URL(e,"https://stacks.invalid").origin==="https://stacks.invalid"}catch{return!1}try{let r=new URL(e);if(r.protocol!=="http:"&&r.protocol!=="https:")return!1;if(r.username||r.password)return!1;return t.includes(r.host)}catch{return!1}}function Un(e,t={}){let r=t.redirectTo??"/";if(!ve(r,t.allowedHosts??[]))throw Error(`[socials] refusing to hand a session to ${r}: relative paths are always allowed; an absolute URL needs its host in allowedHosts.`);return new Response(null,{status:302,headers:{Location:yr(r,e),"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function Rn(e,t={}){let r=t.redirectTo??"/";if(!ve(r,t.allowedHosts??[]))throw Error(`[socials] refusing to hand a session to ${r}: relative paths are always allowed; an absolute URL needs its host in allowedHosts.`);return new Response(null,{status:302,headers:{Location:wr(r,e),"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function Cn(e,t={}){let r=t.redirectTo??"/login";if(!ve(r,t.allowedHosts??[]))throw Error(`[socials] refusing to redirect to ${r}`);let i=r.indexOf("#"),n=i>=0?r.slice(0,i):r,s=i>=0?r.slice(i):"",o=n.includes("?")?"&":"?",a=`${n}${o}social_error=${encodeURIComponent(e)}${s}`;return new Response(null,{status:302,headers:{Location:a,"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}import{Buffer as ot}from"buffer";import{createHash as kr,randomBytes as br,timingSafeEqual as Sr}from"crypto";function j(e){return kr("sha256").update(e).digest("hex")}var Pr=/^[a-f0-9]{64}$/,vr=/^[a-f0-9]{64}$/,xr=/^[\w.:-]{1,64}$/,_r=3600000,at=null;function Ln(e){at=e}function ct(){return at??Ar()}function xe(e=32){return br(e).toString("hex")}function Ir(e,t){if(e.length!==t.length)return!1;return Sr(ot.from(e,"utf8"),ot.from(t,"utf8"))}function _e(e){return`stacks_oauth_${j(e).slice(0,24)}`}async function Tr(){try{let{config:e}=await import("@stacksjs/config");return String(e.app?.url??"").startsWith("https:")}catch{return!1}}function dt(e,t,r,i){return[`${e}=${t}`,`Path=${i.path}`,"HttpOnly",`SameSite=${i.sameSite}`,`Max-Age=${Math.max(0,Math.floor(r))}`,...i.secure?["Secure"]:[]].join("; ")}async function lt(e={}){let t=e.sameSite??"Lax",r=t==="None"?!0:e.secure??await Tr();return{path:e.path??"/",sameSite:t,secure:r}}async function Bn(e){if(!xr.test(e.purpose??""))throw TypeError("[socials] issueOAuthFlow needs a purpose of 1-64 word characters, dots, colons or dashes.");if(!Number.isFinite(e.ttlMs)||e.ttlMs<=0)throw TypeError("[socials] issueOAuthFlow needs a positive ttlMs.");if(e.challenge!==void 0&&!vr.test(e.challenge))throw TypeError("[socials] issueOAuthFlow challenge must be the lowercase hex SHA-256 of the verifier.");if(e.userId!=null&&(!Number.isSafeInteger(e.userId)||e.userId<=0))throw TypeError("[socials] issueOAuthFlow userId must be a positive integer.");let t=Math.min(e.ttlMs,_r),r=xe(),n=(e.challenge?!1:e.bindBrowser!==!1)?xe():null,s=e.nonce===!0?xe():typeof e.nonce==="string"&&e.nonce?e.nonce:void 0,o=new Date,a=new Date(o.getTime()+t),c=ct();try{await c.prune(o)}catch{}await c.insert({stateDigest:j(r),purpose:e.purpose,browserDigest:e.challenge??(n?j(n):null),userId:e.userId??null,nonce:s??null,data:e.data??null,expiresAt:a});let u=n?dt(_e(r),n,t/1000,await lt(e.cookie)):null;return{state:r,cookie:u,secret:n,...s!==void 0&&{nonce:s},expiresAt:a}}async function Mn(e,t){if(typeof e!=="string"||!Pr.test(e))return null;let r=ct(),i=j(e),n=await r.find(i);if(!n)return null;if(n.expiresAt.getTime()<=Date.now())return await r.take(i).catch(()=>!1),null;if(n.purpose!==t.purpose)return null;if(n.browserDigest!==null){let s=t.browserSecret;if(typeof s!=="string"||s.length===0||s.length>512)return null;if(!Ir(j(s),n.browserDigest))return null}if(!await r.take(i))return null;return{purpose:n.purpose,userId:n.userId,nonce:n.nonce,data:n.data,expiresAt:n.expiresAt}}function Dn(e,t){if(!e||!t)return"";let r=_e(t);for(let i of e.split(";")){let n=i.trim();if(n.startsWith(`${r}=`))return n.slice(r.length+1)}return""}async function Nn(e,t={}){return dt(_e(e),"",0,await lt(t))}function zn(){let e=new Map;return{records:e,async insert(t){e.set(t.stateDigest,{...t})},async find(t){let r=e.get(t);return r?{...r}:void 0},async take(t){return e.delete(t)},async prune(t){for(let[r,i]of e)if(i.expiresAt.getTime()<=t.getTime())e.delete(r)}}}var se="oauth_flows";function Ar(){let e=()=>import("@stacksjs/database/runtime");return{async insert(t){let{db:r,sqlDateTime:i}=await e();await r.insertInto(se).values({state_digest:t.stateDigest,purpose:t.purpose,browser_digest:t.browserDigest,user_id:t.userId,nonce:t.nonce,data:t.data?JSON.stringify(t.data):null,expires_at:i(t.expiresAt),created_at:i(new Date)}).execute()},async find(t){let{db:r,parseSqlDateTime:i}=await e(),n=await r.primary.selectFrom(se).where("state_digest","=",t).selectAll().executeTakeFirst();if(!n)return;let s=null;if(typeof n.data==="string"&&n.data)try{let o=JSON.parse(n.data);s=o&&typeof o==="object"?o:null}catch{s=null}return{stateDigest:String(n.state_digest),purpose:String(n.purpose),browserDigest:typeof n.browser_digest==="string"&&n.browser_digest?n.browser_digest:null,userId:n.user_id==null?null:Number(n.user_id),nonce:typeof n.nonce==="string"&&n.nonce?n.nonce:null,data:s,expiresAt:i(n.expires_at)??new Date(0)}},async take(t){let{db:r,mutationCount:i}=await e(),n=await r.deleteFrom(se).where("state_digest","=",t).execute();return i(n)===1},async prune(t){let{db:r,sqlDateTime:i}=await e();await r.deleteFrom(se).where("expires_at","<",i(t)).execute()}}}var Ur={bluesky:["identifier","password","service"],twitter:["clientId","clientSecret","accessToken","refreshToken"],linkedin:["accessToken","memberUrn","clientId","clientSecret","apiVersion"],mastodon:["accessToken","instanceUrl"],instagram:["accessToken","accountId","clientId","clientSecret"],threads:["accessToken","userId","clientId","clientSecret"]},Rr={bluesky:["identifier","password"],twitter:["clientId","clientSecret","accessToken"],linkedin:["accessToken","memberUrn"],mastodon:["accessToken","instanceUrl"],instagram:["accessToken","accountId"],threads:["accessToken","userId"]};function Cr(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function oe(e,t,r){let i=r.replace(/[A-Z]/g,(n)=>`_${n}`).toUpperCase();return`SOCIALS_${Cr(e)}_${t.toUpperCase()}_${i}`}class S extends Error{constructor(e){super(e);this.name="SocialIdentityError"}}async function ae(){let{config:e,overridesReady:t}=await import("@stacksjs/config");return await t,e.socials??{}}function ut(e,t){let r=Object.keys(e.identities??{});if(t){if(!r.includes(t))throw new S(`Unknown social identity '${t}'. config/socials.ts declares: ${r.length?r.join(", "):"none"}.`);return t}if(e.default){if(!r.includes(e.default))throw new S(`config/socials.ts sets default: '${e.default}', which is not one of its identities: ${r.length?r.join(", "):"none"}.`);return e.default}if(r.length===1)return r[0];if(r.length===0)throw new S("config/socials.ts declares no identities, so there is no account to post as.");throw new S(`config/socials.ts declares ${r.length} identities (${r.join(", ")}) and no default, so a call has to name one.`)}function Er(e,t,r,i=process.env){let s=(e.identities?.[r]??{}).credentials?.[t]??{},o={};for(let a of Ur[t]){let c=(s[a]??i[oe(r,t,a)]??"").trim();if(c)o[a]=c}return o}function Ie(e,t,r,i=process.env){let n=ut(e,r),s=Er(e,t,n,i),o=Rr[t].filter((a)=>!s[a]);if(o.length){let a=o.map((c)=>oe(n,t,c)).join(", ");throw new S(`Identity '${n}' is not configured for ${t}: ${o.join(", ")} ${o.length===1?"is":"are"} missing. Set ${a}, or supply them inline in config/socials.ts.`)}return s}async function ht(e){return ut(await ae(),e)}async function M(e,t,r){return Ie(await ae(),e,t,r)}function Fn(e,t){return M("bluesky",e,t)}function Vn(e,t){return M("twitter",e,t)}function jn(e,t){return M("linkedin",e,t)}function Hn(e,t){return M("mastodon",e,t)}function Jn(e,t){return M("instagram",e,t)}function Gn(e,t){return M("threads",e,t)}import{randomBytes as $r}from"crypto";function Yn(e){return e==="twitter"}var Or=["tweet.read","tweet.write","users.read","offline.access"],Lr="127.0.0.1",pt="/callback";function Zn(e){if(!Number.isInteger(e)||e<1||e>65535)throw new S(`${e} is not a port a redirect can listen on.`);return`http://${Lr}:${e}${pt}`}function es(){return $r(16).toString("hex")}function ts(e,t){let r;try{r=new URL(e)}catch{return{ok:!1,reason:"not-the-callback",message:`Not a URL: ${e}`}}if(r.pathname!==pt)return{ok:!1,reason:"not-the-callback",message:`Ignoring a request for ${r.pathname}.`};let i=r.searchParams.get("state")??"";if(i&&(!t||i!==t))return{ok:!1,reason:"state-mismatch",message:"The redirect carried the wrong state, so it did not come from this run."};let n=r.searchParams.get("error");if(n){let o=r.searchParams.get("error_description");return{ok:!1,reason:"declined",message:o?`${n}: ${o}`:n}}if(!t||i!==t)return{ok:!1,reason:"state-mismatch",message:"The redirect carried the wrong state, so it did not come from this run."};let s=r.searchParams.get("code")??"";if(!s)return{ok:!1,reason:"no-code",message:"The redirect carried no authorization code."};return{ok:!0,code:s}}function rs(e,t,r){let i=[];for(let[n,s]of Object.entries(r)){if(!s)continue;if(/[\r\n]/.test(s))throw new S(`Refusing to format ${n}: value contains a newline.`);i.push(`${oe(e,t,n)}=${s}`)}return i}async function is(e){let t=new B,r=await t.exchangeCode(e);if(!r.accessToken)throw new S("X returned no access token for that code.");let i=Boolean(r.refreshToken),n=await t.getProfile(r.accessToken);return{handle:n.username,accountId:n.id,accessToken:r.accessToken,refreshToken:r.refreshToken,expiresIn:r.expiresIn,scope:r.scope,renewable:i}}async function ns(e){return new B().createAuthorization({clientId:e.clientId,redirectUrl:e.redirectUrl,scopes:[...Or],state:e.state})}function ss(e,t){let r=(i)=>i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${r(e)}</title><style>body{font:16px/1.5 system-ui,sans-serif;margin:0;display:grid;place-items:center;min-height:100vh;color:#111}main{max-width:28rem;padding:2rem;text-align:center}h1{font-size:1.25rem;margin:0 0 .5rem}p{margin:0;color:#555}@media(prefers-color-scheme:dark){body{background:#111;color:#eee}p{color:#aaa}}</style></head><body><main><h1>${r(e)}</h1><p>${r(t)}</p></main></body></html>`}var Br={bluesky:null,twitter:null,linkedin:"memberUrn",mastodon:"instanceUrl",instagram:"accountId",threads:"userId"};function Mr(e,t){if(e==="bluesky")return t.service?{service:t.service}:{};if(e==="linkedin")return t.apiVersion?{apiVersion:t.apiVersion}:{};return{}}function Dr(e,t){if(e.service||!t.service)return e;return{...e,service:t.service}}function Nr(e,t={}){switch(e){case"bluesky":return new W(t);case"linkedin":return new ye(t);case"twitter":return new B;case"mastodon":return new be;case"instagram":return new we;case"threads":return new Se;default:throw new S(`No publishing driver for '${String(e)}'.`)}}function zr(e,t,r){let i=Br[e],n={handle:(t??"").trim()};if(r.accessToken)n.accessToken=r.accessToken;if(r.refreshToken)n.refreshToken=r.refreshToken;if(i&&r[i])n.did=r[i];return n}function qr(e,t,r){if(!r)return;if(r.includes(t))return;throw new S(`Identity '${e}' is not set up for ${t}. config/socials.ts lists: ${r.length?r.join(", "):"none"}.`)}async function Fr(e,t,r){let i=await ae(),n=await ht(t),s=i.identities?.[n]??{};qr(n,e,s.platforms);let o=Ie(i,e,n,r),a=Mr(e,o);if(e==="bluesky"){let c=await new W(a).createSession({identifier:o.identifier,password:o.password});return{name:n,platform:e,identity:{handle:c.handle,did:c.did,accessToken:c.accessJwt,refreshToken:c.refreshJwt},options:Dr(a,c)}}return{name:n,platform:e,identity:zr(e,s.handle??"",o),options:a}}async function ds(e,t,r,i){let n=await Fr(e,r,i);return Nr(n.platform,n.options).publish(n.identity,t)}export{Lr as AUTHORIZE_HOST,pt as AUTHORIZE_PATH,y as AbstractProvider,de as AppleProvider,ze as BLUESKY_MAX_BATCH_WRITES,Me as BLUESKY_MAX_BLOB_BYTES,Ot as BLUESKY_MAX_IMAGES,Lt as BLUESKY_MAX_LANGS,De as BLUESKY_MAX_VIDEO_BYTES,_ as BlueskyApiError,W as BlueskyPublishingDriver,g as ConfigException,Br as DRIVER_DID_FIELD,pe as FacebookProvider,me as GitHubProvider,fe as GoogleProvider,Ht as INSTAGRAM_MAX_ALT_TEXT,jt as INSTAGRAM_MAX_IMAGES,b as InstagramApiError,we as InstagramPublishingDriver,mt as InvalidStateException,Ke as LINKEDIN_API_VERSION,Wt as LINKEDIN_MAX_ALT_TEXT,Qt as LINKEDIN_MAX_IMAGES,Yt as LINKEDIN_POSTING_ROLES,ni as LINK_LENGTH,w as LinkedInApiError,ye as LinkedInPublishingDriver,L as MASTODON_DEFAULT_LIMITS,Pt as MAX_POST_IMAGE_BYTES,Y as META_GRAPH_VERSION,q as MastodonApiError,be as MastodonPublishingDriver,Ee as PostImageError,Rr as REQUIRED_SOCIAL_CREDENTIALS,Ur as SOCIAL_CREDENTIAL_FIELDS,V as SOCIAL_PROVIDERS,k as SocialApiError,S as SocialIdentityError,F as StacksIssuerError,pr as StacksIssuerProvider,cr as THREADS_MAX_ALT_TEXT,ar as THREADS_MAX_IMAGES,Or as TWITTER_PUBLISH_SCOPES,v as ThreadsApiError,Se as ThreadsPublishingDriver,fr as Token,x as TwitterApiError,Pe as TwitterProvider,B as TwitterPublishingDriver,ur as X_MAX_ALT_TEXT,lr as X_MAX_IMAGES,f as apiFailure,qr as assertPlatformDeclared,mi as blueskyRecordKey,Dr as blueskyTargetOptions,ss as callbackPage,Zn as callbackUri,Q as classifySocialError,Nn as clearOAuthFlowCookie,is as completeTwitterAuthorization,bn as configuredSocialProviders,Mn as consumeOAuthFlow,Tt as countText,Ar as databaseOAuthFlowStore,Dt as detectFacetCandidates,Mr as driverOptions,rs as envLines,oe as envName,Cr as envSegment,Zt as escapeLinkedInText,P as exceedsLimit,C as fetchPostImage,K as graphemes,Yn as isAuthorizablePlatform,gi as isBlueskySessionError,oi as isExpiredSignIn,Z as isMissingGraphObject,ve as isSafeHandoffTarget,st as isSocialProviderConfigured,mr as isSocialProviderName,Bn as issueOAuthFlow,Kt as linkedInVersionSunset,zn as memoryOAuthFlowStore,X as networkReason,es as newState,or as normalizeInstance,_e as oauthFlowCookieName,j as oauthFlowDigest,he as parseAtUri,Ie as pickCredentials,ut as pickIdentity,ds as publishAs,Nr as publishingDriver,ts as readCallback,Er as readCredentials,Ce as readImageDimensions,Dn as readOAuthFlowCookie,I as rejectPostVideo,Fn as resolveBlueskyCredentials,qe as resolveBlueskyService,ht as resolveIdentityName,Jn as resolveInstagramCredentials,jn as resolveLinkedInCredentials,Xt as resolveLinkedInVersion,Hn as resolveMastodonCredentials,E as resolvePostImage,M as resolveSocialCredentials,Gn as resolveThreadsCredentials,Vn as resolveTwitterCredentials,Ut as retryAfterMs,le as sniffImageType,Rn as socialHandoffCodeRedirect,Cn as socialHandoffFailureRedirect,Un as socialHandoffRedirect,Sn as socialProvider,Fr as socialPublishTarget,ae as socialsConfig,ns as startTwitterAuthorization,_n as supportsDeletion,In as supportsEnumeration,xn as supportsMetrics,zr as toDriverIdentity,Ln as useOAuthFlowStore,G as validatePostVideo};
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/socials",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.770",
5
+ "version": "0.75.775",
6
6
  "description": "A simple and elegant social authentication package for Stacks.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -57,15 +57,15 @@
57
57
  "prepublishOnly": "bun run build"
58
58
  },
59
59
  "dependencies": {
60
- "@stacksjs/api": "0.75.770",
61
- "@stacksjs/composables": "0.75.770",
62
- "@stacksjs/config": "0.75.770",
63
- "@stacksjs/database": "0.75.770",
64
- "@stacksjs/security": "0.75.770"
60
+ "@stacksjs/api": "0.75.775",
61
+ "@stacksjs/composables": "0.75.775",
62
+ "@stacksjs/config": "0.75.775",
63
+ "@stacksjs/database": "0.75.775",
64
+ "@stacksjs/security": "0.75.775"
65
65
  },
66
66
  "devDependencies": {
67
- "@stacksjs/error-handling": "0.75.770",
68
- "@stacksjs/router": "0.75.770",
67
+ "@stacksjs/error-handling": "0.75.775",
68
+ "@stacksjs/router": "0.75.775",
69
69
  "better-dx": "^0.2.42"
70
70
  }
71
71
  }