@amaster.ai/auth-client 1.1.70 → 1.1.72

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -14,29 +14,14 @@
14
14
  * ============================================================================
15
15
  */
16
16
  import { HttpClient, ClientResult, HttpClientOptions } from '@amaster.ai/http-client';
17
- import { createAuthModule } from './auth.cjs';
17
+ import { AuthModule, createAuthModule } from './auth.cjs';
18
18
  import { createPermissionsModule } from './permissions.cjs';
19
19
  import { createUserModule } from './user.cjs';
20
20
  import { createOAuthModule } from './oauth.cjs';
21
- import { D as DepartmentPosition, A as AuthClientOptions, a as AuthEvent, E as EventHandler } from './types-C2dUef9b.cjs';
22
- export { b as CaptchaResponse, C as ChangePasswordParams, c as CodeLoginParams, d as CodeLoginType, F as FeishuPublicConfig, L as LoginParams, e as LoginResponse, f as LoginType, M as MiniGetPhoneEvent, g as MiniGetPhoneParams, h as MiniLoginParams, i as MiniProgramLoginParams, k as MiniProgramPhoneParams, l as MiniProgramPhoneResponse, j as MiniProgramPlatform, O as OAuthBinding, m as OAuthLoginTicketResponse, n as OAuthProvider, P as Permission, o as PermissionDetail, R as RefreshTokenResponse, p as RegisterParams, q as RegisterResponse, r as RevokeAllSessionsResponse, s as Role, t as RoleDetail, S as SendCodeParams, u as SendCodeType, v as Session, w as SuccessResponse, U as UpdateMeParams, x as User } from './types-C2dUef9b.cjs';
21
+ import { S as StorageAdapter, D as DepartmentPosition, B as BrowserAuthClientOptions, A as AuthEvent, E as EventHandler, L as LoginResponse, a as AuthClientOptions } from './types-BD5m6HPr.cjs';
22
+ export { b as CaptchaResponse, C as ChangePasswordParams, d as CodeLoginParams, e as CodeLoginType, F as FeishuPublicConfig, f as LoginParams, g as LoginType, M as MiniGetPhoneEvent, h as MiniGetPhoneParams, i as MiniLoginParams, j as MiniProgramLoginParams, l as MiniProgramPhoneParams, m as MiniProgramPhoneResponse, k as MiniProgramPlatform, O as OAuthBinding, n as OAuthLoginTicketResponse, o as OAuthProvider, P as Permission, p as PermissionDetail, R as RefreshTokenResponse, q as RegisterParams, r as RegisterResponse, s as RevokeAllSessionsResponse, t as Role, u as RoleDetail, v as SendCodeParams, w as SendCodeType, x as Session, y as SuccessResponse, U as UpdateMeParams, z as User, c as createMemoryStorage } from './types-BD5m6HPr.cjs';
23
23
  import { createSessionsModule } from './sessions.cjs';
24
24
 
