@stacksjs/socials 0.75.663 → 0.75.667
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/drivers/bluesky.d.ts +8 -0
- package/dist/drivers/instagram.d.ts +8 -0
- package/dist/drivers/linkedin.d.ts +39 -1
- package/dist/drivers/mastodon.d.ts +21 -6
- package/dist/drivers/threads.d.ts +12 -0
- package/dist/drivers/twitter.d.ts +7 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -2
- package/dist/media.d.ts +44 -0
- package/dist/publish-errors.d.ts +44 -0
- package/dist/text.d.ts +33 -0
- package/dist/types.d.ts +2 -0
- package/package.json +8 -7
|
@@ -4,12 +4,20 @@ import type { AuthoredPostPage, BlueskySession, BlueskySessionCredentials, Publi
|
|
|
4
4
|
* repo + collection + rkey, not by the AT-URI itself.
|
|
5
5
|
*/
|
|
6
6
|
export declare function parseAtUri(uri: string): { repo: string, collection: string, rkey: string };
|
|
7
|
+
/** Whether `error` means the Bluesky session has to be refreshed or the account reconnected. */
|
|
8
|
+
export declare function isBlueskySessionError(error: unknown): boolean;
|
|
7
9
|
/**
|
|
8
10
|
* Find link/hashtag/mention spans in post text with UTF-8 byte offsets
|
|
9
11
|
* (ATProto facet ranges are byte-indexed, not character-indexed).
|
|
10
12
|
* Mentions still need their DID resolved before they become facets.
|
|
11
13
|
*/
|
|
12
14
|
export declare function detectFacetCandidates(text: string): FacetCandidate[];
|
|
15
|
+
/** Bluesky refuses a blob over this size. */
|
|
16
|
+
export declare const BLUESKY_MAX_BLOB_BYTES: 1000000;
|
|
17
|
+
/** Bluesky holds up to four images in one post. */
|
|
18
|
+
export declare const BLUESKY_MAX_IMAGES: 4;
|
|
19
|
+
/** Bluesky keeps up to three languages on a post. */
|
|
20
|
+
export declare const BLUESKY_MAX_LANGS: 3;
|
|
13
21
|
export declare interface BlueskyDriverOptions {
|
|
14
22
|
service?: string
|
|
15
23
|
}
|
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
import type { PublishedPost, PublishPostInput, SocialIdentityCredentials, SocialPublishingDriver, TimelineQuery, TimelineResult } from '../types';
|
|
2
|
+
/** Items Instagram takes in one carousel. */
|
|
3
|
+
export declare const INSTAGRAM_MAX_IMAGES: 10;
|
|
4
|
+
export declare interface InstagramLongLivedToken {
|
|
5
|
+
accessToken: string
|
|
6
|
+
expiresIn?: number
|
|
7
|
+
}
|
|
2
8
|
export declare interface InstagramDriverOptions {
|
|
3
9
|
graphVersion?: string
|
|
4
10
|
authBase?: string
|
|
@@ -39,6 +45,7 @@ export declare class InstagramPublishingDriver implements SocialPublishingDriver
|
|
|
39
45
|
readonly provider: 'instagram';
|
|
40
46
|
/** @defaultValue 2200 */
|
|
41
47
|
characterLimit: number;
|
|
48
|
+
maxImages: unknown;
|
|
42
49
|
protected graphVersion: string;
|
|
43
50
|
protected authBase: string;
|
|
44
51
|
protected graphBase: string;
|
|
@@ -46,6 +53,7 @@ export declare class InstagramPublishingDriver implements SocialPublishingDriver
|
|
|
46
53
|
getAuthUrl(input: InstagramAuthUrlInput): string;
|
|
47
54
|
exchangeCode(input: InstagramTokenExchangeInput): Promise<{ accessToken: string, expiresIn?: number }>;
|
|
48
55
|
resolveAccount(accessToken: string): Promise<InstagramAccount>;
|
|
56
|
+
exchangeLongLivedUserToken(clientId: string, clientSecret: string, shortLivedToken: string): Promise<InstagramLongLivedToken>;
|
|
49
57
|
publish(identity: SocialIdentityCredentials, post: PublishPostInput): Promise<PublishedPost>;
|
|
50
58
|
timeline(_identity: SocialIdentityCredentials, _query?: TimelineQuery): Promise<TimelineResult>;
|
|
51
59
|
protected graph<T>(path: string, init: RequestInit, token?: string): Promise<T>;
|
|
@@ -1,10 +1,36 @@
|
|
|
1
1
|
import type { AuthoredPostPage, PublishedPost, PublishPostInput, RemotePostRef, SocialDeletionDriver, SocialIdentityCredentials, SocialPublishingDriver, TimelineQuery, TimelineResult } from '../types';
|
|
2
|
+
/** When LinkedIn retires a `YYYYMM` version: a year on, mid-month. */
|
|
3
|
+
export declare function linkedInVersionSunset(version: string): Date;
|
|
4
|
+
/**
|
|
5
|
+
* The version to send. One that is configured is honoured unless LinkedIn
|
|
6
|
+
* has already retired it: a stale line left in configuration would otherwise
|
|
7
|
+
* break every LinkedIn call with no hint as to why.
|
|
8
|
+
*/
|
|
9
|
+
export declare function resolveLinkedInVersion(wanted: unknown, nowMs?: number): string;
|
|
2
10
|
/**
|
|
3
11
|
* Escape the reserved characters of LinkedIn's "little text" commentary format
|
|
4
12
|
* so the literal text renders as typed. Without this, characters like `(` `)`
|
|
5
|
-
* `@`
|
|
13
|
+
* `@` cause the share to be rejected with a 400.
|
|
14
|
+
*
|
|
15
|
+
* A hashtag is the exception: `#word` is itself an element of the format, so
|
|
16
|
+
* escaping its `#` turned every hashtag into plain text. A `#` that does not
|
|
17
|
+
* start a word (as in "issue # 4", "#1" or "C#") is still escaped.
|
|
6
18
|
*/
|
|
7
19
|
export declare function escapeLinkedInText(text: string): string;
|
|
20
|
+
/**
|
|
21
|
+
* The `LinkedIn-Version` sent unless a driver is given another.
|
|
22
|
+
*
|
|
23
|
+
* LinkedIn publishes a version every month and retires each one a year
|
|
24
|
+
* later. A retired version is answered with an error, so every LinkedIn call
|
|
25
|
+
* fails at once: the previous default, 202405, had been retired since May
|
|
26
|
+
* 2025. A test fails two months before this one is retired, while there is
|
|
27
|
+
* still time to move.
|
|
28
|
+
*/
|
|
29
|
+
export declare const LINKEDIN_API_VERSION: '202611';
|
|
30
|
+
/** Images LinkedIn takes in one multi-image post. */
|
|
31
|
+
export declare const LINKEDIN_MAX_IMAGES: 20;
|
|
32
|
+
/** LinkedIn's limit for an image's alt text. */
|
|
33
|
+
export declare const LINKEDIN_MAX_ALT_TEXT: 4086;
|
|
8
34
|
export declare interface LinkedInDriverOptions {
|
|
9
35
|
apiVersion?: string
|
|
10
36
|
authBase?: string
|
|
@@ -26,6 +52,13 @@ export declare interface LinkedInTokenResponse {
|
|
|
26
52
|
accessToken: string
|
|
27
53
|
expiresIn?: number
|
|
28
54
|
scope?: string
|
|
55
|
+
refreshToken?: string
|
|
56
|
+
refreshTokenExpiresIn?: number
|
|
57
|
+
}
|
|
58
|
+
export declare interface LinkedInRefreshInput {
|
|
59
|
+
clientId: string
|
|
60
|
+
clientSecret: string
|
|
61
|
+
refreshToken: string
|
|
29
62
|
}
|
|
30
63
|
export declare interface LinkedInProfile {
|
|
31
64
|
sub: string
|
|
@@ -50,13 +83,18 @@ export declare class LinkedInPublishingDriver implements SocialPublishingDriver,
|
|
|
50
83
|
readonly provider: 'linkedin';
|
|
51
84
|
/** @defaultValue 3000 */
|
|
52
85
|
characterLimit: number;
|
|
86
|
+
maxImages: unknown;
|
|
87
|
+
fetchImage: unknown;
|
|
53
88
|
protected apiVersion: string;
|
|
54
89
|
protected authBase: string;
|
|
55
90
|
protected apiBase: string;
|
|
56
91
|
constructor(options?: LinkedInDriverOptions);
|
|
57
92
|
getAuthUrl(input: LinkedInAuthUrlInput): string;
|
|
58
93
|
exchangeCode(input: LinkedInTokenExchangeInput): Promise<LinkedInTokenResponse>;
|
|
94
|
+
refreshAccessToken(input: LinkedInRefreshInput): Promise<LinkedInTokenResponse>;
|
|
95
|
+
protected tokenRequest(body: URLSearchParams, missing: string): Promise<LinkedInTokenResponse>;
|
|
59
96
|
getProfile(accessToken: string): Promise<LinkedInProfile>;
|
|
97
|
+
uploadImage(accessToken: string, owner: string, bytes: Uint8Array, mimeType?: string): Promise<string>;
|
|
60
98
|
publish(identity: SocialIdentityCredentials, post: PublishPostInput): Promise<PublishedPost>;
|
|
61
99
|
timeline(_identity: SocialIdentityCredentials, _query?: TimelineQuery): Promise<TimelineResult>;
|
|
62
100
|
listAuthoredPosts(identity: SocialIdentityCredentials, query?: TimelineQuery): Promise<AuthoredPostPage>;
|
|
@@ -1,12 +1,28 @@
|
|
|
1
1
|
import type { AuthoredPostPage, PublishedPost, PublishPostInput, RemotePostRef, SocialDeletionDriver, SocialIdentityCredentials, SocialPublishingDriver, TimelineQuery, TimelineResult } from '../types';
|
|
2
2
|
/** Normalize "mastodon.social" / "https://mastodon.social/" → "https://mastodon.social". */
|
|
3
3
|
export declare function normalizeInstance(value: string): string;
|
|
4
|
+
/** Mastodon's own defaults, for an instance that does not say. */
|
|
5
|
+
export declare const MASTODON_DEFAULT_LIMITS: MastodonLimits;
|
|
4
6
|
export declare interface MastodonAccount {
|
|
5
7
|
accountId: string
|
|
6
8
|
username: string
|
|
7
9
|
displayName?: string
|
|
8
10
|
url: string
|
|
9
11
|
}
|
|
12
|
+
/** What only Mastodon takes, as the third argument to `publish`. */
|
|
13
|
+
export declare interface MastodonPublishOptions {
|
|
14
|
+
idempotencyKey?: string
|
|
15
|
+
visibility?: MastodonVisibility
|
|
16
|
+
spoilerText?: string
|
|
17
|
+
language?: string
|
|
18
|
+
}
|
|
19
|
+
/** One instance's posting limits, from `/api/v2/instance`. */
|
|
20
|
+
export declare interface MastodonLimits {
|
|
21
|
+
characters: number
|
|
22
|
+
charactersPerUrl: number
|
|
23
|
+
mediaAttachments: number
|
|
24
|
+
}
|
|
25
|
+
export type MastodonVisibility = 'public' | 'unlisted' | 'private' | 'direct';
|
|
10
26
|
export declare class MastodonApiError extends Error {
|
|
11
27
|
public status: number;
|
|
12
28
|
public body: string;
|
|
@@ -26,16 +42,15 @@ export declare class MastodonApiError extends Error {
|
|
|
26
42
|
*/
|
|
27
43
|
export declare class MastodonPublishingDriver implements SocialPublishingDriver, SocialDeletionDriver {
|
|
28
44
|
readonly provider: 'mastodon';
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
characterLimit: number;
|
|
45
|
+
characterLimit: unknown;
|
|
46
|
+
fetchImage: unknown;
|
|
47
|
+
private limits;
|
|
48
|
+
instanceLimits(identity: SocialIdentityCredentials): Promise<MastodonLimits>;
|
|
34
49
|
protected instanceOf(identity: SocialIdentityCredentials): string;
|
|
35
50
|
protected tokenOf(identity: SocialIdentityCredentials): string;
|
|
36
51
|
verifyCredentials(identity: SocialIdentityCredentials): Promise<MastodonAccount>;
|
|
37
52
|
uploadMedia(identity: SocialIdentityCredentials, bytes: Uint8Array, mimeType: string, altText?: string): Promise<string>;
|
|
38
|
-
publish(identity: SocialIdentityCredentials, post: PublishPostInput): Promise<PublishedPost>;
|
|
53
|
+
publish(identity: SocialIdentityCredentials, post: PublishPostInput, options?: MastodonPublishOptions): Promise<PublishedPost>;
|
|
39
54
|
timeline(_identity: SocialIdentityCredentials, _query?: TimelineQuery): Promise<TimelineResult>;
|
|
40
55
|
listAuthoredPosts(identity: SocialIdentityCredentials, query?: TimelineQuery): Promise<AuthoredPostPage>;
|
|
41
56
|
deletePost(identity: SocialIdentityCredentials, ref: RemotePostRef): Promise<void>;
|
|
@@ -1,4 +1,12 @@
|
|
|
1
1
|
import type { PublishedPost, PublishPostInput, SocialIdentityCredentials, SocialPublishingDriver, TimelineQuery, TimelineResult } from '../types';
|
|
2
|
+
/** Items Threads takes in one carousel. */
|
|
3
|
+
export declare const THREADS_MAX_IMAGES: 20;
|
|
4
|
+
/** Threads' limit for an image description. */
|
|
5
|
+
export declare const THREADS_MAX_ALT_TEXT: 1000;
|
|
6
|
+
export declare interface ThreadsLongLivedToken {
|
|
7
|
+
accessToken: string
|
|
8
|
+
expiresIn?: number
|
|
9
|
+
}
|
|
2
10
|
export declare interface ThreadsDriverOptions {
|
|
3
11
|
graphVersion?: string
|
|
4
12
|
authBase?: string
|
|
@@ -40,6 +48,7 @@ export declare class ThreadsPublishingDriver implements SocialPublishingDriver {
|
|
|
40
48
|
readonly provider: 'threads';
|
|
41
49
|
/** @defaultValue 500 */
|
|
42
50
|
characterLimit: number;
|
|
51
|
+
maxImages: unknown;
|
|
43
52
|
protected graphVersion: string;
|
|
44
53
|
protected authBase: string;
|
|
45
54
|
protected graphBase: string;
|
|
@@ -47,7 +56,10 @@ export declare class ThreadsPublishingDriver implements SocialPublishingDriver {
|
|
|
47
56
|
getAuthUrl(input: ThreadsAuthUrlInput): string;
|
|
48
57
|
exchangeCode(input: ThreadsTokenExchangeInput): Promise<{ accessToken: string, userId?: string, expiresIn?: number }>;
|
|
49
58
|
resolveAccount(accessToken: string): Promise<ThreadsAccount>;
|
|
59
|
+
exchangeLongLivedToken(clientSecret: string, shortLivedToken: string): Promise<ThreadsLongLivedToken>;
|
|
60
|
+
refreshLongLivedToken(accessToken: string): Promise<ThreadsLongLivedToken>;
|
|
50
61
|
publish(identity: SocialIdentityCredentials, post: PublishPostInput): Promise<PublishedPost>;
|
|
51
62
|
timeline(_identity: SocialIdentityCredentials, _query?: TimelineQuery): Promise<TimelineResult>;
|
|
63
|
+
protected tokenRequest(path: string, body: URLSearchParams): Promise<ThreadsLongLivedToken>;
|
|
52
64
|
protected graph<T>(path: string, init: RequestInit, token?: string): Promise<T>;
|
|
53
65
|
}
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { AbstractProvider } from '../abstract';
|
|
2
2
|
import type { AuthoredPostPage, ProviderInterface, PublishedPost, PublishPostInput, RemotePostRef, SocialDeletionDriver, SocialIdentityCredentials, SocialPublishingDriver, SocialUser, TimelineQuery, TimelineResult } from '../types';
|
|
3
|
+
/** X attaches up to four images to a post. */
|
|
4
|
+
export declare const X_MAX_IMAGES: 4;
|
|
5
|
+
/** X's limit for an image description. */
|
|
6
|
+
export declare const X_MAX_ALT_TEXT: 1000;
|
|
3
7
|
export declare interface TwitterDriverOptions {
|
|
4
8
|
apiBase?: string
|
|
5
9
|
authorizeBase?: string
|
|
@@ -73,6 +77,8 @@ export declare class TwitterPublishingDriver implements SocialPublishingDriver,
|
|
|
73
77
|
readonly provider: 'twitter';
|
|
74
78
|
/** @defaultValue 280 */
|
|
75
79
|
characterLimit: number;
|
|
80
|
+
maxImages: unknown;
|
|
81
|
+
fetchImage: unknown;
|
|
76
82
|
protected apiBase: string;
|
|
77
83
|
protected authorizeBase: string;
|
|
78
84
|
constructor(options?: TwitterDriverOptions);
|
|
@@ -81,6 +87,7 @@ export declare class TwitterPublishingDriver implements SocialPublishingDriver,
|
|
|
81
87
|
refreshAccessToken(input: TwitterRefreshInput): Promise<TwitterToken>;
|
|
82
88
|
getProfile(accessToken: string): Promise<TwitterProfile>;
|
|
83
89
|
uploadMedia(accessToken: string, bytes: Uint8Array, mimeType: string): Promise<string>;
|
|
90
|
+
describeMedia(accessToken: string, mediaId: string, altText: string): Promise<boolean>;
|
|
84
91
|
publish(identity: SocialIdentityCredentials, post: PublishPostInput): Promise<PublishedPost>;
|
|
85
92
|
timeline(_identity: SocialIdentityCredentials, _query?: TimelineQuery): Promise<TimelineResult>;
|
|
86
93
|
listAuthoredPosts(identity: SocialIdentityCredentials, query?: TimelineQuery): Promise<AuthoredPostPage>;
|
package/dist/index.d.ts
CHANGED
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,t={}){let{clientId:r}=this.getConfig(),i;try{i=await C(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=Ue(i)}catch(p){throw new l(`Apple private key could not be parsed: ${p instanceof Error?p.message:String(p)}`)}let u=Ae("sha256",oe.from(a),{key:c,dsaEncoding:"ieee-p1363"});return`${a}.${u.toString("base64url")}`}base64urlJson(e){return oe.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 Re(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 ae 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 $e=new TextEncoder;function m(e){return $e.encode(e).length}function Oe(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)),d=p+m(c);if(i(p,d))continue;t.push({byteStart:p,byteEnd:d,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)),d=p+m(c);if(i(p,d))continue;t.push({byteStart:p,byteEnd:d,type:"mention",value:c.slice(1).replace(/\.+$/,"")})}return t.sort((o,a)=>o.byteStart-a.byteStart)}class U{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 Oe(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}=Re(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 ae(`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 ce}from"@stacksjs/api";import{config as P}from"@stacksjs/config";var A="v24.0";class V extends h{baseUrl="https://www.facebook.com";apiUrl="https://graph.facebook.com";get graphVersion(){return P.services.facebook?.graphVersion??A}getConfig(){let e={clientId:this.clientId||(P.services.facebook?.clientId??""),clientSecret:this.clientSecret||(P.services.facebook?.clientSecret??""),redirectUrl:this.redirectUrl||(P.services.facebook?.redirectUrl??""),scopes:P.services.facebook?.scopes??["email","public_profile"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/${this.graphVersion}/dialog/oauth?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(","),response_type:"code",...await this.pkceFields(),...this.parameters,state:e}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let s=await ce.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 ce.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 M}from"@stacksjs/api";import{config as R}from"@stacksjs/config";class j extends h{baseUrl="https://github.com";apiUrl="https://api.github.com";getConfig(){let e={clientId:this.clientId||(R.services.github?.clientId??""),clientSecret:this.clientSecret||(R.services.github?.clientSecret??""),redirectUrl:this.redirectUrl||(R.services.github?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:R.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 M.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([M.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${e}`}).get(`${this.apiUrl}/user`),M.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 le}from"@stacksjs/api";import{config as O}from"@stacksjs/config";class J extends h{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||(O.services.google?.clientId??""),clientSecret:this.clientSecret||(O.services.google?.clientSecret??""),redirectUrl:this.redirectUrl||(O.services.google?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:O.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 le.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 le.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 C(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 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 G{provider="instagram";characterLimit=2200;graphVersion;authBase;graphBase;constructor(e={}){this.graphVersion=e.graphVersion||A,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 K{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:Ee(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 Ee(e){return e.replace(/[\\|{}@[\]()<>#*_~]/g,"\\$&")}class de 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 Be(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 Q{provider="mastodon";characterLimit=500;instanceOf(e){return Be(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||De(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 de(`Mastodon API failed (${r.status}): ${i||r.statusText}`,r.status,i);return i?JSON.parse(i):{}}}function De(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 W{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 Le}from"buffer";import{fetcher as ue}from"@stacksjs/api";import{config as E}from"@stacksjs/config";class X extends h{baseUrl="https://twitter.com";apiUrl="https://api.twitter.com";_usesPKCE=!0;getConfig(){let e={clientId:this.clientId||(E.services.twitter?.clientId??""),clientSecret:this.clientSecret||(E.services.twitter?.clientSecret??""),redirectUrl:this.redirectUrl||(E.services.twitter?.redirectUrl??""),scopes:E.services.twitter?.scopes??["users.read","tweet.read"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/i/oauth2/authorize?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(" "),response_type:"code",...this.parameters,...await this.pkceFields(),state:e}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let s=this.pkceTokenFields(),n=Le.from(`${t}:${r}`).toString("base64"),o=await ue.asForm().withHeaders({Authorization:`Basic ${n}`}).post(`${this.apiUrl}/2/oauth2/token`,{code:e,grant_type:"authorization_code",redirect_uri:i,...s});if(o.data.error)throw Error(`Twitter OAuth error: ${o.data.error_description}`);return o.data.access_token}async getUserByToken(e){let t=await ue.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 w 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 pe(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=pe(crypto.getRandomValues(new Uint8Array(32))),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),i=pe(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 w("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 w("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 w("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 w(`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 w("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 w(`Twitter API failed (${r.status}): ${i||r.statusText}`,r.status,i);return i?JSON.parse(i):{}}}import{Buffer as Fe}from"buffer";class I extends Error{code;status;constructor(e,t){super(`Stacks issuer refused the request: ${e}`);this.code=e;this.status=t;this.name="StacksIssuerError"}}class Ne extends h{scopeSeparator=" ";settings;constructor(e){super(e);this.settings=e,this._scopes=e.scopes?.length?[...e.scopes]:[],this._usesPKCE=!0}endpoint(e){return(e==="authorize"?this.settings.authorizeUrl:e==="token"?this.settings.tokenUrl:this.settings.revokeUrl)||`${this.settings.issuer.replace(/\/+$/,"")}/${e}`}resources(){let e=this.settings.resource;return e==null?[]:Array.isArray(e)?e:[e]}validateConfig(){if(!this.settings.issuer)throw new l("Stacks issuer not provided");if(!this.clientId)throw new l("Stacks issuer client ID not provided");if(!this.clientSecret)throw new l("Stacks issuer client secret not provided");if(!this.redirectUrl)throw new l("Stacks issuer redirect URL not provided");if(!this.settings.userInfoUrl)throw new l("Stacks issuer userinfo URL not provided")}getTokenUrl(){return this.endpoint("token")}async getAuthUrl(){this.validateConfig();let e=new URLSearchParams({client_id:this.clientId,redirect_uri:this.redirectUrl,response_type:"code",scope:this.formatScopes(this.getScopes(),this.scopeSeparator),state:this.resolveState(),...await this.pkceFields()});for(let t of this.resources())e.append("resource",t);for(let[t,r]of Object.entries(this.parameters))e.set(t,String(r));return`${this.endpoint("authorize")}?${e.toString()}`}async post(e,t){let r=await fetch(e,{method:"POST",headers:{Authorization:`Basic ${Fe.from(`${encodeURIComponent(this.clientId)}:${encodeURIComponent(this.clientSecret)}`).toString("base64")}`,"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:t.toString()}),i=await r.json().catch(()=>({}));if(!r.ok)throw new I(typeof i.error==="string"?i.error:"server_error",r.status);return i}tokens(e){if(typeof e.access_token!=="string"||!e.access_token)throw new I("invalid_token_response",502);return{accessToken:e.access_token,refreshToken:typeof e.refresh_token==="string"?e.refresh_token:null,expiresIn:typeof e.expires_in==="number"?e.expires_in:null,scopes:typeof e.scope==="string"?e.scope.split(" ").filter(Boolean):[]}}async getTokens(e){this.validateConfig();let t=new URLSearchParams({grant_type:"authorization_code",code:e,redirect_uri:this.redirectUrl,...this.pkceTokenFields()});for(let r of this.resources())t.append("resource",r);return this.tokens(await this.post(this.endpoint("token"),t))}async getAccessToken(e){return(await this.getTokens(e)).accessToken}async refreshTokens(e){this.validateConfig();let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e});for(let r of this.resources())t.append("resource",r);return this.tokens(await this.post(this.endpoint("token"),t))}async revokeToken(e,t="refresh_token"){this.validateConfig(),await this.post(this.endpoint("revoke"),new URLSearchParams({token:e,token_type_hint:t}))}async getClaims(e){this.validateConfig();let t=await fetch(this.settings.userInfoUrl,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}}),r=await t.json().catch(()=>({}));if(!t.ok)throw new I(typeof r.error==="string"?r.error:"invalid_token",t.status);if(typeof r.sub!=="string"||!r.sub)throw new I("invalid_userinfo",502);return r}async getUserByToken(e){let t=await this.getClaims(e),r=typeof t.email==="string"?t.email:null;return{id:String(t.sub),nickname:typeof t.preferred_username==="string"?t.preferred_username:null,name:typeof t.name==="string"&&t.name?t.name:r??"",email:r,emailVerified:typeof t.email_verified==="boolean"?t.email_verified:null,avatar:typeof t.picture==="string"?t.picture:null,token:e,raw:t}}}import{config as ze}from"@stacksjs/config";var B=["clientId","clientSecret","redirectUrl"],T=Object.freeze({google:{name:"google",label:"Google",driver:J,required:B,postCallback:!1,pkce:!1,nonce:!1},github:{name:"github",label:"GitHub",driver:j,required:B,postCallback:!1,pkce:!1,nonce:!1},facebook:{name:"facebook",label:"Facebook",driver:V,required:B,postCallback:!1,pkce:!1,nonce:!1},twitter:{name:"twitter",label:"X",driver:X,required:B,postCallback:!1,pkce:!0,nonce:!1},apple:{name:"apple",label:"Apple",driver:H,required:["clientId","teamId","keyId","privateKey","redirectUrl"],postCallback:!0,pkce:!1,nonce:!0}});function he(e){return ze?.services?.[e]}function qe(e){return typeof e==="string"&&e in T}function ge(e){if(!qe(e))return!1;let t=he(e);if(!t)return!1;return T[e].required.every((r)=>Boolean(t[r]))}function dr(){return Object.keys(T).filter(ge).map((e)=>T[e])}function ur(e){if(!ge(e))return null;let t=T[e],r=he(e)??{};return new t.driver({clientSecret:"",...r,clientId:String(r.clientId??""),redirectUrl:String(r.redirectUrl??"")})}class He{accessToken;refreshToken;expiresIn;approvedScopes;constructor(e,t=null,r=null,i=[]){this.accessToken=e;this.refreshToken=t;this.expiresIn=r;this.approvedScopes=i}}function gr(e){return typeof e?.deletePost==="function"}function fr(e){return typeof e?.listAuthoredPosts==="function"}import{buildSessionHandoffCodeUrl as Ve,buildSessionHandoffUrl as Me}from"@stacksjs/composables";function Z(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 yr(e,t={}){let r=t.redirectTo??"/";if(!Z(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:Me(r,e),"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function kr(e,t={}){let r=t.redirectTo??"/";if(!Z(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:Ve(r,e),"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function br(e,t={}){let r=t.redirectTo??"/login";if(!Z(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","Referrer-Policy":"no-referrer"}})}import{Buffer as fe}from"buffer";import{createHash as je,randomBytes as Je,timingSafeEqual as Ge}from"crypto";function x(e){return je("sha256").update(e).digest("hex")}var Ke=/^[a-f0-9]{64}$/,Qe=/^[a-f0-9]{64}$/,We=/^[\w.:-]{1,64}$/,Xe=3600000,me=null;function Ir(e){me=e}function we(){return me??et()}function Y(e=32){return Je(e).toString("hex")}function Ze(e,t){if(e.length!==t.length)return!1;return Ge(fe.from(e,"utf8"),fe.from(t,"utf8"))}function ee(e){return`stacks_oauth_${x(e).slice(0,24)}`}async function Ye(){try{let{config:e}=await import("@stacksjs/config");return String(e.app?.url??"").startsWith("https:")}catch{return!1}}function ye(e,t,r,i){return[`${e}=${t}`,`Path=${i.path}`,"HttpOnly",`SameSite=${i.sameSite}`,`Max-Age=${Math.max(0,Math.floor(r))}`,...i.secure?["Secure"]:[]].join("; ")}async function ke(e={}){let t=e.sameSite??"Lax",r=t==="None"?!0:e.secure??await Ye();return{path:e.path??"/",sameSite:t,secure:r}}async function Tr(e){if(!We.test(e.purpose??""))throw TypeError("[socials] issueOAuthFlow needs a purpose of 1-64 word characters, dots, colons or dashes.");if(!Number.isFinite(e.ttlMs)||e.ttlMs<=0)throw TypeError("[socials] issueOAuthFlow needs a positive ttlMs.");if(e.challenge!==void 0&&!Qe.test(e.challenge))throw TypeError("[socials] issueOAuthFlow challenge must be the lowercase hex SHA-256 of the verifier.");if(e.userId!=null&&(!Number.isSafeInteger(e.userId)||e.userId<=0))throw TypeError("[socials] issueOAuthFlow userId must be a positive integer.");let t=Math.min(e.ttlMs,Xe),r=Y(),s=(e.challenge?!1:e.bindBrowser!==!1)?Y():null,n=e.nonce===!0?Y():typeof e.nonce==="string"&&e.nonce?e.nonce:void 0,o=new Date,a=new Date(o.getTime()+t),c=we();try{await c.prune(o)}catch{}await c.insert({stateDigest:x(r),purpose:e.purpose,browserDigest:e.challenge??(s?x(s):null),userId:e.userId??null,nonce:n??null,data:e.data??null,expiresAt:a});let u=s?ye(ee(r),s,t/1000,await ke(e.cookie)):null;return{state:r,cookie:u,secret:s,...n!==void 0&&{nonce:n},expiresAt:a}}async function xr(e,t){if(typeof e!=="string"||!Ke.test(e))return null;let r=we(),i=x(e),s=await r.find(i);if(!s)return null;if(s.expiresAt.getTime()<=Date.now())return await r.take(i).catch(()=>!1),null;if(s.purpose!==t.purpose)return null;if(s.browserDigest!==null){let n=t.browserSecret;if(typeof n!=="string"||n.length===0||n.length>512)return null;if(!Ze(x(n),s.browserDigest))return null}if(!await r.take(i))return null;return{purpose:s.purpose,userId:s.userId,nonce:s.nonce,data:s.data,expiresAt:s.expiresAt}}function _r(e,t){if(!e||!t)return"";let r=ee(t);for(let i of e.split(";")){let s=i.trim();if(s.startsWith(`${r}=`))return s.slice(r.length+1)}return""}async function Cr(e,t={}){return ye(ee(e),"",0,await ke(t))}function Ur(){let e=new Map;return{records:e,async insert(t){e.set(t.stateDigest,{...t})},async find(t){let r=e.get(t);return r?{...r}:void 0},async take(t){return e.delete(t)},async prune(t){for(let[r,i]of e)if(i.expiresAt.getTime()<=t.getTime())e.delete(r)}}}var D="oauth_flows";function et(){let e=()=>import("@stacksjs/database/runtime");return{async insert(t){let{db:r,sqlDateTime:i}=await e();await r.insertInto(D).values({state_digest:t.stateDigest,purpose:t.purpose,browser_digest:t.browserDigest,user_id:t.userId,nonce:t.nonce,data:t.data?JSON.stringify(t.data):null,expires_at:i(t.expiresAt),created_at:i(new Date)}).execute()},async find(t){let{db:r,parseSqlDateTime:i}=await e(),s=await r.primary.selectFrom(D).where("state_digest","=",t).selectAll().executeTakeFirst();if(!s)return;let n=null;if(typeof s.data==="string"&&s.data)try{let o=JSON.parse(s.data);n=o&&typeof o==="object"?o:null}catch{n=null}return{stateDigest:String(s.state_digest),purpose:String(s.purpose),browserDigest:typeof s.browser_digest==="string"&&s.browser_digest?s.browser_digest:null,userId:s.user_id==null?null:Number(s.user_id),nonce:typeof s.nonce==="string"&&s.nonce?s.nonce:null,data:n,expiresAt:i(s.expires_at)??new Date(0)}},async take(t){let{db:r,mutationCount:i}=await e(),s=await r.deleteFrom(D).where("state_digest","=",t).execute();return i(s)===1},async prune(t){let{db:r,sqlDateTime:i}=await e();await r.deleteFrom(D).where("expires_at","<",i(t)).execute()}}}var tt={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"]},rt={bluesky:["identifier","password"],twitter:["clientId","clientSecret","accessToken"],linkedin:["accessToken","memberUrn"],mastodon:["accessToken","instanceUrl"],instagram:["accessToken","accountId"],threads:["accessToken","userId"]};function it(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function L(e,t,r){let i=r.replace(/[A-Z]/g,(s)=>`_${s}`).toUpperCase();return`SOCIALS_${it(e)}_${t.toUpperCase()}_${i}`}class g extends Error{constructor(e){super(e);this.name="SocialIdentityError"}}async function F(){let{config:e,overridesReady:t}=await import("@stacksjs/config");return await t,e.socials??{}}function be(e,t){let r=Object.keys(e.identities??{});if(t){if(!r.includes(t))throw new g(`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 g(`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 g("config/socials.ts declares no identities, so there is no account to post as.");throw new g(`config/socials.ts declares ${r.length} identities (${r.join(", ")}) and no default, so a call has to name one.`)}function st(e,t,r,i=process.env){let n=(e.identities?.[r]??{}).credentials?.[t]??{},o={};for(let a of tt[t]){let c=(n[a]??i[L(r,t,a)]??"").trim();if(c)o[a]=c}return o}function te(e,t,r,i=process.env){let s=be(e,r),n=st(e,t,s,i),o=rt[t].filter((a)=>!n[a]);if(o.length){let a=o.map((c)=>L(s,t,c)).join(", ");throw new g(`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 Se(e){return be(await F(),e)}async function S(e,t,r){return te(await F(),e,t,r)}function Rr(e,t){return S("bluesky",e,t)}function $r(e,t){return S("twitter",e,t)}function Or(e,t){return S("linkedin",e,t)}function Er(e,t){return S("mastodon",e,t)}function Br(e,t){return S("instagram",e,t)}function Dr(e,t){return S("threads",e,t)}import{randomBytes as nt}from"crypto";function qr(e){return e==="twitter"}var ot=["tweet.read","tweet.write","users.read","offline.access"],at="127.0.0.1",Pe="/callback";function Hr(e){if(!Number.isInteger(e)||e<1||e>65535)throw new g(`${e} is not a port a redirect can listen on.`);return`http://${at}:${e}${Pe}`}function Vr(){return nt(16).toString("hex")}function Mr(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 jr(e,t,r){let i=[];for(let[s,n]of Object.entries(r)){if(!n)continue;i.push(`${L(e,t,s)}=${n}`)}return i}async function Jr(e){let t=new b,r=await t.exchangeCode(e);if(!r.accessToken)throw new g("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 Gr(e){return new b().createAuthorization({clientId:e.clientId,redirectUrl:e.redirectUrl,scopes:[...ot],state:e.state})}function Kr(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 ct={bluesky:null,twitter:null,linkedin:"memberUrn",mastodon:"instanceUrl",instagram:"accountId",threads:"userId"};function lt(e,t){if(e==="bluesky")return t.service?{service:t.service}:{};if(e==="linkedin")return t.apiVersion?{apiVersion:t.apiVersion}:{};return{}}function dt(e,t={}){switch(e){case"bluesky":return new U(t);case"linkedin":return new K(t);case"twitter":return new b;case"mastodon":return new Q;case"instagram":return new G;case"threads":return new W;default:throw new g(`No publishing driver for '${String(e)}'.`)}}function ut(e,t,r){let i=ct[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 pt(e,t,r){if(!r)return;if(r.includes(t))return;throw new g(`Identity '${e}' is not set up for ${t}. config/socials.ts lists: ${r.length?r.join(", "):"none"}.`)}async function ht(e,t,r){let i=await F(),s=await Se(t),n=i.identities?.[s]??{};pt(s,e,n.platforms);let o=te(i,e,s,r),a=lt(e,o);if(e==="bluesky"){let c=await new U(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:ut(e,n.handle??"",o),options:a}}async function Zr(e,t,r,i){let s=await ht(e,r,i);return dt(s.platform,s.options).publish(s.identity,t)}export{at as AUTHORIZE_HOST,Pe as AUTHORIZE_PATH,h as AbstractProvider,H as AppleProvider,ae as BlueskyApiError,U as BlueskyPublishingDriver,l as ConfigException,ct as DRIVER_DID_FIELD,V as FacebookProvider,j as GitHubProvider,J as GoogleProvider,v as InstagramApiError,G as InstagramPublishingDriver,Te as InvalidStateException,f as LinkedInApiError,K as LinkedInPublishingDriver,A as META_GRAPH_VERSION,de as MastodonApiError,Q as MastodonPublishingDriver,rt as REQUIRED_SOCIAL_CREDENTIALS,tt as SOCIAL_CREDENTIAL_FIELDS,T as SOCIAL_PROVIDERS,g as SocialIdentityError,I as StacksIssuerError,Ne as StacksIssuerProvider,ot as TWITTER_PUBLISH_SCOPES,k as ThreadsApiError,W as ThreadsPublishingDriver,He as Token,w as TwitterApiError,X as TwitterProvider,b as TwitterPublishingDriver,pt as assertPlatformDeclared,Kr as callbackPage,Hr as callbackUri,Cr as clearOAuthFlowCookie,Jr as completeTwitterAuthorization,dr as configuredSocialProviders,xr as consumeOAuthFlow,et as databaseOAuthFlowStore,Oe as detectFacetCandidates,lt as driverOptions,jr as envLines,L as envName,it as envSegment,Ee as escapeLinkedInText,qr as isAuthorizablePlatform,Z as isSafeHandoffTarget,ge as isSocialProviderConfigured,qe as isSocialProviderName,Tr as issueOAuthFlow,Ur as memoryOAuthFlowStore,Vr as newState,Be as normalizeInstance,ee as oauthFlowCookieName,x as oauthFlowDigest,Re as parseAtUri,te as pickCredentials,be as pickIdentity,Zr as publishAs,dt as publishingDriver,Mr as readCallback,st as readCredentials,_r as readOAuthFlowCookie,Rr as resolveBlueskyCredentials,Se as resolveIdentityName,Br as resolveInstagramCredentials,Or as resolveLinkedInCredentials,Er as resolveMastodonCredentials,S as resolveSocialCredentials,Dr as resolveThreadsCredentials,$r as resolveTwitterCredentials,kr as socialHandoffCodeRedirect,br as socialHandoffFailureRedirect,yr as socialHandoffRedirect,ur as socialProvider,ht as socialPublishTarget,F as socialsConfig,Gr as startTwitterAuthorization,gr as supportsDeletion,fr as supportsEnumeration,ut as toDriverIdentity,Ir as useOAuthFlowStore};
|
|
2
|
+
var Ne=import.meta.require;import{Buffer as O}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}=Ne("crypto");return r(O.from(e,"utf8"),O.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=O.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 O.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 pe}from"buffer";import{createPrivateKey as He,sign as Ve}from"crypto";import{config as x}from"@stacksjs/config";class Fe extends Error{constructor(e="Invalid state"){super(e);this.name="InvalidStateException"}}class p extends Error{constructor(e){super(e);this.name="ConfigException"}}import{Buffer as G}from"buffer";var ue=new Map,Me=600000,ze=60000;async function le(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 ue.set(e,{keys:s,fetchedAt:t}),s}async function qe(e,t,r){let i=ue.get(e),s=i!==void 0&&r-i.fetchedAt<Me,n=s?i.keys:await le(e,r),o=n.find((a)=>a.kid===t);if(!o&&s&&r-i.fetchedAt>=ze)n=await le(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 de(e,t){try{return JSON.parse(G.from(e,"base64url").toString("utf8"))}catch{throw Error(`id_token verification failed: ${t} is not valid JSON`)}}async function L(e,t){let r=e.split(".");if(r.length!==3)throw Error("id_token verification failed: malformed token");let[i,s,n]=r,o=de(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 qe(t.jwksUrl,o.kid,a),l=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",l,G.from(n,"base64url"),G.from(`${i}.${s}`)))throw Error("id_token verification failed: signature does not match the issuer's key");let u=de(s,"payload"),h=(t.clockSkewSeconds??60)*1000,w=Array.isArray(t.issuer)?t.issuer:[t.issuer];if(!w.includes(u.iss))throw Error(`id_token verification failed: issuer is ${JSON.stringify(u.iss)}, expected ${w.map((J)=>JSON.stringify(J)).join(" or ")}`);let De=Array.isArray(t.audience)?t.audience:[t.audience];if(!(Array.isArray(u.aud)?u.aud:[u.aud]).some((J)=>De.includes(J)))throw Error("id_token verification failed: token is addressed to a different client");if(typeof u.exp!=="number"||u.exp*1000+h<=a)throw Error("id_token verification failed: token has expired");if(typeof u.iat==="number"&&u.iat*1000-h>a)throw Error("id_token verification failed: token was issued in the future");if(typeof u.nbf==="number"&&u.nbf*1000-h>a)throw Error("id_token verification failed: token is not valid yet");if(t.nonce!==void 0&&u.nonce!==t.nonce)throw Error("id_token verification failed: nonce does not match");if(typeof u.sub!=="string"||u.sub==="")throw Error("id_token verification failed: token has no subject");return u}class K 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||(x.services.apple?.clientId??""),teamId:this.teamId||(x.services.apple?.teamId??""),keyId:this.keyId||(x.services.apple?.keyId??""),privateKey:(this.privateKey||(x.services.apple?.privateKey??"")).replace(/\\n/g,`
|
|
3
|
+
`),redirectUrl:this.native?"":this.redirectUrl||(x.services.apple?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:x.services.apple?.scopes??["name","email"]};return this.setScopes(e.scopes),e}async getAuthUrl(){if(this.native)throw new p("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 L(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=He(i)}catch(d){throw new p(`Apple private key could not be parsed: ${d instanceof Error?d.message:String(d)}`)}let l=Ve("sha256",pe.from(a),{key:c,dsaEncoding:"ieee-p1363"});return`${a}.${l.toString("base64url")}`}base64urlJson(e){return pe.from(JSON.stringify(e)).toString("base64url")}validateConfig(){let{clientId:e,teamId:t,keyId:r,privateKey:i,redirectUrl:s}=this.getConfig();if(!e)throw new p(this.native?"Apple client ID (the app's bundle ID) not provided":"Apple client ID (Service ID) not provided");if(!t)throw new p("Apple team ID not provided");if(!r)throw new p("Apple key ID not provided");if(!i)throw new p("Apple private key not provided");if(!s&&!this.native)throw new p("Apple redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/auth/token`}}var hr=23,je=/\bhttps?:\/\/[^\s<>]+|(?<![@\w.-])(?:[a-z0-9-]+\.)+(?:com|org|net|io|dev|app|co|social|blog|ai|me|info|xyz|tv|fm|us|uk|de|fr|jp|ca|au|nl|ch|se|no|es|it)\b(?:\/[^\s<>]*)?/gi,Je=/[.,;:!?)\]}'"]+$/,he;function fe(){return he??=new Intl.Segmenter(void 0,{granularity:"grapheme"}),he}function ge(e){let t=0;for(let r of fe().segment(e))t++;return t}function me(e){let t=[],r=0;for(let i of e.matchAll(je)){let s=i[0].replace(Je,"");if(!s)continue;let n=i.index;if(n>r)t.push({link:!1,value:e.slice(r,n)});t.push({link:!0,value:s}),r=n+s.length}if(r<e.length)t.push({link:!1,value:e.slice(r)});return t}function Ge(e){return e<=4351||e>=8192&&e<=8205||e>=8208&&e<=8223||e>=8242&&e<=8247}function Ke(e){let t=0;for(let{segment:r}of fe().segment(e.normalize("NFC"))){if(/\p{Extended_Pictographic}|\p{Regional_Indicator}/u.test(r)){t+=2;continue}for(let i of r)t+=Ge(i.codePointAt(0))?1:2}return t}function Xe(e,t,r={}){let i=String(t??"");switch(e){case"twitter":return me(i).reduce((s,n)=>s+(n.link?23:Ke(n.value)),0);case"mastodon":{let s=r.linkLength??23;return me(i).reduce((n,o)=>{if(o.link)return n+s;return n+ge(o.value.replace(/(^|[^\w/])(@[\w.-]+)@[\w.-]+\.[a-z]{2,}/gi,"$1$2"))},0)}case"bluesky":case"threads":return ge(i);default:return i.length}}function m(e,t,r,i={}){return r>0&&Xe(e,t,i)>r}var we="app.bsky.feed.post";function Qe(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 X extends Error{status;body;constructor(e,t,r){super(e);this.status=t;this.body=r;this.name="BlueskyApiError"}get isAuthError(){if(this.status===401||this.status===403)return!0;if(this.status!==400)return!1;try{return We.includes(String(JSON.parse(this.body)?.error))}catch{return!1}}}var We=["ExpiredToken","InvalidToken"],ye=1e6,Ye=4,Ze=3;function fr(e){return e instanceof X&&e.isAuthError}var et=new TextEncoder;function S(e){return et.encode(e).length}function tt(e){let t=[],r=/https?:\/\/[^\s<>"']+/g;for(let o of e.matchAll(r)){let a=o[0].replace(/[),.;!?]+$/,"");t.push({byteStart:S(e.slice(0,o.index)),byteEnd:S(e.slice(0,o.index))+S(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 l=(o.index??0)+a.length,d=S(e.slice(0,l)),u=d+S(c);if(i(d,u))continue;t.push({byteStart:d,byteEnd:u,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 l=(o.index??0)+a.length,d=S(e.slice(0,l)),u=d+S(c);if(i(d,u))continue;t.push({byteStart:d,byteEnd:u,type:"mention",value:c.slice(1).replace(/\.+$/,"")})}return t.sort((o,a)=>o.byteStart-a.byteStart)}class B{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(m("bluesky",t.text,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.slice(0,Ze);if(t.reply)i.reply=t.reply;let s=t.facets??await this.buildFacets(t.text);if(s.length)i.facets=s;let n=[],o=(t.media||[]).filter((c)=>c.bytes?.length).slice(0,Ye);if(o.length){let c=[];for(let l of o){let d=await this.uploadBlob(e,l.bytes,l.mimeType||"image/jpeg");c.push({image:d,alt:l.altText||""})}i.embed={$type:"app.bsky.embed.images",images:c}}else if(t.external){let c={uri:t.external.uri,title:t.external.title,description:t.external.description||""},l=t.external.thumb;if(l?.bytes?.length)if(l.bytes.length>ye)n.push("The link card's picture is larger than Bluesky takes, so the card went out without it.");else try{c.thumb=await this.uploadBlob(e,l.bytes,l.mimeType)}catch{n.push("Bluesky did not take the link card's picture, so the card went out without it.")}i.embed={$type:"app.bsky.embed.external",external:c}}let a=await this.post("/xrpc/com.atproto.repo.createRecord",{repo:r,collection:we,record:i},{authorization:`Bearer ${e.accessToken}`});return{provider:this.provider,uri:a.uri,cid:a.cid,url:this.toPostUrl(e.handle,a.uri),...n.length?{warnings:n}:{}}}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 tt(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>ye)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",we),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}=Qe(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 X(`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 ke}from"@stacksjs/api";import{config as U}from"@stacksjs/config";var D="v24.0";class Q extends g{baseUrl="https://www.facebook.com";apiUrl="https://graph.facebook.com";get graphVersion(){return U.services.facebook?.graphVersion??D}getConfig(){let e={clientId:this.clientId||(U.services.facebook?.clientId??""),clientSecret:this.clientSecret||(U.services.facebook?.clientSecret??""),redirectUrl:this.redirectUrl||(U.services.facebook?.redirectUrl??""),scopes:U.services.facebook?.scopes??["email","public_profile"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/${this.graphVersion}/dialog/oauth?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(","),response_type:"code",...await this.pkceFields(),...this.parameters,state:e}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let s=await ke.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 ke.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 p("Facebook client ID not provided");if(!t)throw new p("Facebook client secret not provided");if(!r)throw new p("Facebook redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/${this.graphVersion}/oauth/access_token`}}import{fetcher as W}from"@stacksjs/api";import{config as N}from"@stacksjs/config";class Y extends g{baseUrl="https://github.com";apiUrl="https://api.github.com";getConfig(){let e={clientId:this.clientId||(N.services.github?.clientId??""),clientSecret:this.clientSecret||(N.services.github?.clientSecret??""),redirectUrl:this.redirectUrl||(N.services.github?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:N.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 W.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([W.withHeaders({Accept:"application/vnd.github.v3+json",Authorization:`token ${e}`}).get(`${this.apiUrl}/user`),W.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 p("GitHub client ID not provided");if(!t)throw new p("GitHub client secret not provided");if(!r)throw new p("GitHub redirect URL not provided")}getTokenUrl(){return`${this.baseUrl}/login/oauth/access_token`}}import{fetcher as be}from"@stacksjs/api";import{config as F}from"@stacksjs/config";class Z 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||(F.services.google?.clientId??""),clientSecret:this.clientSecret||(F.services.google?.clientSecret??""),redirectUrl:this.redirectUrl||(F.services.google?.redirectUrl??""),scopes:this._scopes.length>0?this._scopes:F.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 be.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 be.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 L(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 p("Google client ID not provided");if(!t)throw new p("Google client secret not provided");if(!r)throw new p("Google redirect URL not provided")}getTokenUrl(){return this.tokenUrl}}var rt=10;class k 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 ee{provider="instagram";characterLimit=2200;maxImages=rt;graphVersion;authBase;graphBase;constructor(e={}){this.graphVersion=e.graphVersion||D,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 k("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 k("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 exchangeLongLivedUserToken(e,t,r){let i=await this.graph("/oauth/access_token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"fb_exchange_token",client_id:e,client_secret:t,fb_exchange_token:r}).toString()});if(!i.access_token)throw new k("Facebook did not return a long-lived token.",400,JSON.stringify(i));return{accessToken:i.access_token,expiresIn:i.expires_in}}async publish(e,t){if(!e.accessToken)throw Error("Instagram access token is missing for this identity.");let r=e.did;if(!r)throw Error("Instagram account id is required to publish.");let i=(t.media??[]).slice(0,this.maxImages);if(!i.length)throw Error("Instagram requires an image to post.");if(i.some((l)=>!l.url))throw new k("Instagram fetches images from a public address, and this image has none.",422,"");if(m("instagram",t.text,this.characterLimit))throw Error(`Instagram captions must be ${this.characterLimit} characters or fewer.`);let s=e.accessToken,n=async(l)=>{let d=await this.graph(`/${r}/media`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(l).toString()},s);if(!d.id)throw new k("Instagram did not return a media container id.",400,JSON.stringify(d));return d.id},o;if(i.length>1){let l=[];for(let d of i)l.push(await n({image_url:d.url,is_carousel_item:"true"}));o=await n({media_type:"CAROUSEL",children:l.join(","),caption:t.text})}else o=await n({image_url:i[0].url,caption:t.text});let a=await this.graph(`/${r}/media_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:o}).toString()},s);if(!a.id)throw new k("Instagram did not return a published post id.",400,JSON.stringify(a));let c=await this.graph(`/${a.id}?fields=permalink`,{method:"GET"},s).catch(()=>{return});return{provider:this.provider,uri:a.id,url:c?.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(`Instagram API failed (${s.status}): ${a}`,s.status,n)}return o}}import{fetchPublicUrl as it}from"@stacksjs/security";var st=10485760;function Se(e){if(e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255)return"image/jpeg";if(e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71)return"image/png";if(e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56)return"image/gif";if(e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80)return"image/webp";return null}async function v(e,t={}){try{let r=await it(e,{},{allowHttp:!0,timeoutMs:15000,maxBytes:st,...t});if(!r.ok)return null;let i=new Uint8Array(await r.arrayBuffer()),s=Se(i);return s?{bytes:i,mimeType:s}:null}catch{return null}}class Pe extends Error{url;status=422;body="";constructor(e){super(`Could not read the image at ${e}.`);this.url=e;this.name="PostImageError"}}async function T(e,t){if(e.bytes?.length)return{bytes:e.bytes,mimeType:e.mimeType||Se(e.bytes)||"image/jpeg"};if(!e.url)return;let r=await t(e.url);if(!r)throw new Pe(e.url);return r}var xe="202611";function nt(e){let t=Number(e.slice(0,4)),r=Number(e.slice(4,6));return new Date(Date.UTC(t+1,r-1,15))}function ot(e,t=Date.now()){let r=String(e??"").trim();if(!/^\d{6}$/.test(r))return xe;return nt(r).getTime()>t?r:xe}var at=20,ct=4086,M="2.0.0";class y 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 te{provider="linkedin";characterLimit=3000;maxImages=at;fetchImage=v;apiVersion;authBase;apiBase;constructor(e={}){this.apiVersion=ot(e.apiVersion),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});return this.tokenRequest(t,"LinkedIn did not return an access token.")}async refreshAccessToken(e){return this.tokenRequest(new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId,client_secret:e.clientSecret}),"LinkedIn did not return a refreshed access token.")}async tokenRequest(e,t){let r=await this.request(`${this.authBase}/oauth/v2/accessToken`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:e.toString()});if(!r.access_token)throw new y(t,400,JSON.stringify(r));return{accessToken:r.access_token,expiresIn:r.expires_in,scope:r.scope,refreshToken:r.refresh_token,refreshTokenExpiresIn:r.refresh_token_expires_in}}async getProfile(e){if(!e)throw Error("LinkedIn access token is required.");let t=await this.request(`${this.apiBase}/v2/userinfo`,{headers:{authorization:`Bearer ${e}`}});if(!t.sub)throw new y("LinkedIn profile is missing a subject id.",400,JSON.stringify(t));return{sub:t.sub,name:t.name,picture:t.picture}}async uploadImage(e,t,r,i){let s=await this.request(`${this.apiBase}/rest/images?action=initializeUpload`,{method:"POST",headers:{authorization:`Bearer ${e}`,"content-type":"application/json","linkedin-version":this.apiVersion,"x-restli-protocol-version":M},body:JSON.stringify({initializeUploadRequest:{owner:t}})}),n=s.value?.uploadUrl,o=s.value?.image;if(!n||!o)throw new y("LinkedIn did not return an image upload URL.",400,JSON.stringify(s));let a=await fetch(n,{method:"PUT",headers:{authorization:`Bearer ${e}`,"content-type":i||"image/jpeg"},body:new Uint8Array(r)});if(!a.ok){let c=await a.text().catch(()=>"");throw new y(`LinkedIn image upload failed (${a.status}): ${c||a.statusText}`,a.status,c)}return o}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(m("linkedin",t.text,this.characterLimit))throw Error(`LinkedIn posts must be ${this.characterLimit} characters or fewer.`);let i=[];for(let c of(t.media??[]).slice(0,this.maxImages)){let l=await T(c,(h)=>this.fetchImage(h));if(!l)continue;let d=await this.uploadImage(e.accessToken,r,l.bytes,l.mimeType),u=c.altText?.trim();i.push({id:d,...u?{altText:u.slice(0,ct)}:{}})}let s={author:r,commentary:lt(t.text),visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1};if(i.length===1)s.content={media:i[0]};else if(i.length>1)s.content={multiImage:{images:i}};else if(t.external)s.content={article:{source:t.external.uri,title:t.external.title,description:t.external.description||""}};let n=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":M},body:JSON.stringify(s)}),o=await n.text();if(!n.ok)throw new y(`LinkedIn API failed (${n.status}): ${o||n.statusText}`,n.status,o);let a=n.headers.get("x-restli-id")||n.headers.get("x-linkedin-id")||"";return{provider:this.provider,uri:a,url:a?`https://www.linkedin.com/feed/update/${a}`: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":M}})}catch(c){if(c instanceof y&&(c.status===401||c.status===403))throw new y("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":M}});if(!i.ok&&i.status!==404){let s=await i.text().catch(()=>"");throw new y(`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 y(`LinkedIn API failed (${r.status}): ${i||r.statusText}`,r.status,i);return i?JSON.parse(i):{}}}function lt(e){return e.replace(/[\\|{}@[\]()<>#*_~]/g,(t,r)=>{if(t==="#"&&dt(e,r))return t;return`\\${t}`})}function dt(e,t){let r=t===0?"":e[t-1];if(r&&/[\p{L}\p{N}_#&/]/u.test(r))return!1;let i=/^[\p{L}\p{N}_]+/u.exec(e.slice(t+1))?.[0];return Boolean(i&&/\p{L}/u.test(i))}class ve 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}}var I={characters:500,charactersPerUrl:23,mediaAttachments:4},ut=3600000,pt=60000;function ht(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 re{provider="mastodon";characterLimit=I.characters;fetchImage=v;limits=new Map;async instanceLimits(e){let t=this.instanceOf(e),r=this.limits.get(t);if(r&&Date.now()<r.expires)return r.value;try{let i=await fetch(`${t}/api/v2/instance`,{signal:AbortSignal.timeout(5000)});if(!i.ok)throw Error(`HTTP ${i.status}`);let n=(await i.json()).configuration?.statuses??{},o=(c,l)=>Number(c)>0?Math.floor(Number(c)):l,a={characters:o(n.max_characters,I.characters),charactersPerUrl:o(n.characters_reserved_per_url,I.charactersPerUrl),mediaAttachments:o(n.max_media_attachments,I.mediaAttachments)};return this.limits.set(t,{value:a,expires:Date.now()+ut}),a}catch{return this.limits.set(t,{value:I,expires:Date.now()+pt}),I}}instanceOf(e){return ht(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?.trim())s.set("description",i.trim().slice(0,1500));return(await this.request(`${this.instanceOf(e)}/api/v2/media`,{method:"POST",headers:{authorization:`Bearer ${this.tokenOf(e)}`},body:s})).id}async publish(e,t,r={}){let i=this.instanceOf(e),s=this.tokenOf(e),n=await this.instanceLimits(e);if(m("mastodon",t.text,n.characters,{linkLength:n.charactersPerUrl}))throw Error(`Mastodon posts on this instance must be ${n.characters} characters or fewer.`);let o=[];for(let u of(t.media||[]).slice(0,n.mediaAttachments)){let h=await T(u,(w)=>this.fetchImage(w));if(h)o.push(await this.uploadMedia(e,h.bytes,h.mimeType,u.altText))}let a={status:t.text,visibility:r.visibility??"public"};if(o.length)a.media_ids=o;if(t.reply?.parent?.uri)a.in_reply_to_id=t.reply.parent.uri;if(r.spoilerText?.trim())a.spoiler_text=r.spoilerText.trim();let c=r.language??t.langs?.[0];if(c)a.language=c;let l={authorization:`Bearer ${s}`,"content-type":"application/json"};if(r.idempotencyKey)l["idempotency-key"]=r.idempotencyKey;let d=await this.request(`${i}/api/v1/statuses`,{method:"POST",headers:l,body:JSON.stringify(a)});return{provider:this.provider,uri:d.id,cid:d.id,url:d.url||d.uri}}async timeline(e,t={}){return{items:[]}}async listAuthoredPosts(e,t={}){let r=this.instanceOf(e),{accountId:i}=await this.verifyCredentials(e),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||gt(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 ve(`Mastodon API failed (${r.status}): ${i||r.statusText}`,r.status,i);return i?JSON.parse(i):{}}}function gt(e){return String(e||"").replace(/\/+$/,"").split("/").pop()||""}var mt=20,ft=1000;class b 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 ie{provider="threads";characterLimit=500;maxImages=mt;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 b(`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 b("Could not resolve the Threads account for this token.",400,JSON.stringify(r));return{threadsUserId:r.id,username:r.username,accessToken:e}}async exchangeLongLivedToken(e,t){return this.tokenRequest("/access_token",new URLSearchParams({grant_type:"th_exchange_token",client_secret:e,access_token:t}))}async refreshLongLivedToken(e){return this.tokenRequest("/refresh_access_token",new URLSearchParams({grant_type:"th_refresh_token",access_token:e}))}async publish(e,t){if(!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(m("threads",t.text,this.characterLimit))throw Error(`Threads posts must be ${this.characterLimit} characters or fewer.`);let i=(t.media??[]).slice(0,this.maxImages);if(i.some((h)=>!h.url))throw new b("Threads fetches images from a public address, and this image has none.",422,"");let s=e.accessToken,n=async(h)=>{let w=await this.graph(`/${r}/threads`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(h).toString()},s);if(!w.id)throw new b("Threads did not return a media container id.",400,JSON.stringify(w));return w.id},o=t.reply?.parent?.uri,a={text:t.text,...o?{reply_to_id:o}:{}},c=(h)=>({media_type:"IMAGE",image_url:h.url,...h.altText?.trim()?{alt_text:h.altText.trim().slice(0,ft)}:{}}),l;if(i.length>1){let h=[];for(let w of i)h.push(await n({...c(w),is_carousel_item:"true"}));l=await n({media_type:"CAROUSEL",children:h.join(","),...a})}else if(i.length===1)l=await n({...c(i[0]),...a});else l=await n({media_type:"TEXT",...a});let d=await this.graph(`/${r}/threads_publish`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({creation_id:l}).toString()},s);if(!d.id)throw new b("Threads did not return a published post id.",400,JSON.stringify(d));let u=await this.graph(`/${d.id}?fields=permalink`,{method:"GET"},s).catch(()=>{return});return{provider:this.provider,uri:d.id,cid:d.id,url:u?.permalink}}async timeline(e,t={}){return{items:[]}}async tokenRequest(e,t){let r=await fetch(`${this.graphBase}${e}`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:t.toString()}),i=await r.text(),s={};try{s=i?JSON.parse(i):{}}catch{s={}}if(!r.ok||s?.error||!s?.access_token){let n=s?.error?.message||s?.error_message||i||r.statusText;throw new b(`Threads token request failed (${r.status}): ${n}`,r.status,i)}return{accessToken:s.access_token,expiresIn:s.expires_in}}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 b(`Threads API failed (${s.status}): ${a}`,s.status,n)}return o}}import{Buffer as wt}from"buffer";import{fetcher as Te}from"@stacksjs/api";import{config as z}from"@stacksjs/config";class se extends g{baseUrl="https://twitter.com";apiUrl="https://api.twitter.com";_usesPKCE=!0;getConfig(){let e={clientId:this.clientId||(z.services.twitter?.clientId??""),clientSecret:this.clientSecret||(z.services.twitter?.clientSecret??""),redirectUrl:this.redirectUrl||(z.services.twitter?.redirectUrl??""),scopes:z.services.twitter?.scopes??["users.read","tweet.read"]};return this.setScopes(e.scopes),e}async getAuthUrl(){let e=this.resolveState(),{clientId:t,redirectUrl:r,scopes:i}=this.getConfig();return this.validateConfig(),`${this.baseUrl}/i/oauth2/authorize?${new URLSearchParams({client_id:t,redirect_uri:r,scope:i.join(" "),response_type:"code",...this.parameters,...await this.pkceFields(),state:e}).toString()}`}async getAccessToken(e){let{clientId:t,clientSecret:r,redirectUrl:i}=this.getConfig();this.validateConfig();let s=this.pkceTokenFields(),n=wt.from(`${t}:${r}`).toString("base64"),o=await Te.asForm().withHeaders({Authorization:`Basic ${n}`}).post(`${this.apiUrl}/2/oauth2/token`,{code:e,grant_type:"authorization_code",redirect_uri:i,...s});if(o.data.error)throw Error(`Twitter OAuth error: ${o.data.error_description}`);return o.data.access_token}async getUserByToken(e){let t=await Te.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 p("Twitter client ID not provided");if(!t)throw new p("Twitter client secret not provided");if(!r)throw new p("Twitter redirect URL not provided")}getTokenUrl(){return`${this.apiUrl}/2/oauth2/token`}}class P 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}}var yt=4,kt=1000;function Ie(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}class _{provider="twitter";characterLimit=280;maxImages=yt;fetchImage=v;apiBase;authorizeBase;constructor(e={}){this.apiBase=e.apiBase||"https://api.twitter.com",this.authorizeBase=e.authorizeBase||"https://twitter.com"}async createAuthorization(e){let t=Ie(crypto.getRandomValues(new Uint8Array(32))),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),i=Ie(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 P("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 P("Twitter did not return a media id.",400,JSON.stringify(s));return n}async describeMedia(e,t,r){try{return await this.request(`${this.apiBase}/2/media/metadata`,{method:"POST",headers:{authorization:`Bearer ${e}`,"content-type":"application/json"},body:JSON.stringify({id:t,metadata:{alt_text:{text:r.slice(0,kt)}}})}),!0}catch{return!1}}async publish(e,t){if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");if(m("twitter",t.text,this.characterLimit))throw Error(`Twitter posts must be ${this.characterLimit} characters or fewer.`);let r=[],i=[];for(let a of(t.media??[]).slice(0,this.maxImages)){let c=await T(a,(u)=>this.fetchImage(u));if(!c)continue;let l=await this.uploadMedia(e.accessToken,c.bytes,c.mimeType),d=a.altText?.trim();if(d&&!await this.describeMedia(e.accessToken,l,d))i.push(`X did not take the description for image ${r.length+1}.`);r.push(l)}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 P("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}`,...i.length?{warnings:i}:{}}}async timeline(e,t={}){return{items:[]}}async listAuthoredPosts(e,t={}){if(!e.accessToken)throw Error("Twitter access token is missing for this identity.");let r=e.did;if(!r)throw Error("Twitter user id is required to list posts.");let i=new URL(`${this.apiBase}/2/users/${encodeURIComponent(r)}/tweets`);if(i.searchParams.set("max_results",String(Math.min(Math.max(t.limit||100,5),100))),i.searchParams.set("tweet.fields","created_at"),t.cursor)i.searchParams.set("pagination_token",t.cursor);let 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 P(`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 P("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 P(`Twitter API failed (${r.status}): ${i||r.statusText}`,r.status,i);return i?JSON.parse(i):{}}}import{Buffer as bt}from"buffer";class C extends Error{code;status;constructor(e,t){super(`Stacks issuer refused the request: ${e}`);this.code=e;this.status=t;this.name="StacksIssuerError"}}class St extends g{scopeSeparator=" ";settings;constructor(e){super(e);this.settings=e,this._scopes=e.scopes?.length?[...e.scopes]:[],this._usesPKCE=!0}endpoint(e){return(e==="authorize"?this.settings.authorizeUrl:e==="token"?this.settings.tokenUrl:this.settings.revokeUrl)||`${this.settings.issuer.replace(/\/+$/,"")}/${e}`}resources(){let e=this.settings.resource;return e==null?[]:Array.isArray(e)?e:[e]}validateConfig(){if(!this.settings.issuer)throw new p("Stacks issuer not provided");if(!this.clientId)throw new p("Stacks issuer client ID not provided");if(!this.clientSecret)throw new p("Stacks issuer client secret not provided");if(!this.redirectUrl)throw new p("Stacks issuer redirect URL not provided");if(!this.settings.userInfoUrl)throw new p("Stacks issuer userinfo URL not provided")}getTokenUrl(){return this.endpoint("token")}async getAuthUrl(){this.validateConfig();let e=new URLSearchParams({client_id:this.clientId,redirect_uri:this.redirectUrl,response_type:"code",scope:this.formatScopes(this.getScopes(),this.scopeSeparator),state:this.resolveState(),...await this.pkceFields()});for(let t of this.resources())e.append("resource",t);for(let[t,r]of Object.entries(this.parameters))e.set(t,String(r));return`${this.endpoint("authorize")}?${e.toString()}`}async post(e,t){let r=await fetch(e,{method:"POST",headers:{Authorization:`Basic ${bt.from(`${encodeURIComponent(this.clientId)}:${encodeURIComponent(this.clientSecret)}`).toString("base64")}`,"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:t.toString()}),i=await r.json().catch(()=>({}));if(!r.ok)throw new C(typeof i.error==="string"?i.error:"server_error",r.status);return i}tokens(e){if(typeof e.access_token!=="string"||!e.access_token)throw new C("invalid_token_response",502);return{accessToken:e.access_token,refreshToken:typeof e.refresh_token==="string"?e.refresh_token:null,expiresIn:typeof e.expires_in==="number"?e.expires_in:null,scopes:typeof e.scope==="string"?e.scope.split(" ").filter(Boolean):[]}}async getTokens(e){this.validateConfig();let t=new URLSearchParams({grant_type:"authorization_code",code:e,redirect_uri:this.redirectUrl,...this.pkceTokenFields()});for(let r of this.resources())t.append("resource",r);return this.tokens(await this.post(this.endpoint("token"),t))}async getAccessToken(e){return(await this.getTokens(e)).accessToken}async refreshTokens(e){this.validateConfig();let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e});for(let r of this.resources())t.append("resource",r);return this.tokens(await this.post(this.endpoint("token"),t))}async revokeToken(e,t="refresh_token"){this.validateConfig(),await this.post(this.endpoint("revoke"),new URLSearchParams({token:e,token_type_hint:t}))}async getClaims(e){this.validateConfig();let t=await fetch(this.settings.userInfoUrl,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}}),r=await t.json().catch(()=>({}));if(!t.ok)throw new C(typeof r.error==="string"?r.error:"invalid_token",t.status);if(typeof r.sub!=="string"||!r.sub)throw new C("invalid_userinfo",502);return r}async getUserByToken(e){let t=await this.getClaims(e),r=typeof t.email==="string"?t.email:null;return{id:String(t.sub),nickname:typeof t.preferred_username==="string"?t.preferred_username:null,name:typeof t.name==="string"&&t.name?t.name:r??"",email:r,emailVerified:typeof t.email_verified==="boolean"?t.email_verified:null,avatar:typeof t.picture==="string"?t.picture:null,token:e,raw:t}}}import{config as Pt}from"@stacksjs/config";var q=["clientId","clientSecret","redirectUrl"],R=Object.freeze({google:{name:"google",label:"Google",driver:Z,required:q,postCallback:!1,pkce:!1,nonce:!1},github:{name:"github",label:"GitHub",driver:Y,required:q,postCallback:!1,pkce:!1,nonce:!1},facebook:{name:"facebook",label:"Facebook",driver:Q,required:q,postCallback:!1,pkce:!1,nonce:!1},twitter:{name:"twitter",label:"X",driver:se,required:q,postCallback:!1,pkce:!0,nonce:!1},apple:{name:"apple",label:"Apple",driver:K,required:["clientId","teamId","keyId","privateKey","redirectUrl"],postCallback:!0,pkce:!1,nonce:!0}});function _e(e){return Pt?.services?.[e]}function xt(e){return typeof e==="string"&&e in R}function Ae(e){if(!xt(e))return!1;let t=_e(e);if(!t)return!1;return R[e].required.every((r)=>Boolean(t[r]))}function li(){return Object.keys(R).filter(Ae).map((e)=>R[e])}function di(e){if(!Ae(e))return null;let t=R[e],r=_e(e)??{};return new t.driver({clientSecret:"",...r,clientId:String(r.clientId??""),redirectUrl:String(r.redirectUrl??"")})}class vt{accessToken;refreshToken;expiresIn;approvedScopes;constructor(e,t=null,r=null,i=[]){this.accessToken=e;this.refreshToken=t;this.expiresIn=r;this.approvedScopes=i}}function hi(e){return typeof e?.deletePost==="function"}function gi(e){return typeof e?.listAuthoredPosts==="function"}import{buildSessionHandoffCodeUrl as Tt,buildSessionHandoffUrl as It}from"@stacksjs/composables";function ne(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 wi(e,t={}){let r=t.redirectTo??"/";if(!ne(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:It(r,e),"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function yi(e,t={}){let r=t.redirectTo??"/";if(!ne(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:Tt(r,e),"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function ki(e,t={}){let r=t.redirectTo??"/login";if(!ne(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","Referrer-Policy":"no-referrer"}})}import{Buffer as Ue}from"buffer";import{createHash as _t,randomBytes as At,timingSafeEqual as Ut}from"crypto";function E(e){return _t("sha256").update(e).digest("hex")}var Ct=/^[a-f0-9]{64}$/,Rt=/^[a-f0-9]{64}$/,$t=/^[\w.:-]{1,64}$/,Et=3600000,Ce=null;function xi(e){Ce=e}function Re(){return Ce??Bt()}function oe(e=32){return At(e).toString("hex")}function Ot(e,t){if(e.length!==t.length)return!1;return Ut(Ue.from(e,"utf8"),Ue.from(t,"utf8"))}function ae(e){return`stacks_oauth_${E(e).slice(0,24)}`}async function Lt(){try{let{config:e}=await import("@stacksjs/config");return String(e.app?.url??"").startsWith("https:")}catch{return!1}}function $e(e,t,r,i){return[`${e}=${t}`,`Path=${i.path}`,"HttpOnly",`SameSite=${i.sameSite}`,`Max-Age=${Math.max(0,Math.floor(r))}`,...i.secure?["Secure"]:[]].join("; ")}async function Ee(e={}){let t=e.sameSite??"Lax",r=t==="None"?!0:e.secure??await Lt();return{path:e.path??"/",sameSite:t,secure:r}}async function vi(e){if(!$t.test(e.purpose??""))throw TypeError("[socials] issueOAuthFlow needs a purpose of 1-64 word characters, dots, colons or dashes.");if(!Number.isFinite(e.ttlMs)||e.ttlMs<=0)throw TypeError("[socials] issueOAuthFlow needs a positive ttlMs.");if(e.challenge!==void 0&&!Rt.test(e.challenge))throw TypeError("[socials] issueOAuthFlow challenge must be the lowercase hex SHA-256 of the verifier.");if(e.userId!=null&&(!Number.isSafeInteger(e.userId)||e.userId<=0))throw TypeError("[socials] issueOAuthFlow userId must be a positive integer.");let t=Math.min(e.ttlMs,Et),r=oe(),s=(e.challenge?!1:e.bindBrowser!==!1)?oe():null,n=e.nonce===!0?oe():typeof e.nonce==="string"&&e.nonce?e.nonce:void 0,o=new Date,a=new Date(o.getTime()+t),c=Re();try{await c.prune(o)}catch{}await c.insert({stateDigest:E(r),purpose:e.purpose,browserDigest:e.challenge??(s?E(s):null),userId:e.userId??null,nonce:n??null,data:e.data??null,expiresAt:a});let l=s?$e(ae(r),s,t/1000,await Ee(e.cookie)):null;return{state:r,cookie:l,secret:s,...n!==void 0&&{nonce:n},expiresAt:a}}async function Ti(e,t){if(typeof e!=="string"||!Ct.test(e))return null;let r=Re(),i=E(e),s=await r.find(i);if(!s)return null;if(s.expiresAt.getTime()<=Date.now())return await r.take(i).catch(()=>!1),null;if(s.purpose!==t.purpose)return null;if(s.browserDigest!==null){let n=t.browserSecret;if(typeof n!=="string"||n.length===0||n.length>512)return null;if(!Ot(E(n),s.browserDigest))return null}if(!await r.take(i))return null;return{purpose:s.purpose,userId:s.userId,nonce:s.nonce,data:s.data,expiresAt:s.expiresAt}}function Ii(e,t){if(!e||!t)return"";let r=ae(t);for(let i of e.split(";")){let s=i.trim();if(s.startsWith(`${r}=`))return s.slice(r.length+1)}return""}async function _i(e,t={}){return $e(ae(e),"",0,await Ee(t))}function Ai(){let e=new Map;return{records:e,async insert(t){e.set(t.stateDigest,{...t})},async find(t){let r=e.get(t);return r?{...r}:void 0},async take(t){return e.delete(t)},async prune(t){for(let[r,i]of e)if(i.expiresAt.getTime()<=t.getTime())e.delete(r)}}}var H="oauth_flows";function Bt(){let e=()=>import("@stacksjs/database/runtime");return{async insert(t){let{db:r,sqlDateTime:i}=await e();await r.insertInto(H).values({state_digest:t.stateDigest,purpose:t.purpose,browser_digest:t.browserDigest,user_id:t.userId,nonce:t.nonce,data:t.data?JSON.stringify(t.data):null,expires_at:i(t.expiresAt),created_at:i(new Date)}).execute()},async find(t){let{db:r,parseSqlDateTime:i}=await e(),s=await r.primary.selectFrom(H).where("state_digest","=",t).selectAll().executeTakeFirst();if(!s)return;let n=null;if(typeof s.data==="string"&&s.data)try{let o=JSON.parse(s.data);n=o&&typeof o==="object"?o:null}catch{n=null}return{stateDigest:String(s.state_digest),purpose:String(s.purpose),browserDigest:typeof s.browser_digest==="string"&&s.browser_digest?s.browser_digest:null,userId:s.user_id==null?null:Number(s.user_id),nonce:typeof s.nonce==="string"&&s.nonce?s.nonce:null,data:n,expiresAt:i(s.expires_at)??new Date(0)}},async take(t){let{db:r,mutationCount:i}=await e(),s=await r.deleteFrom(H).where("state_digest","=",t).execute();return i(s)===1},async prune(t){let{db:r,sqlDateTime:i}=await e();await r.deleteFrom(H).where("expires_at","<",i(t)).execute()}}}var Dt={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"]},Nt={bluesky:["identifier","password"],twitter:["clientId","clientSecret","accessToken"],linkedin:["accessToken","memberUrn"],mastodon:["accessToken","instanceUrl"],instagram:["accessToken","accountId"],threads:["accessToken","userId"]};function Ft(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function V(e,t,r){let i=r.replace(/[A-Z]/g,(s)=>`_${s}`).toUpperCase();return`SOCIALS_${Ft(e)}_${t.toUpperCase()}_${i}`}class f extends Error{constructor(e){super(e);this.name="SocialIdentityError"}}async function j(){let{config:e,overridesReady:t}=await import("@stacksjs/config");return await t,e.socials??{}}function Oe(e,t){let r=Object.keys(e.identities??{});if(t){if(!r.includes(t))throw new f(`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 f(`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 f("config/socials.ts declares no identities, so there is no account to post as.");throw new f(`config/socials.ts declares ${r.length} identities (${r.join(", ")}) and no default, so a call has to name one.`)}function Mt(e,t,r,i=process.env){let n=(e.identities?.[r]??{}).credentials?.[t]??{},o={};for(let a of Dt[t]){let c=(n[a]??i[V(r,t,a)]??"").trim();if(c)o[a]=c}return o}function ce(e,t,r,i=process.env){let s=Oe(e,r),n=Mt(e,t,s,i),o=Nt[t].filter((a)=>!n[a]);if(o.length){let a=o.map((c)=>V(s,t,c)).join(", ");throw new f(`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 Le(e){return Oe(await j(),e)}async function A(e,t,r){return ce(await j(),e,t,r)}function Ci(e,t){return A("bluesky",e,t)}function Ri(e,t){return A("twitter",e,t)}function $i(e,t){return A("linkedin",e,t)}function Ei(e,t){return A("mastodon",e,t)}function Oi(e,t){return A("instagram",e,t)}function Li(e,t){return A("threads",e,t)}import{randomBytes as zt}from"crypto";function Mi(e){return e==="twitter"}var qt=["tweet.read","tweet.write","users.read","offline.access"],Ht="127.0.0.1",Be="/callback";function zi(e){if(!Number.isInteger(e)||e<1||e>65535)throw new f(`${e} is not a port a redirect can listen on.`);return`http://${Ht}:${e}${Be}`}function qi(){return zt(16).toString("hex")}function Hi(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!==Be)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 Vi(e,t,r){let i=[];for(let[s,n]of Object.entries(r)){if(!n)continue;i.push(`${V(e,t,s)}=${n}`)}return i}async function ji(e){let t=new _,r=await t.exchangeCode(e);if(!r.accessToken)throw new f("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 Ji(e){return new _().createAuthorization({clientId:e.clientId,redirectUrl:e.redirectUrl,scopes:[...qt],state:e.state})}function Gi(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 Vt={bluesky:null,twitter:null,linkedin:"memberUrn",mastodon:"instanceUrl",instagram:"accountId",threads:"userId"};function jt(e,t){if(e==="bluesky")return t.service?{service:t.service}:{};if(e==="linkedin")return t.apiVersion?{apiVersion:t.apiVersion}:{};return{}}function Jt(e,t={}){switch(e){case"bluesky":return new B(t);case"linkedin":return new te(t);case"twitter":return new _;case"mastodon":return new re;case"instagram":return new ee;case"threads":return new ie;default:throw new f(`No publishing driver for '${String(e)}'.`)}}function Gt(e,t,r){let i=Vt[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 Kt(e,t,r){if(!r)return;if(r.includes(t))return;throw new f(`Identity '${e}' is not set up for ${t}. config/socials.ts lists: ${r.length?r.join(", "):"none"}.`)}async function Xt(e,t,r){let i=await j(),s=await Le(t),n=i.identities?.[s]??{};Kt(s,e,n.platforms);let o=ce(i,e,s,r),a=jt(e,o);if(e==="bluesky"){let c=await new B(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:Gt(e,n.handle??"",o),options:a}}async function Wi(e,t,r,i){let s=await Xt(e,r,i);return Jt(s.platform,s.options).publish(s.identity,t)}function Qt(e){let t;try{t=typeof e==="string"?JSON.parse(e):e}catch{return""}if(!t||typeof t!=="object")return"";let r=Array.isArray(t.errors)?t.errors[0]:void 0,i=[t.detail,t.error?.error_user_msg,t.error?.message,t.message,t.error_description,r?.detail,r?.message,typeof t.error==="string"?t.error:void 0];for(let s of i){let n=typeof s==="string"?s.replace(/\s+/g," ").trim():"";if(n&&n.length<=200&&n.includes(" ")&&!/[{}<>]/.test(n))return n.replace(/[.!]+$/,"")}return""}function Wt(e,t){let r=(i)=>i.test(t);if(e===429||r(/rate.?limit|too many requests|usage cap|throttl/i))return"rate-limited";if(r(/duplicate|already (?:posted|published|exists)|DUPLICATE_POST/i))return"duplicate";if(e===401||r(/invalid.?token|expired.?token|token (?:has )?(?:expired|been revoked)|session has (?:expired|been invalidated)|OAuthException.*(?:expired|invalid)|REVOKED_ACCESS_TOKEN/i))return"expired";if(e===413||r(/media|image|video|attachment|aspect ratio|file size|unsupported (?:format|type)|blob/i))return"media";if(e===403||r(/permission|scope|not (?:allowed|authorized|permitted)|forbidden|ACCESS_DENIED|insufficient/i))return"permission";if(e===408||e>=500)return"temporary";if(e===400||e===404||e===409||e===422)return"content";if(r(/fetch failed|network|ENOTFOUND|ECONNREFUSED|ECONNRESET|EAI_AGAIN|timed? ?out|socket|aborted/i))return"temporary";return"unknown"}function Yt(e){let t=e??{},r=Number(t.status)||0,i=String(t.message??e??""),s=Qt(t.body),n=typeof t.body==="string"?t.body.slice(0,2000):"";return{kind:Wt(r,`${s} ${n} ${r?"":i}`),status:r,reason:s}}function Zi(e){return Yt(e).kind==="expired"}export{Ht as AUTHORIZE_HOST,Be as AUTHORIZE_PATH,g as AbstractProvider,K as AppleProvider,ye as BLUESKY_MAX_BLOB_BYTES,Ye as BLUESKY_MAX_IMAGES,Ze as BLUESKY_MAX_LANGS,X as BlueskyApiError,B as BlueskyPublishingDriver,p as ConfigException,Vt as DRIVER_DID_FIELD,Q as FacebookProvider,Y as GitHubProvider,Z as GoogleProvider,rt as INSTAGRAM_MAX_IMAGES,k as InstagramApiError,ee as InstagramPublishingDriver,Fe as InvalidStateException,xe as LINKEDIN_API_VERSION,ct as LINKEDIN_MAX_ALT_TEXT,at as LINKEDIN_MAX_IMAGES,hr as LINK_LENGTH,y as LinkedInApiError,te as LinkedInPublishingDriver,I as MASTODON_DEFAULT_LIMITS,st as MAX_POST_IMAGE_BYTES,D as META_GRAPH_VERSION,ve as MastodonApiError,re as MastodonPublishingDriver,Pe as PostImageError,Nt as REQUIRED_SOCIAL_CREDENTIALS,Dt as SOCIAL_CREDENTIAL_FIELDS,R as SOCIAL_PROVIDERS,f as SocialIdentityError,C as StacksIssuerError,St as StacksIssuerProvider,ft as THREADS_MAX_ALT_TEXT,mt as THREADS_MAX_IMAGES,qt as TWITTER_PUBLISH_SCOPES,b as ThreadsApiError,ie as ThreadsPublishingDriver,vt as Token,P as TwitterApiError,se as TwitterProvider,_ as TwitterPublishingDriver,kt as X_MAX_ALT_TEXT,yt as X_MAX_IMAGES,Kt as assertPlatformDeclared,Gi as callbackPage,zi as callbackUri,Yt as classifySocialError,_i as clearOAuthFlowCookie,ji as completeTwitterAuthorization,li as configuredSocialProviders,Ti as consumeOAuthFlow,Xe as countText,Bt as databaseOAuthFlowStore,tt as detectFacetCandidates,jt as driverOptions,Vi as envLines,V as envName,Ft as envSegment,lt as escapeLinkedInText,m as exceedsLimit,v as fetchPostImage,ge as graphemes,Mi as isAuthorizablePlatform,fr as isBlueskySessionError,Zi as isExpiredSignIn,ne as isSafeHandoffTarget,Ae as isSocialProviderConfigured,xt as isSocialProviderName,vi as issueOAuthFlow,nt as linkedInVersionSunset,Ai as memoryOAuthFlowStore,Qt as networkReason,qi as newState,ht as normalizeInstance,ae as oauthFlowCookieName,E as oauthFlowDigest,Qe as parseAtUri,ce as pickCredentials,Oe as pickIdentity,Wi as publishAs,Jt as publishingDriver,Hi as readCallback,Mt as readCredentials,Ii as readOAuthFlowCookie,Ci as resolveBlueskyCredentials,Le as resolveIdentityName,Oi as resolveInstagramCredentials,$i as resolveLinkedInCredentials,ot as resolveLinkedInVersion,Ei as resolveMastodonCredentials,T as resolvePostImage,A as resolveSocialCredentials,Li as resolveThreadsCredentials,Ri as resolveTwitterCredentials,Se as sniffImageType,yi as socialHandoffCodeRedirect,ki as socialHandoffFailureRedirect,wi as socialHandoffRedirect,di as socialProvider,Xt as socialPublishTarget,j as socialsConfig,Ji as startTwitterAuthorization,hi as supportsDeletion,gi as supportsEnumeration,Gt as toDriverIdentity,xi as useOAuthFlowStore};
|
package/dist/media.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { PublicFetchOptions } from '@stacksjs/security';
|
|
2
|
+
/** Identify an image from its first bytes. */
|
|
3
|
+
export declare function sniffImageType(bytes: Uint8Array): PostImageMimeType | null;
|
|
4
|
+
/**
|
|
5
|
+
* Download the image at `url`. Null when it is refused, cannot be fetched, or
|
|
6
|
+
* is not a JPEG, PNG, GIF or WebP image: the driver decides what a missing
|
|
7
|
+
* image means.
|
|
8
|
+
*/
|
|
9
|
+
export declare function fetchPostImage(url: string, options?: PublicFetchOptions): Promise<PostImage | null>;
|
|
10
|
+
/**
|
|
11
|
+
* The bytes of one attached image: as given, or downloaded from its address.
|
|
12
|
+
* Throws {@link PostImageError} for an address that gives no image, rather
|
|
13
|
+
* than posting without it. Undefined only for an item with neither.
|
|
14
|
+
*/
|
|
15
|
+
export declare function resolvePostImage(item: { url?: string, bytes?: Uint8Array, mimeType?: string }, fetchImage: PostImageFetcher): Promise<{ bytes: Uint8Array, mimeType: string } | undefined>;
|
|
16
|
+
/**
|
|
17
|
+
* Images a post refers to by address.
|
|
18
|
+
*
|
|
19
|
+
* The X and Mastodon drivers used to download such an image with a bare
|
|
20
|
+
* `fetch`: whatever address a post carried, including the server's own
|
|
21
|
+
* loopback services or a cloud metadata endpoint, of any size, following any
|
|
22
|
+
* redirect. An address on a post is somebody else's input, so it goes through
|
|
23
|
+
* `fetchPublicUrl`, which re-checks every hop and caps the body, and the
|
|
24
|
+
* bytes are identified by what they are rather than by the type the other end
|
|
25
|
+
* claimed.
|
|
26
|
+
*/
|
|
27
|
+
/** Larger than any network accepts. Each network's own limit is its own to enforce. */
|
|
28
|
+
export declare const MAX_POST_IMAGE_BYTES: number;
|
|
29
|
+
export declare interface PostImage {
|
|
30
|
+
bytes: Uint8Array
|
|
31
|
+
mimeType: PostImageMimeType
|
|
32
|
+
}
|
|
33
|
+
export type PostImageMimeType = 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp';
|
|
34
|
+
/** How a driver downloads an image given by address. Replaceable per driver, for tests or a local network. */
|
|
35
|
+
export type PostImageFetcher = (url: string) => Promise<PostImage | null>;
|
|
36
|
+
/** Raised when a post's image cannot be read. Carries the same `status` and `body` as a network's own error. */
|
|
37
|
+
export declare class PostImageError extends Error {
|
|
38
|
+
/** @defaultValue 422 */
|
|
39
|
+
readonly status: number;
|
|
40
|
+
/** @defaultValue '' */
|
|
41
|
+
readonly body: string;
|
|
42
|
+
readonly url: string;
|
|
43
|
+
constructor(url: string);
|
|
44
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** The short sentence a network gives as its reason, when it gives one. */
|
|
2
|
+
export declare function networkReason(body: unknown): string;
|
|
3
|
+
/**
|
|
4
|
+
* Classify a publishing failure from any driver.
|
|
5
|
+
*
|
|
6
|
+
* An error without a status is either a network fault (`temporary`) or one a
|
|
7
|
+
* driver raised itself before sending anything ("posts must be 300
|
|
8
|
+
* characters or fewer"), which is `unknown` and whose message is already
|
|
9
|
+
* written for a person.
|
|
10
|
+
*/
|
|
11
|
+
export declare function classifySocialError(error: unknown): SocialErrorClassification;
|
|
12
|
+
/** Whether the failure means the account has to sign in again. */
|
|
13
|
+
export declare function isExpiredSignIn(error: unknown): boolean;
|
|
14
|
+
export declare interface SocialErrorClassification {
|
|
15
|
+
kind: SocialErrorKind
|
|
16
|
+
status: number
|
|
17
|
+
reason: string
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* What kind of failure a network answered with.
|
|
21
|
+
*
|
|
22
|
+
* Every driver error carries the network's HTTP `status` and raw `body`, and
|
|
23
|
+
* each one had its own `isAuthError`, most of them `401 || 403`. That treats
|
|
24
|
+
* X refusing a duplicate post, or a token missing one permission, as a token
|
|
25
|
+
* that is no longer good, and an app that disconnects an account on
|
|
26
|
+
* `isAuthError` disconnected one that was working. Bluesky's counted every
|
|
27
|
+
* 400 as well, so an invalid record looked like an expired session.
|
|
28
|
+
*
|
|
29
|
+
* {@link classifySocialError} reads the status and the network's own words
|
|
30
|
+
* and puts the failure in one of a few kinds. Only `expired` means the
|
|
31
|
+
* account must sign in again. Turning a kind into a sentence for a person is
|
|
32
|
+
* the app's business: it knows where its settings live.
|
|
33
|
+
*
|
|
34
|
+
* No imports: it reads `status`, `body` and `message`, which every driver
|
|
35
|
+
* error carries, so it works on any of them and on a plain `Error`.
|
|
36
|
+
*/
|
|
37
|
+
export type SocialErrorKind = | 'expired'
|
|
38
|
+
| 'permission'
|
|
39
|
+
| 'rate-limited'
|
|
40
|
+
| 'duplicate'
|
|
41
|
+
| 'content'
|
|
42
|
+
| 'media'
|
|
43
|
+
| 'temporary'
|
|
44
|
+
| 'unknown';
|
package/dist/text.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** The number of user-perceived characters. */
|
|
2
|
+
export declare function graphemes(text: string): number;
|
|
3
|
+
/** The length `provider` would measure `text` at. */
|
|
4
|
+
export declare function countText(provider: string, text: string, options?: CountTextOptions): number;
|
|
5
|
+
/** Whether `text` is longer than `limit` on `provider`. A limit of 0 means none. */
|
|
6
|
+
export declare function exceedsLimit(provider: string, text: string, limit: number, options?: CountTextOptions): boolean;
|
|
7
|
+
/**
|
|
8
|
+
* Count a post the way each network counts it.
|
|
9
|
+
*
|
|
10
|
+
* The drivers used to check every limit with `.length`, which counts UTF-16
|
|
11
|
+
* units. No network counts that way, so a driver disagreed with the network
|
|
12
|
+
* in both directions: a Bluesky post of 200 emoji, well within 300, was
|
|
13
|
+
* refused before it was sent, and an X post in Japanese passed here and was
|
|
14
|
+
* refused by X.
|
|
15
|
+
*
|
|
16
|
+
* No imports, so a composer in the browser can run the same code as the
|
|
17
|
+
* server and show the same count.
|
|
18
|
+
*
|
|
19
|
+
* - Bluesky counts graphemes: one emoji, however it is built, is one.
|
|
20
|
+
* - X counts a weighted length: most Latin text is one each, CJK and emoji
|
|
21
|
+
* are two, and a link is always 23 whatever its real length.
|
|
22
|
+
* - Mastodon counts graphemes, a link as 23 (or what the instance says), and
|
|
23
|
+
* a mention without its server (`@name@example.social` counts as `@name`).
|
|
24
|
+
* - Threads counts graphemes.
|
|
25
|
+
* - LinkedIn and Instagram are counted in UTF-16 units. Their documentation
|
|
26
|
+
* gives a limit and no counting rule; UTF-16 is never smaller than the
|
|
27
|
+
* alternatives, so a post that passes here cannot be too long there.
|
|
28
|
+
*/
|
|
29
|
+
/** What X, and Mastodon by default, count a link as. */
|
|
30
|
+
export declare const LINK_LENGTH: 23;
|
|
31
|
+
export declare interface CountTextOptions {
|
|
32
|
+
linkLength?: number
|
|
33
|
+
}
|
package/dist/types.d.ts
CHANGED
|
@@ -121,6 +121,7 @@ export declare interface PublishPostInput {
|
|
|
121
121
|
uri: string
|
|
122
122
|
title: string
|
|
123
123
|
description?: string
|
|
124
|
+
thumb?: { bytes: Uint8Array, mimeType: string }
|
|
124
125
|
}
|
|
125
126
|
reply?: {
|
|
126
127
|
root: { uri: string, cid: string }
|
|
@@ -139,6 +140,7 @@ export declare interface PublishedPost {
|
|
|
139
140
|
uri: string
|
|
140
141
|
cid?: string
|
|
141
142
|
url?: string
|
|
143
|
+
warnings?: string[]
|
|
142
144
|
}
|
|
143
145
|
export declare interface TimelineQuery {
|
|
144
146
|
cursor?: string
|
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.667",
|
|
6
6
|
"description": "A simple and elegant social authentication package for Stacks.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -57,14 +57,15 @@
|
|
|
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.
|
|
63
|
-
"@stacksjs/database": "0.75.
|
|
60
|
+
"@stacksjs/api": "0.75.667",
|
|
61
|
+
"@stacksjs/composables": "0.75.667",
|
|
62
|
+
"@stacksjs/config": "0.75.667",
|
|
63
|
+
"@stacksjs/database": "0.75.667",
|
|
64
|
+
"@stacksjs/security": "0.75.667"
|
|
64
65
|
},
|
|
65
66
|
"devDependencies": {
|
|
66
|
-
"@stacksjs/error-handling": "0.75.
|
|
67
|
-
"@stacksjs/router": "0.75.
|
|
67
|
+
"@stacksjs/error-handling": "0.75.667",
|
|
68
|
+
"@stacksjs/router": "0.75.667",
|
|
68
69
|
"better-dx": "^0.2.39"
|
|
69
70
|
}
|
|
70
71
|
}
|