@amaster.ai/auth-client 1.1.72 → 1.1.73
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/README.md +28 -0
- package/dist/auth.d.cts +8 -3
- package/dist/auth.d.ts +8 -3
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +74 -8
- package/dist/index.d.ts +74 -8
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/oauth.d.cts +1 -1
- package/dist/oauth.d.ts +1 -1
- package/dist/permissions.d.cts +3 -3
- package/dist/permissions.d.ts +3 -3
- package/dist/rbac.cjs +3 -0
- package/dist/rbac.cjs.map +1 -0
- package/dist/rbac.d.cts +552 -0
- package/dist/rbac.d.ts +552 -0
- package/dist/rbac.js +3 -0
- package/dist/rbac.js.map +1 -0
- package/dist/sessions.d.cts +1 -1
- package/dist/sessions.d.ts +1 -1
- package/dist/tenancy.cjs +2 -0
- package/dist/tenancy.cjs.map +1 -0
- package/dist/tenancy.d.cts +157 -0
- package/dist/tenancy.d.ts +157 -0
- package/dist/tenancy.js +2 -0
- package/dist/tenancy.js.map +1 -0
- package/dist/tenant-management.cjs +2 -0
- package/dist/tenant-management.cjs.map +1 -0
- package/dist/tenant-management.d.cts +167 -0
- package/dist/tenant-management.d.ts +167 -0
- package/dist/tenant-management.js +2 -0
- package/dist/tenant-management.js.map +1 -0
- package/dist/tenant-structure.d.cts +38 -0
- package/dist/tenant-structure.d.ts +38 -0
- package/dist/{types-BD5m6HPr.d.cts → types-D5c61dWd.d.cts} +25 -5
- package/dist/{types-BD5m6HPr.d.ts → types-D5c61dWd.d.ts} +25 -5
- package/dist/user.d.cts +2 -1
- package/dist/user.d.ts +2 -1
- package/package.json +17 -2
package/dist/index.d.cts
CHANGED
|
@@ -13,13 +13,13 @@
|
|
|
13
13
|
*
|
|
14
14
|
* ============================================================================
|
|
15
15
|
*/
|
|
16
|
-
import { HttpClient, ClientResult, HttpClientOptions } from '@amaster.ai/http-client';
|
|
16
|
+
import { HttpClient, ClientResult, HttpClientOptions, RequestScopeOptions, RequestSubject } from '@amaster.ai/http-client';
|
|
17
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 { S as StorageAdapter, D as DepartmentPosition, B as BrowserAuthClientOptions, A as AuthEvent, E as EventHandler, L as LoginResponse, a as AuthClientOptions } from './types-
|
|
22
|
-
export { b as CaptchaResponse, C as ChangePasswordParams,
|
|
21
|
+
import { S as StorageAdapter, D as DepartmentPosition, B as BrowserAuthClientOptions, A as AuthEvent, E as EventHandler, L as LoginResponse, a as AuthClientOptions, U as User } from './types-D5c61dWd.cjs';
|
|
22
|
+
export { b as CaptchaResponse, C as ChangePasswordParams, c as CodeLoginParams, d as CodeLoginType, F as FeishuPublicConfig, e as LoginParams, 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, u as SendCodeParams, v as SendCodeType, w as Session, x as SuccessResponse, y as UpdateMeParams, z as createMemoryStorage, G as createStorageAdapter } from './types-D5c61dWd.cjs';
|
|
23
23
|
import { createSessionsModule } from './sessions.cjs';
|
|
24
24
|
|
|
25
25
|
declare function createOrganizationModule({ http, storage }: {
|
|
@@ -48,11 +48,54 @@ type AuthClient = AuthModule & ReturnType<typeof createPermissionsModule> & Retu
|
|
|
48
48
|
type BrowserAuthClient = AuthClient & Pick<ReturnType<typeof createAuthModule>, "getOAuthLoginURL"> & {
|
|
49
49
|
restoreSession(): Promise<ClientResult<LoginResponse>>;
|
|
50
50
|
};
|
|
51
|
-
declare function createAuthClient(options: BrowserAuthClientOptions, http?: HttpClient): BrowserAuthClient;
|
|
52
|
-
declare function createAuthClient(options?: AuthClientOptions, http?: HttpClient): AuthClient;
|
|
51
|
+
declare function createAuthClient(options: BrowserAuthClientOptions, http?: HttpClient, beforeInitialize?: (client: AuthClient) => void): BrowserAuthClient;
|
|
52
|
+
declare function createAuthClient(options?: AuthClientOptions, http?: HttpClient, beforeInitialize?: (client: AuthClient) => void): AuthClient;
|
|
53
53
|
|
|
54
|
-
/**
|
|
55
|
-
declare function
|
|
54
|
+
/** Read-only legacy UI hints. Never starts authentication, refresh or storage writes. */
|
|
55
|
+
declare function createStoredAuthReader(namespace?: string, source?: StorageAdapter): {
|
|
56
|
+
hasRole(roleCode: string): boolean;
|
|
57
|
+
hasPermission(resource: string, action: string): boolean;
|
|
58
|
+
hasAnyPermission(permissions: Array<{
|
|
59
|
+
resource: string;
|
|
60
|
+
action: string;
|
|
61
|
+
}>): boolean;
|
|
62
|
+
hasAllPermissions(permissions: Array<{
|
|
63
|
+
resource: string;
|
|
64
|
+
action: string;
|
|
65
|
+
}>): boolean;
|
|
66
|
+
getAccessToken: () => string | null;
|
|
67
|
+
isAuthenticated: () => boolean;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
type ApplicationHint = {
|
|
71
|
+
applicationCode: string;
|
|
72
|
+
environment: string;
|
|
73
|
+
tenancyEnabled: boolean;
|
|
74
|
+
};
|
|
75
|
+
/** Called only after fresh discovery advertises a preserved boundary. The signature-free reference is a local tombstone, never authority. */
|
|
76
|
+
declare function takePreservedLegacyAccessToken(namespace: string): string | null;
|
|
77
|
+
/** Cached context locates local login UI hints only. A host must freshly discover mode before any I/O. */
|
|
78
|
+
declare function createStoredApplicationAuthReader(key?: string): {
|
|
79
|
+
reader: {
|
|
80
|
+
hasRole(roleCode: string): boolean;
|
|
81
|
+
hasPermission(resource: string, action: string): boolean;
|
|
82
|
+
hasAnyPermission(permissions: Array<{
|
|
83
|
+
resource: string;
|
|
84
|
+
action: string;
|
|
85
|
+
}>): boolean;
|
|
86
|
+
hasAllPermissions(permissions: Array<{
|
|
87
|
+
resource: string;
|
|
88
|
+
action: string;
|
|
89
|
+
}>): boolean;
|
|
90
|
+
getAccessToken: () => string | null;
|
|
91
|
+
isAuthenticated: () => boolean;
|
|
92
|
+
};
|
|
93
|
+
clearConsumerHint: () => void | undefined;
|
|
94
|
+
remember(value: ApplicationHint): void;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/** Read a client's own UI profile without adding requirements to the public AuthClient interface. */
|
|
98
|
+
declare function readCachedAuthUser(client: object): User | null;
|
|
56
99
|
|
|
57
100
|
/**
|
|
58
101
|
* HTTP Client Configuration Utilities
|
|
@@ -82,4 +125,27 @@ declare function transformAmasterResponse<T>(responseData: unknown): T;
|
|
|
82
125
|
*/
|
|
83
126
|
declare const defaultHttpClientOptions: HttpClientOptions;
|
|
84
127
|
|
|
85
|
-
|
|
128
|
+
interface ConsumerUIHint {
|
|
129
|
+
scope: {
|
|
130
|
+
applicationCode: string;
|
|
131
|
+
environment: string;
|
|
132
|
+
appTenantId: string;
|
|
133
|
+
};
|
|
134
|
+
subject: RequestSubject;
|
|
135
|
+
roles: readonly string[];
|
|
136
|
+
permissions: readonly string[];
|
|
137
|
+
isSuperAdmin?: boolean;
|
|
138
|
+
}
|
|
139
|
+
/** Display hints in the authentication storage adapter only. Never hydrates a request controller or an authorization grant. */
|
|
140
|
+
declare function createConsumerUIHint(options: RequestScopeOptions, token: () => string | null): {
|
|
141
|
+
read: () => ConsumerUIHint | null;
|
|
142
|
+
write(value: ConsumerUIHint): void;
|
|
143
|
+
clear(): void;
|
|
144
|
+
hasRole: (role: string) => boolean;
|
|
145
|
+
hasPermission: (resource: string, action: string) => boolean;
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/** Signal completion only. Application credentials are recovered through the application's HttpOnly cookie. */
|
|
149
|
+
declare function completeOAuthPopup(): boolean;
|
|
150
|
+
|
|
151
|
+
export { type AuthClient, AuthClientOptions, AuthEvent, type BrowserAuthClient, BrowserAuthClientOptions, DepartmentPosition, EventHandler, LoginResponse, StorageAdapter, User, completeOAuthPopup, createAuthClient, createConsumerUIHint, createStoredApplicationAuthReader, createStoredAuthReader, defaultHttpClientOptions, readCachedAuthUser, takePreservedLegacyAccessToken, transformAmasterResponse };
|
package/dist/index.d.ts
CHANGED
|
@@ -13,13 +13,13 @@
|
|
|
13
13
|
*
|
|
14
14
|
* ============================================================================
|
|
15
15
|
*/
|
|
16
|
-
import { HttpClient, ClientResult, HttpClientOptions } from '@amaster.ai/http-client';
|
|
16
|
+
import { HttpClient, ClientResult, HttpClientOptions, RequestScopeOptions, RequestSubject } from '@amaster.ai/http-client';
|
|
17
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 { S as StorageAdapter, D as DepartmentPosition, B as BrowserAuthClientOptions, A as AuthEvent, E as EventHandler, L as LoginResponse, a as AuthClientOptions } from './types-
|
|
22
|
-
export { b as CaptchaResponse, C as ChangePasswordParams,
|
|
21
|
+
import { S as StorageAdapter, D as DepartmentPosition, B as BrowserAuthClientOptions, A as AuthEvent, E as EventHandler, L as LoginResponse, a as AuthClientOptions, U as User } from './types-D5c61dWd.js';
|
|
22
|
+
export { b as CaptchaResponse, C as ChangePasswordParams, c as CodeLoginParams, d as CodeLoginType, F as FeishuPublicConfig, e as LoginParams, 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, u as SendCodeParams, v as SendCodeType, w as Session, x as SuccessResponse, y as UpdateMeParams, z as createMemoryStorage, G as createStorageAdapter } from './types-D5c61dWd.js';
|
|
23
23
|
import { createSessionsModule } from './sessions.js';
|
|
24
24
|
|
|
25
25
|
declare function createOrganizationModule({ http, storage }: {
|
|
@@ -48,11 +48,54 @@ type AuthClient = AuthModule & ReturnType<typeof createPermissionsModule> & Retu
|
|
|
48
48
|
type BrowserAuthClient = AuthClient & Pick<ReturnType<typeof createAuthModule>, "getOAuthLoginURL"> & {
|
|
49
49
|
restoreSession(): Promise<ClientResult<LoginResponse>>;
|
|
50
50
|
};
|
|
51
|
-
declare function createAuthClient(options: BrowserAuthClientOptions, http?: HttpClient): BrowserAuthClient;
|
|
52
|
-
declare function createAuthClient(options?: AuthClientOptions, http?: HttpClient): AuthClient;
|
|
51
|
+
declare function createAuthClient(options: BrowserAuthClientOptions, http?: HttpClient, beforeInitialize?: (client: AuthClient) => void): BrowserAuthClient;
|
|
52
|
+
declare function createAuthClient(options?: AuthClientOptions, http?: HttpClient, beforeInitialize?: (client: AuthClient) => void): AuthClient;
|
|
53
53
|
|
|
54
|
-
/**
|
|
55
|
-
declare function
|
|
54
|
+
/** Read-only legacy UI hints. Never starts authentication, refresh or storage writes. */
|
|
55
|
+
declare function createStoredAuthReader(namespace?: string, source?: StorageAdapter): {
|
|
56
|
+
hasRole(roleCode: string): boolean;
|
|
57
|
+
hasPermission(resource: string, action: string): boolean;
|
|
58
|
+
hasAnyPermission(permissions: Array<{
|
|
59
|
+
resource: string;
|
|
60
|
+
action: string;
|
|
61
|
+
}>): boolean;
|
|
62
|
+
hasAllPermissions(permissions: Array<{
|
|
63
|
+
resource: string;
|
|
64
|
+
action: string;
|
|
65
|
+
}>): boolean;
|
|
66
|
+
getAccessToken: () => string | null;
|
|
67
|
+
isAuthenticated: () => boolean;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
type ApplicationHint = {
|
|
71
|
+
applicationCode: string;
|
|
72
|
+
environment: string;
|
|
73
|
+
tenancyEnabled: boolean;
|
|
74
|
+
};
|
|
75
|
+
/** Called only after fresh discovery advertises a preserved boundary. The signature-free reference is a local tombstone, never authority. */
|
|
76
|
+
declare function takePreservedLegacyAccessToken(namespace: string): string | null;
|
|
77
|
+
/** Cached context locates local login UI hints only. A host must freshly discover mode before any I/O. */
|
|
78
|
+
declare function createStoredApplicationAuthReader(key?: string): {
|
|
79
|
+
reader: {
|
|
80
|
+
hasRole(roleCode: string): boolean;
|
|
81
|
+
hasPermission(resource: string, action: string): boolean;
|
|
82
|
+
hasAnyPermission(permissions: Array<{
|
|
83
|
+
resource: string;
|
|
84
|
+
action: string;
|
|
85
|
+
}>): boolean;
|
|
86
|
+
hasAllPermissions(permissions: Array<{
|
|
87
|
+
resource: string;
|
|
88
|
+
action: string;
|
|
89
|
+
}>): boolean;
|
|
90
|
+
getAccessToken: () => string | null;
|
|
91
|
+
isAuthenticated: () => boolean;
|
|
92
|
+
};
|
|
93
|
+
clearConsumerHint: () => void | undefined;
|
|
94
|
+
remember(value: ApplicationHint): void;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/** Read a client's own UI profile without adding requirements to the public AuthClient interface. */
|
|
98
|
+
declare function readCachedAuthUser(client: object): User | null;
|
|
56
99
|
|
|
57
100
|
/**
|
|
58
101
|
* HTTP Client Configuration Utilities
|
|
@@ -82,4 +125,27 @@ declare function transformAmasterResponse<T>(responseData: unknown): T;
|
|
|
82
125
|
*/
|
|
83
126
|
declare const defaultHttpClientOptions: HttpClientOptions;
|
|
84
127
|
|
|
85
|
-
|
|
128
|
+
interface ConsumerUIHint {
|
|
129
|
+
scope: {
|
|
130
|
+
applicationCode: string;
|
|
131
|
+
environment: string;
|
|
132
|
+
appTenantId: string;
|
|
133
|
+
};
|
|
134
|
+
subject: RequestSubject;
|
|
135
|
+
roles: readonly string[];
|
|
136
|
+
permissions: readonly string[];
|
|
137
|
+
isSuperAdmin?: boolean;
|
|
138
|
+
}
|
|
139
|
+
/** Display hints in the authentication storage adapter only. Never hydrates a request controller or an authorization grant. */
|
|
140
|
+
declare function createConsumerUIHint(options: RequestScopeOptions, token: () => string | null): {
|
|
141
|
+
read: () => ConsumerUIHint | null;
|
|
142
|
+
write(value: ConsumerUIHint): void;
|
|
143
|
+
clear(): void;
|
|
144
|
+
hasRole: (role: string) => boolean;
|
|
145
|
+
hasPermission: (resource: string, action: string) => boolean;
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/** Signal completion only. Application credentials are recovered through the application's HttpOnly cookie. */
|
|
149
|
+
declare function completeOAuthPopup(): boolean;
|
|
150
|
+
|
|
151
|
+
export { type AuthClient, AuthClientOptions, AuthEvent, type BrowserAuthClient, BrowserAuthClientOptions, DepartmentPosition, EventHandler, LoginResponse, StorageAdapter, User, completeOAuthPopup, createAuthClient, createConsumerUIHint, createStoredApplicationAuthReader, createStoredAuthReader, defaultHttpClientOptions, readCachedAuthUser, takePreservedLegacyAccessToken, transformAmasterResponse };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
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{
|
|
1
|
+
import {setMiniProgramRuntime,createHttpClient,RequestScopeController,getMiniProgramLogin,detectMiniProgramPlatform}from'@amaster.ai/http-client';var j=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(s){console.error(`[AuthClient] Error in event handler for "${t}":`,s);}});}removeAllListeners(){this.events={};}};function Me(){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 h={ACCESS_TOKEN:"amaster_access_token",REFRESH_TOKEN:"amaster_refresh_token",PENDING_REFRESH:"amaster_pending_refresh",USER:"amaster_user"};function Oe(){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 z(e){return Oe()?.[e]}function _e(){let e=z("wx"),t=z("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 x(e){if(e!==void 0){if(typeof e!="string"||!e||e.length>512)throw new Error("Invalid auth storage namespace");let r=x(),n=s=>`amaster:auth:${JSON.stringify([e,s])}`;return {getItem:s=>r.getItem(n(s)),setItem:(s,c)=>r.setItem(n(s),c),removeItem:s=>r.removeItem(n(s)),clear:()=>Object.values(h).forEach(s=>r.removeItem(n(s)))}}switch(_e()){case "wechat-miniprogram":return ne(z("wx"),"WeChat");case "douyin-miniprogram":return ne(z("tt"),"Douyin");case "browser":return Ue();case "node":return He()}}function Ue(){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{Object.values(h).forEach(t=>e.removeItem(t));}catch(t){console.error("[AuthClient] Failed to clear localStorage:",t);}}}}function ne(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(s){console.error(`[AuthClient] Failed to set item in ${t} storage:`,s);}},removeItem(r){try{e.removeStorageSync(r);}catch(n){console.error(`[AuthClient] Failed to remove item from ${t} storage:`,n);}},clear(){try{Object.values(h).forEach(r=>e.removeStorageSync(r));}catch(r){console.error(`[AuthClient] Failed to clear ${t} storage:`,r);}}}}function He(){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 Fe(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 s=decodeURIComponent(atob(n).split("").map(c=>"%"+("00"+c.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(s)}if(typeof Buffer<"u"){let s=Buffer.from(n,"base64").toString("utf-8");return JSON.parse(s)}return null}catch(t){return console.error("[AuthClient] Failed to parse JWT token:",t),null}}var J=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=Fe(t);if(!n||!n.exp){console.warn("[AuthClient] Cannot schedule refresh: invalid token or missing exp claim");return}let s=n.exp*1e3,c=Date.now(),l=s-c-r*1e3;l<=0?(console.warn("[AuthClient] Token already expired or expiring soon, refreshing immediately"),this.refresh()):this.scheduleRefresh(l);}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 C(){return {data:null,error:{message:"Authentication session changed",code:"session_changed",status:409},status:409}}function se(e,t,r=()=>{},n=()=>false){let s=0,c=e.getItem(h.ACCESS_TOKEN),u=()=>{let m=e.getItem(h.ACCESS_TOKEN);return m!==c&&(c=m,s++,r("replace")),c},l=(m,v)=>{s++,e.setItem(h.ACCESS_TOKEN,m),c=e.getItem(h.ACCESS_TOKEN),r(v);},S=new WeakMap,p={getItem:m=>m===h.ACCESS_TOKEN?u():e.getItem(m),setItem(m,v){m===h.ACCESS_TOKEN?l(v,"replace"):e.setItem(m,v);},removeItem(m){m===h.ACCESS_TOKEN&&s++,e.removeItem(m),m===h.ACCESS_TOKEN&&(c=null,r("clear"));},clear(){s++,e.clear(),c=null,r("clear");}},f=m=>{let v=u(),w=S.get(m);if(!w)return false;if(w.generation===s&&w.token===v)return true;if(!w.profile||!n()||w.generation+1!==s||m.error||m.status!==200||!w.token||!v||w.token===v)return false;try{let E=L=>{if(L.length>16384||L.split(".").length!==3)throw new Error("Invalid token hint");let T=L.split(".")[1];if(!T)throw new Error("Missing token hint");let A=T.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(A),i=>i.charCodeAt(0))))},b=E(w.token),H=E(v),_=new Set(["exp","iat","nbf","jti"]),F=L=>Object.keys(L).filter(T=>!_.has(T)).sort().map(T=>[T,L[T]]);return typeof b.uid=="string"&&b.uid.length>0&&m.data?.uid===b.uid&&H.uid===b.uid&&JSON.stringify(F(b))===JSON.stringify(F(H))}catch{return false}};return {storage:p,http:{async request(m){let v=u(),w={generation:s,token:v,profile:m.url==="/api/auth/me"&&String(m.method??"GET").toUpperCase()==="GET"},E;try{E={...await t.request(m)};}catch(b){if(w.generation!==s||w.token!==e.getItem(h.ACCESS_TOKEN))return C();throw b}return S.set(E,w),f(E)?E:C()}},isCurrentResult:f,capture:()=>{let m=u(),v=s;return ()=>u()===m&&s===v},commitToken:l,beginLogin:()=>{s++;}}}function oe(e){return e&&typeof e=="object"&&("statusCode"in e||"status"in e)&&"data"in e?e.data:e}var Q={transformResponse:oe,logErrors:true};var ie=new WeakMap;function ae(e,t){ie.set(e,t);}function xe(e){return ie.get(e)?.()??null}var Ne="https://lf-scm-cn.feishucdn.com/lark/op/h5-js-sdk-1.5.44.js",ue="amaster-feishu-h5-sdk";var le=null,D=null,B=null;function de(){if(!(typeof window>"u"))return window}function ge(){return de()?.tt}function Z(){return de()?.h5sdk}function he(){typeof window>"u"||le===window||(le=window,D=null,B=null);}function pe(){if(typeof navigator>"u")return false;let e=ge();return /Feishu|Lark/i.test(navigator.userAgent||"")||typeof e?.requestAccess=="function"||typeof e?.requestAuthCode=="function"}function qe(){return he(),typeof document>"u"?Promise.reject(new Error("Feishu H5 SDK is only available in a browser environment")):typeof Z()?.ready=="function"?Promise.resolve():D||(D=new Promise((e,t)=>{let r=document.getElementById(ue),n=!r;r||(r=document.createElement("script"),r.id=ue,r.src=Ne,r.async=true);let s=false,c,u,l=()=>{c&&clearInterval(c),u&&clearTimeout(u),r?.removeEventListener("load",f),r?.removeEventListener("error",O);},S=q=>{if(!s){if(s=true,l(),q){r?.remove(),t(q);return}e();}},p=()=>typeof Z()?.ready=="function"?(S(),true):false,f=()=>{p();},O=()=>{S(new Error("Failed to load Feishu H5 SDK"));};r.addEventListener("load",f),r.addEventListener("error",O),c=setInterval(p,25),u=setTimeout(()=>{S(new Error("Timed out while loading Feishu H5 SDK"));},1e4),!p()&&n&&document.head.appendChild(r);}).catch(e=>{throw D=null,e}),D)}function Ke(){return he(),B||(B=(async()=>{await qe();let e=Z();if(typeof e?.ready!="function")throw new Error("Feishu H5 SDK loaded without exposing h5sdk.ready");return new Promise((t,r)=>{let n=false,s,c=(u,l)=>{n||(n=true,s&&clearTimeout(s),l?r(l):u?t(u):r(new Error("Feishu H5 SDK became ready without exposing the tt bridge")));};s=setTimeout(()=>{c(void 0,new Error("Timed out while waiting for Feishu H5 SDK ready"));},1e4),e.error?.(u=>c(void 0,new Error(X(u))));try{let u=e.ready?.(()=>c(ge()));u&&typeof u.then=="function"&&u.catch(l=>{c(void 0,new Error(`Feishu H5 SDK ready failed: ${l instanceof Error?l.message:String(l)}`));});}catch(u){c(void 0,new Error(`Feishu H5 SDK ready failed: ${u instanceof Error?u.message:String(u)}`));}})})().catch(e=>{throw B=null,e}),B)}function X(e){return e.errString||e.message||`Feishu authorization failed${e.errno?` (${e.errno})`:""}`}function ce(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:s=>{s.code?r(s.code):n(new Error("Feishu requestAuthCode returned no code"));},fail:s=>n(new Error(X(s)))});})}async function fe(e){let t=await Ke();return typeof t.requestAccess!="function"?ce(t,e):new Promise((r,n)=>{t.requestAccess?.({appID:e,scopeList:[],success:s=>{s.code?r(s.code):n(new Error("Feishu requestAccess returned no code"));},fail:s=>{if(s.errno===103){ce(t,e).then(r,n);return}n(new Error(X(s)));}});})}function Be(e){if(e.email)return "email";if(e.username)return "username";if(e.phone)return "phone"}function Ge(e){if(e.email)return "email";if(e.phone)return "phone"}function W(e){return e||(detectMiniProgramPlatform()??"wechat")}function ee(e){return typeof e=="string"?{code:e,platform:W()}:{code:e.code,platform:W(e.platform)}}function me(e,t){return t==="douyin"?`/api/auth/miniprogram/douyin/${e}`:`/api/auth/miniprogram/${e}`}async function je(e){let t=W(e),r=getMiniProgramLogin(t),n=async s=>await new Promise((c,u)=>{let l=false,S=f=>{if(!l){if(l=true,typeof f?.code=="string"&&f.code){c(f.code);return}u(new Error("Mini Program login failed: missing code"));}},p=f=>{l||(l=true,u(new Error(`Mini Program login failed: ${f instanceof Error?f.message:String(f)}`)));};try{let f=s({success:S,fail:p});if(f&&typeof f.then=="function"){f.then(S,p);return}f&&typeof f=="object"&&"code"in f&&S(f);}catch(f){p(f);}});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 ye(e){if(typeof e=="string")return ee(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:W(e.platform)}:null}function ze(e){let t=new URLSearchParams(e);return t.get("access_token")||t.get("accessToken")}function Je(e){return new URLSearchParams(e).get("user")}function Re(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 te={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 $(e,t){if(!e||typeof window>"u"||window.opener)return {handled:false};let r=Re(t);return r?(te.replace(r),{handled:true,target:r}):{handled:false}}function Se(e){let{baseURL:t,getAuthVersion:r=()=>{},http:n,onLoginSuccess:s,onLogout:c,autoRedirectAfterLogin:u,storage:l,clearAuth:S,onRefreshFailure:p,isCurrentResult:f=()=>true,captureSession:O=()=>()=>true,coalesceRefresh:q=()=>true,beginLogin:m=()=>{},verifyRefresh:v,onRefreshSuccess:w=i=>l.setItem(h.ACCESS_TOKEN,i)}=e,E=new Map,b=null,H=null,_=i=>{let o=l.getItem(h.PENDING_REFRESH);if(!o)return null;try{let a=o.length<=65536?JSON.parse(o):null;if(a?.previousAccessToken===i&&typeof a.accessToken=="string"&&a.accessToken.length>0&&a.accessToken.length<=16384)return a.accessToken}catch{}return l.removeItem(h.PENDING_REFRESH),null};function F(i){if(!t)return i;let o=typeof window>"u"?t:new URL(t,window.location.href).href;return new URL(i,o).href}let L=i=>{let o=i.trim(),a=E.get(o);if(a)return a;let d=(async()=>{if(!o)return {data:null,error:{message:"OAuth login ticket is required",status:400},status:400};m();let y=await n.request({url:"/api/auth/oauth/ticket",method:"post",headers:{"Content-Type":"application/json"},data:{ticket:o}});if(!y.data?.accessToken)return {data:null,error:y.error||{message:"OAuth login ticket is invalid, expired, or already used",status:y.status||400},status:y.status||400};if(!f(y))return C();let P=y.data.accessToken,R=await n.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${P}`}});if(!R.data)return {data:null,error:R.error||{message:"OAuth login succeeded but user information could not be loaded",status:R.status||500},status:R.status||500};if(!f(R))return C();if(s(R.data,P)===false)return C();let k=$(u,y.data.returnUrl);return {data:K({user:R.data,accessToken:P},k),error:null,status:200}})();return E.set(o,d),d},T=i=>{if(typeof window>"u")return;let o=Re(i)||"/",a=new URLSearchParams({return_url:o,callback_url:"/auth/callback"});te.assign(`/api/auth/oauth/feishu?${a.toString()}`);},A=async(i,o)=>{m();let a=await n.request({url:"/api/auth/oauth/feishu/code",method:"post",headers:{"Content-Type":"application/json"},data:{code:i}});if(!f(a))return C();if(a.data?.user&&a.data?.accessToken){if(s(a.data.user,a.data.accessToken)===false)return C();let d=$(u,o);a.data=K(a.data,d);}return a};return {async register(i){m();let o=await n.request({url:"/api/auth/register",method:"post",headers:{"Content-Type":"application/json"},data:i});if(!f(o))return C();if(o.data?.user&&o.data?.accessToken){if(s(o.data.user,o.data.accessToken)===false)return C();let a=$(u);o.data=K(o.data,a);}return o},async login(i){let o=i.loginType||Be(i);if(!o)return {data:null,error:{message:"Unable to determine login type. Please provide email, username, or phone.",status:400},status:400};let a={...i,loginType:o};m();let d=await n.request({url:"/api/auth/login",method:"post",headers:{"Content-Type":"application/json"},data:a});if(!f(d))return C();if(d.data?.user&&d.data?.accessToken){if(s(d.data.user,d.data.accessToken)===false)return C();let y=$(u);d.data=K(d.data,y);}return d},async loginWithCode(i){let o=i.loginType||Ge(i);if(!o)return {data:null,error:{message:"Unable to determine login type. Please provide email or phone.",status:400},status:400};let a={...i,loginType:o};m();let d=await n.request({url:"/api/auth/login-with-code",method:"post",headers:{"Content-Type":"application/json"},data:a});if(!f(d))return C();if(d.data?.user&&d.data?.accessToken){if(s(d.data.user,d.data.accessToken)===false)return C();let y=$(u);d.data=K(d.data,y);}return d},async sendCode(i){return n.request({url:"/api/auth/send-code",method:"post",headers:{"Content-Type":"application/json"},data:i})},async getCaptcha(){return n.request({url:"/api/auth/captcha",method:"get"})},getOAuthLoginURL(i,o){let a=new URLSearchParams;return o&&a.set("redirect_uri",o),F(`/api/auth/oauth/${i}${a.size?`?${a}`:""}`)},loginWithOAuth(i,o){if(typeof window>"u"){console.error("[AuthClient] OAuth login is only available in browser environment");return}if(i==="feishu"){T(o);return}let a=new URLSearchParams;if(o&&a.set("redirect_uri",o),i==="wecom"){if(o){let k=new URL(o,window.location.origin);k.origin===window.location.origin&&(k.searchParams.delete("oauth_error"),k.searchParams.delete("error_description"),a.set("redirect_uri",k.pathname+k.search+k.hash));}let P=new URLSearchParams(window.location.search);P.delete("oauth_error"),P.delete("error_description");let R=P.toString();a.set("error_redirect_uri",`${window.location.pathname}${R?`?${R}`:""}`);}let d=a.toString(),y=`/api/auth/oauth/${i}${d?`?${d}`:""}`;te.assign(y);},async loginWithFeishu(i){m();let o=O(),a=r(),d=()=>o()&&(a===void 0||r()===a);if(typeof window>"u")return {data:null,error:{message:"Feishu login is only available in a browser environment",status:400},status:400};if(!pe())return T(i),null;let y=await n.request({url:"/api/auth/oauth/feishu/config",method:"get"});if(!y.data?.enabled||!y.data.appId)return {data:null,error:y.error||{message:"Feishu login is not configured for this application",status:y.status||400},status:y.status||400};try{let P=await fe(y.data.appId);return d()?await A(P,i):C()}catch(P){return d()?{data:null,error:{message:P instanceof Error?P.message:String(P),status:400},status:400}:C()}},async loginWithFeishuCode(i,o){return A(i,o)},async exchangeOAuthLoginTicket(i){return L(i)},handleOAuthCallback(){return b||(m(),b=(async()=>{if(typeof window>"u")return {data:null,error:{message:"OAuth callback is only available in browser environment",status:400},status:400};try{let i=new URLSearchParams(window.location.search),o=i.get("oauth_error");if(o)return {data:null,error:{message:i.get("error_description")||`OAuth callback failed: ${o}`,status:400},status:400};let a=i.get("login_ticket");if(a){i.delete("login_ticket");let M=i.toString();return window.history.replaceState(null,"",`${window.location.pathname}${M?`?${M}`:""}${window.location.hash}`),L(a)}let d=window.location.hash.substring(1),y=ze(d),P=Je(d);if(!y)return {data:null,error:{message:"OAuth callback failed: missing access token",status:400},status:400};let R;if(P)R=JSON.parse(decodeURIComponent(P));else {let M=await n.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${y}`}});if(!M.data)return {data:null,error:{message:"OAuth callback failed: unable to fetch user info",status:M.status||500},status:M.status||500};if(!f(M))return C();R=M.data;}if(s(R,y)===!1)return C();if(window.history&&window.history.replaceState){let M=window.location.pathname+window.location.search;window.history.replaceState(null,"",M);}else window.location.hash="";let k=$(u);return {data:K({user:R,accessToken:y},k),error:null,status:200}}catch(i){return {data:null,error:{message:`OAuth callback failed: ${i instanceof Error?i.message:String(i)}`,status:400},status:400}}})(),b)},async loginWithMiniProgram(i){let{code:o,platform:a}=ee(i);m();let d=await n.request({url:me("login",a),method:"post",headers:{"Content-Type":"application/json"},data:{code:o}});if(!f(d))return C();if(d.data?.user&&d.data?.accessToken){if(s(d.data.user,d.data.accessToken)===false)return C();let y=$(u);d.data=K(d.data,y);}return d},async miniLogin(i={}){m();let o=O(),a=r(),d=()=>o()&&(a===void 0||r()===a);try{let y=await je(i.platform);return d()?await this.loginWithMiniProgram(y):C()}catch(y){return d()?{data:null,error:{message:y instanceof Error?y.message:String(y),status:400},status:400}:C()}},async getMiniProgramPhoneNumber(i){let{code:o,platform:a}=ee(i),d=l.getItem(h.ACCESS_TOKEN);return d?n.request({url:me("phone",a),method:"post",headers:{"Content-Type":"application/json",Authorization:`Bearer ${d}`},data:{code:o}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async miniPhoneLogin(i){let o=ye(i);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};m();let a=await n.request({url:"/api/auth/miniprogram/phone-login",method:"post",headers:{"Content-Type":"application/json"},data:{code:o.code}});if(!f(a))return C();if(a.data?.user&&a.data?.accessToken){if(s(a.data.user,a.data.accessToken)===false)return C();let d=$(u);a.data=K(a.data,d);}return a},async miniGetPhone(i){let o=ye(i);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 i=l.getItem(h.ACCESS_TOKEN),o=v&&_(i)||i;return S(),c(),await n.request({url:"/api/auth/logout",method:"post",headers:o?{Authorization:`Bearer ${o}`}:void 0})},refreshToken(){if(q()&&H?.isCurrent())return H.promise;let i=O(),o=r(),a=()=>i()&&(o===void 0||r()===o),d=(async()=>{let P=l.getItem(h.ACCESS_TOKEN),R;if(v){let k=_(P);k&&(R={data:{accessToken:k},status:200,error:null});}if(!R){if(R=await n.request({url:"/api/auth/refresh",method:"post",headers:P?{Authorization:`Bearer ${P}`}:void 0}),!f(R)||!a())return C();v&&R.data?.accessToken&&l.setItem(h.PENDING_REFRESH,JSON.stringify({previousAccessToken:P,accessToken:R.data.accessToken}));}if(!a())return C();if(R.data?.accessToken){if(v){let k;try{k=await v(R.data.accessToken);}catch{k={data:null,status:503,error:{status:503,code:"dependency_unverifiable",message:"Identity verification unavailable"}};}if(!a())return C();if(k.error||k.status<200||k.status>=300){let M={...k,data:null};return (M.status===401||M.status===403)&&(l.removeItem(h.PENDING_REFRESH),p?.(M)),M}}if(l.removeItem(h.PENDING_REFRESH),w(R.data.accessToken)===false)return C()}else (R.status===401||R.status===403)&&p?.(R);return R})(),y={isCurrent:a,promise:d};return H=y,d.finally(()=>{H===y&&(H=null);}).catch(()=>{}),d}}}function V(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 s=t();if(s?.isSuperAdmin)return true;if(!s||!s.permissions)return false;let c=`${r}.${n}`;return s.permissions.includes(c)},hasAnyPermission(r){return r.some(({resource:n,action:s})=>this.hasPermission(n,s))},hasAllPermissions(r){return r.every(({resource:n,action:s})=>this.hasPermission(n,s))}}}function Ce(e){let{http:t,storage:r,onUserUpdate:n,onAuthFailure:s,getAuthVersion:c,isCurrentResult:u=()=>true}=e;return {async getMe(){let l=c?.(),S=r.getItem("amaster_access_token");if(!S)return {data:null,error:{message:"Not authenticated",status:401},status:401};let p=await t.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${S}`}});return !u(p)||l!==void 0&&(c?.()!==l||r.getItem("amaster_access_token")!==S)?C():(p.data?n(p.data):(p.status===401||p.status===403)&&s?.(p),p)},async updateMe(l){let S=r.getItem("amaster_access_token");if(!S)return {data:null,error:{message:"Not authenticated",status:401},status:401};let p=await t.request({url:"/api/auth/me",method:"put",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},data:l});return u(p)?(p.data&&n(p.data),p):C()},async changePassword(l){let S=r.getItem("amaster_access_token");return S?t.request({url:"/api/auth/change-password",method:"post",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},data:l}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function Ae(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 s=r.getItem("amaster_access_token");return s?t.request({url:`/api/auth/oauth/${n}/unbind`,method:"delete",headers:{Authorization:`Bearer ${s}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function we({http:e,storage:t}){return {async getPositions(){let r=t.getItem(h.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 s=Array.isArray(n.data)?n.data:n.data?.data;return Array.isArray(s)?{...n,data:s}:{...n,data:null,error:{message:"Invalid position definitions response",status:502},status:502}}}}function Pe(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 s=r.getItem("amaster_access_token");return s?n?t.request({url:`/api/auth/sessions/${n}`,method:"delete",headers:{Authorization:`Bearer ${s}`}}):{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 Ye(e={},t,r){let{baseURL:n,storage:s,withCredentials:c,headers:u,onTokenExpired:l,onUnauthorized:S,autoHandleOAuthCallback:p=true,autoRedirectAfterLogin:f=true,runtime:O,autoRefresh:q=true}=e;O&&setMiniProgramRuntime(O);let m=t||createHttpClient({...Q,baseURL:n,withCredentials:c,headers:u,runtime:O}),v=300,w=new j,E=new J,b=null,H=false,_=0,F=!!s&&typeof s.getItem=="function",L=null,T=se(F?s:x(e.storageNamespace),m,g=>{g!=="refresh"&&(_++,L=null,b=null,T.storage.removeItem(h.USER),E.clearSchedule()),g!=="login"&&w.emit("credentialsChanged",g);},()=>!e.storageNamespace&&!e.verifyRefresh&&!F),A=T.storage,i=T.http;try{let g=A.getItem(h.USER);g&&(b=JSON.parse(g));}catch(g){console.error("[AuthClient] Failed to load user from storage:",g);}let o;function a(g,I){H||(H=true,R(),!A.getItem(h.ACCESS_TOKEN)&&(g==="tokenExpired"&&(w.emit("tokenExpired",I?.error),l?.()),w.emit("unauthorized",I?.error),w.emit("logout")));}E.setRefreshCallback(async()=>{let g=T.capture(),I=_,U=await o.refreshToken();if(!(F&&I!==_))if(U.data){if(o.getAccessToken()!==U.data.accessToken||e.syncUserOnInit!==false&&((await o.getMe()).error||o.getAccessToken()!==U.data.accessToken))return;w.emit("tokenRefreshed",U.data.accessToken);}else U.error?.code!=="session_changed"&&g()&&(U.status===0||U.status===409||U.status>=500?E.scheduleRefresh(3e4):a("tokenExpired",U));});function d(g,I){return H=false,A.removeItem(h.PENDING_REFRESH),T.commitToken(I,"login"),A.setItem(h.USER,JSON.stringify(g)),b=g,q&&E.scheduleRefreshFromToken(I,v),w.emit("credentialsChanged","login"),A.getItem(h.ACCESS_TOKEN)!==I?false:(w.emit("login",g),A.getItem(h.ACCESS_TOKEN)===I)}function y(g){b=g,A.setItem(h.USER,JSON.stringify(g));}function P(){A.getItem(h.ACCESS_TOKEN)||w.emit("logout");}function R(){_++,L=null,A.clear();}function k(){return A.getItem(h.ACCESS_TOKEN)?b:null}let M=Se({baseURL:n,http:i,onLoginSuccess:d,onLogout:P,autoRedirectAfterLogin:f,storage:A,clearAuth:R,getAuthVersion:()=>F?_:void 0,onRefreshFailure:g=>a("tokenExpired",g),isCurrentResult:T.isCurrentResult,captureSession:T.capture,beginLogin(){_++,E.clearSchedule(),T.beginLogin();},verifyRefresh:e.verifyRefresh,coalesceRefresh:()=>!!e.storageNamespace||!!e.verifyRefresh||F,onRefreshSuccess(g){return T.commitToken(g,"refresh"),A.getItem(h.ACCESS_TOKEN)!==g?false:(q&&(e.autoRefresh===true||e.storageNamespace||e.verifyRefresh||F)&&E.scheduleRefreshFromToken(g,v),true)}}),Te=V({getCurrentUser:k}),Ee=Ce({http:i,storage:A,getAuthVersion:()=>F?_:void 0,onUserUpdate:y,onAuthFailure:g=>a("unauthorized",g),isCurrentResult:T.isCurrentResult}),be=Ae({http:i,storage:A}),Ie=Pe({http:i,storage:A}),Le=we({http:i,storage:A});if(o={...M,...Te,...Le,...Ee,...be,...Ie,restoreSession(){if(F=true,L)return L;let g=_,I=()=>({data:null,error:{message:"Authentication state changed",status:409},status:409}),U=(async()=>{let N=await o.refreshToken();if(!N.data)return {...N,data:null};if(g!==_)return I();let G=await o.getMe();return G.data?g!==_?I():(d(G.data,N.data.accessToken),{data:{user:G.data,accessToken:N.data.accessToken},error:null,status:200}):{...G,data:null}})();return L=U,U.finally(()=>{L===U&&(L=null);}).catch(()=>{}),U},on(g,I){w.on(g,I);},off(g,I){w.off(g,I);},isAuthenticated(){return !!A.getItem(h.ACCESS_TOKEN)},getAccessToken(){return A.getItem(h.ACCESS_TOKEN)},setAccessToken(g){H=false,A.removeItem(h.PENDING_REFRESH),b=null,A.removeItem(h.USER),E.clearSchedule(),A.setItem(h.ACCESS_TOKEN,g),q&&A.getItem(h.ACCESS_TOKEN)===g&&E.scheduleRefreshFromToken(g,v);},clearAuth(){R(),P();}},ae(o,k),o.on("unauthorized",()=>{S?.();}),r?.(o),e.syncUserOnInit!==false&&o.isAuthenticated()&&o.getMe().then(g=>{g.error&&console.warn("[AuthClient] Failed to sync user info on init:",g.error);}).catch(g=>{console.warn("[AuthClient] Failed to sync user info on init:",g);}),p&&typeof window<"u"){let g=window.location.hash,I=new URLSearchParams(window.location.search);(I.has("login_ticket")||I.has("oauth_error")||g&&(g.includes("access_token")||g.includes("accessToken")))&&o.handleOAuthCallback().then(N=>{N.error&&console.error("[AuthClient] Auto OAuth callback failed:",N.error);}).catch(N=>{console.error("[AuthClient] Auto OAuth callback error:",N);});}return o}function Y(e,t){let r=t??x(e),n=r.getItem(h.ACCESS_TOKEN),s=null;try{let u=JSON.parse(r.getItem(h.USER)??"null");u&&typeof u=="object"&&typeof u.uid=="string"&&Array.isArray(u.roles)&&u.roles.every(l=>typeof l=="string")&&Array.isArray(u.permissions)&&u.permissions.every(l=>typeof l=="string")&&(s=u);}catch{}let c=()=>{let u=r.getItem(h.ACCESS_TOKEN);return u!==n&&(n=u,s=null),n};return {getAccessToken:c,isAuthenticated:()=>!!c(),...V({getCurrentUser:()=>c()?s:null})}}function re(e,t){let r=new RequestScopeController({...e,storage:null}).environment;e={...e,environment:r,storage:e.storage===void 0?x(JSON.stringify([e.applicationCode,r])):e.storage};let n=`amaster:consumer-ui:${JSON.stringify([e.applicationCode,e.environment])}`,s=()=>{let l=t()?.split(".");return l?.length===3&&l.every(Boolean)?JSON.stringify(l.slice(0,2)):null},c=()=>e.storage,u=()=>{try{let l=s(),S=JSON.parse(c()?.getItem(n)??"null"),p=S?.value;if(!l||S?.reference!==l||!p||p.scope?.applicationCode!==e.applicationCode||p.scope.environment!==e.environment||!Array.isArray(p.roles)||!p.roles.every(O=>typeof O=="string")||!Array.isArray(p.permissions)||!p.permissions.every(O=>typeof O=="string")||p.isSuperAdmin!==void 0&&typeof p.isSuperAdmin!="boolean")return null;let f=new RequestScopeController(e);return f.setSubject(p.subject),f.appTenantId===p.scope.appTenantId&&f.appTenantId?p:null}catch{return null}};return {read:u,write(l){try{let S=s();S&&c()?.setItem(n,JSON.stringify({reference:S,value:l}));}catch{}},clear(){try{c()?.removeItem(n);}catch{}},hasRole:l=>!!u()?.isSuperAdmin||(u()?.roles.includes(l)??false),hasPermission:(l,S)=>!!u()?.isSuperAdmin||(u()?.permissions.includes(`${l}.${S}`)??false)}}function Ze(e){let t=Y().getAccessToken(),r=t?.split(".");if(!t||r?.length!==3||r.some(c=>!c))return null;let n=x("legacy-session-migration"),s=JSON.stringify([e,r[0],r[1]]);return n.getItem(s)==="1"?null:(n.setItem(s,"1"),t)}function ke(e){if(!e||typeof e!="object")return false;let t=e;if(typeof t.tenancyEnabled!="boolean")return false;try{return new RequestScopeController({applicationCode:t.applicationCode,environment:t.environment,storage:null}).environment===t.environment}catch{return false}}function Xe(e){let t=x("application-context-ui"),r;try{let c=e?JSON.parse(t.getItem(e)??"null"):null;ke(c)&&(r=c);}catch{}let n=Y(r?.tenancyEnabled?JSON.stringify([r.applicationCode,r.environment]):void 0),s=r?.tenancyEnabled?re(r,n.getAccessToken):void 0;return {reader:r?.tenancyEnabled?{...n,hasRole:c=>s?.hasRole(c)??false,hasPermission:(c,u)=>s?.hasPermission(c,u)??false,hasAnyPermission:c=>c.some(({resource:u,action:l})=>s?.hasPermission(u,l)),hasAllPermissions:c=>c.every(({resource:u,action:l})=>s?.hasPermission(u,l))}:n,clearConsumerHint:()=>s?.clear(),remember(c){if(e&&ke(c))try{t.setItem(e,JSON.stringify(c));}catch{}}}}function et(){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{et as completeOAuthPopup,Ye as createAuthClient,re as createConsumerUIHint,Me as createMemoryStorage,x as createStorageAdapter,Xe as createStoredApplicationAuthReader,Y as createStoredAuthReader,Q as defaultHttpClientOptions,xe as readCachedAuthUser,Ze as takePreservedLegacyAccessToken,oe as transformAmasterResponse};//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|