@stacksjs/socials 0.75.187 → 0.75.188
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/abstract.d.ts +7 -2
- package/dist/drivers/apple.d.ts +14 -8
- package/dist/drivers/google.d.ts +5 -0
- package/dist/id-token.d.ts +29 -0
- package/dist/index.js +2 -2
- package/package.json +6 -6
package/dist/abstract.d.ts
CHANGED
|
@@ -14,6 +14,7 @@ export declare abstract class AbstractProvider implements ProviderInterface {
|
|
|
14
14
|
protected scopeSeparator: string;
|
|
15
15
|
protected _stateless: boolean;
|
|
16
16
|
protected _usesPKCE: boolean;
|
|
17
|
+
protected _codeVerifier: string | null;
|
|
17
18
|
protected _state: string | null;
|
|
18
19
|
protected user: SocialUser | null;
|
|
19
20
|
constructor(config: ProviderConfig);
|
|
@@ -21,7 +22,7 @@ export declare abstract class AbstractProvider implements ProviderInterface {
|
|
|
21
22
|
protected abstract getTokenUrl(): string;
|
|
22
23
|
abstract getAccessToken(code: string): Promise<string>;
|
|
23
24
|
abstract getUserByToken(token: string): Promise<SocialUser>;
|
|
24
|
-
protected getCodeFields(state?: string | null): Record<string, any
|
|
25
|
+
protected getCodeFields(state?: string | null): Promise<Record<string, any>>;
|
|
25
26
|
protected formatScopes(scopes: string[], scopeSeparator: string): string;
|
|
26
27
|
userFromToken(token: string): Promise<SocialUser>;
|
|
27
28
|
scopes(scopes: string | string[]): this;
|
|
@@ -38,8 +39,12 @@ export declare abstract class AbstractProvider implements ProviderInterface {
|
|
|
38
39
|
protected usesPKCE(): boolean;
|
|
39
40
|
enablePKCE(): this;
|
|
40
41
|
protected getCodeVerifier(): string;
|
|
42
|
+
getPkceVerifier(): string | null;
|
|
43
|
+
withCodeVerifier(verifier: string): this;
|
|
44
|
+
protected pkceFields(): Promise<Record<string, string>>;
|
|
45
|
+
protected pkceTokenFields(): Record<string, string>;
|
|
41
46
|
protected getCodeChallenge(): Promise<string>;
|
|
42
47
|
protected getCodeChallengeMethod(): string;
|
|
43
48
|
with(parameters: Record<string, any>): this;
|
|
44
|
-
protected buildAuthUrlFromBase(url: string, state: string | null): string
|
|
49
|
+
protected buildAuthUrlFromBase(url: string, state: string | null): Promise<string>;
|
|
45
50
|
}
|
package/dist/drivers/apple.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { AbstractProvider } from '../abstract';
|
|
2
|
-
import type { AppleIdTokenClaims, ProviderInterface, SocialUser } from '../types';
|
|
3
2
|
import type { ProviderConfig } from '../abstract';
|
|
3
|
+
import type { ProviderInterface, SocialUser } from '../types';
|
|
4
4
|
/**
|
|
5
5
|
* Apple replaces the static client secret with a signed JWT, so its
|
|
6
6
|
* provider config carries the signing inputs instead of clientSecret
|
|
@@ -12,6 +12,10 @@ export declare interface AppleProviderConfig extends ProviderConfig {
|
|
|
12
12
|
privateKey?: string
|
|
13
13
|
native?: boolean
|
|
14
14
|
}
|
|
15
|
+
/** Per-call expectations for {@link AppleProvider.getUserByToken}. */
|
|
16
|
+
export declare interface AppleIdentityOptions {
|
|
17
|
+
nonce?: string
|
|
18
|
+
}
|
|
15
19
|
/**
|
|
16
20
|
* Sign in with Apple (OAuth2 / OIDC).
|
|
17
21
|
*
|
|
@@ -25,11 +29,14 @@ export declare interface AppleProviderConfig extends ProviderConfig {
|
|
|
25
29
|
* builds one per token exchange.
|
|
26
30
|
* 2. There is no userinfo endpoint. Identity comes from the `id_token`
|
|
27
31
|
* returned by the token endpoint, so `getAccessToken()` returns the
|
|
28
|
-
* id_token (not the access token
|
|
29
|
-
* and `getUserByToken()`
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
32
|
+
* id_token (not the access token - there is nothing to spend it on),
|
|
33
|
+
* and `getUserByToken()` verifies it against Apple's published keys
|
|
34
|
+
* before reading a single claim. OIDC Core 3.1.3.7 would permit
|
|
35
|
+
* skipping that for a token this server just redeemed over TLS, and
|
|
36
|
+
* this driver does not take the exemption: `getUserByToken()` is a
|
|
37
|
+
* public method taking a string, so a token posted up by an app
|
|
38
|
+
* reaches it by the same door, and a payload nobody checked is a
|
|
39
|
+
* payload anybody can write (stacksjs/stacks#2907).
|
|
33
40
|
* 3. When scopes are requested (they are by default: name + email),
|
|
34
41
|
* Apple mandates `response_mode=form_post` — the callback arrives as
|
|
35
42
|
* a cross-site POST, not a GET. Applications must register a POST
|
|
@@ -50,9 +57,8 @@ export declare class AppleProvider extends AbstractProvider implements ProviderI
|
|
|
50
57
|
constructor(providerConfig: AppleProviderConfig);
|
|
51
58
|
getAuthUrl(): Promise<string>;
|
|
52
59
|
getAccessToken(code: string): Promise<string>;
|
|
53
|
-
getUserByToken(token: string): Promise<SocialUser>;
|
|
60
|
+
getUserByToken(token: string, options?: AppleIdentityOptions): Promise<SocialUser>;
|
|
54
61
|
protected generateClientSecret(): string;
|
|
55
|
-
protected decodeIdToken(idToken: string): AppleIdTokenClaims;
|
|
56
62
|
protected validateConfig(): void;
|
|
57
63
|
protected getTokenUrl(): string;
|
|
58
64
|
}
|
package/dist/drivers/google.d.ts
CHANGED
|
@@ -4,9 +4,14 @@ export declare class GoogleProvider extends AbstractProvider implements Provider
|
|
|
4
4
|
protected baseUrl: string;
|
|
5
5
|
protected apiUrl: string;
|
|
6
6
|
protected tokenUrl: string;
|
|
7
|
+
protected tokenInfoUrl: string;
|
|
8
|
+
protected certsUrl: string;
|
|
9
|
+
protected issuers: unknown[];
|
|
7
10
|
getAuthUrl(): Promise<string>;
|
|
8
11
|
getAccessToken(code: string): Promise<string>;
|
|
9
12
|
getUserByToken(token: string): Promise<SocialUser>;
|
|
13
|
+
getUserByIdToken(idToken: string, options?: { nonce?: string }): Promise<SocialUser>;
|
|
14
|
+
protected assertTokenWasIssuedToUs(accessToken: string): Promise<void>;
|
|
10
15
|
protected validateConfig(): void;
|
|
11
16
|
protected getTokenUrl(): string;
|
|
12
17
|
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** Drop every cached key set. Exported for tests and key-rotation drills. */
|
|
2
|
+
export declare function clearSigningKeyCache(): void;
|
|
3
|
+
/**
|
|
4
|
+
* Verify `token` and return its claims.
|
|
5
|
+
*
|
|
6
|
+
* Throws on anything short of a complete pass: a bad signature, an unknown
|
|
7
|
+
* key, the wrong issuer or audience, an expired or not-yet-valid token, or a
|
|
8
|
+
* nonce that does not match the one expected. The returned claims have been
|
|
9
|
+
* verified; nothing else in this module hands back unverified ones.
|
|
10
|
+
*/
|
|
11
|
+
export declare function verifyIdToken(token: string, options: VerifyIdTokenOptions): Promise<IdTokenClaims>;
|
|
12
|
+
export declare interface VerifyIdTokenOptions {
|
|
13
|
+
jwksUrl: string
|
|
14
|
+
issuer: string | string[]
|
|
15
|
+
audience: string | string[]
|
|
16
|
+
nonce?: string
|
|
17
|
+
clockSkewSeconds?: number
|
|
18
|
+
now?: number
|
|
19
|
+
}
|
|
20
|
+
export declare interface IdTokenClaims {
|
|
21
|
+
iss: string
|
|
22
|
+
aud: string | string[]
|
|
23
|
+
exp: number
|
|
24
|
+
sub: string
|
|
25
|
+
iat?: number
|
|
26
|
+
nbf?: number
|
|
27
|
+
nonce?: string
|
|
28
|
+
[key: string]: unknown
|
|
29
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
`),redirectUrl:this.native?"":this.redirectUrl||(y.services.apple?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:y.services.apple?.scopes??["name","email"]};return this.setScopes(e.scopes),e}async getAuthUrl(){if(this.native)throw new l("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 s={client_id:t,redirect_uri:r,scope:i.join(" "),state:e,response_type:"code",...this.parameters};if(i.length>0)s.response_mode="form_post";return`${this.baseUrl}/auth/authorize?${new URLSearchParams(s).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()})}),s=await i.json();if(!i.ok||s.error)throw Error(`Apple OAuth error: ${s.error_description??s.error??`HTTP ${i.status}`}`);if(!s.id_token)throw Error("Apple OAuth error: token response contained no id_token");return s.id_token}async getUserByToken(e){let{clientId:t}=this.getConfig(),r=this.decodeIdToken(e),i=r.iss===this.baseUrl,s=Array.isArray(r.aud)?r.aud.includes(t):r.aud===t,n=typeof r.exp==="number"&&r.exp*1000>Date.now();if(!i||!s||!n)throw Error("Apple OAuth error: id_token claims failed validation (iss/aud/exp)");if(!r.sub)throw Error("Apple OAuth error: id_token has no subject");let o=typeof r.email==="string"?r.email:null,a=null;if(r.email_verified===!0||r.email_verified==="true")a=!0;else if(r.email_verified===!1||r.email_verified==="false")a=!1;return{id:String(r.sub),nickname:null,name:"",email:o,emailVerified:a,avatar:null,token:e,raw:r}}generateClientSecret(){let{clientId:e,teamId:t,keyId:r,privateKey:i}=this.getConfig(),s=Math.floor(Date.now()/1000),n={alg:"ES256",kid:r,typ:"JWT"},o={iss:t,iat:s,exp:s+3600,aud:this.baseUrl,sub:e},a=`${this.base64urlJson(n)}.${this.base64urlJson(o)}`,c;try{c=oe(i)}catch(u){throw new l(`Apple private key could not be parsed: ${u instanceof Error?u.message:String(u)}`)}let d=ae("sha256",B.from(a),{key:c,dsaEncoding:"ieee-p1363"});return`${a}.${d.toString("base64url")}`}decodeIdToken(e){let t=e.split(".");if(t.length!==3)throw Error("Apple OAuth error: malformed id_token");return JSON.parse(B.from(t[1],"base64url").toString("utf8"))}base64urlJson(e){return B.from(JSON.stringify(e)).toString("base64url")}validateConfig(){let{clientId:e,teamId:t,keyId:r,privateKey:i,redirectUrl:s}=this.getConfig();if(!e)throw new l(this.native?"Apple client ID (the app's bundle ID) not provided":"Apple client ID (Service ID) not provided");if(!t)throw new l("Apple team ID not provided");if(!r)throw new l("Apple key ID not provided");if(!i)throw new l("Apple private key not provided");if(!s&&!this.native)throw new l("Apple redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/auth/token`}}function ce(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 G extends Error{status;body;constructor(e,t,r){super(e);this.status=t;this.body=r;this.name="BlueskyApiError"}get isAuthError(){return this.status===400||this.status===401||this.status===403}}var le=new TextEncoder;function m(e){return le.encode(e).length}function de(e){let t=[],r=/https?:\/\/[^\s<>"']+/g;for(let o of e.matchAll(r)){let a=o[0].replace(/[),.;!?]+$/,"");t.push({byteStart:m(e.slice(0,o.index)),byteEnd:m(e.slice(0,o.index))+m(a),type:"link",value:a})}let i=(o,a)=>t.some((c)=>c.type==="link"&&o<c.byteEnd&&a>c.byteStart),s=/(^|\s)(#[A-Za-z0-9_]+)/g;for(let o of e.matchAll(s)){let a=o[1],c=o[2];if(a===void 0||c===void 0)continue;if(/^#\d+$/.test(c))continue;let d=(o.index??0)+a.length,u=m(e.slice(0,d)),P=u+m(c);if(i(u,P))continue;t.push({byteStart:u,byteEnd:P,type:"tag",value:c.slice(1)})}let n=/(^|\s)(@[a-z0-9][a-z0-9.-]*\.[a-z]{2,})/gi;for(let o of e.matchAll(n)){let a=o[1],c=o[2];if(a===void 0||c===void 0)continue;let d=(o.index??0)+a.length,u=m(e.slice(0,d)),P=u+m(c);if(i(u,P))continue;t.push({byteStart:u,byteEnd:P,type:"mention",value:c.slice(1).replace(/\.+$/,"")})}return t.sort((o,a)=>o.byteStart-a.byteStart)}class T{provider="bluesky";characterLimit=300;service;constructor(e={}){this.service=e.service||"https://bsky.social"}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.post("/xrpc/com.atproto.server.createSession",{identifier:t,password:r}),s=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:s?.displayName,accessJwt:i.accessJwt,refreshJwt:i.refreshJwt}}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 publish(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.");if(t.text.length>this.characterLimit)throw Error(`Bluesky posts must be ${this.characterLimit} characters or fewer.`);let i={$type:"app.bsky.feed.post",text:t.text,createdAt:t.scheduledAt||new Date().toISOString()};if(t.langs?.length)i.langs=t.langs;if(t.reply)i.reply=t.reply;let s=t.facets??await this.buildFacets(t.text);if(s.length)i.facets=s;if(t.external)i.embed={$type:"app.bsky.embed.external",external:{uri:t.external.uri,title:t.external.title,description:t.external.description||""}};let n=(t.media||[]).filter((a)=>a.bytes?.length).slice(0,4);if(n.length){let a=[];for(let c of n){let d=await this.uploadBlob(e,c.bytes,c.mimeType||"image/jpeg");a.push({image:d,alt:c.altText||""})}i.embed={$type:"app.bsky.embed.images",images:a}}let o=await this.post("/xrpc/com.atproto.repo.createRecord",{repo:r,collection:"app.bsky.feed.post",record:i},{authorization:`Bearer ${e.accessToken}`});return{provider:this.provider,uri:o.uri,cid:o.cid,url:this.toPostUrl(e.handle,o.uri)}}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 s of t.slice(0,25))r.searchParams.append("uris",s);return((await this.request(r,{headers:{authorization:`Bearer ${e.accessToken}`}})).posts||[]).map((s)=>({uri:s.uri,likeCount:s.likeCount||0,repostCount:s.repostCount||0,replyCount:s.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((s)=>{let n=s.post;if(!n?.uri||!n.author?.handle)return[];return[{uri:n.uri,authorHandle:n.author.handle,authorName:n.author.displayName,authorAvatar:n.author.avatar,postUrl:this.toPostUrl(n.author.handle,n.uri),body:n.record?.text||"",postedAt:n.record?.createdAt||new Date().toISOString(),likeCount:n.likeCount||0,repostCount:n.repostCount||0,replyCount:n.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 de(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 s=await this.resolveHandle(r.value);if(s)i={$type:"app.bsky.richtext.facet#mention",did:s}}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 uploadBlob(e,t,r){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(t.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":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","app.bsky.feed.post"),i.searchParams.set("limit",String(Math.min(Math.max(t.limit||100,1),100))),t.cursor)i.searchParams.set("cursor",t.cursor);let s=await this.request(i,{headers:{authorization:`Bearer ${e.accessToken}`}});return{cursor:s.cursor,posts:(s.records||[]).filter((n)=>n?.uri).map((n)=>({uri:n.uri,cid:n.cid,text:n.value?.text,postedAt:n.value?.createdAt,url:e.handle?this.toPostUrl(e.handle,n.uri):void 0}))}}async deletePost(e,t){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let{repo:r,collection:i,rkey:s}=ce(t.uri);await this.post("/xrpc/com.atproto.repo.deleteRecord",{repo:r,collection:i,rkey:s},{authorization:`Bearer ${e.accessToken}`})}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 fetch(e,t),i=await r.text();if(!r.ok)throw new G(`Bluesky API failed (${r.status}): ${i||r.statusText}`,r.status,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 F}from"@stacksjs/api";import{config as S}from"@stacksjs/config";var x="v24.0";class L extends h{baseUrl="https://www.facebook.com";apiUrl="https://graph.facebook.com";get graphVersion(){return S.services.facebook?.graphVersion??x}getConfig(){let e={clientId:S.services.facebook?.clientId??"",clientSecret:S.services.facebook?.clientSecret??"",redirectUrl:S.services.facebook?.redirectUrl??"",scopes:S.services.facebook?.scopes??["email","public_profile"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.getState(),{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(","),state:e,response_type:"code"}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let s=await F.get(`${this.apiUrl}/${this.graphVersion}/oauth/access_token?${new URLSearchParams({client_id:t,client_secret:r,redirect_uri:i,code:e}).toString()}`);if(s.data.error)throw Error(`Facebook OAuth error: ${s.data.error.message}`);return s.data.access_token}async getUserByToken(e){let t=await F.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 l("Facebook client ID not provided");if(!t)throw new l("Facebook client secret not provided");if(!r)throw new l("Facebook redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/${this.graphVersion}/oauth/access_token`}}import{fetcher as D}from"@stacksjs/api";import{config as _}from"@stacksjs/config";class N extends h{baseUrl="https://github.com";apiUrl="https://api.github.com";getConfig(){let e={clientId:this.clientId||(_.services.github?.clientId??""),clientSecret:this.clientSecret||(_.services.github?.clientSecret??""),redirectUrl:this.redirectUrl||(_.services.github?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:_.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",...this.parameters}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let s=await D.post(`${this.baseUrl}/login/oauth/access_token`,{client_id:t,client_secret:r,code:e,redirect_uri:i});if(s.data.error)throw Error(`GitHub OAuth error: ${s.data.error_description}`);return s.data.access_token}async getUserByToken(e){let[t,r]=await Promise.all([D.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${e}`}).get(`${this.apiUrl}/user`),D.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 l("GitHub client ID not provided");if(!t)throw new l("GitHub client secret not provided");if(!r)throw new l("GitHub redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/login/oauth/access_token`}}import{fetcher as Q}from"@stacksjs/api";import{config as C}from"@stacksjs/config";class q extends h{baseUrl="https://accounts.google.com";apiUrl="https://www.googleapis.com";tokenUrl="https://oauth2.googleapis.com/token";getConfig(){let e={clientId:this.clientId||(C.services.google?.clientId??""),clientSecret:this.clientSecret||(C.services.google?.clientSecret??""),redirectUrl:this.redirectUrl||(C.services.google?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:C.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",...this.parameters}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let s=await Q.post(this.tokenUrl,{client_id:t,client_secret:r,code:e,redirect_uri:i,grant_type:"authorization_code"});if(s.data.error)throw Error(`Google OAuth error: ${s.data.error_description}`);return s.data.access_token}async getUserByToken(e){let t=await Q.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}}validateConfig(){let{clientId:e,clientSecret:t,redirectUrl:r}=this.getConfig();if(!e)throw new l("Google client ID not provided");if(!t)throw new l("Google client secret not provided");if(!r)throw new l("Google redirect URL not provided")}getTokenUrl(){return this.tokenUrl}}class v extends Error{status;body;constructor(e,t,r){super(e);this.status=t;this.body=r;this.name="InstagramApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class z{provider="instagram";characterLimit=2200;graphVersion;authBase;graphBase;constructor(e={}){this.graphVersion=e.graphVersion||x,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 v("Facebook did not return an access token.",400,JSON.stringify(t));return{accessToken:t.access_token,expiresIn:t.expires_in}}async resolveAccount(e){let t=new URLSearchParams({fields:"name,access_token,instagram_business_account{id,username}"}),r=await this.graph(`/me/accounts?${t.toString()}`,{method:"GET"},e),i=(r.data||[]).find((n)=>n.instagram_business_account?.id),s=i?.instagram_business_account;if(!s?.id||!i?.access_token)throw new v("No Instagram Business account is linked to your Facebook Pages.",400,JSON.stringify(r));return{igUserId:s.id,username:s.username,pageAccessToken:i.access_token}}async publish(e,t){if(!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?.[0];if(!i?.url)throw Error("Instagram requires an image to post.");if(t.text.length>this.characterLimit)throw Error(`Instagram captions must be ${this.characterLimit} characters or fewer.`);let s=await this.graph(`/${r}/media`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({image_url:i.url,caption:t.text}).toString()},e.accessToken);if(!s.id)throw new v("Instagram did not return a media container id.",400,JSON.stringify(s));let n=await this.graph(`/${r}/media_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:s.id}).toString()},e.accessToken),o=await this.graph(`/${n.id}?fields=permalink`,{method:"GET"},e.accessToken).catch(()=>{return});return{provider:this.provider,uri:n.id,url:o?.permalink}}async timeline(e,t={}){return{items:[]}}async graph(e,t,r){let i=new Headers(t.headers);if(r)i.set("authorization",`Bearer ${r}`);let s=await fetch(`${this.graphBase}/${this.graphVersion}${e}`,{...t,headers:i}),n=await s.text(),o={};try{o=n?JSON.parse(n):{}}catch{o={}}if(!s.ok||o?.error){let a=o?.error?.message||n||s.statusText;throw new v(`Instagram API failed (${s.status}): ${a}`,s.status,n)}return o}}class g extends Error{status;body;constructor(e,t,r){super(e);this.status=t;this.body=r;this.name="LinkedInApiError"}get isAuthError(){return this.status===401||this.status===403}}class V{provider="linkedin";characterLimit=3000;apiVersion;authBase;apiBase;constructor(e={}){this.apiVersion=e.apiVersion||"202405",this.authBase=e.authBase||"https://www.linkedin.com",this.apiBase=e.apiBase||"https://api.linkedin.com"}getAuthUrl(e){let t=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(" "),state:e.state});return`${this.authBase}/oauth/v2/authorization?${t.toString()}`}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}),r=await this.request(`${this.authBase}/oauth/v2/accessToken`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:t.toString()});if(!r.access_token)throw new g("LinkedIn did not return an access token.",400,JSON.stringify(r));return{accessToken:r.access_token,expiresIn:r.expires_in,scope:r.scope}}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 g("LinkedIn profile is missing a subject id.",400,JSON.stringify(t));return{sub:t.sub,name:t.name,picture:t.picture}}async publish(e,t){if(!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let r=e.did;if(!r)throw Error("LinkedIn member URN is required to publish.");if(t.text.length>this.characterLimit)throw Error(`LinkedIn posts must be ${this.characterLimit} characters or fewer.`);let i={author:r,commentary:ue(t.text),visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(t.external)i.content={article:{source:t.external.uri,title:t.external.title,description:t.external.description||""}};let s=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":"2.0.0"},body:JSON.stringify(i)}),n=await s.text();if(!s.ok)throw new g(`LinkedIn API failed (${s.status}): ${n||s.statusText}`,s.status,n);let o=s.headers.get("x-restli-id")||s.headers.get("x-linkedin-id")||"";return{provider:this.provider,uri:o,url:o?`https://www.linkedin.com/feed/update/${o}`:void 0}}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 member URN is required to list posts.");let i=Math.min(Math.max(t.limit||50,1),100),s=Number(t.cursor||0)||0,n=new URL(`${this.apiBase}/rest/posts`);n.searchParams.set("q","author"),n.searchParams.set("author",r),n.searchParams.set("count",String(i)),n.searchParams.set("start",String(s));let o;try{o=await this.request(n.toString(),{headers:{authorization:`Bearer ${e.accessToken}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":"2.0.0"}})}catch(c){if(c instanceof g&&(c.status===401||c.status===403))throw new g("LinkedIn will not list this account's posts - the Posts author finder needs the r_member_social permission, which this app does not hold.",c.status,c.body);throw c}let a=(o.elements||[]).filter((c)=>c?.id).map((c)=>({uri:String(c.id),text:c.commentary,postedAt:c.createdAt?new Date(c.createdAt).toISOString():void 0,url:`https://www.linkedin.com/feed/update/${c.id}`}));return{cursor:a.length===i?String(s+i):void 0,posts:a}}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":"2.0.0"}});if(!i.ok&&i.status!==404){let s=await i.text().catch(()=>"");throw new g(`LinkedIn API failed (${i.status}): ${s||i.statusText}`,i.status,s)}}async request(e,t){let r=await fetch(e,t),i=await r.text();if(!r.ok)throw new g(`LinkedIn API failed (${r.status}): ${i||r.statusText}`,r.status,i);return i?JSON.parse(i):{}}}function ue(e){return e.replace(/[\\|{}@[\]()<>#*_~]/g,"\\$&")}class K extends Error{status;body;constructor(e,t,r){super(e);this.status=t;this.body=r;this.name="MastodonApiError"}get isAuthError(){return this.status===401||this.status===403}}function pe(e){let t=String(e||"").trim().replace(/\/+$/,"");if(!t)throw Error("Mastodon instance URL is required.");let r=/^https?:\/\//i.test(t)?t:`https://${t}`;try{let i=new URL(r);return`${i.protocol}//${i.host}`}catch{throw Error("Mastodon instance URL is invalid.")}}class H{provider="mastodon";characterLimit=500;instanceOf(e){return pe(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 uploadMedia(e,t,r,i){let s=new FormData;if(s.set("file",new Blob([new Uint8Array(t)],{type:r||"image/jpeg"}),"upload"),i)s.set("description",i);return(await this.request(`${this.instanceOf(e)}/api/v2/media`,{method:"POST",headers:{authorization:`Bearer ${this.tokenOf(e)}`},body:s})).id}async publish(e,t){let r=this.instanceOf(e),i=this.tokenOf(e);if(t.text.length>this.characterLimit)throw Error(`Mastodon posts must be ${this.characterLimit} characters or fewer.`);let s=[];for(let a of(t.media||[]).slice(0,4)){let{bytes:c,mimeType:d}=a;if(!c?.length&&a.url){let u=await fetch(a.url);if(!u.ok)continue;c=new Uint8Array(await u.arrayBuffer()),d=d||u.headers.get("content-type")||"image/jpeg"}if(c?.length)s.push(await this.uploadMedia(e,c,d||"image/jpeg",a.altText))}let n={status:t.text,visibility:"public"};if(s.length)n.media_ids=s;if(t.reply?.parent?.uri)n.in_reply_to_id=t.reply.parent.uri;let o=await this.request(`${r}/api/v1/statuses`,{method:"POST",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:JSON.stringify(n)});return{provider:this.provider,uri:o.id,cid:o.id,url:o.url||o.uri}}async timeline(e,t={}){return{items:[]}}async listAuthoredPosts(e,t={}){let r=this.instanceOf(e),{accountId:i}=await this.verifyCredentials(e),s=new URL(`${r}/api/v1/accounts/${encodeURIComponent(i)}/statuses`);if(s.searchParams.set("limit",String(Math.min(Math.max(t.limit||40,1),40))),s.searchParams.set("exclude_reblogs","true"),t.cursor)s.searchParams.set("max_id",t.cursor);let o=(await this.request(s.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||he(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 request(e,t){let r=await fetch(e,t),i=await r.text();if(!r.ok)throw new K(`Mastodon API failed (${r.status}): ${i||r.statusText}`,r.status,i);return i?JSON.parse(i):{}}}function he(e){return String(e||"").replace(/\/+$/,"").split("/").pop()||""}class w extends Error{status;body;constructor(e,t,r){super(e);this.status=t;this.body=r;this.name="ThreadsApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class J{provider="threads";characterLimit=500;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()}),r=await t.text(),i={};try{i=r?JSON.parse(r):{}}catch{i={}}if(!t.ok||i?.error||!i?.access_token){let s=i?.error_message||i?.error?.message||r||t.statusText;throw new w(`Threads token exchange failed (${t.status}): ${s}`,t.status,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 w("Could not resolve the Threads account for this token.",400,JSON.stringify(r));return{threadsUserId:r.id,username:r.username,accessToken:e}}async publish(e,t){if(!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(t.text.length>this.characterLimit)throw Error(`Threads posts must be ${this.characterLimit} characters or fewer.`);let i=t.media?.[0],s=new URLSearchParams({text:t.text});if(i?.url)s.set("media_type","IMAGE"),s.set("image_url",i.url);else s.set("media_type","TEXT");let n=await this.graph(`/${r}/threads`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:s.toString()},e.accessToken);if(!n.id)throw new w("Threads did not return a media container id.",400,JSON.stringify(n));let o=await this.graph(`/${r}/threads_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:n.id}).toString()},e.accessToken);if(!o.id)throw new w("Threads did not return a published post id.",400,JSON.stringify(o));let a=await this.graph(`/${o.id}?fields=permalink`,{method:"GET"},e.accessToken).catch(()=>{return});return{provider:this.provider,uri:o.id,url:a?.permalink}}async timeline(e,t={}){return{items:[]}}async graph(e,t,r){let i=new Headers(t.headers);if(r)i.set("authorization",`Bearer ${r}`);let s=await fetch(`${this.graphBase}/${this.graphVersion}${e}`,{...t,headers:i}),n=await s.text(),o={};try{o=n?JSON.parse(n):{}}catch{o={}}if(!s.ok||o?.error){let a=o?.error?.message||n||s.statusText;throw new w(`Threads API failed (${s.status}): ${a}`,s.status,n)}return o}}import{Buffer as ge}from"buffer";import{createHash as me,randomBytes as fe}from"crypto";import{fetcher as Z}from"@stacksjs/api";import{config as U}from"@stacksjs/config";class j extends h{baseUrl="https://twitter.com";apiUrl="https://api.twitter.com";codeVerifier=null;getConfig(){let e={clientId:U.services.twitter?.clientId??"",clientSecret:U.services.twitter?.clientSecret??"",redirectUrl:U.services.twitter?.redirectUrl??"",scopes:U.services.twitter?.scopes??["users.read","tweet.read"]};return this.setScopes(e.scopes),e}generateCodeVerifier(){return fe(32).toString("base64").replace(/[^a-z0-9]/gi,"").substring(0,128)}generateCodeChallenge(e){return me("sha256").update(e).digest("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async getAuthUrl(){let e=this.getState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();this.validateConfig(),this.codeVerifier=this.generateCodeVerifier();let s=this.generateCodeChallenge(this.codeVerifier);return`${this.baseUrl}/i/oauth2/authorize?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(" "),state:e,response_type:"code",code_challenge:s,code_challenge_method:"S256"}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();if(this.validateConfig(),!this.codeVerifier)throw Error("Code verifier not found. Please ensure getAuthUrl() is called first.");let s=ge.from(`${t}:${r}`).toString("base64"),n=await Z.withHeaders({Authorization:`Basic ${s}`,"Content-Type":"application/x-www-form-urlencoded"}).post(`${this.apiUrl}/2/oauth2/token`,{code:e,grant_type:"authorization_code",redirect_uri:i,code_verifier:this.codeVerifier});if(n.data.error)throw Error(`Twitter OAuth error: ${n.data.error_description}`);return n.data.access_token}async getUserByToken(e){let t=await Z.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 l("Twitter client ID not provided");if(!t)throw new l("Twitter client secret not provided");if(!r)throw new l("Twitter redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/2/oauth2/token`}}class f extends Error{status;body;constructor(e,t,r){super(e);this.status=t;this.body=r;this.name="TwitterApiError"}get isAuthError(){return this.status===401||this.status===403}}function W(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}class b{provider="twitter";characterLimit=280;apiBase;authorizeBase;constructor(e={}){this.apiBase=e.apiBase||"https://api.twitter.com",this.authorizeBase=e.authorizeBase||"https://twitter.com"}async createAuthorization(e){let t=W(crypto.getRandomValues(new Uint8Array(32))),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),i=W(new Uint8Array(r)),s=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(" "),state:e.state,code_challenge:i,code_challenge_method:"S256"});return{url:`${this.authorizeBase}/i/oauth2/authorize?${s.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`,{headers:{authorization:`Bearer ${e}`}});if(!t.data?.id||!t.data.username)throw new f("Twitter did not return the authenticated user.",400,JSON.stringify(t));return{id:t.data.id,username:t.data.username,name:t.data.name}}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 s=await this.request(`${this.apiBase}/2/media/upload`,{method:"POST",headers:{authorization:`Bearer ${e}`},body:i}),n=s.data?.id||s.media_id_string||s.id;if(!n)throw new f("Twitter did not return a media id.",400,JSON.stringify(s));return n}async publish(e,t){if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");if(t.text.length>this.characterLimit)throw Error(`Twitter posts must be ${this.characterLimit} characters or fewer.`);let r=[],i=t.media?.[0];if(i){let{bytes:a,mimeType:c}=i;if(!a?.length&&i.url){let d=await fetch(i.url);if(d.ok)a=new Uint8Array(await d.arrayBuffer()),c=c||d.headers.get("content-type")||"image/jpeg"}if(a?.length)r.push(await this.uploadMedia(e.accessToken,a,c||"image/jpeg"))}let s={text:t.text};if(r.length)s.media={media_ids:r};if(t.reply?.parent?.uri)s.reply={in_reply_to_tweet_id:t.reply.parent.uri};let n=await this.request(`${this.apiBase}/2/tweets`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json"},body:JSON.stringify(s)}),o=n.data?.id;if(!o)throw new f("Twitter did not return a tweet id.",400,JSON.stringify(n));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}`}}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 s=await this.request(i.toString(),{headers:{authorization:`Bearer ${e.accessToken}`}});return{cursor:s.meta?.next_token,posts:(s.data||[]).filter((n)=>n?.id).map((n)=>({uri:n.id,cid:n.id,text:n.text,postedAt:n.created_at,url:`https://x.com/i/web/status/${n.id}`}))}}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 this.request(`${this.apiBase}/2/tweets/${encodeURIComponent(r)}`,{method:"DELETE",headers:{authorization:`Bearer ${e.accessToken}`}});if(i.data&&i.data.deleted===!1)throw new f(`X refused to delete tweet ${r}.`,400,JSON.stringify(i))}async tokenRequest(e,t,r){let i={"content-type":"application/x-www-form-urlencoded"};if(r)i.authorization=`Basic ${btoa(`${t}:${r}`)}`;let s=await this.request(`${this.apiBase}/2/oauth2/token`,{method:"POST",headers:i,body:e.toString()});if(!s.access_token)throw new f("Twitter did not return an access token.",400,JSON.stringify(s));return{accessToken:s.access_token,refreshToken:s.refresh_token,expiresIn:s.expires_in,scope:s.scope}}async request(e,t){let r=await fetch(e,t),i=await r.text();if(!r.ok)throw new f(`Twitter API failed (${r.status}): ${i||r.statusText}`,r.status,i);return i?JSON.parse(i):{}}}import{config as ye}from"@stacksjs/config";var R=["clientId","clientSecret","redirectUrl"],I=Object.freeze({google:{name:"google",label:"Google",driver:q,required:R,postCallback:!1},github:{name:"github",label:"GitHub",driver:N,required:R,postCallback:!1},facebook:{name:"facebook",label:"Facebook",driver:L,required:R,postCallback:!1},twitter:{name:"twitter",label:"X",driver:j,required:R,postCallback:!1},apple:{name:"apple",label:"Apple",driver:O,required:["clientId","teamId","keyId","privateKey","redirectUrl"],postCallback:!0}});function X(e){return ye?.services?.[e]}function we(e){return typeof e==="string"&&e in I}function Y(e){if(!we(e))return!1;let t=X(e);if(!t)return!1;return I[e].required.every((r)=>Boolean(t[r]))}function Pt(){return Object.keys(I).filter(Y).map((e)=>I[e])}function St(e){if(!Y(e))return null;let t=I[e],r=X(e)??{};return new t.driver({clientSecret:"",...r,clientId:String(r.clientId??""),redirectUrl:String(r.redirectUrl??"")})}class be{accessToken;refreshToken;expiresIn;approvedScopes;constructor(e,t=null,r=null,i=[]){this.accessToken=e;this.refreshToken=t;this.expiresIn=r;this.approvedScopes=i}}function Tt(e){return typeof e?.deletePost==="function"}function xt(e){return typeof e?.listAuthoredPosts==="function"}import{buildSessionHandoffUrl as ke}from"@stacksjs/composables";function ee(e,t=[]){if(!e)return!1;if(e.startsWith("//"))return!1;if(e.startsWith("/"))return!0;try{let r=new URL(e);if(r.protocol!=="http:"&&r.protocol!=="https:")return!1;return t.includes(r.host)}catch{return!1}}function Ut(e,t={}){let r=t.redirectTo??"/";if(!ee(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:ke(r,e),"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function Rt(e,t={}){let r=t.redirectTo??"/login";if(!ee(r,t.allowedHosts??[]))throw Error(`[socials] refusing to redirect to ${r}`);let i=r.includes("?")?"&":"?",s=`${r}${i}social_error=${encodeURIComponent(e)}`;return new Response(null,{status:302,headers:{Location:s,"Cache-Control":"no-store"}})}var Pe={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"]},Se={bluesky:["identifier","password"],twitter:["clientId","clientSecret","accessToken"],linkedin:["accessToken","memberUrn"],mastodon:["accessToken","instanceUrl"],instagram:["accessToken","accountId"],threads:["accessToken","userId"]};function ve(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function A(e,t,r){let i=r.replace(/[A-Z]/g,(s)=>`_${s}`).toUpperCase();return`SOCIALS_${ve(e)}_${t.toUpperCase()}_${i}`}class p extends Error{constructor(e){super(e);this.name="SocialIdentityError"}}async function E(){let{config:e,overridesReady:t}=await import("@stacksjs/config");return await t,e.socials??{}}function te(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 Ie(e,t,r,i=process.env){let n=(e.identities?.[r]??{}).credentials?.[t]??{},o={};for(let a of Pe[t]){let c=(n[a]??i[A(r,t,a)]??"").trim();if(c)o[a]=c}return o}function M(e,t,r,i=process.env){let s=te(e,r),n=Ie(e,t,s,i),o=Se[t].filter((a)=>!n[a]);if(o.length){let a=o.map((c)=>A(s,t,c)).join(", ");throw new p(`Identity '${s}' is not configured for ${t}: ${o.join(", ")} ${o.length===1?"is":"are"} missing. Set ${a}, or supply them inline in config/socials.ts.`)}return n}async function re(e){return te(await E(),e)}async function k(e,t,r){return M(await E(),e,t,r)}function At(e,t){return k("bluesky",e,t)}function Et(e,t){return k("twitter",e,t)}function Bt(e,t){return k("linkedin",e,t)}function Ot(e,t){return k("mastodon",e,t)}function Lt(e,t){return k("instagram",e,t)}function Dt(e,t){return k("threads",e,t)}import{randomBytes as Te}from"crypto";function Ht(e){return e==="twitter"}var xe=["tweet.read","tweet.write","users.read","offline.access"],_e="127.0.0.1",ie="/callback";function Jt(e){if(!Number.isInteger(e)||e<1||e>65535)throw new p(`${e} is not a port a redirect can listen on.`);return`http://${_e}:${e}${ie}`}function jt(){return Te(16).toString("hex")}function Mt(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!==ie)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 s=r.searchParams.get("state")??"";if(!t||s!==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("code")??"";if(!n)return{ok:!1,reason:"no-code",message:"The redirect carried no authorization code."};return{ok:!0,code:n}}function Gt(e,t,r){let i=[];for(let[s,n]of Object.entries(r)){if(!n)continue;i.push(`${A(e,t,s)}=${n}`)}return i}async function Ft(e){let t=new b,r=await t.exchangeCode(e);if(!r.accessToken)throw new p("X returned no access token for that code.");let i=Boolean(r.refreshToken),s=await t.getProfile(r.accessToken);return{handle:s.username,accountId:s.id,accessToken:r.accessToken,refreshToken:r.refreshToken,expiresIn:r.expiresIn,scope:r.scope,renewable:i}}async function Qt(e){return new b().createAuthorization({clientId:e.clientId,redirectUrl:e.redirectUrl,scopes:[...xe],state:e.state})}function Kt(e,t){let r=(i)=>i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");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 Ce={bluesky:null,twitter:null,linkedin:"memberUrn",mastodon:"instanceUrl",instagram:"accountId",threads:"userId"};function Ue(e,t){if(e==="bluesky")return t.service?{service:t.service}:{};if(e==="linkedin")return t.apiVersion?{apiVersion:t.apiVersion}:{};return{}}function Re(e,t={}){switch(e){case"bluesky":return new T(t);case"linkedin":return new V(t);case"twitter":return new b;case"mastodon":return new H;case"instagram":return new z;case"threads":return new J;default:throw new p(`No publishing driver for '${String(e)}'.`)}}function $e(e,t,r){let i=Ce[e],s={handle:(t??"").trim()};if(r.accessToken)s.accessToken=r.accessToken;if(r.refreshToken)s.refreshToken=r.refreshToken;if(i&&r[i])s.did=r[i];return s}function Ae(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 Ee(e,t,r){let i=await E(),s=await re(t),n=i.identities?.[s]??{};Ae(s,e,n.platforms);let o=M(i,e,s,r),a=Ue(e,o);if(e==="bluesky"){let c=await new T(a).createSession({identifier:o.identifier,password:o.password});return{name:s,platform:e,identity:{handle:c.handle,did:c.did,accessToken:c.accessJwt,refreshToken:c.refreshJwt},options:a}}return{name:s,platform:e,identity:$e(e,n.handle??"",o),options:a}}async function Yt(e,t,r,i){let s=await Ee(e,r,i);return Re(s.platform,s.options).publish(s.identity,t)}export{_e as AUTHORIZE_HOST,ie as AUTHORIZE_PATH,h as AbstractProvider,O as AppleProvider,G as BlueskyApiError,T as BlueskyPublishingDriver,l as ConfigException,Ce as DRIVER_DID_FIELD,L as FacebookProvider,N as GitHubProvider,q as GoogleProvider,v as InstagramApiError,z as InstagramPublishingDriver,ne as InvalidStateException,g as LinkedInApiError,V as LinkedInPublishingDriver,x as META_GRAPH_VERSION,K as MastodonApiError,H as MastodonPublishingDriver,Se as REQUIRED_SOCIAL_CREDENTIALS,Pe as SOCIAL_CREDENTIAL_FIELDS,I as SOCIAL_PROVIDERS,p as SocialIdentityError,xe as TWITTER_PUBLISH_SCOPES,w as ThreadsApiError,J as ThreadsPublishingDriver,be as Token,f as TwitterApiError,j as TwitterProvider,b as TwitterPublishingDriver,Ae as assertPlatformDeclared,Kt as callbackPage,Jt as callbackUri,Ft as completeTwitterAuthorization,Pt as configuredSocialProviders,de as detectFacetCandidates,Ue as driverOptions,Gt as envLines,A as envName,ve as envSegment,ue as escapeLinkedInText,Ht as isAuthorizablePlatform,ee as isSafeHandoffTarget,Y as isSocialProviderConfigured,we as isSocialProviderName,jt as newState,pe as normalizeInstance,ce as parseAtUri,M as pickCredentials,te as pickIdentity,Yt as publishAs,Re as publishingDriver,Mt as readCallback,Ie as readCredentials,At as resolveBlueskyCredentials,re as resolveIdentityName,Lt as resolveInstagramCredentials,Bt as resolveLinkedInCredentials,Ot as resolveMastodonCredentials,k as resolveSocialCredentials,Dt as resolveThreadsCredentials,Et as resolveTwitterCredentials,Rt as socialHandoffFailureRedirect,Ut as socialHandoffRedirect,St as socialProvider,Ee as socialPublishTarget,E as socialsConfig,Qt as startTwitterAuthorization,Tt as supportsDeletion,xt as supportsEnumeration,$e as toDriverIdentity};
|
|
2
|
+
var ge=import.meta.require;import{Buffer as T}from"buffer";class g{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}=ge("crypto");return r(T.from(e,"utf8"),T.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=T.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 T.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 ee}from"buffer";import{createPrivateKey as ke,sign as be}from"crypto";import{config as w}from"@stacksjs/config";class fe extends Error{constructor(e="Invalid state"){super(e);this.name="InvalidStateException"}}class d extends Error{constructor(e){super(e);this.name="ConfigException"}}import{Buffer as V}from"buffer";var Y=new Map,me=600000,ye=60000;async function Z(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(),s=Array.isArray(i.keys)?i.keys:[];return Y.set(e,{keys:s,fetchedAt:t}),s}async function we(e,t,r){let i=Y.get(e),s=i!==void 0&&r-i.fetchedAt<me,n=s?i.keys:await Z(e,r),o=n.find((a)=>a.kid===t);if(!o&&s&&r-i.fetchedAt>=ye)n=await Z(e,r),o=n.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 X(e,t){try{return JSON.parse(V.from(e,"base64url").toString("utf8"))}catch{throw Error(`id_token verification failed: ${t} is not valid JSON`)}}async function x(e,t){let r=e.split(".");if(r.length!==3)throw Error("id_token verification failed: malformed token");let[i,s,n]=r,o=X(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 we(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,V.from(n,"base64url"),V.from(`${i}.${s}`)))throw Error("id_token verification failed: signature does not match the issuer's key");let l=X(s,"payload"),L=(t.clockSkewSeconds??60)*1000,W=Array.isArray(t.issuer)?t.issuer:[t.issuer];if(!W.includes(l.iss))throw Error(`id_token verification failed: issuer is ${JSON.stringify(l.iss)}, expected ${W.map((D)=>JSON.stringify(D)).join(" or ")}`);let he=Array.isArray(t.audience)?t.audience:[t.audience];if(!(Array.isArray(l.aud)?l.aud:[l.aud]).some((D)=>he.includes(D)))throw Error("id_token verification failed: token is addressed to a different client");if(typeof l.exp!=="number"||l.exp*1000+L<=a)throw Error("id_token verification failed: token has expired");if(typeof l.iat==="number"&&l.iat*1000-L>a)throw Error("id_token verification failed: token was issued in the future");if(typeof l.nbf==="number"&&l.nbf*1000-L>a)throw Error("id_token verification failed: token is not valid yet");if(t.nonce!==void 0&&l.nonce!==t.nonce)throw Error("id_token verification failed: nonce does not match");if(typeof l.sub!=="string"||l.sub==="")throw Error("id_token verification failed: token has no subject");return l}class N extends g{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||(w.services.apple?.clientId??""),teamId:this.teamId||(w.services.apple?.teamId??""),keyId:this.keyId||(w.services.apple?.keyId??""),privateKey:(this.privateKey||(w.services.apple?.privateKey??"")).replace(/\\n/g,`
|
|
3
|
+
`),redirectUrl:this.native?"":this.redirectUrl||(w.services.apple?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:w.services.apple?.scopes??["name","email"]};return this.setScopes(e.scopes),e}async getAuthUrl(){if(this.native)throw new d("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 s={client_id:t,redirect_uri:r,scope:i.join(" "),state:e,response_type:"code",...this.parameters};if(i.length>0)s.response_mode="form_post";return`${this.baseUrl}/auth/authorize?${new URLSearchParams(s).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()})}),s=await i.json();if(!i.ok||s.error)throw Error(`Apple OAuth error: ${s.error_description??s.error??`HTTP ${i.status}`}`);if(!s.id_token)throw Error("Apple OAuth error: token response contained no id_token");return s.id_token}async getUserByToken(e,t={}){let{clientId:r}=this.getConfig(),i;try{i=await x(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 s=typeof i.email==="string"?i.email:null,n=null;if(i.email_verified===!0||i.email_verified==="true")n=!0;else if(i.email_verified===!1||i.email_verified==="false")n=!1;return{id:String(i.sub),nickname:null,name:"",email:s,emailVerified:n,avatar:null,token:e,raw:i}}generateClientSecret(){let{clientId:e,teamId:t,keyId:r,privateKey:i}=this.getConfig(),s=Math.floor(Date.now()/1000),n={alg:"ES256",kid:r,typ:"JWT"},o={iss:t,iat:s,exp:s+3600,aud:this.baseUrl,sub:e},a=`${this.base64urlJson(n)}.${this.base64urlJson(o)}`,c;try{c=ke(i)}catch(p){throw new d(`Apple private key could not be parsed: ${p instanceof Error?p.message:String(p)}`)}let u=be("sha256",ee.from(a),{key:c,dsaEncoding:"ieee-p1363"});return`${a}.${u.toString("base64url")}`}base64urlJson(e){return ee.from(JSON.stringify(e)).toString("base64url")}validateConfig(){let{clientId:e,teamId:t,keyId:r,privateKey:i,redirectUrl:s}=this.getConfig();if(!e)throw new d(this.native?"Apple client ID (the app's bundle ID) not provided":"Apple client ID (Service ID) not provided");if(!t)throw new d("Apple team ID not provided");if(!r)throw new d("Apple key ID not provided");if(!i)throw new d("Apple private key not provided");if(!s&&!this.native)throw new d("Apple redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/auth/token`}}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 te extends Error{status;body;constructor(e,t,r){super(e);this.status=t;this.body=r;this.name="BlueskyApiError"}get isAuthError(){return this.status===400||this.status===401||this.status===403}}var Se=new TextEncoder;function m(e){return Se.encode(e).length}function ve(e){let t=[],r=/https?:\/\/[^\s<>"']+/g;for(let o of e.matchAll(r)){let a=o[0].replace(/[),.;!?]+$/,"");t.push({byteStart:m(e.slice(0,o.index)),byteEnd:m(e.slice(0,o.index))+m(a),type:"link",value:a})}let i=(o,a)=>t.some((c)=>c.type==="link"&&o<c.byteEnd&&a>c.byteStart),s=/(^|\s)(#[A-Za-z0-9_]+)/g;for(let o of e.matchAll(s)){let a=o[1],c=o[2];if(a===void 0||c===void 0)continue;if(/^#\d+$/.test(c))continue;let u=(o.index??0)+a.length,p=m(e.slice(0,u)),l=p+m(c);if(i(p,l))continue;t.push({byteStart:p,byteEnd:l,type:"tag",value:c.slice(1)})}let n=/(^|\s)(@[a-z0-9][a-z0-9.-]*\.[a-z]{2,})/gi;for(let o of e.matchAll(n)){let a=o[1],c=o[2];if(a===void 0||c===void 0)continue;let u=(o.index??0)+a.length,p=m(e.slice(0,u)),l=p+m(c);if(i(p,l))continue;t.push({byteStart:p,byteEnd:l,type:"mention",value:c.slice(1).replace(/\.+$/,"")})}return t.sort((o,a)=>o.byteStart-a.byteStart)}class _{provider="bluesky";characterLimit=300;service;constructor(e={}){this.service=e.service||"https://bsky.social"}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.post("/xrpc/com.atproto.server.createSession",{identifier:t,password:r}),s=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:s?.displayName,accessJwt:i.accessJwt,refreshJwt:i.refreshJwt}}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 publish(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.");if(t.text.length>this.characterLimit)throw Error(`Bluesky posts must be ${this.characterLimit} characters or fewer.`);let i={$type:"app.bsky.feed.post",text:t.text,createdAt:t.scheduledAt||new Date().toISOString()};if(t.langs?.length)i.langs=t.langs;if(t.reply)i.reply=t.reply;let s=t.facets??await this.buildFacets(t.text);if(s.length)i.facets=s;if(t.external)i.embed={$type:"app.bsky.embed.external",external:{uri:t.external.uri,title:t.external.title,description:t.external.description||""}};let n=(t.media||[]).filter((a)=>a.bytes?.length).slice(0,4);if(n.length){let a=[];for(let c of n){let u=await this.uploadBlob(e,c.bytes,c.mimeType||"image/jpeg");a.push({image:u,alt:c.altText||""})}i.embed={$type:"app.bsky.embed.images",images:a}}let o=await this.post("/xrpc/com.atproto.repo.createRecord",{repo:r,collection:"app.bsky.feed.post",record:i},{authorization:`Bearer ${e.accessToken}`});return{provider:this.provider,uri:o.uri,cid:o.cid,url:this.toPostUrl(e.handle,o.uri)}}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 s of t.slice(0,25))r.searchParams.append("uris",s);return((await this.request(r,{headers:{authorization:`Bearer ${e.accessToken}`}})).posts||[]).map((s)=>({uri:s.uri,likeCount:s.likeCount||0,repostCount:s.repostCount||0,replyCount:s.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((s)=>{let n=s.post;if(!n?.uri||!n.author?.handle)return[];return[{uri:n.uri,authorHandle:n.author.handle,authorName:n.author.displayName,authorAvatar:n.author.avatar,postUrl:this.toPostUrl(n.author.handle,n.uri),body:n.record?.text||"",postedAt:n.record?.createdAt||new Date().toISOString(),likeCount:n.likeCount||0,repostCount:n.repostCount||0,replyCount:n.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 ve(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 s=await this.resolveHandle(r.value);if(s)i={$type:"app.bsky.richtext.facet#mention",did:s}}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 uploadBlob(e,t,r){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");if(t.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":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","app.bsky.feed.post"),i.searchParams.set("limit",String(Math.min(Math.max(t.limit||100,1),100))),t.cursor)i.searchParams.set("cursor",t.cursor);let s=await this.request(i,{headers:{authorization:`Bearer ${e.accessToken}`}});return{cursor:s.cursor,posts:(s.records||[]).filter((n)=>n?.uri).map((n)=>({uri:n.uri,cid:n.cid,text:n.value?.text,postedAt:n.value?.createdAt,url:e.handle?this.toPostUrl(e.handle,n.uri):void 0}))}}async deletePost(e,t){if(!e.accessToken)throw Error("Bluesky access token is missing for this identity.");let{repo:r,collection:i,rkey:s}=Pe(t.uri);await this.post("/xrpc/com.atproto.repo.deleteRecord",{repo:r,collection:i,rkey:s},{authorization:`Bearer ${e.accessToken}`})}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 fetch(e,t),i=await r.text();if(!r.ok)throw new te(`Bluesky API failed (${r.status}): ${i||r.statusText}`,r.status,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 re}from"@stacksjs/api";import{config as S}from"@stacksjs/config";var C="v24.0";class q extends g{baseUrl="https://www.facebook.com";apiUrl="https://graph.facebook.com";get graphVersion(){return S.services.facebook?.graphVersion??C}getConfig(){let e={clientId:S.services.facebook?.clientId??"",clientSecret:S.services.facebook?.clientSecret??"",redirectUrl:S.services.facebook?.redirectUrl??"",scopes:S.services.facebook?.scopes??["email","public_profile"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.getState(),{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(","),state:e,response_type:"code",...await this.pkceFields()}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let s=await re.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(s.data.error)throw Error(`Facebook OAuth error: ${s.data.error.message}`);return s.data.access_token}async getUserByToken(e){let t=await re.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 d("Facebook client ID not provided");if(!t)throw new d("Facebook client secret not provided");if(!r)throw new d("Facebook redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/${this.graphVersion}/oauth/access_token`}}import{fetcher as z}from"@stacksjs/api";import{config as U}from"@stacksjs/config";class H extends g{baseUrl="https://github.com";apiUrl="https://api.github.com";getConfig(){let e={clientId:this.clientId||(U.services.github?.clientId??""),clientSecret:this.clientSecret||(U.services.github?.clientSecret??""),redirectUrl:this.redirectUrl||(U.services.github?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:U.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 s=await z.post(`${this.baseUrl}/login/oauth/access_token`,{client_id:t,client_secret:r,code:e,redirect_uri:i,...this.pkceTokenFields()});if(s.data.error)throw Error(`GitHub OAuth error: ${s.data.error_description}`);return s.data.access_token}async getUserByToken(e){let[t,r]=await Promise.all([z.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${e}`}).get(`${this.apiUrl}/user`),z.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 d("GitHub client ID not provided");if(!t)throw new d("GitHub client secret not provided");if(!r)throw new d("GitHub redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/login/oauth/access_token`}}import{fetcher as ie}from"@stacksjs/api";import{config as R}from"@stacksjs/config";class J extends g{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||(R.services.google?.clientId??""),clientSecret:this.clientSecret||(R.services.google?.clientSecret??""),redirectUrl:this.redirectUrl||(R.services.google?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:R.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 s=await ie.post(this.tokenUrl,{client_id:t,client_secret:r,code:e,redirect_uri:i,grant_type:"authorization_code",...this.pkceTokenFields()});if(s.data.error)throw Error(`Google OAuth error: ${s.data.error_description}`);return s.data.access_token}async getUserByToken(e){await this.assertTokenWasIssuedToUs(e);let t=await ie.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 x(e,{jwksUrl:this.certsUrl,issuer:this.issuers,audience:r,nonce:t.nonce})}catch(n){throw Error(`Google OAuth error: ${n instanceof Error?n.message:String(n)}`)}let s=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:s,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 s=i.aud??i.audience;if(!s)throw Error("Google OAuth error: tokeninfo did not report an audience for the access token");if(s!==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 d("Google client ID not provided");if(!t)throw new d("Google client secret not provided");if(!r)throw new d("Google redirect URL not provided")}getTokenUrl(){return this.tokenUrl}}class v extends Error{status;body;constructor(e,t,r){super(e);this.status=t;this.body=r;this.name="InstagramApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class j{provider="instagram";characterLimit=2200;graphVersion;authBase;graphBase;constructor(e={}){this.graphVersion=e.graphVersion||C,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 v("Facebook did not return an access token.",400,JSON.stringify(t));return{accessToken:t.access_token,expiresIn:t.expires_in}}async resolveAccount(e){let t=new URLSearchParams({fields:"name,access_token,instagram_business_account{id,username}"}),r=await this.graph(`/me/accounts?${t.toString()}`,{method:"GET"},e),i=(r.data||[]).find((n)=>n.instagram_business_account?.id),s=i?.instagram_business_account;if(!s?.id||!i?.access_token)throw new v("No Instagram Business account is linked to your Facebook Pages.",400,JSON.stringify(r));return{igUserId:s.id,username:s.username,pageAccessToken:i.access_token}}async publish(e,t){if(!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?.[0];if(!i?.url)throw Error("Instagram requires an image to post.");if(t.text.length>this.characterLimit)throw Error(`Instagram captions must be ${this.characterLimit} characters or fewer.`);let s=await this.graph(`/${r}/media`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({image_url:i.url,caption:t.text}).toString()},e.accessToken);if(!s.id)throw new v("Instagram did not return a media container id.",400,JSON.stringify(s));let n=await this.graph(`/${r}/media_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:s.id}).toString()},e.accessToken),o=await this.graph(`/${n.id}?fields=permalink`,{method:"GET"},e.accessToken).catch(()=>{return});return{provider:this.provider,uri:n.id,url:o?.permalink}}async timeline(e,t={}){return{items:[]}}async graph(e,t,r){let i=new Headers(t.headers);if(r)i.set("authorization",`Bearer ${r}`);let s=await fetch(`${this.graphBase}/${this.graphVersion}${e}`,{...t,headers:i}),n=await s.text(),o={};try{o=n?JSON.parse(n):{}}catch{o={}}if(!s.ok||o?.error){let a=o?.error?.message||n||s.statusText;throw new v(`Instagram API failed (${s.status}): ${a}`,s.status,n)}return o}}class f extends Error{status;body;constructor(e,t,r){super(e);this.status=t;this.body=r;this.name="LinkedInApiError"}get isAuthError(){return this.status===401||this.status===403}}class G{provider="linkedin";characterLimit=3000;apiVersion;authBase;apiBase;constructor(e={}){this.apiVersion=e.apiVersion||"202405",this.authBase=e.authBase||"https://www.linkedin.com",this.apiBase=e.apiBase||"https://api.linkedin.com"}getAuthUrl(e){let t=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(" "),state:e.state});return`${this.authBase}/oauth/v2/authorization?${t.toString()}`}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}),r=await this.request(`${this.authBase}/oauth/v2/accessToken`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:t.toString()});if(!r.access_token)throw new f("LinkedIn did not return an access token.",400,JSON.stringify(r));return{accessToken:r.access_token,expiresIn:r.expires_in,scope:r.scope}}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 f("LinkedIn profile is missing a subject id.",400,JSON.stringify(t));return{sub:t.sub,name:t.name,picture:t.picture}}async publish(e,t){if(!e.accessToken)throw Error("LinkedIn access token is missing for this identity.");let r=e.did;if(!r)throw Error("LinkedIn member URN is required to publish.");if(t.text.length>this.characterLimit)throw Error(`LinkedIn posts must be ${this.characterLimit} characters or fewer.`);let i={author:r,commentary:Ie(t.text),visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(t.external)i.content={article:{source:t.external.uri,title:t.external.title,description:t.external.description||""}};let s=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":"2.0.0"},body:JSON.stringify(i)}),n=await s.text();if(!s.ok)throw new f(`LinkedIn API failed (${s.status}): ${n||s.statusText}`,s.status,n);let o=s.headers.get("x-restli-id")||s.headers.get("x-linkedin-id")||"";return{provider:this.provider,uri:o,url:o?`https://www.linkedin.com/feed/update/${o}`:void 0}}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 member URN is required to list posts.");let i=Math.min(Math.max(t.limit||50,1),100),s=Number(t.cursor||0)||0,n=new URL(`${this.apiBase}/rest/posts`);n.searchParams.set("q","author"),n.searchParams.set("author",r),n.searchParams.set("count",String(i)),n.searchParams.set("start",String(s));let o;try{o=await this.request(n.toString(),{headers:{authorization:`Bearer ${e.accessToken}`,"linkedin-version":this.apiVersion,"x-restli-protocol-version":"2.0.0"}})}catch(c){if(c instanceof f&&(c.status===401||c.status===403))throw new f("LinkedIn will not list this account's posts - the Posts author finder needs the r_member_social permission, which this app does not hold.",c.status,c.body);throw c}let a=(o.elements||[]).filter((c)=>c?.id).map((c)=>({uri:String(c.id),text:c.commentary,postedAt:c.createdAt?new Date(c.createdAt).toISOString():void 0,url:`https://www.linkedin.com/feed/update/${c.id}`}));return{cursor:a.length===i?String(s+i):void 0,posts:a}}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":"2.0.0"}});if(!i.ok&&i.status!==404){let s=await i.text().catch(()=>"");throw new f(`LinkedIn API failed (${i.status}): ${s||i.statusText}`,i.status,s)}}async request(e,t){let r=await fetch(e,t),i=await r.text();if(!r.ok)throw new f(`LinkedIn API failed (${r.status}): ${i||r.statusText}`,r.status,i);return i?JSON.parse(i):{}}}function Ie(e){return e.replace(/[\\|{}@[\]()<>#*_~]/g,"\\$&")}class se extends Error{status;body;constructor(e,t,r){super(e);this.status=t;this.body=r;this.name="MastodonApiError"}get isAuthError(){return this.status===401||this.status===403}}function Te(e){let t=String(e||"").trim().replace(/\/+$/,"");if(!t)throw Error("Mastodon instance URL is required.");let r=/^https?:\/\//i.test(t)?t:`https://${t}`;try{let i=new URL(r);return`${i.protocol}//${i.host}`}catch{throw Error("Mastodon instance URL is invalid.")}}class M{provider="mastodon";characterLimit=500;instanceOf(e){return Te(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 uploadMedia(e,t,r,i){let s=new FormData;if(s.set("file",new Blob([new Uint8Array(t)],{type:r||"image/jpeg"}),"upload"),i)s.set("description",i);return(await this.request(`${this.instanceOf(e)}/api/v2/media`,{method:"POST",headers:{authorization:`Bearer ${this.tokenOf(e)}`},body:s})).id}async publish(e,t){let r=this.instanceOf(e),i=this.tokenOf(e);if(t.text.length>this.characterLimit)throw Error(`Mastodon posts must be ${this.characterLimit} characters or fewer.`);let s=[];for(let a of(t.media||[]).slice(0,4)){let{bytes:c,mimeType:u}=a;if(!c?.length&&a.url){let p=await fetch(a.url);if(!p.ok)continue;c=new Uint8Array(await p.arrayBuffer()),u=u||p.headers.get("content-type")||"image/jpeg"}if(c?.length)s.push(await this.uploadMedia(e,c,u||"image/jpeg",a.altText))}let n={status:t.text,visibility:"public"};if(s.length)n.media_ids=s;if(t.reply?.parent?.uri)n.in_reply_to_id=t.reply.parent.uri;let o=await this.request(`${r}/api/v1/statuses`,{method:"POST",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:JSON.stringify(n)});return{provider:this.provider,uri:o.id,cid:o.id,url:o.url||o.uri}}async timeline(e,t={}){return{items:[]}}async listAuthoredPosts(e,t={}){let r=this.instanceOf(e),{accountId:i}=await this.verifyCredentials(e),s=new URL(`${r}/api/v1/accounts/${encodeURIComponent(i)}/statuses`);if(s.searchParams.set("limit",String(Math.min(Math.max(t.limit||40,1),40))),s.searchParams.set("exclude_reblogs","true"),t.cursor)s.searchParams.set("max_id",t.cursor);let o=(await this.request(s.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||xe(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 request(e,t){let r=await fetch(e,t),i=await r.text();if(!r.ok)throw new se(`Mastodon API failed (${r.status}): ${i||r.statusText}`,r.status,i);return i?JSON.parse(i):{}}}function xe(e){return String(e||"").replace(/\/+$/,"").split("/").pop()||""}class k extends Error{status;body;constructor(e,t,r){super(e);this.status=t;this.body=r;this.name="ThreadsApiError"}get isAuthError(){return this.status===401||this.status===403||this.status===190}}class F{provider="threads";characterLimit=500;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()}),r=await t.text(),i={};try{i=r?JSON.parse(r):{}}catch{i={}}if(!t.ok||i?.error||!i?.access_token){let s=i?.error_message||i?.error?.message||r||t.statusText;throw new k(`Threads token exchange failed (${t.status}): ${s}`,t.status,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 k("Could not resolve the Threads account for this token.",400,JSON.stringify(r));return{threadsUserId:r.id,username:r.username,accessToken:e}}async publish(e,t){if(!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(t.text.length>this.characterLimit)throw Error(`Threads posts must be ${this.characterLimit} characters or fewer.`);let i=t.media?.[0],s=new URLSearchParams({text:t.text});if(i?.url)s.set("media_type","IMAGE"),s.set("image_url",i.url);else s.set("media_type","TEXT");let n=await this.graph(`/${r}/threads`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:s.toString()},e.accessToken);if(!n.id)throw new k("Threads did not return a media container id.",400,JSON.stringify(n));let o=await this.graph(`/${r}/threads_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:n.id}).toString()},e.accessToken);if(!o.id)throw new k("Threads did not return a published post id.",400,JSON.stringify(o));let a=await this.graph(`/${o.id}?fields=permalink`,{method:"GET"},e.accessToken).catch(()=>{return});return{provider:this.provider,uri:o.id,url:a?.permalink}}async timeline(e,t={}){return{items:[]}}async graph(e,t,r){let i=new Headers(t.headers);if(r)i.set("authorization",`Bearer ${r}`);let s=await fetch(`${this.graphBase}/${this.graphVersion}${e}`,{...t,headers:i}),n=await s.text(),o={};try{o=n?JSON.parse(n):{}}catch{o={}}if(!s.ok||o?.error){let a=o?.error?.message||n||s.statusText;throw new k(`Threads API failed (${s.status}): ${a}`,s.status,n)}return o}}import{Buffer as _e}from"buffer";import{createHash as Ce,randomBytes as Ue}from"crypto";import{fetcher as ne}from"@stacksjs/api";import{config as A}from"@stacksjs/config";class K extends g{baseUrl="https://twitter.com";apiUrl="https://api.twitter.com";codeVerifier=null;getConfig(){let e={clientId:A.services.twitter?.clientId??"",clientSecret:A.services.twitter?.clientSecret??"",redirectUrl:A.services.twitter?.redirectUrl??"",scopes:A.services.twitter?.scopes??["users.read","tweet.read"]};return this.setScopes(e.scopes),e}generateCodeVerifier(){return Ue(32).toString("base64").replace(/[^a-z0-9]/gi,"").substring(0,128)}generateCodeChallenge(e){return Ce("sha256").update(e).digest("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async getAuthUrl(){let e=this.getState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();this.validateConfig(),this.codeVerifier=this.generateCodeVerifier();let s=this.generateCodeChallenge(this.codeVerifier);return`${this.baseUrl}/i/oauth2/authorize?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(" "),state:e,response_type:"code",code_challenge:s,code_challenge_method:"S256"}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();if(this.validateConfig(),!this.codeVerifier)throw Error("Code verifier not found. Please ensure getAuthUrl() is called first.");let s=_e.from(`${t}:${r}`).toString("base64"),n=await ne.withHeaders({Authorization:`Basic ${s}`,"Content-Type":"application/x-www-form-urlencoded"}).post(`${this.apiUrl}/2/oauth2/token`,{code:e,grant_type:"authorization_code",redirect_uri:i,code_verifier:this.codeVerifier});if(n.data.error)throw Error(`Twitter OAuth error: ${n.data.error_description}`);return n.data.access_token}async getUserByToken(e){let t=await ne.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 d("Twitter client ID not provided");if(!t)throw new d("Twitter client secret not provided");if(!r)throw new d("Twitter redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/2/oauth2/token`}}class y extends Error{status;body;constructor(e,t,r){super(e);this.status=t;this.body=r;this.name="TwitterApiError"}get isAuthError(){return this.status===401||this.status===403}}function oe(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}class b{provider="twitter";characterLimit=280;apiBase;authorizeBase;constructor(e={}){this.apiBase=e.apiBase||"https://api.twitter.com",this.authorizeBase=e.authorizeBase||"https://twitter.com"}async createAuthorization(e){let t=oe(crypto.getRandomValues(new Uint8Array(32))),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),i=oe(new Uint8Array(r)),s=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:e.redirectUrl,scope:e.scopes.join(" "),state:e.state,code_challenge:i,code_challenge_method:"S256"});return{url:`${this.authorizeBase}/i/oauth2/authorize?${s.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`,{headers:{authorization:`Bearer ${e}`}});if(!t.data?.id||!t.data.username)throw new y("Twitter did not return the authenticated user.",400,JSON.stringify(t));return{id:t.data.id,username:t.data.username,name:t.data.name}}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 s=await this.request(`${this.apiBase}/2/media/upload`,{method:"POST",headers:{authorization:`Bearer ${e}`},body:i}),n=s.data?.id||s.media_id_string||s.id;if(!n)throw new y("Twitter did not return a media id.",400,JSON.stringify(s));return n}async publish(e,t){if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");if(t.text.length>this.characterLimit)throw Error(`Twitter posts must be ${this.characterLimit} characters or fewer.`);let r=[],i=t.media?.[0];if(i){let{bytes:a,mimeType:c}=i;if(!a?.length&&i.url){let u=await fetch(i.url);if(u.ok)a=new Uint8Array(await u.arrayBuffer()),c=c||u.headers.get("content-type")||"image/jpeg"}if(a?.length)r.push(await this.uploadMedia(e.accessToken,a,c||"image/jpeg"))}let s={text:t.text};if(r.length)s.media={media_ids:r};if(t.reply?.parent?.uri)s.reply={in_reply_to_tweet_id:t.reply.parent.uri};let n=await this.request(`${this.apiBase}/2/tweets`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json"},body:JSON.stringify(s)}),o=n.data?.id;if(!o)throw new y("Twitter did not return a tweet id.",400,JSON.stringify(n));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}`}}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 s=await this.request(i.toString(),{headers:{authorization:`Bearer ${e.accessToken}`}});return{cursor:s.meta?.next_token,posts:(s.data||[]).filter((n)=>n?.id).map((n)=>({uri:n.id,cid:n.id,text:n.text,postedAt:n.created_at,url:`https://x.com/i/web/status/${n.id}`}))}}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 this.request(`${this.apiBase}/2/tweets/${encodeURIComponent(r)}`,{method:"DELETE",headers:{authorization:`Bearer ${e.accessToken}`}});if(i.data&&i.data.deleted===!1)throw new y(`X refused to delete tweet ${r}.`,400,JSON.stringify(i))}async tokenRequest(e,t,r){let i={"content-type":"application/x-www-form-urlencoded"};if(r)i.authorization=`Basic ${btoa(`${t}:${r}`)}`;let s=await this.request(`${this.apiBase}/2/oauth2/token`,{method:"POST",headers:i,body:e.toString()});if(!s.access_token)throw new y("Twitter did not return an access token.",400,JSON.stringify(s));return{accessToken:s.access_token,refreshToken:s.refresh_token,expiresIn:s.expires_in,scope:s.scope}}async request(e,t){let r=await fetch(e,t),i=await r.text();if(!r.ok)throw new y(`Twitter API failed (${r.status}): ${i||r.statusText}`,r.status,i);return i?JSON.parse(i):{}}}import{config as Re}from"@stacksjs/config";var E=["clientId","clientSecret","redirectUrl"],I=Object.freeze({google:{name:"google",label:"Google",driver:J,required:E,postCallback:!1},github:{name:"github",label:"GitHub",driver:H,required:E,postCallback:!1},facebook:{name:"facebook",label:"Facebook",driver:q,required:E,postCallback:!1},twitter:{name:"twitter",label:"X",driver:K,required:E,postCallback:!1},apple:{name:"apple",label:"Apple",driver:N,required:["clientId","teamId","keyId","privateKey","redirectUrl"],postCallback:!0}});function ae(e){return Re?.services?.[e]}function $e(e){return typeof e==="string"&&e in I}function ce(e){if(!$e(e))return!1;let t=ae(e);if(!t)return!1;return I[e].required.every((r)=>Boolean(t[r]))}function qt(){return Object.keys(I).filter(ce).map((e)=>I[e])}function zt(e){if(!ce(e))return null;let t=I[e],r=ae(e)??{};return new t.driver({clientSecret:"",...r,clientId:String(r.clientId??""),redirectUrl:String(r.redirectUrl??"")})}class Ae{accessToken;refreshToken;expiresIn;approvedScopes;constructor(e,t=null,r=null,i=[]){this.accessToken=e;this.refreshToken=t;this.expiresIn=r;this.approvedScopes=i}}function jt(e){return typeof e?.deletePost==="function"}function Gt(e){return typeof e?.listAuthoredPosts==="function"}import{buildSessionHandoffUrl as Ee}from"@stacksjs/composables";function de(e,t=[]){if(!e)return!1;if(e.startsWith("//"))return!1;if(e.startsWith("/"))return!0;try{let r=new URL(e);if(r.protocol!=="http:"&&r.protocol!=="https:")return!1;return t.includes(r.host)}catch{return!1}}function Kt(e,t={}){let r=t.redirectTo??"/";if(!de(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:Ee(r,e),"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function Qt(e,t={}){let r=t.redirectTo??"/login";if(!de(r,t.allowedHosts??[]))throw Error(`[socials] refusing to redirect to ${r}`);let i=r.includes("?")?"&":"?",s=`${r}${i}social_error=${encodeURIComponent(e)}`;return new Response(null,{status:302,headers:{Location:s,"Cache-Control":"no-store"}})}var Oe={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"]},Be={bluesky:["identifier","password"],twitter:["clientId","clientSecret","accessToken"],linkedin:["accessToken","memberUrn"],mastodon:["accessToken","instanceUrl"],instagram:["accessToken","accountId"],threads:["accessToken","userId"]};function Le(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function O(e,t,r){let i=r.replace(/[A-Z]/g,(s)=>`_${s}`).toUpperCase();return`SOCIALS_${Le(e)}_${t.toUpperCase()}_${i}`}class h extends Error{constructor(e){super(e);this.name="SocialIdentityError"}}async function B(){let{config:e,overridesReady:t}=await import("@stacksjs/config");return await t,e.socials??{}}function le(e,t){let r=Object.keys(e.identities??{});if(t){if(!r.includes(t))throw new h(`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 h(`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 h("config/socials.ts declares no identities, so there is no account to post as.");throw new h(`config/socials.ts declares ${r.length} identities (${r.join(", ")}) and no default, so a call has to name one.`)}function De(e,t,r,i=process.env){let n=(e.identities?.[r]??{}).credentials?.[t]??{},o={};for(let a of Oe[t]){let c=(n[a]??i[O(r,t,a)]??"").trim();if(c)o[a]=c}return o}function Q(e,t,r,i=process.env){let s=le(e,r),n=De(e,t,s,i),o=Be[t].filter((a)=>!n[a]);if(o.length){let a=o.map((c)=>O(s,t,c)).join(", ");throw new h(`Identity '${s}' is not configured for ${t}: ${o.join(", ")} ${o.length===1?"is":"are"} missing. Set ${a}, or supply them inline in config/socials.ts.`)}return n}async function ue(e){return le(await B(),e)}async function P(e,t,r){return Q(await B(),e,t,r)}function Zt(e,t){return P("bluesky",e,t)}function Xt(e,t){return P("twitter",e,t)}function Yt(e,t){return P("linkedin",e,t)}function er(e,t){return P("mastodon",e,t)}function tr(e,t){return P("instagram",e,t)}function rr(e,t){return P("threads",e,t)}import{randomBytes as Ve}from"crypto";function ar(e){return e==="twitter"}var Ne=["tweet.read","tweet.write","users.read","offline.access"],qe="127.0.0.1",pe="/callback";function cr(e){if(!Number.isInteger(e)||e<1||e>65535)throw new h(`${e} is not a port a redirect can listen on.`);return`http://${qe}:${e}${pe}`}function dr(){return Ve(16).toString("hex")}function lr(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!==pe)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 s=r.searchParams.get("state")??"";if(!t||s!==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("code")??"";if(!n)return{ok:!1,reason:"no-code",message:"The redirect carried no authorization code."};return{ok:!0,code:n}}function ur(e,t,r){let i=[];for(let[s,n]of Object.entries(r)){if(!n)continue;i.push(`${O(e,t,s)}=${n}`)}return i}async function pr(e){let t=new b,r=await t.exchangeCode(e);if(!r.accessToken)throw new h("X returned no access token for that code.");let i=Boolean(r.refreshToken),s=await t.getProfile(r.accessToken);return{handle:s.username,accountId:s.id,accessToken:r.accessToken,refreshToken:r.refreshToken,expiresIn:r.expiresIn,scope:r.scope,renewable:i}}async function hr(e){return new b().createAuthorization({clientId:e.clientId,redirectUrl:e.redirectUrl,scopes:[...Ne],state:e.state})}function gr(e,t){let r=(i)=>i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");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 ze={bluesky:null,twitter:null,linkedin:"memberUrn",mastodon:"instanceUrl",instagram:"accountId",threads:"userId"};function He(e,t){if(e==="bluesky")return t.service?{service:t.service}:{};if(e==="linkedin")return t.apiVersion?{apiVersion:t.apiVersion}:{};return{}}function Je(e,t={}){switch(e){case"bluesky":return new _(t);case"linkedin":return new G(t);case"twitter":return new b;case"mastodon":return new M;case"instagram":return new j;case"threads":return new F;default:throw new h(`No publishing driver for '${String(e)}'.`)}}function je(e,t,r){let i=ze[e],s={handle:(t??"").trim()};if(r.accessToken)s.accessToken=r.accessToken;if(r.refreshToken)s.refreshToken=r.refreshToken;if(i&&r[i])s.did=r[i];return s}function Ge(e,t,r){if(!r)return;if(r.includes(t))return;throw new h(`Identity '${e}' is not set up for ${t}. config/socials.ts lists: ${r.length?r.join(", "):"none"}.`)}async function Me(e,t,r){let i=await B(),s=await ue(t),n=i.identities?.[s]??{};Ge(s,e,n.platforms);let o=Q(i,e,s,r),a=He(e,o);if(e==="bluesky"){let c=await new _(a).createSession({identifier:o.identifier,password:o.password});return{name:s,platform:e,identity:{handle:c.handle,did:c.did,accessToken:c.accessJwt,refreshToken:c.refreshJwt},options:a}}return{name:s,platform:e,identity:je(e,n.handle??"",o),options:a}}async function wr(e,t,r,i){let s=await Me(e,r,i);return Je(s.platform,s.options).publish(s.identity,t)}export{qe as AUTHORIZE_HOST,pe as AUTHORIZE_PATH,g as AbstractProvider,N as AppleProvider,te as BlueskyApiError,_ as BlueskyPublishingDriver,d as ConfigException,ze as DRIVER_DID_FIELD,q as FacebookProvider,H as GitHubProvider,J as GoogleProvider,v as InstagramApiError,j as InstagramPublishingDriver,fe as InvalidStateException,f as LinkedInApiError,G as LinkedInPublishingDriver,C as META_GRAPH_VERSION,se as MastodonApiError,M as MastodonPublishingDriver,Be as REQUIRED_SOCIAL_CREDENTIALS,Oe as SOCIAL_CREDENTIAL_FIELDS,I as SOCIAL_PROVIDERS,h as SocialIdentityError,Ne as TWITTER_PUBLISH_SCOPES,k as ThreadsApiError,F as ThreadsPublishingDriver,Ae as Token,y as TwitterApiError,K as TwitterProvider,b as TwitterPublishingDriver,Ge as assertPlatformDeclared,gr as callbackPage,cr as callbackUri,pr as completeTwitterAuthorization,qt as configuredSocialProviders,ve as detectFacetCandidates,He as driverOptions,ur as envLines,O as envName,Le as envSegment,Ie as escapeLinkedInText,ar as isAuthorizablePlatform,de as isSafeHandoffTarget,ce as isSocialProviderConfigured,$e as isSocialProviderName,dr as newState,Te as normalizeInstance,Pe as parseAtUri,Q as pickCredentials,le as pickIdentity,wr as publishAs,Je as publishingDriver,lr as readCallback,De as readCredentials,Zt as resolveBlueskyCredentials,ue as resolveIdentityName,tr as resolveInstagramCredentials,Yt as resolveLinkedInCredentials,er as resolveMastodonCredentials,P as resolveSocialCredentials,rr as resolveThreadsCredentials,Xt as resolveTwitterCredentials,Qt as socialHandoffFailureRedirect,Kt as socialHandoffRedirect,zt as socialProvider,Me as socialPublishTarget,B as socialsConfig,hr as startTwitterAuthorization,jt as supportsDeletion,Gt as supportsEnumeration,je as toDriverIdentity};
|
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.
|
|
5
|
+
"version": "0.75.188",
|
|
6
6
|
"description": "A simple and elegant social authentication package for Stacks.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -57,13 +57,13 @@
|
|
|
57
57
|
"prepublishOnly": "bun run build"
|
|
58
58
|
},
|
|
59
59
|
"dependencies": {
|
|
60
|
-
"@stacksjs/api": "0.75.
|
|
61
|
-
"@stacksjs/composables": "0.75.
|
|
62
|
-
"@stacksjs/config": "0.75.
|
|
60
|
+
"@stacksjs/api": "0.75.188",
|
|
61
|
+
"@stacksjs/composables": "0.75.188",
|
|
62
|
+
"@stacksjs/config": "0.75.188"
|
|
63
63
|
},
|
|
64
64
|
"devDependencies": {
|
|
65
|
-
"@stacksjs/error-handling": "0.75.
|
|
66
|
-
"@stacksjs/router": "0.75.
|
|
65
|
+
"@stacksjs/error-handling": "0.75.188",
|
|
66
|
+
"@stacksjs/router": "0.75.188",
|
|
67
67
|
"better-dx": "^0.2.24"
|
|
68
68
|
}
|
|
69
69
|
}
|