@stacksjs/socials 0.70.258 → 0.70.259

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.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from './abstract';
2
2
  export * from './drivers/index';
3
3
  export * from './exceptions';
4
+ export * from './registry';
4
5
  export * from './token';
5
6
  export * from './types';
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- var q=import.meta.require;class _{clientId;clientSecret;redirectUrl;parameters={};_scopes=[];scopeSeparator=",";_stateless=!1;_usesPKCE=!1;_state=null;user=null;constructor(D){this.clientId=D.clientId,this.clientSecret=D.clientSecret,this.redirectUrl=D.redirectUrl}getCodeFields(D=null){let G={client_id:this.clientId,redirect_uri:this.redirectUrl,scope:this.formatScopes(this.getScopes(),this.scopeSeparator),response_type:"code"};if(this.usesState())G.state=D;if(this.usesPKCE())G.code_challenge=this.getCodeChallenge(),G.code_challenge_method=this.getCodeChallengeMethod();return{...G,...this.parameters}}formatScopes(D,G){return D.join(G)}async userFromToken(D){return{...await this.getUserByToken(D),token:D}}scopes(D){let G=Array.isArray(D)?D:[D];return this._scopes=[...new Set([...this._scopes,...G])],this}setScopes(D){let G=Array.isArray(D)?D:[D];return this._scopes=[...new Set(G)],this}getScopes(){return this._scopes}setRedirectUrl(D){if(typeof D!=="string"||D.length===0)throw Error("[socials] setRedirectUrl requires a non-empty string");let G;try{G=new URL(D)}catch{throw Error(`[socials] setRedirectUrl: invalid URL: ${D}`)}if(G.protocol!=="https:"&&G.protocol!=="http:")throw Error(`[socials] setRedirectUrl protocol must be http(s)://, got ${G.protocol}`);return this.redirectUrl=D,this}withState(D){if(typeof D!=="string"||D.length===0)throw Error("[socials] withState requires a non-empty string");return this._state=D,this}resolveState(){return this._state??this.getState()}usesState(){return!this._stateless}validateState(D,G){if(typeof D!=="string"||typeof G!=="string")return!1;if(D.length===0||G.length===0)return!1;if(D.length!==G.length)return!1;try{let{timingSafeEqual:J}=q("crypto");return J(Buffer.from(D,"utf8"),Buffer.from(G,"utf8"))}catch{let J=0;for(let N=0;N<D.length;N++)J|=D.charCodeAt(N)^G.charCodeAt(N);return J===0}}isStateless(){return this._stateless}stateless(){return this._stateless=!0,this}getState(){let D=new Uint8Array(32);return crypto.getRandomValues(D),Array.from(D).map((G)=>G.toString(16).padStart(2,"0")).join("")}usesPKCE(){return this._usesPKCE}enablePKCE(){return this._usesPKCE=!0,this}getCodeVerifier(){let D=new Uint8Array(48);return crypto.getRandomValues(D),Array.from(D).map((G)=>G.toString(16).padStart(2,"0")).join("")}async getCodeChallenge(){let G=new TextEncoder().encode(this.getCodeVerifier()),J=await crypto.subtle.digest("SHA-256",G),{Buffer:N}=await import("buffer");return N.from(new Uint8Array(J)).toString("base64url")}getCodeChallengeMethod(){return"S256"}with(D){return this.parameters=D,this}buildAuthUrlFromBase(D,G){let J=new URLSearchParams(this.getCodeFields(G));return`${D}?${J.toString()}`}}import{Buffer as j}from"buffer";import{createPrivateKey as k,sign as b}from"crypto";import{config as M}from"@stacksjs/config";class x extends Error{constructor(D="Invalid state"){super(D);this.name="InvalidStateException"}}class z extends Error{constructor(D){super(D);this.name="ConfigException"}}class h extends _{baseUrl="https://appleid.apple.com";teamId="";keyId="";privateKey="";constructor(D){super(D);this.teamId=D.teamId??"",this.keyId=D.keyId??"",this.privateKey=D.privateKey??""}getConfig(){let D={clientId:this.clientId||(M.services.apple?.clientId??""),teamId:this.teamId||(M.services.apple?.teamId??""),keyId:this.keyId||(M.services.apple?.keyId??""),privateKey:(this.privateKey||(M.services.apple?.privateKey??"")).replace(/\\n/g,`
3
- `),redirectUrl:this.redirectUrl||(M.services.apple?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:M.services.apple?.scopes??["name","email"]};return this.setScopes(D.scopes),D}async getAuthUrl(){let D=this.resolveState(),{clientId:G,redirectUrl:J,scopes:N}=this.getConfig();this.validateConfig();let Q={client_id:G,redirect_uri:J,scope:N.join(" "),state:D,response_type:"code",...this.parameters};if(N.length>0)Q.response_mode="form_post";return`${this.baseUrl}/auth/authorize?${new URLSearchParams(Q).toString()}`}async getAccessToken(D){let{clientId:G,redirectUrl:J}=this.getConfig();this.validateConfig();let N=await fetch(`${this.baseUrl}/auth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:D,redirect_uri:J,client_id:G,client_secret:this.generateClientSecret()})}),Q=await N.json();if(!N.ok||Q.error)throw Error(`Apple OAuth error: ${Q.error_description??Q.error??`HTTP ${N.status}`}`);if(!Q.id_token)throw Error("Apple OAuth error: token response contained no id_token");return Q.id_token}async getUserByToken(D){let{clientId:G}=this.getConfig(),J=this.decodeIdToken(D),N=J.iss===this.baseUrl,Q=Array.isArray(J.aud)?J.aud.includes(G):J.aud===G,X=typeof J.exp==="number"&&J.exp*1000>Date.now();if(!N||!Q||!X)throw Error("Apple OAuth error: id_token claims failed validation (iss/aud/exp)");if(!J.sub)throw Error("Apple OAuth error: id_token has no subject");let Y=typeof J.email==="string"?J.email:null,Z=null;if(J.email_verified===!0||J.email_verified==="true")Z=!0;else if(J.email_verified===!1||J.email_verified==="false")Z=!1;return{id:String(J.sub),nickname:null,name:"",email:Y,emailVerified:Z,avatar:null,token:D,raw:J}}generateClientSecret(){let{clientId:D,teamId:G,keyId:J,privateKey:N}=this.getConfig(),Q=Math.floor(Date.now()/1000),X={alg:"ES256",kid:J,typ:"JWT"},Y={iss:G,iat:Q,exp:Q+3600,aud:this.baseUrl,sub:D},Z=`${this.base64urlJson(X)}.${this.base64urlJson(Y)}`,$;try{$=k(N)}catch(H){throw new z(`Apple private key could not be parsed: ${H instanceof Error?H.message:String(H)}`)}let F=b("sha256",j.from(Z),{key:$,dsaEncoding:"ieee-p1363"});return`${Z}.${F.toString("base64url")}`}decodeIdToken(D){let G=D.split(".");if(G.length!==3)throw Error("Apple OAuth error: malformed id_token");return JSON.parse(j.from(G[1],"base64url").toString("utf8"))}base64urlJson(D){return j.from(JSON.stringify(D)).toString("base64url")}validateConfig(){let{clientId:D,teamId:G,keyId:J,privateKey:N,redirectUrl:Q}=this.getConfig();if(!D)throw new z("Apple client ID (Service ID) not provided");if(!G)throw new z("Apple team ID not provided");if(!J)throw new z("Apple key ID not provided");if(!N)throw new z("Apple private key not provided");if(!Q)throw new z("Apple redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/auth/token`}}function g(D){let G=/^at:\/\/([^/]+)\/([^/]+)\/([^/]+)$/.exec(String(D||"").trim());if(!G)throw Error(`"${D}" is not a Bluesky post URI.`);return{repo:G[1],collection:G[2],rkey:G[3]}}class C extends Error{status;body;constructor(D,G,J){super(D);this.status=G;this.body=J;this.name="BlueskyApiError"}get isAuthError(){return this.status===400||this.status===401||this.status===403}}var f=new TextEncoder;function O(D){return f.encode(D).length}function m(D){let G=[],J=/https?:\/\/[^\s<>"']+/g;for(let Y of D.matchAll(J)){let Z=Y[0].replace(/[),.;!?]+$/,"");G.push({byteStart:O(D.slice(0,Y.index)),byteEnd:O(D.slice(0,Y.index))+O(Z),type:"link",value:Z})}let N=(Y,Z)=>G.some(($)=>$.type==="link"&&Y<$.byteEnd&&Z>$.byteStart),Q=/(^|\s)(#[A-Za-z0-9_]+)/g;for(let Y of D.matchAll(Q)){let Z=Y[1],$=Y[2];if(Z===void 0||$===void 0)continue;if(/^#\d+$/.test($))continue;let F=(Y.index??0)+Z.length,H=O(D.slice(0,F)),V=H+O($);if(N(H,V))continue;G.push({byteStart:H,byteEnd:V,type:"tag",value:$.slice(1)})}let X=/(^|\s)(@[a-z0-9][a-z0-9.-]*\.[a-z]{2,})/gi;for(let Y of D.matchAll(X)){let Z=Y[1],$=Y[2];if(Z===void 0||$===void 0)continue;let F=(Y.index??0)+Z.length,H=O(D.slice(0,F)),V=H+O($);if(N(H,V))continue;G.push({byteStart:H,byteEnd:V,type:"mention",value:$.slice(1).replace(/\.+$/,"")})}return G.sort((Y,Z)=>Y.byteStart-Z.byteStart)}class l{provider="bluesky";characterLimit=300;service;constructor(D={}){this.service=D.service||"https://bsky.social"}async createSession(D){let G=D.identifier.trim(),J=D.password.trim();if(!G)throw Error("Bluesky identifier is required.");if(!J)throw Error("Bluesky app password is required.");let N=await this.post("/xrpc/com.atproto.server.createSession",{identifier:G,password:J}),Q=await this.getProfile({did:N.did,handle:N.handle,accessToken:N.accessJwt,refreshToken:N.refreshJwt}).catch(()=>{return});return{did:N.did,handle:N.handle,displayName:Q?.displayName,accessJwt:N.accessJwt,refreshJwt:N.refreshJwt}}async refreshSession(D){if(!D)throw Error("Bluesky refresh token is required.");let G=await this.post("/xrpc/com.atproto.server.refreshSession",void 0,{authorization:`Bearer ${D}`});return{did:G.did,handle:G.handle,accessJwt:G.accessJwt,refreshJwt:G.refreshJwt}}async publish(D,G){let J=D.did||D.handle;if(!D.accessToken)throw Error("Bluesky access token is missing for this identity.");if(!J)throw Error("Bluesky identity DID or handle is required.");if(G.text.length>this.characterLimit)throw Error(`Bluesky posts must be ${this.characterLimit} characters or fewer.`);let N={$type:"app.bsky.feed.post",text:G.text,createdAt:G.scheduledAt||new Date().toISOString()};if(G.langs?.length)N.langs=G.langs;if(G.reply)N.reply=G.reply;let Q=G.facets??await this.buildFacets(G.text);if(Q.length)N.facets=Q;if(G.external)N.embed={$type:"app.bsky.embed.external",external:{uri:G.external.uri,title:G.external.title,description:G.external.description||""}};let X=(G.media||[]).filter((Z)=>Z.bytes?.length).slice(0,4);if(X.length){let Z=[];for(let $ of X){let F=await this.uploadBlob(D,$.bytes,$.mimeType||"image/jpeg");Z.push({image:F,alt:$.altText||""})}N.embed={$type:"app.bsky.embed.images",images:Z}}let Y=await this.post("/xrpc/com.atproto.repo.createRecord",{repo:J,collection:"app.bsky.feed.post",record:N},{authorization:`Bearer ${D.accessToken}`});return{provider:this.provider,uri:Y.uri,cid:Y.cid,url:this.toPostUrl(D.handle,Y.uri)}}async postMetrics(D,G){if(!D.accessToken)throw Error("Bluesky access token is missing for this identity.");if(G.length===0)return[];let J=new URL(`${this.service}/xrpc/app.bsky.feed.getPosts`);for(let Q of G.slice(0,25))J.searchParams.append("uris",Q);return((await this.request(J,{headers:{authorization:`Bearer ${D.accessToken}`}})).posts||[]).map((Q)=>({uri:Q.uri,likeCount:Q.likeCount||0,repostCount:Q.repostCount||0,replyCount:Q.replyCount||0}))}async timeline(D,G={}){if(!D.accessToken)throw Error("Bluesky access token is missing for this identity.");let J=new URL(`${this.service}/xrpc/app.bsky.feed.getTimeline`);if(J.searchParams.set("limit",String(Math.min(Math.max(G.limit||30,1),100))),G.cursor)J.searchParams.set("cursor",G.cursor);let N=await this.request(J,{headers:{authorization:`Bearer ${D.accessToken}`}});return{cursor:N.cursor,items:(N.feed||[]).flatMap((Q)=>{let X=Q.post;if(!X?.uri||!X.author?.handle)return[];return[{uri:X.uri,authorHandle:X.author.handle,authorName:X.author.displayName,authorAvatar:X.author.avatar,postUrl:this.toPostUrl(X.author.handle,X.uri),body:X.record?.text||"",postedAt:X.record?.createdAt||new Date().toISOString(),likeCount:X.likeCount||0,repostCount:X.repostCount||0,replyCount:X.replyCount||0}]})}}async getProfile(D){if(!D.accessToken)throw Error("Bluesky access token is missing for this identity.");let G=D.did||D.handle;if(!G)throw Error("Bluesky identity DID or handle is required.");let J=new URL(`${this.service}/xrpc/app.bsky.actor.getProfile`);return J.searchParams.set("actor",G),await this.request(J,{headers:{authorization:`Bearer ${D.accessToken}`}})}async buildFacets(D){let G=[];for(let J of m(D)){let N=null;if(J.type==="link")N={$type:"app.bsky.richtext.facet#link",uri:J.value};else if(J.type==="tag")N={$type:"app.bsky.richtext.facet#tag",tag:J.value};else if(J.type==="mention"){let Q=await this.resolveHandle(J.value);if(Q)N={$type:"app.bsky.richtext.facet#mention",did:Q}}if(N)G.push({index:{byteStart:J.byteStart,byteEnd:J.byteEnd},features:[N]})}return G}async resolveHandle(D){try{let G=new URL(`${this.service}/xrpc/com.atproto.identity.resolveHandle`);return G.searchParams.set("handle",D),(await this.request(G,{})).did||null}catch{return null}}async uploadBlob(D,G,J){if(!D.accessToken)throw Error("Bluesky access token is missing for this identity.");if(G.length>1e6)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":J,authorization:`Bearer ${D.accessToken}`},body:new Uint8Array(G)})).blob}async listAuthoredPosts(D,G={}){let J=D.did||D.handle;if(!D.accessToken)throw Error("Bluesky access token is missing for this identity.");if(!J)throw Error("Bluesky identity DID or handle is required.");let N=new URL(`${this.service}/xrpc/com.atproto.repo.listRecords`);if(N.searchParams.set("repo",J),N.searchParams.set("collection","app.bsky.feed.post"),N.searchParams.set("limit",String(Math.min(Math.max(G.limit||100,1),100))),G.cursor)N.searchParams.set("cursor",G.cursor);let Q=await this.request(N,{headers:{authorization:`Bearer ${D.accessToken}`}});return{cursor:Q.cursor,posts:(Q.records||[]).filter((X)=>X?.uri).map((X)=>({uri:X.uri,cid:X.cid,text:X.value?.text,postedAt:X.value?.createdAt,url:D.handle?this.toPostUrl(D.handle,X.uri):void 0}))}}async deletePost(D,G){if(!D.accessToken)throw Error("Bluesky access token is missing for this identity.");let{repo:J,collection:N,rkey:Q}=g(G.uri);await this.post("/xrpc/com.atproto.repo.deleteRecord",{repo:J,collection:N,rkey:Q},{authorization:`Bearer ${D.accessToken}`})}async post(D,G,J={}){return await this.request(new URL(`${this.service}${D}`),{method:"POST",headers:{...G===void 0?{}:{"content-type":"application/json"},...J},...G===void 0?{}:{body:JSON.stringify(G)}})}async request(D,G){let J=await fetch(D,G),N=await J.text();if(!J.ok)throw new C(`Bluesky API failed (${J.status}): ${N||J.statusText}`,J.status,N);return N?JSON.parse(N):{}}toPostUrl(D,G){let J=G.split("/").pop();return`https://bsky.app/profile/${D}/post/${J}`}}import{fetcher as v}from"@stacksjs/api";import{config as P}from"@stacksjs/config";class u extends _{baseUrl="https://www.facebook.com";apiUrl="https://graph.facebook.com";getConfig(){let D={clientId:P.services.facebook?.clientId??"",clientSecret:P.services.facebook?.clientSecret??"",redirectUrl:P.services.facebook?.redirectUrl??"",scopes:P.services.facebook?.scopes??["email","public_profile"]};return this.setScopes(D.scopes),D}async getAuthUrl(){let D=this.getState(),{clientId:G,redirectUrl:J,scopes:N}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/v18.0/dialog/oauth?${new URLSearchParams({client_id:G,redirect_uri:J,scope:N.join(","),state:D,response_type:"code"}).toString()}`}async getAccessToken(D){let{clientId:G,clientSecret:J,redirectUrl:N}=this.getConfig();this.validateConfig();let Q=await v.get(`${this.apiUrl}/v18.0/oauth/access_token?${new URLSearchParams({client_id:G,client_secret:J,redirect_uri:N,code:D}).toString()}`);if(Q.data.error)throw Error(`Facebook OAuth error: ${Q.data.error.message}`);return Q.data.access_token}async getUserByToken(D){let G=await v.get(`${this.apiUrl}/v18.0/me?${new URLSearchParams({access_token:D,fields:"id,name,email,picture"}).toString()}`);return{id:G.data.id,nickname:null,name:G.data.name,email:G.data.email??null,avatar:G.data.picture?.data.url??null,token:D,raw:G.data}}validateConfig(){let{clientId:D,clientSecret:G,redirectUrl:J}=this.getConfig();if(!D)throw new z("Facebook client ID not provided");if(!G)throw new z("Facebook client secret not provided");if(!J)throw new z("Facebook redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/v18.0/oauth/access_token`}}import{fetcher as w}from"@stacksjs/api";import{config as S}from"@stacksjs/config";class y extends _{baseUrl="https://github.com";apiUrl="https://api.github.com";getConfig(){let D={clientId:this.clientId||(S.services.github?.clientId??""),clientSecret:this.clientSecret||(S.services.github?.clientSecret??""),redirectUrl:this.redirectUrl||(S.services.github?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:S.services.github?.scopes??["read:user","user:email"]};return this.setScopes(D.scopes),D}async getAuthUrl(){let D=this.resolveState(),{clientId:G,redirectUrl:J,scopes:N}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/login/oauth/authorize?${new URLSearchParams({client_id:G,redirect_uri:J,scope:N.join(" "),state:D,response_type:"code",...this.parameters}).toString()}`}async getAccessToken(D){let{clientId:G,clientSecret:J,redirectUrl:N}=this.getConfig();this.validateConfig();let Q=await w.post(`${this.baseUrl}/login/oauth/access_token`,{client_id:G,client_secret:J,code:D,redirect_uri:N});if(Q.data.error)throw Error(`GitHub OAuth error: ${Q.data.error_description}`);return Q.data.access_token}async getUserByToken(D){let[G,J]=await Promise.all([w.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${D}`}).get(`${this.apiUrl}/user`),w.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${D}`}).get(`${this.apiUrl}/user/emails`)]),N=this.pickEmail(J.data);return{id:G.data.id.toString(),nickname:G.data.login,name:G.data.name??G.data.login,email:N?.email??G.data.email??null,emailVerified:N?N.verified:null,avatar:G.data.avatar_url,token:D,raw:G.data}}pickEmail(D){if(!Array.isArray(D)||D.length===0)return null;let G=D.find((N)=>N.primary&&N.verified),J=D.find((N)=>N.verified);return G??J??D.find((N)=>N.primary)??D[0]??null}getEmail(D){return this.pickEmail(D)?.email??null}validateConfig(){let{clientId:D,clientSecret:G,redirectUrl:J}=this.getConfig();if(!D)throw new z("GitHub client ID not provided");if(!G)throw new z("GitHub client secret not provided");if(!J)throw new z("GitHub redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/login/oauth/access_token`}}import{fetcher as A}from"@stacksjs/api";import{config as U}from"@stacksjs/config";class c extends _{baseUrl="https://accounts.google.com";apiUrl="https://www.googleapis.com";getConfig(){let D={clientId:this.clientId||(U.services.google?.clientId??""),clientSecret:this.clientSecret||(U.services.google?.clientSecret??""),redirectUrl:this.redirectUrl||(U.services.google?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:U.services.google?.scopes??["openid","email"]};return this.setScopes(D.scopes),D}async getAuthUrl(){let D=this.resolveState(),{clientId:G,redirectUrl:J,scopes:N}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/o/oauth2/v2/auth?${new URLSearchParams({client_id:G,redirect_uri:J,scope:N.join(" "),state:D,response_type:"code",access_type:"offline",prompt:"consent",...this.parameters}).toString()}`}async getAccessToken(D){let{clientId:G,clientSecret:J,redirectUrl:N}=this.getConfig();this.validateConfig();let Q=await A.post(`${this.baseUrl}/oauth2/v4/token`,{client_id:G,client_secret:J,code:D,redirect_uri:N,grant_type:"authorization_code"});if(Q.data.error)throw Error(`Google OAuth error: ${Q.data.error_description}`);return Q.data.access_token}async getUserByToken(D){let G=await A.withHeaders({Authorization:`Bearer ${D}`}).get(`${this.apiUrl}/oauth2/v2/userinfo`);return{id:G.data.id,nickname:G.data.given_name,name:G.data.name,email:G.data.email,emailVerified:typeof G.data.verified_email==="boolean"?G.data.verified_email:null,avatar:G.data.picture,token:D,raw:G.data}}validateConfig(){let{clientId:D,clientSecret:G,redirectUrl:J}=this.getConfig();if(!D)throw new z("Google client ID not provided");if(!G)throw new z("Google client secret not provided");if(!J)throw new z("Google redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/oauth2/v4/token`}}class B extends Error{status;body;constructor(D,G,J){super(D);this.status=G;this.body=J;this.name="InstagramApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class p{provider="instagram";characterLimit=2200;graphVersion;authBase;graphBase;constructor(D={}){this.graphVersion=D.graphVersion||"v21.0",this.authBase=D.authBase||"https://www.facebook.com",this.graphBase=D.graphBase||"https://graph.facebook.com"}getAuthUrl(D){let G=new URLSearchParams({client_id:D.clientId,redirect_uri:D.redirectUrl,scope:D.scopes.join(","),state:D.state,response_type:"code"});return`${this.authBase}/${this.graphVersion}/dialog/oauth?${G.toString()}`}async exchangeCode(D){let G=new URLSearchParams({client_id:D.clientId,client_secret:D.clientSecret,redirect_uri:D.redirectUrl,code:D.code}),J=await this.graph(`/oauth/access_token?${G.toString()}`,{method:"GET"});if(!J.access_token)throw new B("Facebook did not return an access token.",400,JSON.stringify(J));return{accessToken:J.access_token,expiresIn:J.expires_in}}async resolveAccount(D){let G=new URLSearchParams({fields:"name,access_token,instagram_business_account{id,username}",access_token:D}),J=await this.graph(`/me/accounts?${G.toString()}`,{method:"GET"}),N=(J.data||[]).find((X)=>X.instagram_business_account?.id),Q=N?.instagram_business_account;if(!Q?.id||!N?.access_token)throw new B("No Instagram Business account is linked to your Facebook Pages.",400,JSON.stringify(J));return{igUserId:Q.id,username:Q.username,pageAccessToken:N.access_token}}async publish(D,G){if(!D.accessToken)throw Error("Instagram access token is missing for this identity.");let J=D.did;if(!J)throw Error("Instagram account id is required to publish.");let N=G.media?.[0];if(!N?.url)throw Error("Instagram requires an image to post.");if(G.text.length>this.characterLimit)throw Error(`Instagram captions must be ${this.characterLimit} characters or fewer.`);let Q=await this.graph(`/${J}/media`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({image_url:N.url,caption:G.text,access_token:D.accessToken}).toString()});if(!Q.id)throw new B("Instagram did not return a media container id.",400,JSON.stringify(Q));let X=await this.graph(`/${J}/media_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:Q.id,access_token:D.accessToken}).toString()}),Y=await this.graph(`/${X.id}?fields=permalink&access_token=${encodeURIComponent(D.accessToken)}`,{method:"GET"}).catch(()=>{return});return{provider:this.provider,uri:X.id,url:Y?.permalink}}async timeline(D,G={}){return{items:[]}}async graph(D,G){let J=await fetch(`${this.graphBase}/${this.graphVersion}${D}`,G),N=await J.text(),Q={};try{Q=N?JSON.parse(N):{}}catch{Q={}}if(!J.ok||Q?.error){let X=Q?.error?.message||N||J.statusText;throw new B(`Instagram API failed (${J.status}): ${X}`,J.status,N)}return Q}}class W extends Error{status;body;constructor(D,G,J){super(D);this.status=G;this.body=J;this.name="LinkedInApiError"}get isAuthError(){return this.status===401||this.status===403}}class d{provider="linkedin";characterLimit=3000;apiVersion;authBase;apiBase;constructor(D={}){this.apiVersion=D.apiVersion||"202405",this.authBase=D.authBase||"https://www.linkedin.com",this.apiBase=D.apiBase||"https://api.linkedin.com"}getAuthUrl(D){let G=new URLSearchParams({response_type:"code",client_id:D.clientId,redirect_uri:D.redirectUrl,scope:D.scopes.join(" "),state:D.state});return`${this.authBase}/oauth/v2/authorization?${G.toString()}`}async exchangeCode(D){let G=new URLSearchParams({grant_type:"authorization_code",code:D.code,redirect_uri:D.redirectUrl,client_id:D.clientId,client_secret:D.clientSecret}),J=await this.request(`${this.authBase}/oauth/v2/accessToken`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:G.toString()});if(!J.access_token)throw new W("LinkedIn did not return an access token.",400,JSON.stringify(J));return{accessToken:J.access_token,expiresIn:J.expires_in,scope:J.scope}}async getProfile(D){if(!D)throw Error("LinkedIn access token is required.");let G=await this.request(`${this.apiBase}/v2/userinfo`,{headers:{authorization:`Bearer ${D}`}});if(!G.sub)throw new W("LinkedIn profile is missing a subject id.",400,JSON.stringify(G));return{sub:G.sub,name:G.name,picture:G.picture}}async publish(D,G){if(!D.accessToken)throw Error("LinkedIn access token is missing for this identity.");let J=D.did;if(!J)throw Error("LinkedIn member URN is required to publish.");if(G.text.length>this.characterLimit)throw Error(`LinkedIn posts must be ${this.characterLimit} characters or fewer.`);let N={author:J,commentary:a(G.text),visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(G.external)N.content={article:{source:G.external.uri,title:G.external.title,description:G.external.description||""}};let Q=await fetch(`${this.apiBase}/rest/posts`,{method:"POST",headers:{authorization:`Bearer ${D.accessToken}`,"content-type":"application/json","linkedin-version":this.apiVersion,"x-restli-protocol-version":"2.0.0"},body:JSON.stringify(N)}),X=await Q.text();if(!Q.ok)throw new W(`LinkedIn API failed (${Q.status}): ${X||Q.statusText}`,Q.status,X);let Y=Q.headers.get("x-restli-id")||Q.headers.get("x-linkedin-id")||"";return{provider:this.provider,uri:Y,url:Y?`https://www.linkedin.com/feed/update/${Y}`:void 0}}async timeline(D,G={}){return{items:[]}}async listAuthoredPosts(D,G={}){if(!D.accessToken)throw Error("LinkedIn access token is missing for this identity.");let J=D.did;if(!J)throw Error("LinkedIn member URN is required to list posts.");let N=Math.min(Math.max(G.limit||50,1),100),Q=Number(G.cursor||0)||0,X=new URL(`${this.apiBase}/rest/posts`);X.searchParams.set("q","author"),X.searchParams.set("author",J),X.searchParams.set("count",String(N)),X.searchParams.set("start",String(Q));let Y;try{Y=await this.request(X.toString(),{headers:{authorization:`Bearer ${D.accessToken}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":"2.0.0"}})}catch($){if($ instanceof W&&($.status===401||$.status===403))throw new W("LinkedIn will not list this account's posts \u2014 the Posts author finder needs the r_member_social permission, which this app does not hold.",$.status,$.body);throw $}let Z=(Y.elements||[]).filter(($)=>$?.id).map(($)=>({uri:String($.id),text:$.commentary,postedAt:$.createdAt?new Date($.createdAt).toISOString():void 0,url:`https://www.linkedin.com/feed/update/${$.id}`}));return{cursor:Z.length===N?String(Q+N):void 0,posts:Z}}async deletePost(D,G){if(!D.accessToken)throw Error("LinkedIn access token is missing for this identity.");let J=String(G.uri||"").trim();if(!J)throw Error("A LinkedIn post URN is required to delete a post.");let N=await fetch(`${this.apiBase}/rest/posts/${encodeURIComponent(J)}`,{method:"DELETE",headers:{authorization:`Bearer ${D.accessToken}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":"2.0.0"}});if(!N.ok&&N.status!==404){let Q=await N.text().catch(()=>"");throw new W(`LinkedIn API failed (${N.status}): ${Q||N.statusText}`,N.status,Q)}}async request(D,G){let J=await fetch(D,G),N=await J.text();if(!J.ok)throw new W(`LinkedIn API failed (${J.status}): ${N||J.statusText}`,J.status,N);return N?JSON.parse(N):{}}}function a(D){return D.replace(/[\\|{}@[\]()<>#*_~]/g,"\\$&")}class T extends Error{status;body;constructor(D,G,J){super(D);this.status=G;this.body=J;this.name="MastodonApiError"}get isAuthError(){return this.status===401||this.status===403}}function o(D){let G=String(D||"").trim().replace(/\/+$/,"");if(!G)throw Error("Mastodon instance URL is required.");let J=/^https?:\/\//i.test(G)?G:`https://${G}`;try{let N=new URL(J);return`${N.protocol}//${N.host}`}catch{throw Error("Mastodon instance URL is invalid.")}}class n{provider="mastodon";characterLimit=500;instanceOf(D){return o(D.did||"")}tokenOf(D){if(!D.accessToken)throw Error("Mastodon access token is missing for this identity.");return D.accessToken}async verifyCredentials(D){let G=await this.request(`${this.instanceOf(D)}/api/v1/accounts/verify_credentials`,{headers:{authorization:`Bearer ${this.tokenOf(D)}`}});return{accountId:G.id,username:G.username,displayName:G.display_name||void 0,url:G.url}}async uploadMedia(D,G,J,N){let Q=new FormData;if(Q.set("file",new Blob([new Uint8Array(G)],{type:J||"image/jpeg"}),"upload"),N)Q.set("description",N);return(await this.request(`${this.instanceOf(D)}/api/v2/media`,{method:"POST",headers:{authorization:`Bearer ${this.tokenOf(D)}`},body:Q})).id}async publish(D,G){let J=this.instanceOf(D),N=this.tokenOf(D);if(G.text.length>this.characterLimit)throw Error(`Mastodon posts must be ${this.characterLimit} characters or fewer.`);let Q=[];for(let Z of(G.media||[]).slice(0,4)){let{bytes:$,mimeType:F}=Z;if(!$?.length&&Z.url){let H=await fetch(Z.url);if(!H.ok)continue;$=new Uint8Array(await H.arrayBuffer()),F=F||H.headers.get("content-type")||"image/jpeg"}if($?.length)Q.push(await this.uploadMedia(D,$,F||"image/jpeg",Z.altText))}let X={status:G.text,visibility:"public"};if(Q.length)X.media_ids=Q;if(G.reply?.parent?.uri)X.in_reply_to_id=G.reply.parent.uri;let Y=await this.request(`${J}/api/v1/statuses`,{method:"POST",headers:{authorization:`Bearer ${N}`,"content-type":"application/json"},body:JSON.stringify(X)});return{provider:this.provider,uri:Y.id,cid:Y.id,url:Y.url||Y.uri}}async timeline(D,G={}){return{items:[]}}async listAuthoredPosts(D,G={}){let J=this.instanceOf(D),{accountId:N}=await this.verifyCredentials(D),Q=new URL(`${J}/api/v1/accounts/${encodeURIComponent(N)}/statuses`);if(Q.searchParams.set("limit",String(Math.min(Math.max(G.limit||40,1),40))),Q.searchParams.set("exclude_reblogs","true"),G.cursor)Q.searchParams.set("max_id",G.cursor);let Y=(await this.request(Q.toString(),{headers:{authorization:`Bearer ${this.tokenOf(D)}`}})||[]).filter((Z)=>Z?.id).map((Z)=>({uri:Z.id,cid:Z.id,text:Z.content,postedAt:Z.created_at,url:Z.url}));return{cursor:Y.length?Y[Y.length-1]?.uri:void 0,posts:Y}}async deletePost(D,G){let J=String(G.cid||s(G.uri)||"").trim();if(!J)throw Error("A status id is required to delete a post.");await this.request(`${this.instanceOf(D)}/api/v1/statuses/${encodeURIComponent(J)}`,{method:"DELETE",headers:{authorization:`Bearer ${this.tokenOf(D)}`}})}async request(D,G){let J=await fetch(D,G),N=await J.text();if(!J.ok)throw new T(`Mastodon API failed (${J.status}): ${N||J.statusText}`,J.status,N);return N?JSON.parse(N):{}}}function s(D){return String(D||"").replace(/\/+$/,"").split("/").pop()||""}class R extends Error{status;body;constructor(D,G,J){super(D);this.status=G;this.body=J;this.name="ThreadsApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class r{provider="threads";characterLimit=500;graphVersion;authBase;graphBase;constructor(D={}){this.graphVersion=D.graphVersion||"v1.0",this.authBase=D.authBase||"https://threads.net",this.graphBase=D.graphBase||"https://graph.threads.net"}getAuthUrl(D){let G=new URLSearchParams({client_id:D.clientId,redirect_uri:D.redirectUrl,scope:D.scopes.join(","),response_type:"code",state:D.state});return`${this.authBase}/oauth/authorize?${G.toString()}`}async exchangeCode(D){let G=await fetch(`${this.graphBase}/oauth/access_token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:D.clientId,client_secret:D.clientSecret,grant_type:"authorization_code",redirect_uri:D.redirectUrl,code:D.code}).toString()}),J=await G.text(),N={};try{N=J?JSON.parse(J):{}}catch{N={}}if(!G.ok||N?.error||!N?.access_token){let Q=N?.error_message||N?.error?.message||J||G.statusText;throw new R(`Threads token exchange failed (${G.status}): ${Q}`,G.status,J)}return{accessToken:N.access_token,userId:N.user_id!=null?String(N.user_id):void 0,expiresIn:N.expires_in}}async resolveAccount(D){let G=new URLSearchParams({fields:"id,username",access_token:D}),J=await this.graph(`/me?${G.toString()}`,{method:"GET"});if(!J.id)throw new R("Could not resolve the Threads account for this token.",400,JSON.stringify(J));return{threadsUserId:J.id,username:J.username,accessToken:D}}async publish(D,G){if(!D.accessToken)throw Error("Threads access token is missing for this identity.");let J=D.did;if(!J)throw Error("Threads account id is required to publish.");if(G.text.length>this.characterLimit)throw Error(`Threads posts must be ${this.characterLimit} characters or fewer.`);let N=G.media?.[0],Q=new URLSearchParams({text:G.text,access_token:D.accessToken});if(N?.url)Q.set("media_type","IMAGE"),Q.set("image_url",N.url);else Q.set("media_type","TEXT");let X=await this.graph(`/${J}/threads`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:Q.toString()});if(!X.id)throw new R("Threads did not return a media container id.",400,JSON.stringify(X));let Y=await this.graph(`/${J}/threads_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:X.id,access_token:D.accessToken}).toString()});if(!Y.id)throw new R("Threads did not return a published post id.",400,JSON.stringify(Y));let Z=await this.graph(`/${Y.id}?fields=permalink&access_token=${encodeURIComponent(D.accessToken)}`,{method:"GET"}).catch(()=>{return});return{provider:this.provider,uri:Y.id,url:Z?.permalink}}async timeline(D,G={}){return{items:[]}}async graph(D,G){let J=await fetch(`${this.graphBase}/${this.graphVersion}${D}`,G),N=await J.text(),Q={};try{Q=N?JSON.parse(N):{}}catch{Q={}}if(!J.ok||Q?.error){let X=Q?.error?.message||N||J.statusText;throw new R(`Threads API failed (${J.status}): ${X}`,J.status,N)}return Q}}import{Buffer as i}from"buffer";import{createHash as t,randomBytes as e}from"crypto";import{fetcher as I}from"@stacksjs/api";import{config as L}from"@stacksjs/config";class DD extends _{baseUrl="https://twitter.com";apiUrl="https://api.twitter.com";codeVerifier=null;getConfig(){let D={clientId:L.services.twitter?.clientId??"",clientSecret:L.services.twitter?.clientSecret??"",redirectUrl:L.services.twitter?.redirectUrl??"",scopes:L.services.twitter?.scopes??["users.read","tweet.read"]};return this.setScopes(D.scopes),D}generateCodeVerifier(){return e(32).toString("base64").replace(/[^a-z0-9]/gi,"").substring(0,128)}generateCodeChallenge(D){return t("sha256").update(D).digest("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async getAuthUrl(){let D=this.getState(),{clientId:G,redirectUrl:J,scopes:N}=this.getConfig();this.validateConfig(),this.codeVerifier=this.generateCodeVerifier();let Q=this.generateCodeChallenge(this.codeVerifier);return`${this.baseUrl}/i/oauth2/authorize?${new URLSearchParams({client_id:G,redirect_uri:J,scope:N.join(" "),state:D,response_type:"code",code_challenge:Q,code_challenge_method:"S256"}).toString()}`}async getAccessToken(D){let{clientId:G,clientSecret:J,redirectUrl:N}=this.getConfig();if(this.validateConfig(),!this.codeVerifier)throw Error("Code verifier not found. Please ensure getAuthUrl() is called first.");let Q=i.from(`${G}:${J}`).toString("base64"),X=await I.withHeaders({Authorization:`Basic ${Q}`,"Content-Type":"application/x-www-form-urlencoded"}).post(`${this.apiUrl}/2/oauth2/token`,{code:D,grant_type:"authorization_code",redirect_uri:N,code_verifier:this.codeVerifier});if(X.data.error)throw Error(`Twitter OAuth error: ${X.data.error_description}`);return X.data.access_token}async getUserByToken(D){let G=await I.withHeaders({Authorization:`Bearer ${D}`}).get(`${this.apiUrl}/2/users/me?user.fields=profile_image_url`);return{id:G.data.id,nickname:G.data.username,name:G.data.name,email:G.data.email??null,avatar:G.data.profile_image_url??null,token:D,raw:G.data}}validateConfig(){let{clientId:D,clientSecret:G,redirectUrl:J}=this.getConfig();if(!D)throw new z("Twitter client ID not provided");if(!G)throw new z("Twitter client secret not provided");if(!J)throw new z("Twitter redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/2/oauth2/token`}}class K extends Error{status;body;constructor(D,G,J){super(D);this.status=G;this.body=J;this.name="TwitterApiError"}get isAuthError(){return this.status===401||this.status===403}}function E(D){let G="";for(let J of D)G+=String.fromCharCode(J);return btoa(G).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}class GD{provider="twitter";characterLimit=280;apiBase;authorizeBase;constructor(D={}){this.apiBase=D.apiBase||"https://api.twitter.com",this.authorizeBase=D.authorizeBase||"https://twitter.com"}async createAuthorization(D){let G=E(crypto.getRandomValues(new Uint8Array(32))),J=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(G)),N=E(new Uint8Array(J)),Q=new URLSearchParams({response_type:"code",client_id:D.clientId,redirect_uri:D.redirectUrl,scope:D.scopes.join(" "),state:D.state,code_challenge:N,code_challenge_method:"S256"});return{url:`${this.authorizeBase}/i/oauth2/authorize?${Q.toString()}`,codeVerifier:G}}async exchangeCode(D){return this.tokenRequest(new URLSearchParams({grant_type:"authorization_code",code:D.code,redirect_uri:D.redirectUrl,code_verifier:D.codeVerifier,client_id:D.clientId}),D.clientId,D.clientSecret)}async refreshAccessToken(D){return this.tokenRequest(new URLSearchParams({grant_type:"refresh_token",refresh_token:D.refreshToken,client_id:D.clientId}),D.clientId,D.clientSecret)}async getProfile(D){let G=await this.request(`${this.apiBase}/2/users/me?user.fields=username,name`,{headers:{authorization:`Bearer ${D}`}});if(!G.data?.id||!G.data.username)throw new K("Twitter did not return the authenticated user.",400,JSON.stringify(G));return{id:G.data.id,username:G.data.username,name:G.data.name}}async uploadMedia(D,G,J){let N=new FormData;N.set("media",new Blob([new Uint8Array(G)],{type:J||"image/jpeg"})),N.set("media_category","tweet_image");let Q=await this.request(`${this.apiBase}/2/media/upload`,{method:"POST",headers:{authorization:`Bearer ${D}`},body:N}),X=Q.data?.id||Q.media_id_string||Q.id;if(!X)throw new K("Twitter did not return a media id.",400,JSON.stringify(Q));return X}async publish(D,G){if(!D.accessToken)throw Error("Twitter access token is missing for this identity.");if(G.text.length>this.characterLimit)throw Error(`Twitter posts must be ${this.characterLimit} characters or fewer.`);let J=[],N=G.media?.[0];if(N){let{bytes:Z,mimeType:$}=N;if(!Z?.length&&N.url){let F=await fetch(N.url);if(F.ok)Z=new Uint8Array(await F.arrayBuffer()),$=$||F.headers.get("content-type")||"image/jpeg"}if(Z?.length)J.push(await this.uploadMedia(D.accessToken,Z,$||"image/jpeg"))}let Q={text:G.text};if(J.length)Q.media={media_ids:J};if(G.reply?.parent?.uri)Q.reply={in_reply_to_tweet_id:G.reply.parent.uri};let X=await this.request(`${this.apiBase}/2/tweets`,{method:"POST",headers:{authorization:`Bearer ${D.accessToken}`,"content-type":"application/json"},body:JSON.stringify(Q)}),Y=X.data?.id;if(!Y)throw new K("Twitter did not return a tweet id.",400,JSON.stringify(X));return{provider:this.provider,uri:Y,cid:Y,url:D.handle?`https://x.com/${D.handle}/status/${Y}`:`https://x.com/i/web/status/${Y}`}}async timeline(D,G={}){return{items:[]}}async listAuthoredPosts(D,G={}){if(!D.accessToken)throw Error("Twitter access token is missing for this identity.");let J=D.did;if(!J)throw Error("Twitter user id is required to list posts.");let N=new URL(`${this.apiBase}/2/users/${encodeURIComponent(J)}/tweets`);if(N.searchParams.set("max_results",String(Math.min(Math.max(G.limit||100,5),100))),N.searchParams.set("tweet.fields","created_at"),G.cursor)N.searchParams.set("pagination_token",G.cursor);let Q=await this.request(N.toString(),{headers:{authorization:`Bearer ${D.accessToken}`}});return{cursor:Q.meta?.next_token,posts:(Q.data||[]).filter((X)=>X?.id).map((X)=>({uri:X.id,cid:X.id,text:X.text,postedAt:X.created_at,url:`https://x.com/i/web/status/${X.id}`}))}}async deletePost(D,G){if(!D.accessToken)throw Error("Twitter access token is missing for this identity.");let J=String(G.uri||"").trim();if(!J)throw Error("A tweet id is required to delete a post.");let N=await this.request(`${this.apiBase}/2/tweets/${encodeURIComponent(J)}`,{method:"DELETE",headers:{authorization:`Bearer ${D.accessToken}`}});if(N.data&&N.data.deleted===!1)throw new K(`X refused to delete tweet ${J}.`,400,JSON.stringify(N))}async tokenRequest(D,G,J){let N={"content-type":"application/x-www-form-urlencoded"};if(J)N.authorization=`Basic ${btoa(`${G}:${J}`)}`;let Q=await this.request(`${this.apiBase}/2/oauth2/token`,{method:"POST",headers:N,body:D.toString()});if(!Q.access_token)throw new K("Twitter did not return an access token.",400,JSON.stringify(Q));return{accessToken:Q.access_token,refreshToken:Q.refresh_token,expiresIn:Q.expires_in,scope:Q.scope}}async request(D,G){let J=await fetch(D,G),N=await J.text();if(!J.ok)throw new K(`Twitter API failed (${J.status}): ${N||J.statusText}`,J.status,N);return N?JSON.parse(N):{}}}class JD{accessToken;refreshToken;expiresIn;approvedScopes;constructor(D,G=null,J=null,N=[]){this.accessToken=D;this.refreshToken=G;this.expiresIn=J;this.approvedScopes=N}}function lD(D){return typeof D?.deletePost==="function"}function uD(D){return typeof D?.listAuthoredPosts==="function"}export{uD as supportsEnumeration,lD as supportsDeletion,g as parseAtUri,o as normalizeInstance,a as escapeLinkedInText,m as detectFacetCandidates,GD as TwitterPublishingDriver,DD as TwitterProvider,K as TwitterApiError,JD as Token,r as ThreadsPublishingDriver,R as ThreadsApiError,n as MastodonPublishingDriver,T as MastodonApiError,d as LinkedInPublishingDriver,W as LinkedInApiError,x as InvalidStateException,p as InstagramPublishingDriver,B as InstagramApiError,c as GoogleProvider,y as GitHubProvider,u as FacebookProvider,z as ConfigException,l as BlueskyPublishingDriver,C as BlueskyApiError,h as AppleProvider,_ as AbstractProvider};
2
+ var x=import.meta.require;class M{clientId;clientSecret;redirectUrl;parameters={};_scopes=[];scopeSeparator=",";_stateless=!1;_usesPKCE=!1;_state=null;user=null;constructor(J){this.clientId=J.clientId,this.clientSecret=J.clientSecret,this.redirectUrl=J.redirectUrl}getCodeFields(J=null){let X={client_id:this.clientId,redirect_uri:this.redirectUrl,scope:this.formatScopes(this.getScopes(),this.scopeSeparator),response_type:"code"};if(this.usesState())X.state=J;if(this.usesPKCE())X.code_challenge=this.getCodeChallenge(),X.code_challenge_method=this.getCodeChallengeMethod();return{...X,...this.parameters}}formatScopes(J,X){return J.join(X)}async userFromToken(J){return{...await this.getUserByToken(J),token:J}}scopes(J){let X=Array.isArray(J)?J:[J];return this._scopes=[...new Set([...this._scopes,...X])],this}setScopes(J){let X=Array.isArray(J)?J:[J];return this._scopes=[...new Set(X)],this}getScopes(){return this._scopes}setRedirectUrl(J){if(typeof J!=="string"||J.length===0)throw Error("[socials] setRedirectUrl requires a non-empty string");let X;try{X=new URL(J)}catch{throw Error(`[socials] setRedirectUrl: invalid URL: ${J}`)}if(X.protocol!=="https:"&&X.protocol!=="http:")throw Error(`[socials] setRedirectUrl protocol must be http(s)://, got ${X.protocol}`);return this.redirectUrl=J,this}withState(J){if(typeof J!=="string"||J.length===0)throw Error("[socials] withState requires a non-empty string");return this._state=J,this}resolveState(){return this._state??this.getState()}usesState(){return!this._stateless}validateState(J,X){if(typeof J!=="string"||typeof X!=="string")return!1;if(J.length===0||X.length===0)return!1;if(J.length!==X.length)return!1;try{let{timingSafeEqual:Y}=x("crypto");return Y(Buffer.from(J,"utf8"),Buffer.from(X,"utf8"))}catch{let Y=0;for(let Z=0;Z<J.length;Z++)Y|=J.charCodeAt(Z)^X.charCodeAt(Z);return Y===0}}isStateless(){return this._stateless}stateless(){return this._stateless=!0,this}getState(){let J=new Uint8Array(32);return crypto.getRandomValues(J),Array.from(J).map((X)=>X.toString(16).padStart(2,"0")).join("")}usesPKCE(){return this._usesPKCE}enablePKCE(){return this._usesPKCE=!0,this}getCodeVerifier(){let J=new Uint8Array(48);return crypto.getRandomValues(J),Array.from(J).map((X)=>X.toString(16).padStart(2,"0")).join("")}async getCodeChallenge(){let X=new TextEncoder().encode(this.getCodeVerifier()),Y=await crypto.subtle.digest("SHA-256",X),{Buffer:Z}=await import("buffer");return Z.from(new Uint8Array(Y)).toString("base64url")}getCodeChallengeMethod(){return"S256"}with(J){return this.parameters=J,this}buildAuthUrlFromBase(J,X){let Y=new URLSearchParams(this.getCodeFields(X));return`${J}?${Y.toString()}`}}import{Buffer as q}from"buffer";import{createPrivateKey as c,sign as p}from"crypto";import{config as B}from"@stacksjs/config";class y extends Error{constructor(J="Invalid state"){super(J);this.name="InvalidStateException"}}class F extends Error{constructor(J){super(J);this.name="ConfigException"}}class C extends M{baseUrl="https://appleid.apple.com";teamId="";keyId="";privateKey="";constructor(J){super(J);this.teamId=J.teamId??"",this.keyId=J.keyId??"",this.privateKey=J.privateKey??""}getConfig(){let J={clientId:this.clientId||(B.services.apple?.clientId??""),teamId:this.teamId||(B.services.apple?.teamId??""),keyId:this.keyId||(B.services.apple?.keyId??""),privateKey:(this.privateKey||(B.services.apple?.privateKey??"")).replace(/\\n/g,`
3
+ `),redirectUrl:this.redirectUrl||(B.services.apple?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:B.services.apple?.scopes??["name","email"]};return this.setScopes(J.scopes),J}async getAuthUrl(){let J=this.resolveState(),{clientId:X,redirectUrl:Y,scopes:Z}=this.getConfig();this.validateConfig();let $={client_id:X,redirect_uri:Y,scope:Z.join(" "),state:J,response_type:"code",...this.parameters};if(Z.length>0)$.response_mode="form_post";return`${this.baseUrl}/auth/authorize?${new URLSearchParams($).toString()}`}async getAccessToken(J){let{clientId:X,redirectUrl:Y}=this.getConfig();this.validateConfig();let Z=await fetch(`${this.baseUrl}/auth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:J,redirect_uri:Y,client_id:X,client_secret:this.generateClientSecret()})}),$=await Z.json();if(!Z.ok||$.error)throw Error(`Apple OAuth error: ${$.error_description??$.error??`HTTP ${Z.status}`}`);if(!$.id_token)throw Error("Apple OAuth error: token response contained no id_token");return $.id_token}async getUserByToken(J){let{clientId:X}=this.getConfig(),Y=this.decodeIdToken(J),Z=Y.iss===this.baseUrl,$=Array.isArray(Y.aud)?Y.aud.includes(X):Y.aud===X,z=typeof Y.exp==="number"&&Y.exp*1000>Date.now();if(!Z||!$||!z)throw Error("Apple OAuth error: id_token claims failed validation (iss/aud/exp)");if(!Y.sub)throw Error("Apple OAuth error: id_token has no subject");let N=typeof Y.email==="string"?Y.email:null,G=null;if(Y.email_verified===!0||Y.email_verified==="true")G=!0;else if(Y.email_verified===!1||Y.email_verified==="false")G=!1;return{id:String(Y.sub),nickname:null,name:"",email:N,emailVerified:G,avatar:null,token:J,raw:Y}}generateClientSecret(){let{clientId:J,teamId:X,keyId:Y,privateKey:Z}=this.getConfig(),$=Math.floor(Date.now()/1000),z={alg:"ES256",kid:Y,typ:"JWT"},N={iss:X,iat:$,exp:$+3600,aud:this.baseUrl,sub:J},G=`${this.base64urlJson(z)}.${this.base64urlJson(N)}`,W;try{W=c(Z)}catch(Q){throw new F(`Apple private key could not be parsed: ${Q instanceof Error?Q.message:String(Q)}`)}let K=p("sha256",q.from(G),{key:W,dsaEncoding:"ieee-p1363"});return`${G}.${K.toString("base64url")}`}decodeIdToken(J){let X=J.split(".");if(X.length!==3)throw Error("Apple OAuth error: malformed id_token");return JSON.parse(q.from(X[1],"base64url").toString("utf8"))}base64urlJson(J){return q.from(JSON.stringify(J)).toString("base64url")}validateConfig(){let{clientId:J,teamId:X,keyId:Y,privateKey:Z,redirectUrl:$}=this.getConfig();if(!J)throw new F("Apple client ID (Service ID) not provided");if(!X)throw new F("Apple team ID not provided");if(!Y)throw new F("Apple key ID not provided");if(!Z)throw new F("Apple private key not provided");if(!$)throw new F("Apple redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/auth/token`}}function d(J){let X=/^at:\/\/([^/]+)\/([^/]+)\/([^/]+)$/.exec(String(J||"").trim());if(!X)throw Error(`"${J}" is not a Bluesky post URI.`);return{repo:X[1],collection:X[2],rkey:X[3]}}class b extends Error{status;body;constructor(J,X,Y){super(J);this.status=X;this.body=Y;this.name="BlueskyApiError"}get isAuthError(){return this.status===400||this.status===401||this.status===403}}var a=new TextEncoder;function D(J){return a.encode(J).length}function o(J){let X=[],Y=/https?:\/\/[^\s<>"']+/g;for(let N of J.matchAll(Y)){let G=N[0].replace(/[),.;!?]+$/,"");X.push({byteStart:D(J.slice(0,N.index)),byteEnd:D(J.slice(0,N.index))+D(G),type:"link",value:G})}let Z=(N,G)=>X.some((W)=>W.type==="link"&&N<W.byteEnd&&G>W.byteStart),$=/(^|\s)(#[A-Za-z0-9_]+)/g;for(let N of J.matchAll($)){let G=N[1],W=N[2];if(G===void 0||W===void 0)continue;if(/^#\d+$/.test(W))continue;let K=(N.index??0)+G.length,Q=D(J.slice(0,K)),V=Q+D(W);if(Z(Q,V))continue;X.push({byteStart:Q,byteEnd:V,type:"tag",value:W.slice(1)})}let z=/(^|\s)(@[a-z0-9][a-z0-9.-]*\.[a-z]{2,})/gi;for(let N of J.matchAll(z)){let G=N[1],W=N[2];if(G===void 0||W===void 0)continue;let K=(N.index??0)+G.length,Q=D(J.slice(0,K)),V=Q+D(W);if(Z(Q,V))continue;X.push({byteStart:Q,byteEnd:V,type:"mention",value:W.slice(1).replace(/\.+$/,"")})}return X.sort((N,G)=>N.byteStart-G.byteStart)}class s{provider="bluesky";characterLimit=300;service;constructor(J={}){this.service=J.service||"https://bsky.social"}async createSession(J){let X=J.identifier.trim(),Y=J.password.trim();if(!X)throw Error("Bluesky identifier is required.");if(!Y)throw Error("Bluesky app password is required.");let Z=await this.post("/xrpc/com.atproto.server.createSession",{identifier:X,password:Y}),$=await this.getProfile({did:Z.did,handle:Z.handle,accessToken:Z.accessJwt,refreshToken:Z.refreshJwt}).catch(()=>{return});return{did:Z.did,handle:Z.handle,displayName:$?.displayName,accessJwt:Z.accessJwt,refreshJwt:Z.refreshJwt}}async refreshSession(J){if(!J)throw Error("Bluesky refresh token is required.");let X=await this.post("/xrpc/com.atproto.server.refreshSession",void 0,{authorization:`Bearer ${J}`});return{did:X.did,handle:X.handle,accessJwt:X.accessJwt,refreshJwt:X.refreshJwt}}async publish(J,X){let Y=J.did||J.handle;if(!J.accessToken)throw Error("Bluesky access token is missing for this identity.");if(!Y)throw Error("Bluesky identity DID or handle is required.");if(X.text.length>this.characterLimit)throw Error(`Bluesky posts must be ${this.characterLimit} characters or fewer.`);let Z={$type:"app.bsky.feed.post",text:X.text,createdAt:X.scheduledAt||new Date().toISOString()};if(X.langs?.length)Z.langs=X.langs;if(X.reply)Z.reply=X.reply;let $=X.facets??await this.buildFacets(X.text);if($.length)Z.facets=$;if(X.external)Z.embed={$type:"app.bsky.embed.external",external:{uri:X.external.uri,title:X.external.title,description:X.external.description||""}};let z=(X.media||[]).filter((G)=>G.bytes?.length).slice(0,4);if(z.length){let G=[];for(let W of z){let K=await this.uploadBlob(J,W.bytes,W.mimeType||"image/jpeg");G.push({image:K,alt:W.altText||""})}Z.embed={$type:"app.bsky.embed.images",images:G}}let N=await this.post("/xrpc/com.atproto.repo.createRecord",{repo:Y,collection:"app.bsky.feed.post",record:Z},{authorization:`Bearer ${J.accessToken}`});return{provider:this.provider,uri:N.uri,cid:N.cid,url:this.toPostUrl(J.handle,N.uri)}}async postMetrics(J,X){if(!J.accessToken)throw Error("Bluesky access token is missing for this identity.");if(X.length===0)return[];let Y=new URL(`${this.service}/xrpc/app.bsky.feed.getPosts`);for(let $ of X.slice(0,25))Y.searchParams.append("uris",$);return((await this.request(Y,{headers:{authorization:`Bearer ${J.accessToken}`}})).posts||[]).map(($)=>({uri:$.uri,likeCount:$.likeCount||0,repostCount:$.repostCount||0,replyCount:$.replyCount||0}))}async timeline(J,X={}){if(!J.accessToken)throw Error("Bluesky access token is missing for this identity.");let Y=new URL(`${this.service}/xrpc/app.bsky.feed.getTimeline`);if(Y.searchParams.set("limit",String(Math.min(Math.max(X.limit||30,1),100))),X.cursor)Y.searchParams.set("cursor",X.cursor);let Z=await this.request(Y,{headers:{authorization:`Bearer ${J.accessToken}`}});return{cursor:Z.cursor,items:(Z.feed||[]).flatMap(($)=>{let z=$.post;if(!z?.uri||!z.author?.handle)return[];return[{uri:z.uri,authorHandle:z.author.handle,authorName:z.author.displayName,authorAvatar:z.author.avatar,postUrl:this.toPostUrl(z.author.handle,z.uri),body:z.record?.text||"",postedAt:z.record?.createdAt||new Date().toISOString(),likeCount:z.likeCount||0,repostCount:z.repostCount||0,replyCount:z.replyCount||0}]})}}async getProfile(J){if(!J.accessToken)throw Error("Bluesky access token is missing for this identity.");let X=J.did||J.handle;if(!X)throw Error("Bluesky identity DID or handle is required.");let Y=new URL(`${this.service}/xrpc/app.bsky.actor.getProfile`);return Y.searchParams.set("actor",X),await this.request(Y,{headers:{authorization:`Bearer ${J.accessToken}`}})}async buildFacets(J){let X=[];for(let Y of o(J)){let Z=null;if(Y.type==="link")Z={$type:"app.bsky.richtext.facet#link",uri:Y.value};else if(Y.type==="tag")Z={$type:"app.bsky.richtext.facet#tag",tag:Y.value};else if(Y.type==="mention"){let $=await this.resolveHandle(Y.value);if($)Z={$type:"app.bsky.richtext.facet#mention",did:$}}if(Z)X.push({index:{byteStart:Y.byteStart,byteEnd:Y.byteEnd},features:[Z]})}return X}async resolveHandle(J){try{let X=new URL(`${this.service}/xrpc/com.atproto.identity.resolveHandle`);return X.searchParams.set("handle",J),(await this.request(X,{})).did||null}catch{return null}}async uploadBlob(J,X,Y){if(!J.accessToken)throw Error("Bluesky access token is missing for this identity.");if(X.length>1e6)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":Y,authorization:`Bearer ${J.accessToken}`},body:new Uint8Array(X)})).blob}async listAuthoredPosts(J,X={}){let Y=J.did||J.handle;if(!J.accessToken)throw Error("Bluesky access token is missing for this identity.");if(!Y)throw Error("Bluesky identity DID or handle is required.");let Z=new URL(`${this.service}/xrpc/com.atproto.repo.listRecords`);if(Z.searchParams.set("repo",Y),Z.searchParams.set("collection","app.bsky.feed.post"),Z.searchParams.set("limit",String(Math.min(Math.max(X.limit||100,1),100))),X.cursor)Z.searchParams.set("cursor",X.cursor);let $=await this.request(Z,{headers:{authorization:`Bearer ${J.accessToken}`}});return{cursor:$.cursor,posts:($.records||[]).filter((z)=>z?.uri).map((z)=>({uri:z.uri,cid:z.cid,text:z.value?.text,postedAt:z.value?.createdAt,url:J.handle?this.toPostUrl(J.handle,z.uri):void 0}))}}async deletePost(J,X){if(!J.accessToken)throw Error("Bluesky access token is missing for this identity.");let{repo:Y,collection:Z,rkey:$}=d(X.uri);await this.post("/xrpc/com.atproto.repo.deleteRecord",{repo:Y,collection:Z,rkey:$},{authorization:`Bearer ${J.accessToken}`})}async post(J,X,Y={}){return await this.request(new URL(`${this.service}${J}`),{method:"POST",headers:{...X===void 0?{}:{"content-type":"application/json"},...Y},...X===void 0?{}:{body:JSON.stringify(X)}})}async request(J,X){let Y=await fetch(J,X),Z=await Y.text();if(!Y.ok)throw new b(`Bluesky API failed (${Y.status}): ${Z||Y.statusText}`,Y.status,Z);return Z?JSON.parse(Z):{}}toPostUrl(J,X){let Y=X.split("/").pop();return`https://bsky.app/profile/${J}/post/${Y}`}}import{fetcher as k}from"@stacksjs/api";import{config as j}from"@stacksjs/config";class v extends M{baseUrl="https://www.facebook.com";apiUrl="https://graph.facebook.com";getConfig(){let J={clientId:j.services.facebook?.clientId??"",clientSecret:j.services.facebook?.clientSecret??"",redirectUrl:j.services.facebook?.redirectUrl??"",scopes:j.services.facebook?.scopes??["email","public_profile"]};return this.setScopes(J.scopes),J}async getAuthUrl(){let J=this.getState(),{clientId:X,redirectUrl:Y,scopes:Z}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/v18.0/dialog/oauth?${new URLSearchParams({client_id:X,redirect_uri:Y,scope:Z.join(","),state:J,response_type:"code"}).toString()}`}async getAccessToken(J){let{clientId:X,clientSecret:Y,redirectUrl:Z}=this.getConfig();this.validateConfig();let $=await k.get(`${this.apiUrl}/v18.0/oauth/access_token?${new URLSearchParams({client_id:X,client_secret:Y,redirect_uri:Z,code:J}).toString()}`);if($.data.error)throw Error(`Facebook OAuth error: ${$.data.error.message}`);return $.data.access_token}async getUserByToken(J){let X=await k.get(`${this.apiUrl}/v18.0/me?${new URLSearchParams({access_token:J,fields:"id,name,email,picture"}).toString()}`);return{id:X.data.id,nickname:null,name:X.data.name,email:X.data.email??null,avatar:X.data.picture?.data.url??null,token:J,raw:X.data}}validateConfig(){let{clientId:J,clientSecret:X,redirectUrl:Y}=this.getConfig();if(!J)throw new F("Facebook client ID not provided");if(!X)throw new F("Facebook client secret not provided");if(!Y)throw new F("Facebook redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/v18.0/oauth/access_token`}}import{fetcher as T}from"@stacksjs/api";import{config as L}from"@stacksjs/config";class A extends M{baseUrl="https://github.com";apiUrl="https://api.github.com";getConfig(){let J={clientId:this.clientId||(L.services.github?.clientId??""),clientSecret:this.clientSecret||(L.services.github?.clientSecret??""),redirectUrl:this.redirectUrl||(L.services.github?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:L.services.github?.scopes??["read:user","user:email"]};return this.setScopes(J.scopes),J}async getAuthUrl(){let J=this.resolveState(),{clientId:X,redirectUrl:Y,scopes:Z}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/login/oauth/authorize?${new URLSearchParams({client_id:X,redirect_uri:Y,scope:Z.join(" "),state:J,response_type:"code",...this.parameters}).toString()}`}async getAccessToken(J){let{clientId:X,clientSecret:Y,redirectUrl:Z}=this.getConfig();this.validateConfig();let $=await T.post(`${this.baseUrl}/login/oauth/access_token`,{client_id:X,client_secret:Y,code:J,redirect_uri:Z});if($.data.error)throw Error(`GitHub OAuth error: ${$.data.error_description}`);return $.data.access_token}async getUserByToken(J){let[X,Y]=await Promise.all([T.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${J}`}).get(`${this.apiUrl}/user`),T.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${J}`}).get(`${this.apiUrl}/user/emails`)]),Z=this.pickEmail(Y.data);return{id:X.data.id.toString(),nickname:X.data.login,name:X.data.name??X.data.login,email:Z?.email??X.data.email??null,emailVerified:Z?Z.verified:null,avatar:X.data.avatar_url,token:J,raw:X.data}}pickEmail(J){if(!Array.isArray(J)||J.length===0)return null;let X=J.find((Z)=>Z.primary&&Z.verified),Y=J.find((Z)=>Z.verified);return X??Y??J.find((Z)=>Z.primary)??J[0]??null}getEmail(J){return this.pickEmail(J)?.email??null}validateConfig(){let{clientId:J,clientSecret:X,redirectUrl:Y}=this.getConfig();if(!J)throw new F("GitHub client ID not provided");if(!X)throw new F("GitHub client secret not provided");if(!Y)throw new F("GitHub redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/login/oauth/access_token`}}import{fetcher as h}from"@stacksjs/api";import{config as w}from"@stacksjs/config";class I extends M{baseUrl="https://accounts.google.com";apiUrl="https://www.googleapis.com";getConfig(){let J={clientId:this.clientId||(w.services.google?.clientId??""),clientSecret:this.clientSecret||(w.services.google?.clientSecret??""),redirectUrl:this.redirectUrl||(w.services.google?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:w.services.google?.scopes??["openid","email"]};return this.setScopes(J.scopes),J}async getAuthUrl(){let J=this.resolveState(),{clientId:X,redirectUrl:Y,scopes:Z}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/o/oauth2/v2/auth?${new URLSearchParams({client_id:X,redirect_uri:Y,scope:Z.join(" "),state:J,response_type:"code",access_type:"offline",prompt:"consent",...this.parameters}).toString()}`}async getAccessToken(J){let{clientId:X,clientSecret:Y,redirectUrl:Z}=this.getConfig();this.validateConfig();let $=await h.post(`${this.baseUrl}/oauth2/v4/token`,{client_id:X,client_secret:Y,code:J,redirect_uri:Z,grant_type:"authorization_code"});if($.data.error)throw Error(`Google OAuth error: ${$.data.error_description}`);return $.data.access_token}async getUserByToken(J){let X=await h.withHeaders({Authorization:`Bearer ${J}`}).get(`${this.apiUrl}/oauth2/v2/userinfo`);return{id:X.data.id,nickname:X.data.given_name,name:X.data.name,email:X.data.email,emailVerified:typeof X.data.verified_email==="boolean"?X.data.verified_email:null,avatar:X.data.picture,token:J,raw:X.data}}validateConfig(){let{clientId:J,clientSecret:X,redirectUrl:Y}=this.getConfig();if(!J)throw new F("Google client ID not provided");if(!X)throw new F("Google client secret not provided");if(!Y)throw new F("Google redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/oauth2/v4/token`}}class P extends Error{status;body;constructor(J,X,Y){super(J);this.status=X;this.body=Y;this.name="InstagramApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class r{provider="instagram";characterLimit=2200;graphVersion;authBase;graphBase;constructor(J={}){this.graphVersion=J.graphVersion||"v21.0",this.authBase=J.authBase||"https://www.facebook.com",this.graphBase=J.graphBase||"https://graph.facebook.com"}getAuthUrl(J){let X=new URLSearchParams({client_id:J.clientId,redirect_uri:J.redirectUrl,scope:J.scopes.join(","),state:J.state,response_type:"code"});return`${this.authBase}/${this.graphVersion}/dialog/oauth?${X.toString()}`}async exchangeCode(J){let X=new URLSearchParams({client_id:J.clientId,client_secret:J.clientSecret,redirect_uri:J.redirectUrl,code:J.code}),Y=await this.graph(`/oauth/access_token?${X.toString()}`,{method:"GET"});if(!Y.access_token)throw new P("Facebook did not return an access token.",400,JSON.stringify(Y));return{accessToken:Y.access_token,expiresIn:Y.expires_in}}async resolveAccount(J){let X=new URLSearchParams({fields:"name,access_token,instagram_business_account{id,username}",access_token:J}),Y=await this.graph(`/me/accounts?${X.toString()}`,{method:"GET"}),Z=(Y.data||[]).find((z)=>z.instagram_business_account?.id),$=Z?.instagram_business_account;if(!$?.id||!Z?.access_token)throw new P("No Instagram Business account is linked to your Facebook Pages.",400,JSON.stringify(Y));return{igUserId:$.id,username:$.username,pageAccessToken:Z.access_token}}async publish(J,X){if(!J.accessToken)throw Error("Instagram access token is missing for this identity.");let Y=J.did;if(!Y)throw Error("Instagram account id is required to publish.");let Z=X.media?.[0];if(!Z?.url)throw Error("Instagram requires an image to post.");if(X.text.length>this.characterLimit)throw Error(`Instagram captions must be ${this.characterLimit} characters or fewer.`);let $=await this.graph(`/${Y}/media`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({image_url:Z.url,caption:X.text,access_token:J.accessToken}).toString()});if(!$.id)throw new P("Instagram did not return a media container id.",400,JSON.stringify($));let z=await this.graph(`/${Y}/media_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:$.id,access_token:J.accessToken}).toString()}),N=await this.graph(`/${z.id}?fields=permalink&access_token=${encodeURIComponent(J.accessToken)}`,{method:"GET"}).catch(()=>{return});return{provider:this.provider,uri:z.id,url:N?.permalink}}async timeline(J,X={}){return{items:[]}}async graph(J,X){let Y=await fetch(`${this.graphBase}/${this.graphVersion}${J}`,X),Z=await Y.text(),$={};try{$=Z?JSON.parse(Z):{}}catch{$={}}if(!Y.ok||$?.error){let z=$?.error?.message||Z||Y.statusText;throw new P(`Instagram API failed (${Y.status}): ${z}`,Y.status,Z)}return $}}class H extends Error{status;body;constructor(J,X,Y){super(J);this.status=X;this.body=Y;this.name="LinkedInApiError"}get isAuthError(){return this.status===401||this.status===403}}class n{provider="linkedin";characterLimit=3000;apiVersion;authBase;apiBase;constructor(J={}){this.apiVersion=J.apiVersion||"202405",this.authBase=J.authBase||"https://www.linkedin.com",this.apiBase=J.apiBase||"https://api.linkedin.com"}getAuthUrl(J){let X=new URLSearchParams({response_type:"code",client_id:J.clientId,redirect_uri:J.redirectUrl,scope:J.scopes.join(" "),state:J.state});return`${this.authBase}/oauth/v2/authorization?${X.toString()}`}async exchangeCode(J){let X=new URLSearchParams({grant_type:"authorization_code",code:J.code,redirect_uri:J.redirectUrl,client_id:J.clientId,client_secret:J.clientSecret}),Y=await this.request(`${this.authBase}/oauth/v2/accessToken`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:X.toString()});if(!Y.access_token)throw new H("LinkedIn did not return an access token.",400,JSON.stringify(Y));return{accessToken:Y.access_token,expiresIn:Y.expires_in,scope:Y.scope}}async getProfile(J){if(!J)throw Error("LinkedIn access token is required.");let X=await this.request(`${this.apiBase}/v2/userinfo`,{headers:{authorization:`Bearer ${J}`}});if(!X.sub)throw new H("LinkedIn profile is missing a subject id.",400,JSON.stringify(X));return{sub:X.sub,name:X.name,picture:X.picture}}async publish(J,X){if(!J.accessToken)throw Error("LinkedIn access token is missing for this identity.");let Y=J.did;if(!Y)throw Error("LinkedIn member URN is required to publish.");if(X.text.length>this.characterLimit)throw Error(`LinkedIn posts must be ${this.characterLimit} characters or fewer.`);let Z={author:Y,commentary:i(X.text),visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(X.external)Z.content={article:{source:X.external.uri,title:X.external.title,description:X.external.description||""}};let $=await fetch(`${this.apiBase}/rest/posts`,{method:"POST",headers:{authorization:`Bearer ${J.accessToken}`,"content-type":"application/json","linkedin-version":this.apiVersion,"x-restli-protocol-version":"2.0.0"},body:JSON.stringify(Z)}),z=await $.text();if(!$.ok)throw new H(`LinkedIn API failed (${$.status}): ${z||$.statusText}`,$.status,z);let N=$.headers.get("x-restli-id")||$.headers.get("x-linkedin-id")||"";return{provider:this.provider,uri:N,url:N?`https://www.linkedin.com/feed/update/${N}`:void 0}}async timeline(J,X={}){return{items:[]}}async listAuthoredPosts(J,X={}){if(!J.accessToken)throw Error("LinkedIn access token is missing for this identity.");let Y=J.did;if(!Y)throw Error("LinkedIn member URN is required to list posts.");let Z=Math.min(Math.max(X.limit||50,1),100),$=Number(X.cursor||0)||0,z=new URL(`${this.apiBase}/rest/posts`);z.searchParams.set("q","author"),z.searchParams.set("author",Y),z.searchParams.set("count",String(Z)),z.searchParams.set("start",String($));let N;try{N=await this.request(z.toString(),{headers:{authorization:`Bearer ${J.accessToken}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":"2.0.0"}})}catch(W){if(W instanceof H&&(W.status===401||W.status===403))throw new H("LinkedIn will not list this account's posts \u2014 the Posts author finder needs the r_member_social permission, which this app does not hold.",W.status,W.body);throw W}let G=(N.elements||[]).filter((W)=>W?.id).map((W)=>({uri:String(W.id),text:W.commentary,postedAt:W.createdAt?new Date(W.createdAt).toISOString():void 0,url:`https://www.linkedin.com/feed/update/${W.id}`}));return{cursor:G.length===Z?String($+Z):void 0,posts:G}}async deletePost(J,X){if(!J.accessToken)throw Error("LinkedIn access token is missing for this identity.");let Y=String(X.uri||"").trim();if(!Y)throw Error("A LinkedIn post URN is required to delete a post.");let Z=await fetch(`${this.apiBase}/rest/posts/${encodeURIComponent(Y)}`,{method:"DELETE",headers:{authorization:`Bearer ${J.accessToken}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":"2.0.0"}});if(!Z.ok&&Z.status!==404){let $=await Z.text().catch(()=>"");throw new H(`LinkedIn API failed (${Z.status}): ${$||Z.statusText}`,Z.status,$)}}async request(J,X){let Y=await fetch(J,X),Z=await Y.text();if(!Y.ok)throw new H(`LinkedIn API failed (${Y.status}): ${Z||Y.statusText}`,Y.status,Z);return Z?JSON.parse(Z):{}}}function i(J){return J.replace(/[\\|{}@[\]()<>#*_~]/g,"\\$&")}class g extends Error{status;body;constructor(J,X,Y){super(J);this.status=X;this.body=Y;this.name="MastodonApiError"}get isAuthError(){return this.status===401||this.status===403}}function t(J){let X=String(J||"").trim().replace(/\/+$/,"");if(!X)throw Error("Mastodon instance URL is required.");let Y=/^https?:\/\//i.test(X)?X:`https://${X}`;try{let Z=new URL(Y);return`${Z.protocol}//${Z.host}`}catch{throw Error("Mastodon instance URL is invalid.")}}class e{provider="mastodon";characterLimit=500;instanceOf(J){return t(J.did||"")}tokenOf(J){if(!J.accessToken)throw Error("Mastodon access token is missing for this identity.");return J.accessToken}async verifyCredentials(J){let X=await this.request(`${this.instanceOf(J)}/api/v1/accounts/verify_credentials`,{headers:{authorization:`Bearer ${this.tokenOf(J)}`}});return{accountId:X.id,username:X.username,displayName:X.display_name||void 0,url:X.url}}async uploadMedia(J,X,Y,Z){let $=new FormData;if($.set("file",new Blob([new Uint8Array(X)],{type:Y||"image/jpeg"}),"upload"),Z)$.set("description",Z);return(await this.request(`${this.instanceOf(J)}/api/v2/media`,{method:"POST",headers:{authorization:`Bearer ${this.tokenOf(J)}`},body:$})).id}async publish(J,X){let Y=this.instanceOf(J),Z=this.tokenOf(J);if(X.text.length>this.characterLimit)throw Error(`Mastodon posts must be ${this.characterLimit} characters or fewer.`);let $=[];for(let G of(X.media||[]).slice(0,4)){let{bytes:W,mimeType:K}=G;if(!W?.length&&G.url){let Q=await fetch(G.url);if(!Q.ok)continue;W=new Uint8Array(await Q.arrayBuffer()),K=K||Q.headers.get("content-type")||"image/jpeg"}if(W?.length)$.push(await this.uploadMedia(J,W,K||"image/jpeg",G.altText))}let z={status:X.text,visibility:"public"};if($.length)z.media_ids=$;if(X.reply?.parent?.uri)z.in_reply_to_id=X.reply.parent.uri;let N=await this.request(`${Y}/api/v1/statuses`,{method:"POST",headers:{authorization:`Bearer ${Z}`,"content-type":"application/json"},body:JSON.stringify(z)});return{provider:this.provider,uri:N.id,cid:N.id,url:N.url||N.uri}}async timeline(J,X={}){return{items:[]}}async listAuthoredPosts(J,X={}){let Y=this.instanceOf(J),{accountId:Z}=await this.verifyCredentials(J),$=new URL(`${Y}/api/v1/accounts/${encodeURIComponent(Z)}/statuses`);if($.searchParams.set("limit",String(Math.min(Math.max(X.limit||40,1),40))),$.searchParams.set("exclude_reblogs","true"),X.cursor)$.searchParams.set("max_id",X.cursor);let N=(await this.request($.toString(),{headers:{authorization:`Bearer ${this.tokenOf(J)}`}})||[]).filter((G)=>G?.id).map((G)=>({uri:G.id,cid:G.id,text:G.content,postedAt:G.created_at,url:G.url}));return{cursor:N.length?N[N.length-1]?.uri:void 0,posts:N}}async deletePost(J,X){let Y=String(X.cid||JJ(X.uri)||"").trim();if(!Y)throw Error("A status id is required to delete a post.");await this.request(`${this.instanceOf(J)}/api/v1/statuses/${encodeURIComponent(Y)}`,{method:"DELETE",headers:{authorization:`Bearer ${this.tokenOf(J)}`}})}async request(J,X){let Y=await fetch(J,X),Z=await Y.text();if(!Y.ok)throw new g(`Mastodon API failed (${Y.status}): ${Z||Y.statusText}`,Y.status,Z);return Z?JSON.parse(Z):{}}}function JJ(J){return String(J||"").replace(/\/+$/,"").split("/").pop()||""}class O extends Error{status;body;constructor(J,X,Y){super(J);this.status=X;this.body=Y;this.name="ThreadsApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class XJ{provider="threads";characterLimit=500;graphVersion;authBase;graphBase;constructor(J={}){this.graphVersion=J.graphVersion||"v1.0",this.authBase=J.authBase||"https://threads.net",this.graphBase=J.graphBase||"https://graph.threads.net"}getAuthUrl(J){let X=new URLSearchParams({client_id:J.clientId,redirect_uri:J.redirectUrl,scope:J.scopes.join(","),response_type:"code",state:J.state});return`${this.authBase}/oauth/authorize?${X.toString()}`}async exchangeCode(J){let X=await fetch(`${this.graphBase}/oauth/access_token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:J.clientId,client_secret:J.clientSecret,grant_type:"authorization_code",redirect_uri:J.redirectUrl,code:J.code}).toString()}),Y=await X.text(),Z={};try{Z=Y?JSON.parse(Y):{}}catch{Z={}}if(!X.ok||Z?.error||!Z?.access_token){let $=Z?.error_message||Z?.error?.message||Y||X.statusText;throw new O(`Threads token exchange failed (${X.status}): ${$}`,X.status,Y)}return{accessToken:Z.access_token,userId:Z.user_id!=null?String(Z.user_id):void 0,expiresIn:Z.expires_in}}async resolveAccount(J){let X=new URLSearchParams({fields:"id,username",access_token:J}),Y=await this.graph(`/me?${X.toString()}`,{method:"GET"});if(!Y.id)throw new O("Could not resolve the Threads account for this token.",400,JSON.stringify(Y));return{threadsUserId:Y.id,username:Y.username,accessToken:J}}async publish(J,X){if(!J.accessToken)throw Error("Threads access token is missing for this identity.");let Y=J.did;if(!Y)throw Error("Threads account id is required to publish.");if(X.text.length>this.characterLimit)throw Error(`Threads posts must be ${this.characterLimit} characters or fewer.`);let Z=X.media?.[0],$=new URLSearchParams({text:X.text,access_token:J.accessToken});if(Z?.url)$.set("media_type","IMAGE"),$.set("image_url",Z.url);else $.set("media_type","TEXT");let z=await this.graph(`/${Y}/threads`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:$.toString()});if(!z.id)throw new O("Threads did not return a media container id.",400,JSON.stringify(z));let N=await this.graph(`/${Y}/threads_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:z.id,access_token:J.accessToken}).toString()});if(!N.id)throw new O("Threads did not return a published post id.",400,JSON.stringify(N));let G=await this.graph(`/${N.id}?fields=permalink&access_token=${encodeURIComponent(J.accessToken)}`,{method:"GET"}).catch(()=>{return});return{provider:this.provider,uri:N.id,url:G?.permalink}}async timeline(J,X={}){return{items:[]}}async graph(J,X){let Y=await fetch(`${this.graphBase}/${this.graphVersion}${J}`,X),Z=await Y.text(),$={};try{$=Z?JSON.parse(Z):{}}catch{$={}}if(!Y.ok||$?.error){let z=$?.error?.message||Z||Y.statusText;throw new O(`Threads API failed (${Y.status}): ${z}`,Y.status,Z)}return $}}import{Buffer as YJ}from"buffer";import{createHash as ZJ,randomBytes as $J}from"crypto";import{fetcher as f}from"@stacksjs/api";import{config as S}from"@stacksjs/config";class E extends M{baseUrl="https://twitter.com";apiUrl="https://api.twitter.com";codeVerifier=null;getConfig(){let J={clientId:S.services.twitter?.clientId??"",clientSecret:S.services.twitter?.clientSecret??"",redirectUrl:S.services.twitter?.redirectUrl??"",scopes:S.services.twitter?.scopes??["users.read","tweet.read"]};return this.setScopes(J.scopes),J}generateCodeVerifier(){return $J(32).toString("base64").replace(/[^a-z0-9]/gi,"").substring(0,128)}generateCodeChallenge(J){return ZJ("sha256").update(J).digest("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async getAuthUrl(){let J=this.getState(),{clientId:X,redirectUrl:Y,scopes:Z}=this.getConfig();this.validateConfig(),this.codeVerifier=this.generateCodeVerifier();let $=this.generateCodeChallenge(this.codeVerifier);return`${this.baseUrl}/i/oauth2/authorize?${new URLSearchParams({client_id:X,redirect_uri:Y,scope:Z.join(" "),state:J,response_type:"code",code_challenge:$,code_challenge_method:"S256"}).toString()}`}async getAccessToken(J){let{clientId:X,clientSecret:Y,redirectUrl:Z}=this.getConfig();if(this.validateConfig(),!this.codeVerifier)throw Error("Code verifier not found. Please ensure getAuthUrl() is called first.");let $=YJ.from(`${X}:${Y}`).toString("base64"),z=await f.withHeaders({Authorization:`Basic ${$}`,"Content-Type":"application/x-www-form-urlencoded"}).post(`${this.apiUrl}/2/oauth2/token`,{code:J,grant_type:"authorization_code",redirect_uri:Z,code_verifier:this.codeVerifier});if(z.data.error)throw Error(`Twitter OAuth error: ${z.data.error_description}`);return z.data.access_token}async getUserByToken(J){let X=await f.withHeaders({Authorization:`Bearer ${J}`}).get(`${this.apiUrl}/2/users/me?user.fields=profile_image_url`);return{id:X.data.id,nickname:X.data.username,name:X.data.name,email:X.data.email??null,avatar:X.data.profile_image_url??null,token:J,raw:X.data}}validateConfig(){let{clientId:J,clientSecret:X,redirectUrl:Y}=this.getConfig();if(!J)throw new F("Twitter client ID not provided");if(!X)throw new F("Twitter client secret not provided");if(!Y)throw new F("Twitter redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/2/oauth2/token`}}class _ extends Error{status;body;constructor(J,X,Y){super(J);this.status=X;this.body=Y;this.name="TwitterApiError"}get isAuthError(){return this.status===401||this.status===403}}function m(J){let X="";for(let Y of J)X+=String.fromCharCode(Y);return btoa(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}class zJ{provider="twitter";characterLimit=280;apiBase;authorizeBase;constructor(J={}){this.apiBase=J.apiBase||"https://api.twitter.com",this.authorizeBase=J.authorizeBase||"https://twitter.com"}async createAuthorization(J){let X=m(crypto.getRandomValues(new Uint8Array(32))),Y=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(X)),Z=m(new Uint8Array(Y)),$=new URLSearchParams({response_type:"code",client_id:J.clientId,redirect_uri:J.redirectUrl,scope:J.scopes.join(" "),state:J.state,code_challenge:Z,code_challenge_method:"S256"});return{url:`${this.authorizeBase}/i/oauth2/authorize?${$.toString()}`,codeVerifier:X}}async exchangeCode(J){return this.tokenRequest(new URLSearchParams({grant_type:"authorization_code",code:J.code,redirect_uri:J.redirectUrl,code_verifier:J.codeVerifier,client_id:J.clientId}),J.clientId,J.clientSecret)}async refreshAccessToken(J){return this.tokenRequest(new URLSearchParams({grant_type:"refresh_token",refresh_token:J.refreshToken,client_id:J.clientId}),J.clientId,J.clientSecret)}async getProfile(J){let X=await this.request(`${this.apiBase}/2/users/me?user.fields=username,name`,{headers:{authorization:`Bearer ${J}`}});if(!X.data?.id||!X.data.username)throw new _("Twitter did not return the authenticated user.",400,JSON.stringify(X));return{id:X.data.id,username:X.data.username,name:X.data.name}}async uploadMedia(J,X,Y){let Z=new FormData;Z.set("media",new Blob([new Uint8Array(X)],{type:Y||"image/jpeg"})),Z.set("media_category","tweet_image");let $=await this.request(`${this.apiBase}/2/media/upload`,{method:"POST",headers:{authorization:`Bearer ${J}`},body:Z}),z=$.data?.id||$.media_id_string||$.id;if(!z)throw new _("Twitter did not return a media id.",400,JSON.stringify($));return z}async publish(J,X){if(!J.accessToken)throw Error("Twitter access token is missing for this identity.");if(X.text.length>this.characterLimit)throw Error(`Twitter posts must be ${this.characterLimit} characters or fewer.`);let Y=[],Z=X.media?.[0];if(Z){let{bytes:G,mimeType:W}=Z;if(!G?.length&&Z.url){let K=await fetch(Z.url);if(K.ok)G=new Uint8Array(await K.arrayBuffer()),W=W||K.headers.get("content-type")||"image/jpeg"}if(G?.length)Y.push(await this.uploadMedia(J.accessToken,G,W||"image/jpeg"))}let $={text:X.text};if(Y.length)$.media={media_ids:Y};if(X.reply?.parent?.uri)$.reply={in_reply_to_tweet_id:X.reply.parent.uri};let z=await this.request(`${this.apiBase}/2/tweets`,{method:"POST",headers:{authorization:`Bearer ${J.accessToken}`,"content-type":"application/json"},body:JSON.stringify($)}),N=z.data?.id;if(!N)throw new _("Twitter did not return a tweet id.",400,JSON.stringify(z));return{provider:this.provider,uri:N,cid:N,url:J.handle?`https://x.com/${J.handle}/status/${N}`:`https://x.com/i/web/status/${N}`}}async timeline(J,X={}){return{items:[]}}async listAuthoredPosts(J,X={}){if(!J.accessToken)throw Error("Twitter access token is missing for this identity.");let Y=J.did;if(!Y)throw Error("Twitter user id is required to list posts.");let Z=new URL(`${this.apiBase}/2/users/${encodeURIComponent(Y)}/tweets`);if(Z.searchParams.set("max_results",String(Math.min(Math.max(X.limit||100,5),100))),Z.searchParams.set("tweet.fields","created_at"),X.cursor)Z.searchParams.set("pagination_token",X.cursor);let $=await this.request(Z.toString(),{headers:{authorization:`Bearer ${J.accessToken}`}});return{cursor:$.meta?.next_token,posts:($.data||[]).filter((z)=>z?.id).map((z)=>({uri:z.id,cid:z.id,text:z.text,postedAt:z.created_at,url:`https://x.com/i/web/status/${z.id}`}))}}async deletePost(J,X){if(!J.accessToken)throw Error("Twitter access token is missing for this identity.");let Y=String(X.uri||"").trim();if(!Y)throw Error("A tweet id is required to delete a post.");let Z=await this.request(`${this.apiBase}/2/tweets/${encodeURIComponent(Y)}`,{method:"DELETE",headers:{authorization:`Bearer ${J.accessToken}`}});if(Z.data&&Z.data.deleted===!1)throw new _(`X refused to delete tweet ${Y}.`,400,JSON.stringify(Z))}async tokenRequest(J,X,Y){let Z={"content-type":"application/x-www-form-urlencoded"};if(Y)Z.authorization=`Basic ${btoa(`${X}:${Y}`)}`;let $=await this.request(`${this.apiBase}/2/oauth2/token`,{method:"POST",headers:Z,body:J.toString()});if(!$.access_token)throw new _("Twitter did not return an access token.",400,JSON.stringify($));return{accessToken:$.access_token,refreshToken:$.refresh_token,expiresIn:$.expires_in,scope:$.scope}}async request(J,X){let Y=await fetch(J,X),Z=await Y.text();if(!Y.ok)throw new _(`Twitter API failed (${Y.status}): ${Z||Y.statusText}`,Y.status,Z);return Z?JSON.parse(Z):{}}}import{config as NJ}from"@stacksjs/config";var U=["clientId","clientSecret","redirectUrl"],R=Object.freeze({google:{name:"google",label:"Google",driver:I,required:U,postCallback:!1},github:{name:"github",label:"GitHub",driver:A,required:U,postCallback:!1},facebook:{name:"facebook",label:"Facebook",driver:v,required:U,postCallback:!1},twitter:{name:"twitter",label:"X",driver:E,required:U,postCallback:!1},apple:{name:"apple",label:"Apple",driver:C,required:["clientId","teamId","keyId","privateKey","redirectUrl"],postCallback:!0}});function l(J){return NJ?.services?.[J]}function GJ(J){return typeof J==="string"&&J in R}function u(J){if(!GJ(J))return!1;let X=l(J);if(!X)return!1;return R[J].required.every((Y)=>Boolean(X[Y]))}function oJ(){return Object.keys(R).filter(u).map((J)=>R[J])}function sJ(J){if(!u(J))return null;let X=R[J],Y=l(J)??{};return new X.driver({clientSecret:"",...Y,clientId:String(Y.clientId??""),redirectUrl:String(Y.redirectUrl??"")})}class WJ{accessToken;refreshToken;expiresIn;approvedScopes;constructor(J,X=null,Y=null,Z=[]){this.accessToken=J;this.refreshToken=X;this.expiresIn=Y;this.approvedScopes=Z}}function iJ(J){return typeof J?.deletePost==="function"}function tJ(J){return typeof J?.listAuthoredPosts==="function"}export{tJ as supportsEnumeration,iJ as supportsDeletion,sJ as socialProvider,d as parseAtUri,t as normalizeInstance,GJ as isSocialProviderName,u as isSocialProviderConfigured,i as escapeLinkedInText,o as detectFacetCandidates,oJ as configuredSocialProviders,zJ as TwitterPublishingDriver,E as TwitterProvider,_ as TwitterApiError,WJ as Token,XJ as ThreadsPublishingDriver,O as ThreadsApiError,R as SOCIAL_PROVIDERS,e as MastodonPublishingDriver,g as MastodonApiError,n as LinkedInPublishingDriver,H as LinkedInApiError,y as InvalidStateException,r as InstagramPublishingDriver,P as InstagramApiError,I as GoogleProvider,A as GitHubProvider,v as FacebookProvider,F as ConfigException,s as BlueskyPublishingDriver,b as BlueskyApiError,C as AppleProvider,M as AbstractProvider};
@@ -0,0 +1,56 @@
1
+ import type { ProviderInterface } from './types';
2
+ /** Is `name` a provider this package can drive? */
3
+ export declare function isSocialProviderName(name: unknown): name is SocialProviderName;
4
+ /**
5
+ * Does this provider have everything it needs to complete a sign-in?
6
+ *
7
+ * Never throws, so it is safe to call while rendering. An unknown name is
8
+ * simply not configured.
9
+ */
10
+ export declare function isSocialProviderConfigured(name: unknown): boolean;
11
+ /**
12
+ * Every provider that would work if a visitor clicked it, in the order
13
+ * they are declared above. Render sign-in buttons straight off this and a
14
+ * half-configured provider never reaches a visitor as a dead button.
15
+ */
16
+ export declare function configuredSocialProviders(): SocialProviderDescriptor[];
17
+ /**
18
+ * Build a provider, or null when it is not configured.
19
+ *
20
+ * The whole `config.services[name]` block is passed to the driver, so
21
+ * provider-specific fields (Apple's teamId, keyId and privateKey) arrive
22
+ * rather than being dropped by a caller that only knew about clientId and
23
+ * clientSecret. Returning null rather than throwing lets a route answer
24
+ * 404 for an unconfigured provider instead of redirecting a visitor to a
25
+ * provider error page that reads to them as the application's fault.
26
+ */
27
+ export declare function socialProvider(name: unknown): ProviderInterface | null;
28
+ declare const OAUTH2_REQUIRED: readonly ['clientId', 'clientSecret', 'redirectUrl'];
29
+ export declare const SOCIAL_PROVIDERS: Readonly<Record<SocialProviderName, SocialProviderDescriptor>>;
30
+ export declare interface SocialProviderDescriptor {
31
+ name: SocialProviderName
32
+ label: string
33
+ driver: new (providerConfig: any) => ProviderInterface
34
+ required: readonly string[]
35
+ postCallback: boolean
36
+ }
37
+ /**
38
+ * Which social providers are usable in this application right now.
39
+ *
40
+ * Every driver already knows what it needs, but only as a throw: each
41
+ * `validateConfig()` raises a ConfigException part-way through an auth
42
+ * flow. A sign-in page has the opposite question, and has to answer it
43
+ * before rendering anything: which buttons will actually work?
44
+ *
45
+ * Without an answer here, applications hand-roll one, and the shape they
46
+ * reach for is `clientId && clientSecret`, because that is true of every
47
+ * provider except the one it is not true of. Apple has no static client
48
+ * secret at all (the driver signs a short-lived ES256 JWT from teamId +
49
+ * keyId + privateKey), so a hand-rolled check silently classifies a fully
50
+ * configured Apple as absent, and Sign in with Apple never appears.
51
+ *
52
+ * The same registry drives construction, so a provider is built with the
53
+ * whole of its config block rather than the three fields the OAuth2
54
+ * providers happen to share.
55
+ */
56
+ export type SocialProviderName = 'apple' | 'facebook' | 'github' | 'google' | 'twitter';
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/socials",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.70.258",
5
+ "version": "0.70.259",
6
6
  "description": "A simple and elegant social authentication package for Stacks.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -33,9 +33,16 @@
33
33
  "default": "./dist/index.js"
34
34
  },
35
35
  "./*": {
36
- "bun": "./dist/*",
37
- "import": "./dist/*",
38
- "default": "./dist/*"
36
+ "types": "./dist/*.d.ts",
37
+ "bun": "./dist/*.js",
38
+ "import": "./dist/*.js",
39
+ "default": "./dist/*.js"
40
+ },
41
+ "./*.js": {
42
+ "types": "./dist/*.d.ts",
43
+ "bun": "./dist/*.js",
44
+ "import": "./dist/*.js",
45
+ "default": "./dist/*.js"
39
46
  }
40
47
  },
41
48
  "module": "dist/index.js",
@@ -51,7 +58,7 @@
51
58
  },
52
59
  "devDependencies": {
53
60
  "better-dx": "^0.2.17",
54
- "@stacksjs/error-handling": "0.70.258",
55
- "@stacksjs/router": "0.70.258"
61
+ "@stacksjs/error-handling": "0.70.259",
62
+ "@stacksjs/router": "0.70.259"
56
63
  }
57
64
  }