25
- /**
26
- * Storage adapter for token and user data persistence
27
- * Auto-detects environment and uses appropriate storage:
28
- * - Browser: localStorage
29
- * - WeChat Mini Program: wx.setStorageSync/wx.getStorageSync
30
- * - Douyin Mini Program: `tt.setStorageSync` / `tt.getStorageSync`
31
- * - SSR/Node.js: No-op (no persistence)
32
- */
33
- interface StorageAdapter {
34
- getItem(key: string): string | null;
35
- setItem(key: string, value: string): void;
36
- removeItem(key: string): void;
37
- clear(): void;
38
- }
39
-
40
25
  declare function createOrganizationModule({ http, storage }: {
41
26
  http: HttpClient;
42
27
  storage: Pick<StorageAdapter, "getItem">;
@@ -51,7 +36,7 @@ declare function createOrganizationModule({ http, storage }: {
51
36
  * Combines all modules into a unified client interface
52
37
  */
53
38
 
54
- type AuthClient = ReturnType<typeof createAuthModule> & ReturnType<typeof createPermissionsModule> & ReturnType<typeof createOrganizationModule> & ReturnType<typeof createUserModule> & ReturnType<typeof createOAuthModule> & ReturnType<typeof createSessionsModule> & {
39
+ type AuthClient = AuthModule & ReturnType<typeof createPermissionsModule> & ReturnType<typeof createOrganizationModule> & ReturnType<typeof createUserModule> & ReturnType<typeof createOAuthModule> & ReturnType<typeof createSessionsModule> & {
55
40
  on(event: AuthEvent, handler: EventHandler): void;
56
41
  off(event: AuthEvent, handler: EventHandler): void;
57
42
  isAuthenticated(): boolean;
@@ -59,8 +44,16 @@ type AuthClient = ReturnType<typeof createAuthModule> & ReturnType<typeof create
59
44
  setAccessToken(token: string): void;
60
45
  clearAuth(): void;
61
46
  };
47
+ /** Browser-session capabilities extend the legacy client without changing its contract. */
48
+ type BrowserAuthClient = AuthClient & Pick<ReturnType<typeof createAuthModule>, "getOAuthLoginURL"> & {
49
+ restoreSession(): Promise<ClientResult<LoginResponse>>;
50
+ };
51
+ declare function createAuthClient(options: BrowserAuthClientOptions, http?: HttpClient): BrowserAuthClient;
62
52
  declare function createAuthClient(options?: AuthClientOptions, http?: HttpClient): AuthClient;
63
53
 
54
+ /** Signal completion only. Application credentials are recovered through the application's HttpOnly cookie. */
55
+ declare function completeOAuthPopup(): boolean;
56
+
64
57
  /**
65
58
  * HTTP Client Configuration Utilities
66
59
  *
@@ -89,4 +82,4 @@ declare function transformAmasterResponse<T>(responseData: unknown): T;
89
82
  */
90
83
  declare const defaultHttpClientOptions: HttpClientOptions;
91
84
 
92
- export { type AuthClient, AuthClientOptions, AuthEvent, DepartmentPosition, EventHandler, createAuthClient, defaultHttpClientOptions, transformAmasterResponse };
85
+ export { type AuthClient, AuthClientOptions, AuthEvent, type BrowserAuthClient, BrowserAuthClientOptions, DepartmentPosition, EventHandler, LoginResponse, StorageAdapter, completeOAuthPopup, createAuthClient, defaultHttpClientOptions, transformAmasterResponse };
package/dist/index.d.ts CHANGED
@@ -14,29 +14,14 @@
14
14
  * ============================================================================
15
15
  */
16
16
  import { HttpClient, ClientResult, HttpClientOptions } from '@amaster.ai/http-client';
17
- import { createAuthModule } from './auth.js';
17
+ import { AuthModule, createAuthModule } from './auth.js';
18
18
  import { createPermissionsModule } from './permissions.js';
19
19
  import { createUserModule } from './user.js';
20
20
  import { createOAuthModule } from './oauth.js';
21
- import { D as DepartmentPosition, A as AuthClientOptions, a as AuthEvent, E as EventHandler } from './types-C2dUef9b.js';
22
- export { b as CaptchaResponse, C as ChangePasswordParams, c as CodeLoginParams, d as CodeLoginType, F as FeishuPublicConfig, L as LoginParams, e as LoginResponse, f as LoginType, M as MiniGetPhoneEvent, g as MiniGetPhoneParams, h as MiniLoginParams, i as MiniProgramLoginParams, k as MiniProgramPhoneParams, l as MiniProgramPhoneResponse, j as MiniProgramPlatform, O as OAuthBinding, m as OAuthLoginTicketResponse, n as OAuthProvider, P as Permission, o as PermissionDetail, R as RefreshTokenResponse, p as RegisterParams, q as RegisterResponse, r as RevokeAllSessionsResponse, s as Role, t as RoleDetail, S as SendCodeParams, u as SendCodeType, v as Session, w as SuccessResponse, U as UpdateMeParams, x as User } from './types-C2dUef9b.js';
21
+ import { S as StorageAdapter, D as DepartmentPosition, B as BrowserAuthClientOptions, A as AuthEvent, E as EventHandler, L as LoginResponse, a as AuthClientOptions } from './types-BD5m6HPr.js';
22
+ export { b as CaptchaResponse, C as ChangePasswordParams, d as CodeLoginParams, e as CodeLoginType, F as FeishuPublicConfig, f as LoginParams, g as LoginType, M as MiniGetPhoneEvent, h as MiniGetPhoneParams, i as MiniLoginParams, j as MiniProgramLoginParams, l as MiniProgramPhoneParams, m as MiniProgramPhoneResponse, k as MiniProgramPlatform, O as OAuthBinding, n as OAuthLoginTicketResponse, o as OAuthProvider, P as Permission, p as PermissionDetail, R as RefreshTokenResponse, q as RegisterParams, r as RegisterResponse, s as RevokeAllSessionsResponse, t as Role, u as RoleDetail, v as SendCodeParams, w as SendCodeType, x as Session, y as SuccessResponse, U as UpdateMeParams, z as User, c as createMemoryStorage } from './types-BD5m6HPr.js';
23
23
  import { createSessionsModule } from './sessions.js';
24
24
 
25
- /**
26
- * Storage adapter for token and user data persistence
27
- * Auto-detects environment and uses appropriate storage:
28
- * - Browser: localStorage
29
- * - WeChat Mini Program: wx.setStorageSync/wx.getStorageSync
30
- * - Douyin Mini Program: `tt.setStorageSync` / `tt.getStorageSync`
31
- * - SSR/Node.js: No-op (no persistence)
32
- */
33
- interface StorageAdapter {
34
- getItem(key: string): string | null;
35
- setItem(key: string, value: string): void;
36
- removeItem(key: string): void;
37
- clear(): void;
38
- }
39
-
40
25
  declare function createOrganizationModule({ http, storage }: {
41
26
  http: HttpClient;
42
27
  storage: Pick<StorageAdapter, "getItem">;
@@ -51,7 +36,7 @@ declare function createOrganizationModule({ http, storage }: {
51
36
  * Combines all modules into a unified client interface
52
37
  */
53
38
 
54
- type AuthClient = ReturnType<typeof createAuthModule> & ReturnType<typeof createPermissionsModule> & ReturnType<typeof createOrganizationModule> & ReturnType<typeof createUserModule> & ReturnType<typeof createOAuthModule> & ReturnType<typeof createSessionsModule> & {
39
+ type AuthClient = AuthModule & ReturnType<typeof createPermissionsModule> & ReturnType<typeof createOrganizationModule> & ReturnType<typeof createUserModule> & ReturnType<typeof createOAuthModule> & ReturnType<typeof createSessionsModule> & {
55
40
  on(event: AuthEvent, handler: EventHandler): void;
56
41
  off(event: AuthEvent, handler: EventHandler): void;
57
42
  isAuthenticated(): boolean;
@@ -59,8 +44,16 @@ type AuthClient = ReturnType<typeof createAuthModule> & ReturnType<typeof create
59
44
  setAccessToken(token: string): void;
60
45
  clearAuth(): void;
61
46
  };
47
+ /** Browser-session capabilities extend the legacy client without changing its contract. */
48
+ type BrowserAuthClient = AuthClient & Pick<ReturnType<typeof createAuthModule>, "getOAuthLoginURL"> & {
49
+ restoreSession(): Promise<ClientResult<LoginResponse>>;
50
+ };
51
+ declare function createAuthClient(options: BrowserAuthClientOptions, http?: HttpClient): BrowserAuthClient;
62
52
  declare function createAuthClient(options?: AuthClientOptions, http?: HttpClient): AuthClient;
63
53
 
54
+ /** Signal completion only. Application credentials are recovered through the application's HttpOnly cookie. */
55
+ declare function completeOAuthPopup(): boolean;
56
+
64
57
  /**
65
58
  * HTTP Client Configuration Utilities
66
59
  *
@@ -89,4 +82,4 @@ declare function transformAmasterResponse<T>(responseData: unknown): T;
89
82
  */
90
83
  declare const defaultHttpClientOptions: HttpClientOptions;
91
84
 
92
- export { type AuthClient, AuthClientOptions, AuthEvent, DepartmentPosition, EventHandler, createAuthClient, defaultHttpClientOptions, transformAmasterResponse };
85
+ export { type AuthClient, AuthClientOptions, AuthEvent, type BrowserAuthClient, BrowserAuthClientOptions, DepartmentPosition, EventHandler, LoginResponse, StorageAdapter, completeOAuthPopup, createAuthClient, defaultHttpClientOptions, transformAmasterResponse };
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import {setMiniProgramRuntime,createHttpClient,getMiniProgramLogin,detectMiniProgramPlatform}from'@amaster.ai/http-client';var L=class{constructor(){this.events={};}on(t,r){this.events[t]||(this.events[t]=[]),this.events[t].push(r);}off(t,r){this.events[t]&&(this.events[t]=this.events[t].filter(n=>n!==r));}emit(t,...r){this.events[t]&&this.events[t].forEach(n=>{try{n(...r);}catch(i){console.error(`[AuthClient] Error in event handler for "${t}":`,i);}});}removeAllListeners(){this.events={};}};var p={ACCESS_TOKEN:"amaster_access_token",REFRESH_TOKEN:"amaster_refresh_token",USER:"amaster_user"};function ge(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;try{return Function("return this")()}catch{return}}function _(e){return ge()?.[e]}function me(){let e=_("wx"),t=_("tt");return e?.getStorageSync&&e?.setStorageSync&&e?.removeStorageSync?"wechat-miniprogram":t?.getStorageSync&&t?.setStorageSync&&t?.removeStorageSync?"douyin-miniprogram":typeof window<"u"&&typeof window.localStorage<"u"?"browser":"node"}function K(){switch(me()){case "wechat-miniprogram":return D(_("wx"),"WeChat");case "douyin-miniprogram":return D(_("tt"),"Douyin");case "browser":return pe();case "node":return fe()}}function pe(){let e=window.localStorage;return {getItem(t){try{return e.getItem(t)}catch(r){return console.error("[AuthClient] Failed to get item from localStorage:",r),null}},setItem(t,r){try{e.setItem(t,r);}catch(n){console.error("[AuthClient] Failed to set item in localStorage:",n);}},removeItem(t){try{e.removeItem(t);}catch(r){console.error("[AuthClient] Failed to remove item from localStorage:",r);}},clear(){try{e.removeItem(p.ACCESS_TOKEN),e.removeItem(p.REFRESH_TOKEN),e.removeItem(p.USER);}catch(t){console.error("[AuthClient] Failed to clear localStorage:",t);}}}}function D(e,t){return {getItem(r){try{return e.getStorageSync(r)||null}catch(n){return console.error(`[AuthClient] Failed to get item from ${t} storage:`,n),null}},setItem(r,n){try{e.setStorageSync(r,n);}catch(i){console.error(`[AuthClient] Failed to set item in ${t} storage:`,i);}},removeItem(r){try{e.removeStorageSync(r);}catch(n){console.error(`[AuthClient] Failed to remove item from ${t} storage:`,n);}},clear(){try{e.removeStorageSync(p.ACCESS_TOKEN),e.removeStorageSync(p.REFRESH_TOKEN),e.removeStorageSync(p.USER);}catch(r){console.error(`[AuthClient] Failed to clear ${t} storage:`,r);}}}}function fe(){let e=new Map;return {getItem(t){return e.get(t)??null},setItem(t,r){e.set(t,r);},removeItem(t){e.delete(t);},clear(){e.clear();}}}function ye(e){try{let t=e.split(".");if(t.length!==3)return null;let n=(t[1]||"").replace(/-/g,"+").replace(/_/g,"/");if(typeof atob<"u"){let i=decodeURIComponent(atob(n).split("").map(d=>"%"+("00"+d.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(i)}if(typeof Buffer<"u"){let i=Buffer.from(n,"base64").toString("utf-8");return JSON.parse(i)}return null}catch(t){return console.error("[AuthClient] Failed to parse JWT token:",t),null}}var O=class{constructor(){this.refreshTimer=null;this.isRefreshing=false;this.refreshCallback=null;}setRefreshCallback(t){this.refreshCallback=t;}scheduleRefresh(t){this.clearSchedule(),!(t<=0)&&(this.refreshTimer=setTimeout(()=>{this.refresh();},t));}scheduleRefreshFromToken(t,r=300){let n=ye(t);if(!n||!n.exp){console.warn("[AuthClient] Cannot schedule refresh: invalid token or missing exp claim");return}let i=n.exp*1e3,d=Date.now(),m=i-d-r*1e3;m<=0?(console.warn("[AuthClient] Token already expired or expiring soon, refreshing immediately"),this.refresh()):this.scheduleRefresh(m);}async refresh(){if(!this.isRefreshing){if(!this.refreshCallback){console.error("[AuthClient] No refresh callback set");return}this.isRefreshing=true;try{await this.refreshCallback();}catch(t){console.error("[AuthClient] Token refresh failed:",t);}finally{this.isRefreshing=false;}}}clearSchedule(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null);}isCurrentlyRefreshing(){return this.isRefreshing}destroy(){this.clearSchedule(),this.refreshCallback=null,this.isRefreshing=false;}};function N(e){return e&&typeof e=="object"&&("statusCode"in e||"status"in e)&&"data"in e?e.data:e}var U={transformResponse:N,logErrors:true};var Pe="https://lf-scm-cn.feishucdn.com/lark/op/h5-js-sdk-1.5.44.js",B="amaster-feishu-h5-sdk";var G=null,E=null,M=null;function W(){if(!(typeof window>"u"))return window}function j(){return W()?.tt}function H(){return W()?.h5sdk}function J(){typeof window>"u"||G===window||(G=window,E=null,M=null);}function Y(){if(typeof navigator>"u")return false;let e=j();return /Feishu|Lark/i.test(navigator.userAgent||"")||typeof e?.requestAccess=="function"||typeof e?.requestAuthCode=="function"}function Se(){return J(),typeof document>"u"?Promise.reject(new Error("Feishu H5 SDK is only available in a browser environment")):typeof H()?.ready=="function"?Promise.resolve():E||(E=new Promise((e,t)=>{let r=document.getElementById(B),n=!r;r||(r=document.createElement("script"),r.id=B,r.src=Pe,r.async=true);let i=false,d,c,m=()=>{d&&clearInterval(d),c&&clearTimeout(c),r?.removeEventListener("load",g),r?.removeEventListener("error",v);},S=f=>{if(!i){if(i=true,m(),f){r?.remove(),t(f);return}e();}},y=()=>typeof H()?.ready=="function"?(S(),true):false,g=()=>{y();},v=()=>{S(new Error("Failed to load Feishu H5 SDK"));};r.addEventListener("load",g),r.addEventListener("error",v),d=setInterval(y,25),c=setTimeout(()=>{S(new Error("Timed out while loading Feishu H5 SDK"));},1e4),!y()&&n&&document.head.appendChild(r);}).catch(e=>{throw E=null,e}),E)}function Re(){return J(),M||(M=(async()=>{await Se();let e=H();if(typeof e?.ready!="function")throw new Error("Feishu H5 SDK loaded without exposing h5sdk.ready");return new Promise((t,r)=>{let n=false,i,d=(c,m)=>{n||(n=true,i&&clearTimeout(i),m?r(m):c?t(c):r(new Error("Feishu H5 SDK became ready without exposing the tt bridge")));};i=setTimeout(()=>{d(void 0,new Error("Timed out while waiting for Feishu H5 SDK ready"));},1e4),e.error?.(c=>d(void 0,new Error(x(c))));try{let c=e.ready?.(()=>d(j()));c&&typeof c.then=="function"&&c.catch(m=>{d(void 0,new Error(`Feishu H5 SDK ready failed: ${m instanceof Error?m.message:String(m)}`));});}catch(c){d(void 0,new Error(`Feishu H5 SDK ready failed: ${c instanceof Error?c.message:String(c)}`));}})})().catch(e=>{throw M=null,e}),M)}function x(e){return e.errString||e.message||`Feishu authorization failed${e.errno?` (${e.errno})`:""}`}function z(e,t){return typeof e.requestAuthCode!="function"?Promise.reject(new Error("The current Feishu client does not support requestAuthCode")):new Promise((r,n)=>{e.requestAuthCode?.({appId:t,success:i=>{i.code?r(i.code):n(new Error("Feishu requestAuthCode returned no code"));},fail:i=>n(new Error(x(i)))});})}async function Q(e){let t=await Re();return typeof t.requestAccess!="function"?z(t,e):new Promise((r,n)=>{t.requestAccess?.({appID:e,scopeList:[],success:i=>{i.code?r(i.code):n(new Error("Feishu requestAccess returned no code"));},fail:i=>{if(i.errno===103){z(t,e).then(r,n);return}n(new Error(x(i)));}});})}function Ae(e){if(e.email)return "email";if(e.username)return "username";if(e.phone)return "phone"}function ve(e){if(e.email)return "email";if(e.phone)return "phone"}function F(e){return e||(detectMiniProgramPlatform()??"wechat")}function q(e){return typeof e=="string"?{code:e,platform:F()}:{code:e.code,platform:F(e.platform)}}function V(e,t){return t==="douyin"?`/api/auth/miniprogram/douyin/${e}`:`/api/auth/miniprogram/${e}`}async function ke(e){let t=F(e),r=getMiniProgramLogin(t),n=async i=>await new Promise((d,c)=>{let m=false,S=g=>{if(!m){if(m=true,typeof g?.code=="string"&&g.code){d(g.code);return}c(new Error("Mini Program login failed: missing code"));}},y=g=>{m||(m=true,c(new Error(`Mini Program login failed: ${g instanceof Error?g.message:String(g)}`)));};try{let g=i({success:S,fail:y});if(g&&typeof g.then=="function"){g.then(S,y);return}g&&typeof g=="object"&&"code"in g&&S(g);}catch(g){y(g);}});if(typeof r!="function")throw new Error(`Mini Program login API is not available for platform '${t}'`);return {code:await n(r),platform:t}}function X(e){if(typeof e=="string")return q(e);let t="detail"in e&&e.detail&&typeof e.detail=="object"?e.detail:null,r=typeof t?.code=="string"&&t.code?t.code:typeof e.code=="string"&&e.code?e.code:void 0;return r?{code:r,platform:F(e.platform)}:null}function Te(e){let t=new URLSearchParams(e);return t.get("access_token")||t.get("accessToken")}function Ee(e){return new URLSearchParams(e).get("user")}function Z(e){if(typeof window>"u")return null;try{let t=e||new URLSearchParams(window.location.search).get("redirect");if(!t)return null;let r=new URL(t,window.location.origin);return r.origin!==window.location.origin?(console.warn("[AuthClient] Ignored cross-origin redirect target:",t),null):`${r.pathname}${r.search}${r.hash}`}catch(t){return console.warn("[AuthClient] Failed to resolve redirect target:",t),null}}var $={assign(e){window.location.assign(e);},replace(e){window.location.replace(e);}};function k(e,t){return t.handled?{...e,redirectHandled:true,redirectTarget:t.target}:e}function T(e,t){if(!e||typeof window>"u"||window.opener)return {handled:false};let r=Z(t);return r?($.replace(r),{handled:true,target:r}):{handled:false}}function ee(e){let{http:t,onLoginSuccess:r,onLogout:n,autoRedirectAfterLogin:i,storage:d,clearAuth:c,onRefreshFailure:m}=e,S=new Map,y=null,g=o=>{let s=o.trim(),a=S.get(s);if(a)return a;let u=(async()=>{if(!s)return {data:null,error:{message:"OAuth login ticket is required",status:400},status:400};let h=await t.request({url:"/api/auth/oauth/ticket",method:"post",headers:{"Content-Type":"application/json"},data:{ticket:s}});if(!h.data?.accessToken)return {data:null,error:h.error||{message:"OAuth login ticket is invalid, expired, or already used",status:h.status||400},status:h.status||400};let w=d.getItem(p.ACCESS_TOKEN),R=h.data.accessToken;d.setItem(p.ACCESS_TOKEN,R);let P=await t.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${R}`}});if(!P.data)return w?d.setItem(p.ACCESS_TOKEN,w):d.removeItem(p.ACCESS_TOKEN),{data:null,error:P.error||{message:"OAuth login succeeded but user information could not be loaded",status:P.status||500},status:P.status||500};r(P.data,R);let C=T(i,h.data.returnUrl);return {data:k({user:P.data,accessToken:R},C),error:null,status:200}})();return S.set(s,u),u},v=o=>{if(typeof window>"u")return;let s=Z(o)||"/",a=new URLSearchParams({return_url:s,callback_url:"/auth/callback"});$.assign(`/api/auth/oauth/feishu?${a.toString()}`);},f=async(o,s)=>{let a=await t.request({url:"/api/auth/oauth/feishu/code",method:"post",headers:{"Content-Type":"application/json"},data:{code:o}});if(a.data?.user&&a.data?.accessToken){r(a.data.user,a.data.accessToken);let u=T(i,s);a.data=k(a.data,u);}return a};return {async register(o){let s=await t.request({url:"/api/auth/register",method:"post",headers:{"Content-Type":"application/json"},data:o});if(s.data?.user&&s.data?.accessToken){r(s.data.user,s.data.accessToken);let a=T(i);s.data=k(s.data,a);}return s},async login(o){let s=o.loginType||Ae(o);if(!s)return {data:null,error:{message:"Unable to determine login type. Please provide email, username, or phone.",status:400},status:400};let a={...o,loginType:s},u=await t.request({url:"/api/auth/login",method:"post",headers:{"Content-Type":"application/json"},data:a});if(u.data?.user&&u.data?.accessToken){r(u.data.user,u.data.accessToken);let h=T(i);u.data=k(u.data,h);}return u},async loginWithCode(o){let s=o.loginType||ve(o);if(!s)return {data:null,error:{message:"Unable to determine login type. Please provide email or phone.",status:400},status:400};let a={...o,loginType:s},u=await t.request({url:"/api/auth/login-with-code",method:"post",headers:{"Content-Type":"application/json"},data:a});if(u.data?.user&&u.data?.accessToken){r(u.data.user,u.data.accessToken);let h=T(i);u.data=k(u.data,h);}return u},async sendCode(o){return t.request({url:"/api/auth/send-code",method:"post",headers:{"Content-Type":"application/json"},data:o})},async getCaptcha(){return t.request({url:"/api/auth/captcha",method:"get"})},loginWithOAuth(o,s){if(typeof window>"u"){console.error("[AuthClient] OAuth login is only available in browser environment");return}if(o==="feishu"){v(s);return}let a=new URLSearchParams;if(s&&a.set("redirect_uri",s),o==="wecom"){if(s){let P=new URL(s,window.location.origin);P.origin===window.location.origin&&(P.searchParams.delete("oauth_error"),P.searchParams.delete("error_description"),a.set("redirect_uri",P.pathname+P.search+P.hash));}let w=new URLSearchParams(window.location.search);w.delete("oauth_error"),w.delete("error_description");let R=w.toString();a.set("error_redirect_uri",`${window.location.pathname}${R?`?${R}`:""}`);}let u=a.toString(),h=`/api/auth/oauth/${o}${u?`?${u}`:""}`;$.assign(h);},async loginWithFeishu(o){if(typeof window>"u")return {data:null,error:{message:"Feishu login is only available in a browser environment",status:400},status:400};if(!Y())return v(o),null;let s=await t.request({url:"/api/auth/oauth/feishu/config",method:"get"});if(!s.data?.enabled||!s.data.appId)return {data:null,error:s.error||{message:"Feishu login is not configured for this application",status:s.status||400},status:s.status||400};try{let a=await Q(s.data.appId);return await f(a,o)}catch(a){return {data:null,error:{message:a instanceof Error?a.message:String(a),status:400},status:400}}},async loginWithFeishuCode(o,s){return f(o,s)},async exchangeOAuthLoginTicket(o){return g(o)},handleOAuthCallback(){return y||(y=(async()=>{if(typeof window>"u")return {data:null,error:{message:"OAuth callback is only available in browser environment",status:400},status:400};try{let o=new URLSearchParams(window.location.search),s=o.get("oauth_error");if(s)return {data:null,error:{message:o.get("error_description")||`OAuth callback failed: ${s}`,status:400},status:400};let a=o.get("login_ticket");if(a){o.delete("login_ticket");let C=o.toString();return window.history.replaceState(null,"",`${window.location.pathname}${C?`?${C}`:""}${window.location.hash}`),g(a)}let u=window.location.hash.substring(1),h=Te(u),w=Ee(u);if(!h)return {data:null,error:{message:"OAuth callback failed: missing access token",status:400},status:400};let R;if(w)R=JSON.parse(decodeURIComponent(w));else {d.setItem(p.ACCESS_TOKEN,h);let C=await t.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${h}`}});if(!C.data)return {data:null,error:{message:"OAuth callback failed: unable to fetch user info",status:C.status||500},status:C.status||500};R=C.data;}if(r(R,h),window.history&&window.history.replaceState){let C=window.location.pathname+window.location.search;window.history.replaceState(null,"",C);}else window.location.hash="";let P=T(i);return {data:k({user:R,accessToken:h},P),error:null,status:200}}catch(o){return {data:null,error:{message:`OAuth callback failed: ${o instanceof Error?o.message:String(o)}`,status:400},status:400}}})(),y)},async loginWithMiniProgram(o){let{code:s,platform:a}=q(o),u=await t.request({url:V("login",a),method:"post",headers:{"Content-Type":"application/json"},data:{code:s}});if(u.data?.user&&u.data?.accessToken){r(u.data.user,u.data.accessToken);let h=T(i);u.data=k(u.data,h);}return u},async miniLogin(o={}){try{let s=await ke(o.platform);return await this.loginWithMiniProgram(s)}catch(s){return {data:null,error:{message:s instanceof Error?s.message:String(s),status:400},status:400}}},async getMiniProgramPhoneNumber(o){let{code:s,platform:a}=q(o),u=d.getItem(p.ACCESS_TOKEN);return u?t.request({url:V("phone",a),method:"post",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`},data:{code:s}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async miniPhoneLogin(o){let s=X(o);if(!s||typeof s.code!="string"||!s.code.trim()||s.platform!=="wechat")return {data:null,error:{message:"A WeChat phone authorization code is required",status:400},status:400};let a=await t.request({url:"/api/auth/miniprogram/phone-login",method:"post",headers:{"Content-Type":"application/json"},data:{code:s.code}});if(a.data?.user&&a.data?.accessToken){r(a.data.user,a.data.accessToken);let u=T(i);a.data=k(a.data,u);}return a},async miniGetPhone(o){let s=X(o);return s?this.getMiniProgramPhoneNumber(s):{data:null,error:{message:"Unable to resolve mini-program phone code from input",status:400},status:400}},async logout(){let o=d.getItem("amaster_access_token"),s=await t.request({url:"/api/auth/logout",method:"post",headers:o?{Authorization:`Bearer ${o}`}:void 0});return c(),n(),s},async refreshToken(){let o=await t.request({url:"/api/auth/refresh",method:"post"});return o.data?.accessToken?d.setItem("amaster_access_token",o.data.accessToken):(o.status===401||o.status===403)&&m?.(o),o}}}function te(e){let{getCurrentUser:t}=e;return {hasRole(r){let n=t();return n?.isSuperAdmin?true:!n||!n.roles?false:n.roles.includes(r)},hasPermission(r,n){let i=t();if(i?.isSuperAdmin)return true;if(!i||!i.permissions)return false;let d=`${r}.${n}`;return i.permissions.includes(d)},hasAnyPermission(r){return r.some(({resource:n,action:i})=>this.hasPermission(n,i))},hasAllPermissions(r){return r.every(({resource:n,action:i})=>this.hasPermission(n,i))}}}function re(e){let{http:t,storage:r,onUserUpdate:n,onAuthFailure:i}=e;return {async getMe(){let d=r.getItem("amaster_access_token");if(!d)return {data:null,error:{message:"Not authenticated",status:401},status:401};let c=await t.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${d}`}});return c.data?n(c.data):(c.status===401||c.status===403)&&i?.(c),c},async updateMe(d){let c=r.getItem("amaster_access_token");if(!c)return {data:null,error:{message:"Not authenticated",status:401},status:401};let m=await t.request({url:"/api/auth/me",method:"put",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},data:d});return m.data&&n(m.data),m},async changePassword(d){let c=r.getItem("amaster_access_token");return c?t.request({url:"/api/auth/change-password",method:"post",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},data:d}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function ne(e){let{http:t,storage:r}=e;return {async getOAuthBindings(){let n=r.getItem("amaster_access_token");return n?t.request({url:"/api/auth/oauth-bindings",method:"get",headers:{Authorization:`Bearer ${n}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},bindOAuth(n){if(typeof window>"u"){console.error("[AuthClient] OAuth binding is only available in browser environment");return}window.location.href=`/api/auth/oauth/${n}/bind`;},async unbindOAuth(n){let i=r.getItem("amaster_access_token");return i?t.request({url:`/api/auth/oauth/${n}/unbind`,method:"delete",headers:{Authorization:`Bearer ${i}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function oe({http:e,storage:t}){return {async getPositions(){let r=t.getItem(p.ACCESS_TOKEN);if(!r)return {data:null,error:{message:"Not authenticated",status:401},status:401};let n=await e.request({url:"/api/org/positions",method:"get",headers:{Authorization:`Bearer ${r}`}});if(n.error)return {...n,data:null};let i=Array.isArray(n.data)?n.data:n.data?.data;return Array.isArray(i)?{...n,data:i}:{...n,data:null,error:{message:"Invalid position definitions response",status:502},status:502}}}}function se(e){let{http:t,storage:r}=e;return {async getSession(){let n=r.getItem("amaster_access_token");return n?t.request({url:"/api/auth/sessions/current",method:"get",headers:{Authorization:`Bearer ${n}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async getSessions(){let n=r.getItem("amaster_access_token");return n?t.request({url:"/api/auth/sessions",method:"get",headers:{Authorization:`Bearer ${n}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async revokeSession(n){let i=r.getItem("amaster_access_token");return i?n?t.request({url:`/api/auth/sessions/${n}`,method:"delete",headers:{Authorization:`Bearer ${i}`}}):{data:null,error:{message:"Session ID is required",status:400},status:400}:{data:null,error:{message:"Not authenticated",status:401},status:401}},async revokeAllSessions(){let n=r.getItem("amaster_access_token");return n?t.request({url:"/api/auth/sessions",method:"delete",headers:{Authorization:`Bearer ${n}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function Le(e={},t){let{baseURL:r,headers:n,onTokenExpired:i,onUnauthorized:d,autoHandleOAuthCallback:c=true,autoRedirectAfterLogin:m=true,runtime:S}=e;S&&setMiniProgramRuntime(S);let y=t||createHttpClient({...U,baseURL:r,headers:n,runtime:S}),v=300,f=K(),o=new L,s=new O,a=null,u=false;try{let l=f.getItem(p.USER);l&&(a=JSON.parse(l));}catch(l){console.error("[AuthClient] Failed to load user from storage:",l);}let h;function w(l,A){u||(u=true,I(),l==="tokenExpired"&&(o.emit("tokenExpired",A?.error),i?.()),o.emit("unauthorized",A?.error),o.emit("logout"));}s.setRefreshCallback(async()=>{let l=await h.refreshToken();if(l.data){if((await h.getMe()).error)return;o.emit("tokenRefreshed",l.data.accessToken);}else w("tokenExpired",l);});function R(l,A){u=false,f.setItem(p.ACCESS_TOKEN,A),f.setItem(p.USER,JSON.stringify(l)),a=l,s.scheduleRefreshFromToken(A,v),o.emit("login",l);}function P(l){a=l,f.setItem(p.USER,JSON.stringify(l));}function C(){o.emit("logout");}function I(){f.clear(),a=null,s.clearSchedule();}function ie(){return a}let ae=ee({http:y,onLoginSuccess:R,onLogout:C,autoRedirectAfterLogin:m,storage:f,clearAuth:I,onRefreshFailure:l=>w("tokenExpired",l)}),ue=te({getCurrentUser:ie}),le=re({http:y,storage:f,onUserUpdate:P,onAuthFailure:l=>w("unauthorized",l)}),ce=ne({http:y,storage:f}),de=se({http:y,storage:f}),he=oe({http:y,storage:f});if(h={...ae,...ue,...he,...le,...ce,...de,on(l,A){o.on(l,A);},off(l,A){o.off(l,A);},isAuthenticated(){return !!f.getItem(p.ACCESS_TOKEN)},getAccessToken(){return f.getItem(p.ACCESS_TOKEN)},setAccessToken(l){u=false,f.setItem(p.ACCESS_TOKEN,l),s.scheduleRefreshFromToken(l,v);},clearAuth:I},h.on("unauthorized",()=>{d?.();}),h.isAuthenticated()&&h.getMe().then(l=>{l.error&&console.warn("[AuthClient] Failed to sync user info on init:",l.error);}).catch(l=>{console.warn("[AuthClient] Failed to sync user info on init:",l);}),c&&typeof window<"u"){let l=window.location.hash,A=new URLSearchParams(window.location.search);(A.has("login_ticket")||A.has("oauth_error")||l&&(l.includes("access_token")||l.includes("accessToken")))&&h.handleOAuthCallback().then(b=>{b.error&&console.error("[AuthClient] Auto OAuth callback failed:",b.error);}).catch(b=>{console.error("[AuthClient] Auto OAuth callback error:",b);});}return h}
2
- export{Le as createAuthClient,U as defaultHttpClientOptions,N as transformAmasterResponse};//# sourceMappingURL=index.js.map
1
+ import {setMiniProgramRuntime,createHttpClient,getMiniProgramLogin,detectMiniProgramPlatform}from'@amaster.ai/http-client';var q=class{constructor(){this.events={};}on(t,r){this.events[t]||(this.events[t]=[]),this.events[t].push(r);}off(t,r){this.events[t]&&(this.events[t]=this.events[t].filter(n=>n!==r));}emit(t,...r){this.events[t]&&this.events[t].forEach(n=>{try{n(...r);}catch(i){console.error(`[AuthClient] Error in event handler for "${t}":`,i);}});}removeAllListeners(){this.events={};}};function Se(){let e=new Map;return {getItem:t=>e.get(t)??null,setItem:(t,r)=>{e.set(t,r);},removeItem:t=>{e.delete(t);},clear:()=>{e.clear();}}}var f={ACCESS_TOKEN:"amaster_access_token",REFRESH_TOKEN:"amaster_refresh_token",USER:"amaster_user"};function we(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;try{return Function("return this")()}catch{return}}function $(e){return we()?.[e]}function Ae(){let e=$("wx"),t=$("tt");return e?.getStorageSync&&e?.setStorageSync&&e?.removeStorageSync?"wechat-miniprogram":t?.getStorageSync&&t?.setStorageSync&&t?.removeStorageSync?"douyin-miniprogram":typeof window<"u"&&typeof window.localStorage<"u"?"browser":"node"}function J(){switch(Ae()){case "wechat-miniprogram":return j($("wx"),"WeChat");case "douyin-miniprogram":return j($("tt"),"Douyin");case "browser":return Ce();case "node":return ve()}}function Ce(){let e=window.localStorage;return {getItem(t){try{return e.getItem(t)}catch(r){return console.error("[AuthClient] Failed to get item from localStorage:",r),null}},setItem(t,r){try{e.setItem(t,r);}catch(n){console.error("[AuthClient] Failed to set item in localStorage:",n);}},removeItem(t){try{e.removeItem(t);}catch(r){console.error("[AuthClient] Failed to remove item from localStorage:",r);}},clear(){try{e.removeItem(f.ACCESS_TOKEN),e.removeItem(f.REFRESH_TOKEN),e.removeItem(f.USER);}catch(t){console.error("[AuthClient] Failed to clear localStorage:",t);}}}}function j(e,t){return {getItem(r){try{return e.getStorageSync(r)||null}catch(n){return console.error(`[AuthClient] Failed to get item from ${t} storage:`,n),null}},setItem(r,n){try{e.setStorageSync(r,n);}catch(i){console.error(`[AuthClient] Failed to set item in ${t} storage:`,i);}},removeItem(r){try{e.removeStorageSync(r);}catch(n){console.error(`[AuthClient] Failed to remove item from ${t} storage:`,n);}},clear(){try{e.removeStorageSync(f.ACCESS_TOKEN),e.removeStorageSync(f.REFRESH_TOKEN),e.removeStorageSync(f.USER);}catch(r){console.error(`[AuthClient] Failed to clear ${t} storage:`,r);}}}}function ve(){let e=new Map;return {getItem(t){return e.get(t)??null},setItem(t,r){e.set(t,r);},removeItem(t){e.delete(t);},clear(){e.clear();}}}function ke(e){try{let t=e.split(".");if(t.length!==3)return null;let n=(t[1]||"").replace(/-/g,"+").replace(/_/g,"/");if(typeof atob<"u"){let i=decodeURIComponent(atob(n).split("").map(d=>"%"+("00"+d.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(i)}if(typeof Buffer<"u"){let i=Buffer.from(n,"base64").toString("utf-8");return JSON.parse(i)}return null}catch(t){return console.error("[AuthClient] Failed to parse JWT token:",t),null}}var D=class{constructor(){this.refreshTimer=null;this.isRefreshing=false;this.refreshCallback=null;}setRefreshCallback(t){this.refreshCallback=t;}scheduleRefresh(t){this.clearSchedule(),!(t<=0)&&(this.refreshTimer=setTimeout(()=>{this.refresh();},t));}scheduleRefreshFromToken(t,r=300){let n=ke(t);if(!n||!n.exp){console.warn("[AuthClient] Cannot schedule refresh: invalid token or missing exp claim");return}let i=n.exp*1e3,d=Date.now(),c=i-d-r*1e3;c<=0?(console.warn("[AuthClient] Token already expired or expiring soon, refreshing immediately"),this.refresh()):this.scheduleRefresh(c);}async refresh(){if(!this.isRefreshing){if(!this.refreshCallback){console.error("[AuthClient] No refresh callback set");return}this.isRefreshing=true;try{await this.refreshCallback();}catch(t){console.error("[AuthClient] Token refresh failed:",t);}finally{this.isRefreshing=false;}}}clearSchedule(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null);}isCurrentlyRefreshing(){return this.isRefreshing}destroy(){this.clearSchedule(),this.refreshCallback=null,this.isRefreshing=false;}};function V(e){return e&&typeof e=="object"&&("statusCode"in e||"status"in e)&&"data"in e?e.data:e}var B={transformResponse:V,logErrors:true};var Te="https://lf-scm-cn.feishucdn.com/lark/op/h5-js-sdk-1.5.44.js",Y="amaster-feishu-h5-sdk";var Q=null,U=null,H=null;function X(){if(!(typeof window>"u"))return window}function ee(){return X()?.tt}function N(){return X()?.h5sdk}function te(){typeof window>"u"||Q===window||(Q=window,U=null,H=null);}function re(){if(typeof navigator>"u")return false;let e=ee();return /Feishu|Lark/i.test(navigator.userAgent||"")||typeof e?.requestAccess=="function"||typeof e?.requestAuthCode=="function"}function Ee(){return te(),typeof document>"u"?Promise.reject(new Error("Feishu H5 SDK is only available in a browser environment")):typeof N()?.ready=="function"?Promise.resolve():U||(U=new Promise((e,t)=>{let r=document.getElementById(Y),n=!r;r||(r=document.createElement("script"),r.id=Y,r.src=Te,r.async=true);let i=false,d,h,c=()=>{d&&clearInterval(d),h&&clearTimeout(h),r?.removeEventListener("load",m),r?.removeEventListener("error",E);},g=w=>{if(!i){if(i=true,c(),w){r?.remove(),t(w);return}e();}},v=()=>typeof N()?.ready=="function"?(g(),true):false,m=()=>{v();},E=()=>{g(new Error("Failed to load Feishu H5 SDK"));};r.addEventListener("load",m),r.addEventListener("error",E),d=setInterval(v,25),h=setTimeout(()=>{g(new Error("Timed out while loading Feishu H5 SDK"));},1e4),!v()&&n&&document.head.appendChild(r);}).catch(e=>{throw U=null,e}),U)}function Me(){return te(),H||(H=(async()=>{await Ee();let e=N();if(typeof e?.ready!="function")throw new Error("Feishu H5 SDK loaded without exposing h5sdk.ready");return new Promise((t,r)=>{let n=false,i,d=(h,c)=>{n||(n=true,i&&clearTimeout(i),c?r(c):h?t(h):r(new Error("Feishu H5 SDK became ready without exposing the tt bridge")));};i=setTimeout(()=>{d(void 0,new Error("Timed out while waiting for Feishu H5 SDK ready"));},1e4),e.error?.(h=>d(void 0,new Error(z(h))));try{let h=e.ready?.(()=>d(ee()));h&&typeof h.then=="function"&&h.catch(c=>{d(void 0,new Error(`Feishu H5 SDK ready failed: ${c instanceof Error?c.message:String(c)}`));});}catch(h){d(void 0,new Error(`Feishu H5 SDK ready failed: ${h instanceof Error?h.message:String(h)}`));}})})().catch(e=>{throw H=null,e}),H)}function z(e){return e.errString||e.message||`Feishu authorization failed${e.errno?` (${e.errno})`:""}`}function Z(e,t){return typeof e.requestAuthCode!="function"?Promise.reject(new Error("The current Feishu client does not support requestAuthCode")):new Promise((r,n)=>{e.requestAuthCode?.({appId:t,success:i=>{i.code?r(i.code):n(new Error("Feishu requestAuthCode returned no code"));},fail:i=>n(new Error(z(i)))});})}async function ne(e){let t=await Me();return typeof t.requestAccess!="function"?Z(t,e):new Promise((r,n)=>{t.requestAccess?.({appID:e,scopeList:[],success:i=>{i.code?r(i.code):n(new Error("Feishu requestAccess returned no code"));},fail:i=>{if(i.errno===103){Z(t,e).then(r,n);return}n(new Error(z(i)));}});})}function Oe(e){if(e.email)return "email";if(e.username)return "username";if(e.phone)return "phone"}function _e(e){if(e.email)return "email";if(e.phone)return "phone"}function K(e){return e||(detectMiniProgramPlatform()??"wechat")}function G(e){return typeof e=="string"?{code:e,platform:K()}:{code:e.code,platform:K(e.platform)}}function oe(e,t){return t==="douyin"?`/api/auth/miniprogram/douyin/${e}`:`/api/auth/miniprogram/${e}`}async function Ie(e){let t=K(e),r=getMiniProgramLogin(t),n=async i=>await new Promise((d,h)=>{let c=false,g=m=>{if(!c){if(c=true,typeof m?.code=="string"&&m.code){d(m.code);return}h(new Error("Mini Program login failed: missing code"));}},v=m=>{c||(c=true,h(new Error(`Mini Program login failed: ${m instanceof Error?m.message:String(m)}`)));};try{let m=i({success:g,fail:v});if(m&&typeof m.then=="function"){m.then(g,v);return}m&&typeof m=="object"&&"code"in m&&g(m);}catch(m){v(m);}});if(typeof r!="function")throw new Error(`Mini Program login API is not available for platform '${t}'`);return {code:await n(r),platform:t}}function se(e){if(typeof e=="string")return G(e);let t="detail"in e&&e.detail&&typeof e.detail=="object"?e.detail:null,r=typeof t?.code=="string"&&t.code?t.code:typeof e.code=="string"&&e.code?e.code:void 0;return r?{code:r,platform:K(e.platform)}:null}function Fe(e){let t=new URLSearchParams(e);return t.get("access_token")||t.get("accessToken")}function Ue(e){return new URLSearchParams(e).get("user")}function ie(e){if(typeof window>"u")return null;try{let t=e||new URLSearchParams(window.location.search).get("redirect");if(!t)return null;let r=new URL(t,window.location.origin);return r.origin!==window.location.origin?(console.warn("[AuthClient] Ignored cross-origin redirect target:",t),null):`${r.pathname}${r.search}${r.hash}`}catch(t){return console.warn("[AuthClient] Failed to resolve redirect target:",t),null}}var W={assign(e){window.location.assign(e);},replace(e){window.location.replace(e);}};function b(e,t){return t.handled?{...e,redirectHandled:true,redirectTarget:t.target}:e}function O(e,t){if(!e||typeof window>"u"||window.opener)return {handled:false};let r=ie(t);return r?(W.replace(r),{handled:true,target:r}):{handled:false}}function ae(e){let{baseURL:t,getAuthVersion:r=()=>{},onRefreshSuccess:n,http:i,onLoginSuccess:d,onLogout:h,autoRedirectAfterLogin:c,storage:g,clearAuth:v,onRefreshFailure:m}=e,E=new Map,w=null,M=null,R=-1;function k(s){if(!t)return s;let o=typeof window>"u"?t:new URL(t,window.location.href).href;return new URL(s,o).href}let _=s=>{let o=s.trim(),a=E.get(o);if(a)return a;let u=(async()=>{if(!o)return {data:null,error:{message:"OAuth login ticket is required",status:400},status:400};let p=await i.request({url:"/api/auth/oauth/ticket",method:"post",headers:{"Content-Type":"application/json"},data:{ticket:o}});if(!p.data?.accessToken)return {data:null,error:p.error||{message:"OAuth login ticket is invalid, expired, or already used",status:p.status||400},status:p.status||400};let C=g.getItem(f.ACCESS_TOKEN),A=p.data.accessToken;g.setItem(f.ACCESS_TOKEN,A);let P=await i.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${A}`}});if(!P.data)return C?g.setItem(f.ACCESS_TOKEN,C):g.removeItem(f.ACCESS_TOKEN),{data:null,error:P.error||{message:"OAuth login succeeded but user information could not be loaded",status:P.status||500},status:P.status||500};d(P.data,A);let S=O(c,p.data.returnUrl);return {data:b({user:P.data,accessToken:A},S),error:null,status:200}})();return E.set(o,u),u},L=s=>{if(typeof window>"u")return;let o=ie(s)||"/",a=new URLSearchParams({return_url:o,callback_url:"/auth/callback"});W.assign(`/api/auth/oauth/feishu?${a.toString()}`);},I=async(s,o)=>{let a=await i.request({url:"/api/auth/oauth/feishu/code",method:"post",headers:{"Content-Type":"application/json"},data:{code:s}});if(a.data?.user&&a.data?.accessToken){d(a.data.user,a.data.accessToken);let u=O(c,o);a.data=b(a.data,u);}return a};return {async register(s){let o=await i.request({url:"/api/auth/register",method:"post",headers:{"Content-Type":"application/json"},data:s});if(o.data?.user&&o.data?.accessToken){d(o.data.user,o.data.accessToken);let a=O(c);o.data=b(o.data,a);}return o},async login(s){let o=s.loginType||Oe(s);if(!o)return {data:null,error:{message:"Unable to determine login type. Please provide email, username, or phone.",status:400},status:400};let a={...s,loginType:o},u=await i.request({url:"/api/auth/login",method:"post",headers:{"Content-Type":"application/json"},data:a});if(u.data?.user&&u.data?.accessToken){d(u.data.user,u.data.accessToken);let p=O(c);u.data=b(u.data,p);}return u},async loginWithCode(s){let o=s.loginType||_e(s);if(!o)return {data:null,error:{message:"Unable to determine login type. Please provide email or phone.",status:400},status:400};let a={...s,loginType:o},u=await i.request({url:"/api/auth/login-with-code",method:"post",headers:{"Content-Type":"application/json"},data:a});if(u.data?.user&&u.data?.accessToken){d(u.data.user,u.data.accessToken);let p=O(c);u.data=b(u.data,p);}return u},async sendCode(s){return i.request({url:"/api/auth/send-code",method:"post",headers:{"Content-Type":"application/json"},data:s})},async getCaptcha(){return i.request({url:"/api/auth/captcha",method:"get"})},getOAuthLoginURL(s,o){let a=new URLSearchParams;return o&&a.set("redirect_uri",o),k(`/api/auth/oauth/${s}${a.size?`?${a}`:""}`)},loginWithOAuth(s,o){if(typeof window>"u"){console.error("[AuthClient] OAuth login is only available in browser environment");return}if(s==="feishu"){L(o);return}let a=new URLSearchParams;if(o&&a.set("redirect_uri",o),s==="wecom"){if(o){let P=new URL(o,window.location.origin);P.origin===window.location.origin&&(P.searchParams.delete("oauth_error"),P.searchParams.delete("error_description"),a.set("redirect_uri",P.pathname+P.search+P.hash));}let C=new URLSearchParams(window.location.search);C.delete("oauth_error"),C.delete("error_description");let A=C.toString();a.set("error_redirect_uri",`${window.location.pathname}${A?`?${A}`:""}`);}let u=a.toString(),p=`/api/auth/oauth/${s}${u?`?${u}`:""}`;W.assign(p);},async loginWithFeishu(s){if(typeof window>"u")return {data:null,error:{message:"Feishu login is only available in a browser environment",status:400},status:400};if(!re())return L(s),null;let o=await i.request({url:"/api/auth/oauth/feishu/config",method:"get"});if(!o.data?.enabled||!o.data.appId)return {data:null,error:o.error||{message:"Feishu login is not configured for this application",status:o.status||400},status:o.status||400};try{let a=await ne(o.data.appId);return await I(a,s)}catch(a){return {data:null,error:{message:a instanceof Error?a.message:String(a),status:400},status:400}}},async loginWithFeishuCode(s,o){return I(s,o)},async exchangeOAuthLoginTicket(s){return _(s)},handleOAuthCallback(){return w||(w=(async()=>{if(typeof window>"u")return {data:null,error:{message:"OAuth callback is only available in browser environment",status:400},status:400};try{let s=new URLSearchParams(window.location.search),o=s.get("oauth_error");if(o)return {data:null,error:{message:s.get("error_description")||`OAuth callback failed: ${o}`,status:400},status:400};let a=s.get("login_ticket");if(a){s.delete("login_ticket");let S=s.toString();return window.history.replaceState(null,"",`${window.location.pathname}${S?`?${S}`:""}${window.location.hash}`),_(a)}let u=window.location.hash.substring(1),p=Fe(u),C=Ue(u);if(!p)return {data:null,error:{message:"OAuth callback failed: missing access token",status:400},status:400};let A;if(C)A=JSON.parse(decodeURIComponent(C));else {g.setItem(f.ACCESS_TOKEN,p);let S=await i.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${p}`}});if(!S.data)return {data:null,error:{message:"OAuth callback failed: unable to fetch user info",status:S.status||500},status:S.status||500};A=S.data;}if(d(A,p),window.history&&window.history.replaceState){let S=window.location.pathname+window.location.search;window.history.replaceState(null,"",S);}else window.location.hash="";let P=O(c);return {data:b({user:A,accessToken:p},P),error:null,status:200}}catch(s){return {data:null,error:{message:`OAuth callback failed: ${s instanceof Error?s.message:String(s)}`,status:400},status:400}}})(),w)},async loginWithMiniProgram(s){let{code:o,platform:a}=G(s),u=await i.request({url:oe("login",a),method:"post",headers:{"Content-Type":"application/json"},data:{code:o}});if(u.data?.user&&u.data?.accessToken){d(u.data.user,u.data.accessToken);let p=O(c);u.data=b(u.data,p);}return u},async miniLogin(s={}){try{let o=await Ie(s.platform);return await this.loginWithMiniProgram(o)}catch(o){return {data:null,error:{message:o instanceof Error?o.message:String(o),status:400},status:400}}},async getMiniProgramPhoneNumber(s){let{code:o,platform:a}=G(s),u=g.getItem(f.ACCESS_TOKEN);return u?i.request({url:oe("phone",a),method:"post",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`},data:{code:o}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async miniPhoneLogin(s){let o=se(s);if(!o||typeof o.code!="string"||!o.code.trim()||o.platform!=="wechat")return {data:null,error:{message:"A WeChat phone authorization code is required",status:400},status:400};let a=await i.request({url:"/api/auth/miniprogram/phone-login",method:"post",headers:{"Content-Type":"application/json"},data:{code:o.code}});if(a.data?.user&&a.data?.accessToken){d(a.data.user,a.data.accessToken);let u=O(c);a.data=b(a.data,u);}return a},async miniGetPhone(s){let o=se(s);return o?this.getMiniProgramPhoneNumber(o):{data:null,error:{message:"Unable to resolve mini-program phone code from input",status:400},status:400}},async logout(){let s=g.getItem("amaster_access_token"),o=await i.request({url:"/api/auth/logout",method:"post",headers:s?{Authorization:`Bearer ${s}`}:void 0});return v(),h(),o},refreshToken(){let s=r();if(s!==void 0&&M&&R===s)return M;let o=(async()=>{let a=await i.request({url:"/api/auth/refresh",method:"post"});return s!==void 0&&r()!==s?{data:null,error:{message:"Authentication state changed",status:409},status:409}:(a.data?.accessToken?s!==void 0&&n?n(a.data.accessToken):g.setItem("amaster_access_token",a.data.accessToken):(a.status===401||a.status===403)&&m?.(a),a)})();return s!==void 0&&(R=s,M=o,o.finally(()=>{M===o&&(M=null);}).catch(()=>{})),o}}}function ue(e){let{getCurrentUser:t}=e;return {hasRole(r){let n=t();return n?.isSuperAdmin?true:!n||!n.roles?false:n.roles.includes(r)},hasPermission(r,n){let i=t();if(i?.isSuperAdmin)return true;if(!i||!i.permissions)return false;let d=`${r}.${n}`;return i.permissions.includes(d)},hasAnyPermission(r){return r.some(({resource:n,action:i})=>this.hasPermission(n,i))},hasAllPermissions(r){return r.every(({resource:n,action:i})=>this.hasPermission(n,i))}}}function le(e){let{http:t,storage:r,onUserUpdate:n,onAuthFailure:i,getAuthVersion:d}=e;return {async getMe(){let h=d?.(),c=r.getItem("amaster_access_token");if(!c)return {data:null,error:{message:"Not authenticated",status:401},status:401};let g=await t.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${c}`}});return h!==void 0&&(d?.()!==h||r.getItem("amaster_access_token")!==c)?{data:null,error:{message:"Authentication state changed",status:409},status:409}:(g.data?n(g.data):(g.status===401||g.status===403)&&i?.(g),g)},async updateMe(h){let c=r.getItem("amaster_access_token");if(!c)return {data:null,error:{message:"Not authenticated",status:401},status:401};let g=await t.request({url:"/api/auth/me",method:"put",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},data:h});return g.data&&n(g.data),g},async changePassword(h){let c=r.getItem("amaster_access_token");return c?t.request({url:"/api/auth/change-password",method:"post",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},data:h}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function ce(e){let{http:t,storage:r}=e;return {async getOAuthBindings(){let n=r.getItem("amaster_access_token");return n?t.request({url:"/api/auth/oauth-bindings",method:"get",headers:{Authorization:`Bearer ${n}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},bindOAuth(n){if(typeof window>"u"){console.error("[AuthClient] OAuth binding is only available in browser environment");return}window.location.href=`/api/auth/oauth/${n}/bind`;},async unbindOAuth(n){let i=r.getItem("amaster_access_token");return i?t.request({url:`/api/auth/oauth/${n}/unbind`,method:"delete",headers:{Authorization:`Bearer ${i}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function de({http:e,storage:t}){return {async getPositions(){let r=t.getItem(f.ACCESS_TOKEN);if(!r)return {data:null,error:{message:"Not authenticated",status:401},status:401};let n=await e.request({url:"/api/org/positions",method:"get",headers:{Authorization:`Bearer ${r}`}});if(n.error)return {...n,data:null};let i=Array.isArray(n.data)?n.data:n.data?.data;return Array.isArray(i)?{...n,data:i}:{...n,data:null,error:{message:"Invalid position definitions response",status:502},status:502}}}}function he(e){let{http:t,storage:r}=e;return {async getSession(){let n=r.getItem("amaster_access_token");return n?t.request({url:"/api/auth/sessions/current",method:"get",headers:{Authorization:`Bearer ${n}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async getSessions(){let n=r.getItem("amaster_access_token");return n?t.request({url:"/api/auth/sessions",method:"get",headers:{Authorization:`Bearer ${n}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async revokeSession(n){let i=r.getItem("amaster_access_token");return i?n?t.request({url:`/api/auth/sessions/${n}`,method:"delete",headers:{Authorization:`Bearer ${i}`}}):{data:null,error:{message:"Session ID is required",status:400},status:400}:{data:null,error:{message:"Not authenticated",status:401},status:401}},async revokeAllSessions(){let n=r.getItem("amaster_access_token");return n?t.request({url:"/api/auth/sessions",method:"delete",headers:{Authorization:`Bearer ${n}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function qe(e={},t){let{baseURL:r,storage:n,withCredentials:i,headers:d,onTokenExpired:h,onUnauthorized:c,autoHandleOAuthCallback:g=true,autoRedirectAfterLogin:v=true,runtime:m,autoRefresh:E=true}=e;m&&setMiniProgramRuntime(m);let w=t||createHttpClient({...B,baseURL:r,withCredentials:i,headers:d,runtime:m}),M=300,R=n&&typeof n.getItem=="function"?n:J(),k=new q,_=new D,L=null,I=false,s=0,o=R===n,a=null;try{let l=R.getItem(f.USER);l&&(L=JSON.parse(l));}catch(l){console.error("[AuthClient] Failed to load user from storage:",l);}let u;function p(l,y){I||(I=true,S(),l==="tokenExpired"&&(k.emit("tokenExpired",y?.error),h?.()),k.emit("unauthorized",y?.error),k.emit("logout"));}_.setRefreshCallback(async()=>{let l=s,y=await u.refreshToken();if(!(o&&l!==s))if(y.data){if((await u.getMe()).error)return;k.emit("tokenRefreshed",y.data.accessToken);}else p("tokenExpired",y);});function C(l,y){I=false,R.setItem(f.ACCESS_TOKEN,y),R.setItem(f.USER,JSON.stringify(l)),L=l,E&&_.scheduleRefreshFromToken(y,M),k.emit("login",l);}function A(l){L=l,R.setItem(f.USER,JSON.stringify(l));}function P(){k.emit("logout");}function S(){s++,a=null,R.clear(),L=null,_.clearSchedule();}function ge(){return L}let me=ae({baseURL:r,http:w,onLoginSuccess:C,onLogout:P,autoRedirectAfterLogin:v,storage:R,clearAuth:S,getAuthVersion:()=>o?s:void 0,onRefreshSuccess:l=>u.setAccessToken(l),onRefreshFailure:l=>p("tokenExpired",l)}),pe=ue({getCurrentUser:ge}),fe=le({http:w,storage:R,getAuthVersion:()=>o?s:void 0,onUserUpdate:A,onAuthFailure:l=>p("unauthorized",l)}),ye=ce({http:w,storage:R}),Re=he({http:w,storage:R}),Pe=de({http:w,storage:R});if(u={...me,...pe,...Pe,...fe,...ye,...Re,restoreSession(){if(o=true,a)return a;let l=s,y=()=>({data:null,error:{message:"Authentication state changed",status:409},status:409}),F=(async()=>{let T=await u.refreshToken();if(!T.data)return {...T,data:null};if(l!==s)return y();let x=await u.getMe();return x.data?l!==s?y():(C(x.data,T.data.accessToken),{data:{user:x.data,accessToken:T.data.accessToken},error:null,status:200}):{...x,data:null}})();return a=F,F.finally(()=>{a===F&&(a=null);}).catch(()=>{}),F},on(l,y){k.on(l,y);},off(l,y){k.off(l,y);},isAuthenticated(){return !!R.getItem(f.ACCESS_TOKEN)},getAccessToken(){return R.getItem(f.ACCESS_TOKEN)},setAccessToken(l){I=false,R.setItem(f.ACCESS_TOKEN,l),E&&_.scheduleRefreshFromToken(l,M);},clearAuth:S},u.on("unauthorized",()=>{c?.();}),u.isAuthenticated()&&u.getMe().then(l=>{l.error&&console.warn("[AuthClient] Failed to sync user info on init:",l.error);}).catch(l=>{console.warn("[AuthClient] Failed to sync user info on init:",l);}),g&&typeof window<"u"){let l=window.location.hash,y=new URLSearchParams(window.location.search);(y.has("login_ticket")||y.has("oauth_error")||l&&(l.includes("access_token")||l.includes("accessToken")))&&u.handleOAuthCallback().then(T=>{T.error&&console.error("[AuthClient] Auto OAuth callback failed:",T.error);}).catch(T=>{console.error("[AuthClient] Auto OAuth callback error:",T);});}return u}function $e(){if(typeof window>"u")return false;let e=new URLSearchParams(window.location.search),t=e.get("requestId"),r=e.get("openerOrigin");if(window.history.replaceState(null,"",window.location.pathname),!window.opener||!t||!/^[a-zA-Z0-9_-]{16,128}$/.test(t)||!r)return false;let n;try{n=new URL(r);}catch{return false}return !["https:","http:"].includes(n.protocol)||n.origin!==r?false:(window.opener.postMessage({type:"amaster:oauth-complete",requestId:t},n.origin),window.close(),true)}
2
+ export{$e as completeOAuthPopup,qe as createAuthClient,Se as createMemoryStorage,B as defaultHttpClientOptions,V as transformAmasterResponse};//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map