@ram_28/kf-ai-sdk 2.0.23 → 2.0.24

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/auth.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var J=Object.defineProperty;var X=(e,t,o)=>t in e?J(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o;var Q=(e,t,o)=>X(e,typeof t!="symbol"?t+"":t,o);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("react/jsx-runtime"),n=require("react"),M=require("@tanstack/react-query"),K=require("./client-D5k4SYuw.cjs"),W=require("./constants-DEmYwKfC.cjs"),Y={sessionEndpoint:"/api/id",providers:{google:{loginPath:"/api/auth/google/login",logoutPath:"/api/auth/logout"}},defaultProvider:"google",autoRedirect:!1,sessionCheckInterval:0,retry:{count:3,delay:1e3},staleTime:5*60*1e3,refetchOnWindowFocus:!1,refetchOnReconnect:!0};let h={...Y};function G(e){h={...h,...e,providers:{...h.providers,...e.providers},retry:{...h.retry,...e.retry}}}function Z(e,t){h.providers[e]=t}function b(){return{...h}}function k(){return h.baseUrl||K.getApiBaseUrl()||(typeof window<"u"?window.location.origin:"")}function H(e){return h.providers[e]}function D(){h={...Y}}class m extends Error{constructor(o,r){super(o);Q(this,"statusCode");this.name="AuthenticationError",this.statusCode=r}}async function ee(){const e=b(),t=k(),o=K.getDefaultHeaders(),r=await fetch(`${t}${e.sessionEndpoint}`,{method:"GET",headers:o,credentials:"include"});if(!r.ok)throw r.status===401||r.status===403?new m("Not authenticated",r.status):new m(`Session check failed: ${r.statusText}`,r.status);return await r.json()}function N(e,t){return new Promise(()=>{const o=b(),r=k();if(!r)throw new Error('Auth base URL is not configured. Call setApiBaseUrl("https://...") or configureAuth({ baseUrl: "https://..." }) first.');const i=e||o.defaultProvider,l=H(i);if(!l){const A=Object.keys(o.providers||{}).join(", ")||"none";throw new Error(`Auth provider "${i}" is not configured. Available providers: ${A}`)}if(!l.loginPath)throw new Error(`Login path not configured for provider "${i}". Configure it with: configureAuth({ providers: { ${i}: { loginPath: '/api/auth/...' } } })`);let g;try{g=new URL(`${r}${l.loginPath}`)}catch{throw new Error(`Failed to construct login URL. Base URL: "${r}", Login path: "${l.loginPath}". Ensure baseUrl is a valid URL (e.g., "https://example.com").`)}(t!=null&&t.callbackUrl||o.callbackUrl)&&g.searchParams.set("callbackUrl",(t==null?void 0:t.callbackUrl)||o.callbackUrl||window.location.href),t!=null&&t.params&&Object.entries(t.params).forEach(([A,v])=>{g.searchParams.set(A,v)}),window.open(g.toString(),"_blank")})}async function te(e){const t=b(),o=k(),r=H(t.defaultProvider),i=r==null?void 0:r.logoutPath;if(i&&(e==null?void 0:e.callLogoutEndpoint)!==!1)try{await fetch(`${o}${i}`)}catch(l){console.warn("Logout endpoint call failed:",l)}e!=null&&e.redirectUrl?window.location.href=e.redirectUrl:t.loginRedirectUrl&&(window.location.href=t.loginRedirectUrl)}const V=n.createContext(null),_=["auth","session"];function re({children:e,config:t,onAuthChange:o,onError:r,loadingComponent:i,unauthenticatedComponent:l,skipInitialCheck:g=!1}){const A=n.useRef(!1);t&&!A.current&&(G(t),A.current=!0);const v=M.useQueryClient(),c=b(),{data:u,isLoading:f,error:U,refetch:R,isFetching:C}=M.useQuery({queryKey:_,queryFn:ee,enabled:!g,retry:(s,w)=>w instanceof m&&(w.statusCode===401||w.statusCode===403)?!1:s<c.retry.count,retryDelay:c.retry.delay,staleTime:c.staleTime,gcTime:c.staleTime*2,refetchOnWindowFocus:c.refetchOnWindowFocus??!0,refetchOnReconnect:c.refetchOnReconnect??!0,refetchInterval:c.sessionCheckInterval||!1}),[S,L]=n.useState(null),d=n.useMemo(()=>f||C?"loading":Object.keys((u==null?void 0:u.userDetails)||{}).length>0?"authenticated":"unauthenticated",[f,C,u]),a=(u==null?void 0:u.userDetails)||null,x=(u==null?void 0:u.staticBaseUrl)||null,$=(u==null?void 0:u.buildId)||null,j=d==="authenticated",P=n.useRef(o);P.current=o;const E=n.useRef(r);E.current=r,n.useEffect(()=>{var s;f||(s=P.current)==null||s.call(P,d,a)},[d,a,f]),n.useEffect(()=>{var s;U&&(L(U),(s=E.current)==null||s.call(E,U))},[U]),n.useEffect(()=>{d==="unauthenticated"&&c.autoRedirect&&!f&&N()},[d,f,c.autoRedirect]);const p=n.useCallback((s,w)=>{N(s,w)},[]),q=n.useCallback(async s=>{v.removeQueries({queryKey:_}),await te(s)},[v]),B=n.useCallback(async()=>{if(C)return u||null;try{return(await R()).data||null}catch(s){return L(s),null}},[R,C,u]),O=n.useCallback(s=>(a==null?void 0:a.Role)===s,[a]),I=n.useCallback(s=>s.includes((a==null?void 0:a.Role)||""),[a]),F=n.useCallback(()=>{L(null)},[]),T=n.useCallback(()=>{R()},[R]),z=n.useMemo(()=>({user:a,staticBaseUrl:x,buildId:$,status:d,isAuthenticated:j,isLoading:f,login:p,logout:q,refreshSession:B,hasRole:O,hasAnyRole:I,error:S,clearError:F,_forceCheck:T}),[a,x,$,d,j,f,p,q,B,O,I,S,F,T]);return d==="loading"&&i?y.jsx(y.Fragment,{children:i}):d==="unauthenticated"&&!c.autoRedirect&&l?y.jsx(y.Fragment,{children:l}):y.jsx(V.Provider,{value:z,children:e})}function ne(){const e=n.useContext(V);if(!e)throw new Error("useAuth must be used within an AuthProvider");return e}function oe(){const e=ne();return n.useMemo(()=>({user:e.user,staticBaseUrl:e.staticBaseUrl,buildId:e.buildId,status:e.status,isAuthenticated:e.isAuthenticated,isLoading:e.isLoading,login:e.login,logout:e.logout,refreshSession:e.refreshSession,hasRole:e.hasRole,hasAnyRole:e.hasAnyRole,error:e.error,clearError:e.clearError}),[e.user,e.staticBaseUrl,e.buildId,e.status,e.isAuthenticated,e.isLoading,e.login,e.logout,e.refreshSession,e.hasRole,e.hasAnyRole,e.error,e.clearError])}exports.AuthProviderName=W.AuthProviderName;exports.AuthStatus=W.AuthStatus;exports.AuthProvider=re;exports.AuthenticationError=m;exports.configureAuth=G;exports.getAuthBaseUrl=k;exports.getAuthConfig=b;exports.resetAuthConfig=D;exports.setAuthProvider=Z;exports.useAuth=oe;
1
+ "use strict";var J=Object.defineProperty;var X=(e,t,o)=>t in e?J(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o;var Q=(e,t,o)=>X(e,typeof t!="symbol"?t+"":t,o);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("react/jsx-runtime"),n=require("react"),M=require("@tanstack/react-query"),K=require("./client-D5k4SYuw.cjs"),W=require("./constants-DEmYwKfC.cjs"),Y={sessionEndpoint:"/api/id",providers:{google:{loginPath:"/api/auth/google/login",logoutPath:"/api/auth/logout"}},defaultProvider:"google",autoRedirect:!1,sessionCheckInterval:0,retry:{count:3,delay:1e3},staleTime:5*60*1e3,refetchOnWindowFocus:!1,refetchOnReconnect:!0};let h={...Y};function G(e){h={...h,...e,providers:{...h.providers,...e.providers},retry:{...h.retry,...e.retry}}}function Z(e,t){h.providers[e]=t}function b(){return{...h}}function k(){return h.baseUrl||K.getApiBaseUrl()||(typeof window<"u"?window.location.origin:"")}function H(e){return h.providers[e]}function D(){h={...Y}}class E extends Error{constructor(o,r){super(o);Q(this,"statusCode");this.name="AuthenticationError",this.statusCode=r}}async function ee(){const e=b(),t=k(),o=K.getDefaultHeaders(),r=await fetch(`${t}${e.sessionEndpoint}`,{method:"GET",headers:o,credentials:"include"});if(!r.ok)throw r.status===401||r.status===403?new E("Not authenticated",r.status):new E(`Session check failed: ${r.statusText}`,r.status);return await r.json()}function N(e,t){return new Promise(()=>{const o=b(),r=k();if(!r)throw new Error('Auth base URL is not configured. Call setApiBaseUrl("https://...") or configureAuth({ baseUrl: "https://..." }) first.');const i=e||o.defaultProvider,l=H(i);if(!l){const A=Object.keys(o.providers||{}).join(", ")||"none";throw new Error(`Auth provider "${i}" is not configured. Available providers: ${A}`)}if(!l.loginPath)throw new Error(`Login path not configured for provider "${i}". Configure it with: configureAuth({ providers: { ${i}: { loginPath: '/api/auth/...' } } })`);let g;try{g=new URL(`${r}${l.loginPath}`)}catch{throw new Error(`Failed to construct login URL. Base URL: "${r}", Login path: "${l.loginPath}". Ensure baseUrl is a valid URL (e.g., "https://example.com").`)}(t!=null&&t.callbackUrl||o.callbackUrl)&&g.searchParams.set("callbackUrl",(t==null?void 0:t.callbackUrl)||o.callbackUrl||window.location.href),t!=null&&t.params&&Object.entries(t.params).forEach(([A,v])=>{g.searchParams.set(A,v)}),window.open(g.toString(),"_blank")})}async function te(e){const t=b(),o=k(),r=H(t.defaultProvider),i=r==null?void 0:r.logoutPath;if(i&&(e==null?void 0:e.callLogoutEndpoint)!==!1)try{await fetch(`${o}${i}`,{method:"POST"})}catch(l){console.warn("Logout endpoint call failed:",l)}e!=null&&e.redirectUrl?window.location.href=e.redirectUrl:t.loginRedirectUrl&&(window.location.href=t.loginRedirectUrl)}const V=n.createContext(null),_=["auth","session"];function re({children:e,config:t,onAuthChange:o,onError:r,loadingComponent:i,unauthenticatedComponent:l,skipInitialCheck:g=!1}){const A=n.useRef(!1);t&&!A.current&&(G(t),A.current=!0);const v=M.useQueryClient(),c=b(),{data:u,isLoading:f,error:U,refetch:R,isFetching:P}=M.useQuery({queryKey:_,queryFn:ee,enabled:!g,retry:(s,w)=>w instanceof E&&(w.statusCode===401||w.statusCode===403)?!1:s<c.retry.count,retryDelay:c.retry.delay,staleTime:c.staleTime,gcTime:c.staleTime*2,refetchOnWindowFocus:c.refetchOnWindowFocus??!0,refetchOnReconnect:c.refetchOnReconnect??!0,refetchInterval:c.sessionCheckInterval||!1}),[L,S]=n.useState(null),d=n.useMemo(()=>f||P?"loading":Object.keys((u==null?void 0:u.userDetails)||{}).length>0?"authenticated":"unauthenticated",[f,P,u]),a=(u==null?void 0:u.userDetails)||null,x=(u==null?void 0:u.staticBaseUrl)||null,$=(u==null?void 0:u.buildId)||null,O=d==="authenticated",C=n.useRef(o);C.current=o;const m=n.useRef(r);m.current=r,n.useEffect(()=>{var s;f||(s=C.current)==null||s.call(C,d,a)},[d,a,f]),n.useEffect(()=>{var s;U&&(S(U),(s=m.current)==null||s.call(m,U))},[U]),n.useEffect(()=>{d==="unauthenticated"&&c.autoRedirect&&!f&&N()},[d,f,c.autoRedirect]);const j=n.useCallback((s,w)=>{N(s,w)},[]),p=n.useCallback(async s=>{v.removeQueries({queryKey:_}),await te(s)},[v]),q=n.useCallback(async()=>{if(P)return u||null;try{return(await R()).data||null}catch(s){return S(s),null}},[R,P,u]),B=n.useCallback(s=>(a==null?void 0:a.Role)===s,[a]),I=n.useCallback(s=>s.includes((a==null?void 0:a.Role)||""),[a]),T=n.useCallback(()=>{S(null)},[]),F=n.useCallback(()=>{R()},[R]),z=n.useMemo(()=>({user:a,staticBaseUrl:x,buildId:$,status:d,isAuthenticated:O,isLoading:f,login:j,logout:p,refreshSession:q,hasRole:B,hasAnyRole:I,error:L,clearError:T,_forceCheck:F}),[a,x,$,d,O,f,j,p,q,B,I,L,T,F]);return d==="loading"&&i?y.jsx(y.Fragment,{children:i}):d==="unauthenticated"&&!c.autoRedirect&&l?y.jsx(y.Fragment,{children:l}):y.jsx(V.Provider,{value:z,children:e})}function ne(){const e=n.useContext(V);if(!e)throw new Error("useAuth must be used within an AuthProvider");return e}function oe(){const e=ne();return n.useMemo(()=>({user:e.user,staticBaseUrl:e.staticBaseUrl,buildId:e.buildId,status:e.status,isAuthenticated:e.isAuthenticated,isLoading:e.isLoading,login:e.login,logout:e.logout,refreshSession:e.refreshSession,hasRole:e.hasRole,hasAnyRole:e.hasAnyRole,error:e.error,clearError:e.clearError}),[e.user,e.staticBaseUrl,e.buildId,e.status,e.isAuthenticated,e.isLoading,e.login,e.logout,e.refreshSession,e.hasRole,e.hasAnyRole,e.error,e.clearError])}exports.AuthProviderName=W.AuthProviderName;exports.AuthStatus=W.AuthStatus;exports.AuthProvider=re;exports.AuthenticationError=E;exports.configureAuth=G;exports.getAuthBaseUrl=k;exports.getAuthConfig=b;exports.resetAuthConfig=D;exports.setAuthProvider=Z;exports.useAuth=oe;
package/dist/auth.mjs CHANGED
@@ -43,10 +43,10 @@ function ie(e) {
43
43
  function ge(e, t) {
44
44
  d.providers[e] = t;
45
45
  }
46
- function E() {
46
+ function P() {
47
47
  return { ...d };
48
48
  }
49
- function $() {
49
+ function S() {
50
50
  return d.baseUrl || ne() || (typeof window < "u" ? window.location.origin : "");
51
51
  }
52
52
  function M(e) {
@@ -63,7 +63,7 @@ class x extends Error {
63
63
  }
64
64
  }
65
65
  async function ae() {
66
- const e = E(), t = $(), n = oe(), r = await fetch(`${t}${e.sessionEndpoint}`, {
66
+ const e = P(), t = S(), n = oe(), r = await fetch(`${t}${e.sessionEndpoint}`, {
67
67
  method: "GET",
68
68
  headers: n,
69
69
  credentials: "include"
@@ -77,7 +77,7 @@ async function ae() {
77
77
  }
78
78
  function Y(e, t) {
79
79
  return new Promise(() => {
80
- const n = E(), r = $();
80
+ const n = P(), r = S();
81
81
  if (!r)
82
82
  throw new Error(
83
83
  'Auth base URL is not configured. Call setApiBaseUrl("https://...") or configureAuth({ baseUrl: "https://..." }) first.'
@@ -110,10 +110,10 @@ function Y(e, t) {
110
110
  });
111
111
  }
112
112
  async function se(e) {
113
- const t = E(), n = $(), r = M(t.defaultProvider), s = r == null ? void 0 : r.logoutPath;
113
+ const t = P(), n = S(), r = M(t.defaultProvider), s = r == null ? void 0 : r.logoutPath;
114
114
  if (s && (e == null ? void 0 : e.callLogoutEndpoint) !== !1)
115
115
  try {
116
- await fetch(`${n}${s}`);
116
+ await fetch(`${n}${s}`, { method: "POST" });
117
117
  } catch (u) {
118
118
  console.warn("Logout endpoint call failed:", u);
119
119
  }
@@ -131,7 +131,7 @@ function ye({
131
131
  }) {
132
132
  const w = p(!1);
133
133
  t && !w.current && (ie(t), w.current = !0);
134
- const A = te(), c = E(), {
134
+ const A = te(), c = P(), {
135
135
  data: i,
136
136
  isLoading: h,
137
137
  error: U,
@@ -148,7 +148,7 @@ function ye({
148
148
  refetchOnWindowFocus: c.refetchOnWindowFocus ?? !0,
149
149
  refetchOnReconnect: c.refetchOnReconnect ?? !0,
150
150
  refetchInterval: c.sessionCheckInterval || !1
151
- }), [S, P] = Z(null), l = k(() => h || m ? "loading" : Object.keys((i == null ? void 0 : i.userDetails) || {}).length > 0 ? "authenticated" : "unauthenticated", [h, m, i]), a = (i == null ? void 0 : i.userDetails) || null, B = (i == null ? void 0 : i.staticBaseUrl) || null, I = (i == null ? void 0 : i.buildId) || null, O = l === "authenticated", b = p(n);
151
+ }), [$, E] = Z(null), l = k(() => h || m ? "loading" : Object.keys((i == null ? void 0 : i.userDetails) || {}).length > 0 ? "authenticated" : "unauthenticated", [h, m, i]), a = (i == null ? void 0 : i.userDetails) || null, O = (i == null ? void 0 : i.staticBaseUrl) || null, B = (i == null ? void 0 : i.buildId) || null, I = l === "authenticated", b = p(n);
152
152
  b.current = n;
153
153
  const R = p(r);
154
154
  R.current = r, L(() => {
@@ -156,16 +156,16 @@ function ye({
156
156
  h || (o = b.current) == null || o.call(b, l, a);
157
157
  }, [l, a, h]), L(() => {
158
158
  var o;
159
- U && (P(U), (o = R.current) == null || o.call(R, U));
159
+ U && (E(U), (o = R.current) == null || o.call(R, U));
160
160
  }, [U]), L(() => {
161
161
  l === "unauthenticated" && c.autoRedirect && !h && Y();
162
162
  }, [l, h, c.autoRedirect]);
163
- const F = f(
163
+ const T = f(
164
164
  (o, y) => {
165
165
  Y(o, y);
166
166
  },
167
167
  []
168
- ), T = f(
168
+ ), F = f(
169
169
  async (o) => {
170
170
  A.removeQueries({ queryKey: G }), await se(o);
171
171
  },
@@ -176,7 +176,7 @@ function ye({
176
176
  try {
177
177
  return (await v()).data || null;
178
178
  } catch (o) {
179
- return P(o), null;
179
+ return E(o), null;
180
180
  }
181
181
  }, [v, m, i]), q = f(
182
182
  (o) => (a == null ? void 0 : a.Role) === o,
@@ -185,39 +185,39 @@ function ye({
185
185
  (o) => o.includes((a == null ? void 0 : a.Role) || ""),
186
186
  [a]
187
187
  ), _ = f(() => {
188
- P(null);
188
+ E(null);
189
189
  }, []), K = f(() => {
190
190
  v();
191
191
  }, [v]), z = k(
192
192
  () => ({
193
193
  user: a,
194
- staticBaseUrl: B,
195
- buildId: I,
194
+ staticBaseUrl: O,
195
+ buildId: B,
196
196
  status: l,
197
- isAuthenticated: O,
197
+ isAuthenticated: I,
198
198
  isLoading: h,
199
- login: F,
200
- logout: T,
199
+ login: T,
200
+ logout: F,
201
201
  refreshSession: j,
202
202
  hasRole: q,
203
203
  hasAnyRole: Q,
204
- error: S,
204
+ error: $,
205
205
  clearError: _,
206
206
  _forceCheck: K
207
207
  }),
208
208
  [
209
209
  a,
210
+ O,
210
211
  B,
211
- I,
212
212
  l,
213
- O,
213
+ I,
214
214
  h,
215
- F,
216
215
  T,
216
+ F,
217
217
  j,
218
218
  q,
219
219
  Q,
220
- S,
220
+ $,
221
221
  _,
222
222
  K
223
223
  ]
@@ -271,8 +271,8 @@ export {
271
271
  be as AuthStatus,
272
272
  x as AuthenticationError,
273
273
  ie as configureAuth,
274
- $ as getAuthBaseUrl,
275
- E as getAuthConfig,
274
+ S as getAuthBaseUrl,
275
+ P as getAuthConfig,
276
276
  we as resetAuthConfig,
277
277
  ge as setAuthProvider,
278
278
  Ae as useAuth
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ram_28/kf-ai-sdk",
3
- "version": "2.0.23",
3
+ "version": "2.0.24",
4
4
  "description": "Type-safe, AI-driven SDK for building modern web applications with role-based access control",
5
5
  "author": "Ramprasad",
6
6
  "license": "MIT",
@@ -155,7 +155,7 @@ export async function performLogout(
155
155
 
156
156
  if (logoutPath && options?.callLogoutEndpoint !== false) {
157
157
  try {
158
- await fetch(`${baseUrl}${logoutPath}`);
158
+ await fetch(`${baseUrl}${logoutPath}`, { method: "POST" });
159
159
  } catch (error) {
160
160
  console.warn("Logout endpoint call failed:", error);
161
161
  }