tevrocsdk 0.1.80 → 0.1.82

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/tevroc-sdk.esm.js CHANGED
@@ -3657,6 +3657,7 @@ __export(useGoogleAuth_exports, {
3657
3657
  subscribeGoogleLogin: () => subscribeGoogleLogin
3658
3658
  });
3659
3659
  function emitGoogleLogin(user, err2 = null) {
3660
+ debugAuth("Emitting login result", { success: Boolean(user), error: err2?.message || null });
3660
3661
  googleListeners.forEach((cb) => {
3661
3662
  try {
3662
3663
  cb(user, err2);
@@ -3666,13 +3667,15 @@ function emitGoogleLogin(user, err2 = null) {
3666
3667
  });
3667
3668
  }
3668
3669
  function subscribeGoogleLogin(cb) {
3670
+ debugAuth("Listener subscribed", { count: googleListeners.length + 1 });
3669
3671
  googleListeners.push(cb);
3670
3672
  return () => {
3671
3673
  const i4 = googleListeners.indexOf(cb);
3672
3674
  if (i4 !== -1) googleListeners.splice(i4, 1);
3675
+ debugAuth("Listener unsubscribed", { count: googleListeners.length });
3673
3676
  };
3674
3677
  }
3675
- var capacitorPluginsPromise, tauriWebviewWindowPromise, getCapacitorPlugins, getTauriWebviewWindow, googleInitialized, googleListeners, authWindowRef, authCleanupTimer, authMessageListener, closeAllTauriWebviews, cleanupAuthWindow, handleCallback, initializeGoogleLogin, createGoogleLogin;
3678
+ var capacitorPluginsPromise, tauriWebviewWindowPromise, getCapacitorPlugins, debugAuth, debugAuthWarn, debugAuthError, getTauriWebviewWindow, googleInitialized, googleListeners, authWindowRef, authCleanupTimer, authMessageListener, closeAllTauriWebviews, cleanupAuthWindow, handleCallback, initializeGoogleLogin, createGoogleLogin;
3676
3679
  var init_useGoogleAuth = __esm({
3677
3680
  "src/services/useGoogleAuth.js"() {
3678
3681
  init_usePlatform();
@@ -3681,6 +3684,9 @@ var init_useGoogleAuth = __esm({
3681
3684
  capacitorPluginsPromise ??= Promise.all([Promise.resolve().then(() => (init_esm(), esm_exports)), Promise.resolve().then(() => (init_esm2(), esm_exports2))]).then(([appModule, browserModule]) => ({ App: appModule.App, Browser: browserModule.Browser }));
3682
3685
  return capacitorPluginsPromise;
3683
3686
  };
3687
+ debugAuth = (...args) => debugLog("[tevrocsdk][google-auth]", ...args);
3688
+ debugAuthWarn = (...args) => debugWarn("[tevrocsdk][google-auth]", ...args);
3689
+ debugAuthError = (...args) => debugError("[tevrocsdk][google-auth]", ...args);
3684
3690
  getTauriWebviewWindow = async () => {
3685
3691
  tauriWebviewWindowPromise ??= Promise.resolve().then(() => (init_webviewWindow(), webviewWindow_exports)).then((module) => module.WebviewWindow);
3686
3692
  return tauriWebviewWindowPromise;
@@ -3719,6 +3725,7 @@ var init_useGoogleAuth = __esm({
3719
3725
  }
3720
3726
  };
3721
3727
  cleanupAuthWindow = async () => {
3728
+ debugAuth("Cleaning up auth window", { hasWindow: Boolean(authWindowRef), isTauri, isCapacitor });
3722
3729
  if (authCleanupTimer) {
3723
3730
  clearInterval(authCleanupTimer);
3724
3731
  authCleanupTimer = null;
@@ -3762,11 +3769,15 @@ var init_useGoogleAuth = __esm({
3762
3769
  };
3763
3770
  handleCallback = async (url) => {
3764
3771
  try {
3772
+ debugAuth("Callback received", { hasUrl: Boolean(url), hasToken: Boolean(url?.includes("token=")) });
3765
3773
  await cleanupAuthWindow();
3766
- if (!url?.includes("token=")) return;
3774
+ if (!url?.includes("token=")) {
3775
+ debugAuthWarn("Callback did not include a token");
3776
+ return;
3777
+ }
3767
3778
  const params = new URLSearchParams(url.split("?")[1]);
3768
3779
  const token = params.get("token");
3769
- debugLog("Google login token:", token);
3780
+ debugAuth("Verifying provider token", { tokenPresent: Boolean(token) });
3770
3781
  const res = await fetch(
3771
3782
  "https://www.googleapis.com/oauth2/v3/userinfo",
3772
3783
  {
@@ -3776,6 +3787,7 @@ var init_useGoogleAuth = __esm({
3776
3787
  }
3777
3788
  );
3778
3789
  const googleUser = await res.json();
3790
+ debugAuth("Provider profile received", { idPresent: Boolean(googleUser.sub), emailPresent: Boolean(googleUser.email) });
3779
3791
  const profile = {
3780
3792
  id: googleUser.sub,
3781
3793
  firstName: googleUser.given_name,
@@ -3789,19 +3801,26 @@ var init_useGoogleAuth = __esm({
3789
3801
  localStorage.setItem("idToken", token);
3790
3802
  emitGoogleLogin(profile, null);
3791
3803
  } catch (err2) {
3804
+ debugAuthError("Callback failed", err2);
3792
3805
  emitGoogleLogin(null, err2);
3793
3806
  }
3794
3807
  };
3795
3808
  initializeGoogleLogin = async () => {
3796
- if (googleInitialized) return;
3809
+ if (googleInitialized) {
3810
+ debugAuth("Already initialized");
3811
+ return;
3812
+ }
3797
3813
  googleInitialized = true;
3814
+ debugAuth("Initializing listeners", { isCapacitor, isTauri });
3798
3815
  if (isCapacitor) {
3816
+ debugAuth("Registering Capacitor appUrlOpen listener");
3799
3817
  const { App: App2 } = await getCapacitorPlugins();
3800
3818
  App2.addListener("appUrlOpen", (event) => {
3801
3819
  handleCallback(event.url);
3802
3820
  });
3803
3821
  }
3804
3822
  if (isTauri) {
3823
+ debugAuth("Registering Tauri deep-link listener");
3805
3824
  const { listen: listen2 } = await Promise.resolve().then(() => (init_event(), event_exports));
3806
3825
  await listen2("deep-link://open-url", async (event) => {
3807
3826
  let url = event.payload;
@@ -3818,16 +3837,17 @@ var init_useGoogleAuth = __esm({
3818
3837
  appName = "Tevroc",
3819
3838
  serviceUrl = "https://tevrocsoftapi.netlify.app"
3820
3839
  } = {}) => {
3821
- debugLog("appId:", appId, "serviceUrl:", serviceUrl);
3822
- debugLog(isCapacitor, isTauri);
3840
+ debugAuth("Creating login", { appId, appName, serviceUrl, isCapacitor, isTauri });
3823
3841
  await initializeGoogleLogin();
3824
3842
  let authUrl = `${serviceUrl}/auth/google/login?mode=mobile&app=${encodeURIComponent(appId)}&name=${encodeURIComponent(appName)}`;
3825
3843
  if (isCapacitor) {
3844
+ debugAuth("Opening mobile auth browser");
3826
3845
  const { Browser: Browser3 } = await getCapacitorPlugins();
3827
3846
  await Browser3.open({ url: authUrl });
3828
3847
  return;
3829
3848
  }
3830
3849
  if (isTauri) {
3850
+ debugAuth("Opening desktop auth window");
3831
3851
  const WebviewWindow2 = await getTauriWebviewWindow();
3832
3852
  await closeAllTauriWebviews();
3833
3853
  const url = `${serviceUrl}/auth/google/login?mode=desktop&app=${encodeURIComponent(appId)}&name=${encodeURIComponent(appName)}`;
@@ -3841,10 +3861,10 @@ var init_useGoogleAuth = __esm({
3841
3861
  });
3842
3862
  authWindowRef = win;
3843
3863
  win.once("tauri://created", () => {
3844
- debugLog("Auth window opened");
3864
+ debugAuth("Auth window opened");
3845
3865
  });
3846
3866
  win.once("tauri://error", (e2) => {
3847
- debugError("Auth window error:", e2);
3867
+ debugAuthError("Auth window error", e2);
3848
3868
  });
3849
3869
  return;
3850
3870
  }
@@ -3855,19 +3875,21 @@ var init_useGoogleAuth = __esm({
3855
3875
  detectedAppId
3856
3876
  )}&name=${encodeURIComponent(appName)}`;
3857
3877
  if (isLocalhost) {
3878
+ debugAuth("Opening web auth popup", { mode, appId: detectedAppId });
3858
3879
  const popup = window.open(
3859
3880
  finalUrl,
3860
3881
  "googleLogin",
3861
3882
  "width=500,height=650"
3862
3883
  );
3863
3884
  if (!popup) {
3864
- debugError("Popup blocked");
3885
+ debugAuthError("Popup blocked");
3865
3886
  }
3866
3887
  authWindowRef = popup;
3867
3888
  authMessageListener = async (event) => {
3868
3889
  const serviceOrigin = new URL(serviceUrl).origin;
3869
3890
  if (event.origin !== serviceOrigin) return;
3870
3891
  if (event.data?.type === "google-auth") {
3892
+ debugAuth("Received popup auth message", { origin: event.origin });
3871
3893
  const token = event.data?.token || null;
3872
3894
  const url = token ? `${window.location.href}${window.location.href.includes("?") ? "&" : "?"}token=${token}` : window.location.href;
3873
3895
  await handleCallback(url);
@@ -3886,6 +3908,521 @@ var init_useGoogleAuth = __esm({
3886
3908
  }
3887
3909
  });
3888
3910
 
3911
+ // src/services/useFacebookAuth.js
3912
+ var useFacebookAuth_exports = {};
3913
+ __export(useFacebookAuth_exports, {
3914
+ createFacebookLogin: () => createFacebookLogin,
3915
+ initializeFacebookLogin: () => initializeFacebookLogin,
3916
+ subscribeFacebookLogin: () => subscribeFacebookLogin
3917
+ });
3918
+ function emitFacebookLogin(user, err2 = null) {
3919
+ debugAuth2("Emitting login result", { success: Boolean(user), error: err2?.message || null });
3920
+ facebookListeners.forEach((cb) => {
3921
+ try {
3922
+ cb(user, err2);
3923
+ } catch (e2) {
3924
+ debugError("Facebook listener error:", e2);
3925
+ }
3926
+ });
3927
+ }
3928
+ function subscribeFacebookLogin(cb) {
3929
+ debugAuth2("Listener subscribed", { count: facebookListeners.length + 1 });
3930
+ facebookListeners.push(cb);
3931
+ return () => {
3932
+ const i4 = facebookListeners.indexOf(cb);
3933
+ if (i4 !== -1) facebookListeners.splice(i4, 1);
3934
+ debugAuth2("Listener unsubscribed", { count: facebookListeners.length });
3935
+ };
3936
+ }
3937
+ var capacitorPluginsPromise2, tauriWebviewWindowPromise2, getCapacitorPlugins2, debugAuth2, debugAuthWarn2, debugAuthError2, getTauriWebviewWindow2, facebookInitialized, facebookListeners, authWindowRef2, authCleanupTimer2, authMessageListener2, closeAllTauriWebviews2, cleanupAuthWindow2, handleCallback2, initializeFacebookLogin, createFacebookLogin;
3938
+ var init_useFacebookAuth = __esm({
3939
+ "src/services/useFacebookAuth.js"() {
3940
+ init_usePlatform();
3941
+ init_debug();
3942
+ getCapacitorPlugins2 = () => {
3943
+ capacitorPluginsPromise2 ??= Promise.all([Promise.resolve().then(() => (init_esm(), esm_exports)), Promise.resolve().then(() => (init_esm2(), esm_exports2))]).then(([appModule, browserModule]) => ({ App: appModule.App, Browser: browserModule.Browser }));
3944
+ return capacitorPluginsPromise2;
3945
+ };
3946
+ debugAuth2 = (...args) => debugLog("[tevrocsdk][facebook-auth]", ...args);
3947
+ debugAuthWarn2 = (...args) => debugWarn("[tevrocsdk][facebook-auth]", ...args);
3948
+ debugAuthError2 = (...args) => debugError("[tevrocsdk][facebook-auth]", ...args);
3949
+ getTauriWebviewWindow2 = async () => {
3950
+ tauriWebviewWindowPromise2 ??= Promise.resolve().then(() => (init_webviewWindow(), webviewWindow_exports)).then((module) => module.WebviewWindow);
3951
+ return tauriWebviewWindowPromise2;
3952
+ };
3953
+ facebookInitialized = false;
3954
+ facebookListeners = [];
3955
+ authWindowRef2 = null;
3956
+ authCleanupTimer2 = null;
3957
+ authMessageListener2 = null;
3958
+ closeAllTauriWebviews2 = async () => {
3959
+ if (!isTauri) return;
3960
+ const WebviewWindow2 = await getTauriWebviewWindow2();
3961
+ try {
3962
+ if (typeof WebviewWindow2.getAll === "function") {
3963
+ const windows = await WebviewWindow2.getAll();
3964
+ for (const webview of windows || []) {
3965
+ try {
3966
+ if (webview?.label && webview.label !== "main") {
3967
+ await webview.close();
3968
+ }
3969
+ } catch (e2) {
3970
+ debugWarn("Error closing Tauri webview:", e2);
3971
+ }
3972
+ }
3973
+ }
3974
+ } catch (e2) {
3975
+ debugWarn("Error listing Tauri webviews:", e2);
3976
+ }
3977
+ try {
3978
+ const tauriAuthWindow = await WebviewWindow2.getByLabel("auth");
3979
+ if (tauriAuthWindow) {
3980
+ await tauriAuthWindow.close();
3981
+ }
3982
+ } catch (e2) {
3983
+ debugWarn("Error closing Tauri auth window by label:", e2);
3984
+ }
3985
+ };
3986
+ cleanupAuthWindow2 = async () => {
3987
+ debugAuth2("Cleaning up auth window", { hasWindow: Boolean(authWindowRef2), isTauri, isCapacitor });
3988
+ if (authCleanupTimer2) {
3989
+ clearInterval(authCleanupTimer2);
3990
+ authCleanupTimer2 = null;
3991
+ }
3992
+ if (authMessageListener2 && typeof window !== "undefined") {
3993
+ window.removeEventListener("message", authMessageListener2);
3994
+ authMessageListener2 = null;
3995
+ }
3996
+ if (authWindowRef2) {
3997
+ const currentAuthWindow = authWindowRef2;
3998
+ authWindowRef2 = null;
3999
+ try {
4000
+ if (typeof currentAuthWindow?.close === "function") {
4001
+ await currentAuthWindow.close();
4002
+ }
4003
+ } catch (e2) {
4004
+ debugWarn("Error closing auth window:", e2);
4005
+ }
4006
+ }
4007
+ if (isTauri) {
4008
+ const WebviewWindow2 = await getTauriWebviewWindow2();
4009
+ await closeAllTauriWebviews2();
4010
+ }
4011
+ if (isCapacitor) {
4012
+ try {
4013
+ const { Browser: Browser3 } = await getCapacitorPlugins2();
4014
+ await Browser3.close();
4015
+ } catch (e2) {
4016
+ debugWarn("Error closing Capacitor browser:", e2);
4017
+ }
4018
+ }
4019
+ if (typeof window !== "undefined" && window !== window.parent) {
4020
+ try {
4021
+ if (authWindowRef2 && typeof authWindowRef2.close === "function") {
4022
+ await authWindowRef2.close();
4023
+ }
4024
+ } catch (e2) {
4025
+ debugWarn("Error closing popup fallback:", e2);
4026
+ }
4027
+ }
4028
+ };
4029
+ handleCallback2 = async (url) => {
4030
+ try {
4031
+ debugAuth2("Callback received", { hasUrl: Boolean(url), hasToken: Boolean(url?.includes("token=")) });
4032
+ await cleanupAuthWindow2();
4033
+ if (!url?.includes("token=")) {
4034
+ debugAuthWarn2("Callback did not include a token");
4035
+ return;
4036
+ }
4037
+ const params = new URLSearchParams(url.split("?")[1]);
4038
+ const token = params.get("token");
4039
+ debugAuth2("Verifying provider token", { tokenPresent: Boolean(token) });
4040
+ const res = await fetch(
4041
+ `https://graph.facebook.com/me?fields=id,first_name,last_name,email,picture&access_token=${encodeURIComponent(token)}`
4042
+ );
4043
+ if (!res.ok) {
4044
+ throw new Error(`Facebook profile request failed: ${res.status}`);
4045
+ }
4046
+ const facebookUser = await res.json();
4047
+ debugAuth2("Provider profile received", { idPresent: Boolean(facebookUser.id), emailPresent: Boolean(facebookUser.email) });
4048
+ const profile = {
4049
+ id: facebookUser.id,
4050
+ firstName: facebookUser.first_name,
4051
+ lastName: facebookUser.last_name,
4052
+ email: facebookUser.email,
4053
+ photo: facebookUser.picture?.data?.url,
4054
+ accessToken: token
4055
+ };
4056
+ debugLog("Facebook user profile:", profile);
4057
+ localStorage.setItem("user", JSON.stringify(profile));
4058
+ localStorage.setItem("idToken", token);
4059
+ emitFacebookLogin(profile, null);
4060
+ } catch (err2) {
4061
+ debugAuthError2("Callback failed", err2);
4062
+ emitFacebookLogin(null, err2);
4063
+ }
4064
+ };
4065
+ initializeFacebookLogin = async () => {
4066
+ if (facebookInitialized) {
4067
+ debugAuth2("Already initialized");
4068
+ return;
4069
+ }
4070
+ facebookInitialized = true;
4071
+ debugAuth2("Initializing listeners", { isCapacitor, isTauri });
4072
+ if (isCapacitor) {
4073
+ debugAuth2("Registering Capacitor appUrlOpen listener");
4074
+ const { App: App2 } = await getCapacitorPlugins2();
4075
+ App2.addListener("appUrlOpen", (event) => {
4076
+ handleCallback2(event.url);
4077
+ });
4078
+ }
4079
+ if (isTauri) {
4080
+ debugAuth2("Registering Tauri deep-link listener");
4081
+ const { listen: listen2 } = await Promise.resolve().then(() => (init_event(), event_exports));
4082
+ await listen2("deep-link://open-url", async (event) => {
4083
+ let url = event.payload;
4084
+ if (typeof url === "object") {
4085
+ url = url?.url || url?.payload || null;
4086
+ }
4087
+ if (!url) return;
4088
+ await handleCallback2(url);
4089
+ });
4090
+ }
4091
+ };
4092
+ createFacebookLogin = async ({
4093
+ appId = "tevrocsoft",
4094
+ appName = "Tevroc",
4095
+ serviceUrl = "https://tevrocsoftapi.netlify.app"
4096
+ } = {}) => {
4097
+ debugAuth2("Creating login", { appId, appName, serviceUrl, isCapacitor, isTauri });
4098
+ await initializeFacebookLogin();
4099
+ let authUrl = `${serviceUrl}/auth/facebook/login?mode=mobile&app=${encodeURIComponent(appId)}&name=${encodeURIComponent(appName)}`;
4100
+ if (isCapacitor) {
4101
+ debugAuth2("Opening mobile auth browser");
4102
+ const { Browser: Browser3 } = await getCapacitorPlugins2();
4103
+ await Browser3.open({ url: authUrl });
4104
+ return;
4105
+ }
4106
+ if (isTauri) {
4107
+ debugAuth2("Opening desktop auth window");
4108
+ const WebviewWindow2 = await getTauriWebviewWindow2();
4109
+ await closeAllTauriWebviews2();
4110
+ const url = `${serviceUrl}/auth/facebook/login?mode=desktop&app=${encodeURIComponent(appId)}&name=${encodeURIComponent(appName)}`;
4111
+ const win = new WebviewWindow2("auth", {
4112
+ url,
4113
+ title: `${appName} Login`,
4114
+ width: 550,
4115
+ height: 500,
4116
+ resizable: true,
4117
+ center: true
4118
+ });
4119
+ authWindowRef2 = win;
4120
+ win.once("tauri://created", () => {
4121
+ debugAuth2("Auth window opened");
4122
+ });
4123
+ win.once("tauri://error", (e2) => {
4124
+ debugAuthError2("Auth window error", e2);
4125
+ });
4126
+ return;
4127
+ }
4128
+ const isLocalhost = true;
4129
+ const detectedAppId = typeof window !== "undefined" ? window.location.host : appId;
4130
+ const mode = isLocalhost ? "localhost" : "netlify";
4131
+ const finalUrl = `${serviceUrl}/auth/facebook/login?mode=${mode}&app=${encodeURIComponent(
4132
+ detectedAppId
4133
+ )}&name=${encodeURIComponent(appName)}`;
4134
+ if (isLocalhost) {
4135
+ debugAuth2("Opening web auth popup", { mode, appId: detectedAppId });
4136
+ const popup = window.open(
4137
+ finalUrl,
4138
+ "facebookLogin",
4139
+ "width=500,height=650"
4140
+ );
4141
+ if (!popup) {
4142
+ debugAuthError2("Popup blocked");
4143
+ throw new Error("Facebook sign-in popup was blocked. Allow popups and try again.");
4144
+ }
4145
+ authWindowRef2 = popup;
4146
+ authMessageListener2 = async (event) => {
4147
+ const serviceOrigin = new URL(serviceUrl).origin;
4148
+ if (event.origin !== serviceOrigin) return;
4149
+ if (event.data?.type === "facebook-auth") {
4150
+ debugAuth2("Received popup auth message", { origin: event.origin });
4151
+ const token = event.data?.token || null;
4152
+ const url = token ? `${window.location.href}${window.location.href.includes("?") ? "&" : "?"}token=${token}` : window.location.href;
4153
+ await handleCallback2(url);
4154
+ }
4155
+ };
4156
+ window.addEventListener("message", authMessageListener2);
4157
+ authCleanupTimer2 = setInterval(() => {
4158
+ if (popup.closed) {
4159
+ cleanupAuthWindow2().catch(() => {
4160
+ });
4161
+ }
4162
+ }, 500);
4163
+ return;
4164
+ }
4165
+ };
4166
+ }
4167
+ });
4168
+
4169
+ // src/services/useMetaAuth.js
4170
+ var useMetaAuth_exports = {};
4171
+ __export(useMetaAuth_exports, {
4172
+ createMetaLogin: () => createMetaLogin,
4173
+ initializeMetaLogin: () => initializeMetaLogin,
4174
+ subscribeMetaLogin: () => subscribeMetaLogin
4175
+ });
4176
+ function emitMetaLogin(user, err2 = null) {
4177
+ debugAuth3("Emitting login result", { success: Boolean(user), error: err2?.message || null });
4178
+ metaListeners.forEach((cb) => {
4179
+ try {
4180
+ cb(user, err2);
4181
+ } catch (e2) {
4182
+ debugError("Meta listener error:", e2);
4183
+ }
4184
+ });
4185
+ }
4186
+ function subscribeMetaLogin(cb) {
4187
+ debugAuth3("Listener subscribed", { count: metaListeners.length + 1 });
4188
+ metaListeners.push(cb);
4189
+ return () => {
4190
+ const i4 = metaListeners.indexOf(cb);
4191
+ if (i4 !== -1) metaListeners.splice(i4, 1);
4192
+ debugAuth3("Listener unsubscribed", { count: metaListeners.length });
4193
+ };
4194
+ }
4195
+ var capacitorPluginsPromise3, tauriWebviewWindowPromise3, getCapacitorPlugins3, debugAuth3, debugAuthWarn3, debugAuthError3, getTauriWebviewWindow3, metaInitialized, metaListeners, authWindowRef3, authCleanupTimer3, authMessageListener3, closeAllTauriWebviews3, cleanupAuthWindow3, handleCallback3, initializeMetaLogin, createMetaLogin;
4196
+ var init_useMetaAuth = __esm({
4197
+ "src/services/useMetaAuth.js"() {
4198
+ init_usePlatform();
4199
+ init_debug();
4200
+ getCapacitorPlugins3 = () => {
4201
+ capacitorPluginsPromise3 ??= Promise.all([Promise.resolve().then(() => (init_esm(), esm_exports)), Promise.resolve().then(() => (init_esm2(), esm_exports2))]).then(([appModule, browserModule]) => ({ App: appModule.App, Browser: browserModule.Browser }));
4202
+ return capacitorPluginsPromise3;
4203
+ };
4204
+ debugAuth3 = (...args) => debugLog("[tevrocsdk][meta-auth]", ...args);
4205
+ debugAuthWarn3 = (...args) => debugWarn("[tevrocsdk][meta-auth]", ...args);
4206
+ debugAuthError3 = (...args) => debugError("[tevrocsdk][meta-auth]", ...args);
4207
+ getTauriWebviewWindow3 = async () => {
4208
+ tauriWebviewWindowPromise3 ??= Promise.resolve().then(() => (init_webviewWindow(), webviewWindow_exports)).then((module) => module.WebviewWindow);
4209
+ return tauriWebviewWindowPromise3;
4210
+ };
4211
+ metaInitialized = false;
4212
+ metaListeners = [];
4213
+ authWindowRef3 = null;
4214
+ authCleanupTimer3 = null;
4215
+ authMessageListener3 = null;
4216
+ closeAllTauriWebviews3 = async () => {
4217
+ if (!isTauri) return;
4218
+ const WebviewWindow2 = await getTauriWebviewWindow3();
4219
+ try {
4220
+ if (typeof WebviewWindow2.getAll === "function") {
4221
+ const windows = await WebviewWindow2.getAll();
4222
+ for (const webview of windows || []) {
4223
+ try {
4224
+ if (webview?.label && webview.label !== "main") {
4225
+ await webview.close();
4226
+ }
4227
+ } catch (e2) {
4228
+ debugWarn("Error closing Tauri webview:", e2);
4229
+ }
4230
+ }
4231
+ }
4232
+ } catch (e2) {
4233
+ debugWarn("Error listing Tauri webviews:", e2);
4234
+ }
4235
+ try {
4236
+ const tauriAuthWindow = await WebviewWindow2.getByLabel("auth");
4237
+ if (tauriAuthWindow) {
4238
+ await tauriAuthWindow.close();
4239
+ }
4240
+ } catch (e2) {
4241
+ debugWarn("Error closing Tauri auth window by label:", e2);
4242
+ }
4243
+ };
4244
+ cleanupAuthWindow3 = async () => {
4245
+ debugAuth3("Cleaning up auth window", { hasWindow: Boolean(authWindowRef3), isTauri, isCapacitor });
4246
+ if (authCleanupTimer3) {
4247
+ clearInterval(authCleanupTimer3);
4248
+ authCleanupTimer3 = null;
4249
+ }
4250
+ if (authMessageListener3 && typeof window !== "undefined") {
4251
+ window.removeEventListener("message", authMessageListener3);
4252
+ authMessageListener3 = null;
4253
+ }
4254
+ if (authWindowRef3) {
4255
+ const currentAuthWindow = authWindowRef3;
4256
+ authWindowRef3 = null;
4257
+ try {
4258
+ if (typeof currentAuthWindow?.close === "function") {
4259
+ await currentAuthWindow.close();
4260
+ }
4261
+ } catch (e2) {
4262
+ debugWarn("Error closing auth window:", e2);
4263
+ }
4264
+ }
4265
+ if (isTauri) {
4266
+ const WebviewWindow2 = await getTauriWebviewWindow3();
4267
+ await closeAllTauriWebviews3();
4268
+ }
4269
+ if (isCapacitor) {
4270
+ try {
4271
+ const { Browser: Browser3 } = await getCapacitorPlugins3();
4272
+ await Browser3.close();
4273
+ } catch (e2) {
4274
+ debugWarn("Error closing Capacitor browser:", e2);
4275
+ }
4276
+ }
4277
+ if (typeof window !== "undefined" && window !== window.parent) {
4278
+ try {
4279
+ if (authWindowRef3 && typeof authWindowRef3.close === "function") {
4280
+ await authWindowRef3.close();
4281
+ }
4282
+ } catch (e2) {
4283
+ debugWarn("Error closing popup fallback:", e2);
4284
+ }
4285
+ }
4286
+ };
4287
+ handleCallback3 = async (url) => {
4288
+ try {
4289
+ debugAuth3("Callback received", { hasUrl: Boolean(url), hasToken: Boolean(url?.includes("token=")) });
4290
+ await cleanupAuthWindow3();
4291
+ if (!url?.includes("token=")) {
4292
+ debugAuthWarn3("Callback did not include a token");
4293
+ return;
4294
+ }
4295
+ const params = new URLSearchParams(url.split("?")[1]);
4296
+ const token = params.get("token");
4297
+ debugAuth3("Verifying provider token", { tokenPresent: Boolean(token) });
4298
+ const res = await fetch(
4299
+ `https://graph.facebook.com/me?fields=id,name,first_name,last_name,email,picture&access_token=${encodeURIComponent(token)}`
4300
+ );
4301
+ if (!res.ok) throw new Error(`Meta profile request failed: ${res.status}`);
4302
+ const metaUser = await res.json();
4303
+ debugAuth3("Provider profile received", { idPresent: Boolean(metaUser.id), emailPresent: Boolean(metaUser.email) });
4304
+ const profile = {
4305
+ id: metaUser.id,
4306
+ name: metaUser.name,
4307
+ firstName: metaUser.first_name,
4308
+ lastName: metaUser.last_name,
4309
+ email: metaUser.email,
4310
+ photo: metaUser.picture?.data?.url,
4311
+ accessToken: token
4312
+ };
4313
+ debugLog("Meta user profile:", profile);
4314
+ localStorage.setItem("user", JSON.stringify(profile));
4315
+ localStorage.setItem("idToken", token);
4316
+ emitMetaLogin(profile, null);
4317
+ } catch (err2) {
4318
+ debugAuthError3("Callback failed", err2);
4319
+ emitMetaLogin(null, err2);
4320
+ }
4321
+ };
4322
+ initializeMetaLogin = async () => {
4323
+ if (metaInitialized) {
4324
+ debugAuth3("Already initialized");
4325
+ return;
4326
+ }
4327
+ metaInitialized = true;
4328
+ debugAuth3("Initializing listeners", { isCapacitor, isTauri });
4329
+ if (isCapacitor) {
4330
+ debugAuth3("Registering Capacitor appUrlOpen listener");
4331
+ const { App: App2 } = await getCapacitorPlugins3();
4332
+ App2.addListener("appUrlOpen", (event) => {
4333
+ handleCallback3(event.url);
4334
+ });
4335
+ }
4336
+ if (isTauri) {
4337
+ debugAuth3("Registering Tauri deep-link listener");
4338
+ const { listen: listen2 } = await Promise.resolve().then(() => (init_event(), event_exports));
4339
+ await listen2("deep-link://open-url", async (event) => {
4340
+ let url = event.payload;
4341
+ if (typeof url === "object") {
4342
+ url = url?.url || url?.payload || null;
4343
+ }
4344
+ if (!url) return;
4345
+ await handleCallback3(url);
4346
+ });
4347
+ }
4348
+ };
4349
+ createMetaLogin = async ({
4350
+ appId = "tevrocsoft",
4351
+ appName = "Tevroc",
4352
+ serviceUrl = "https://tevrocsoftapi.netlify.app"
4353
+ } = {}) => {
4354
+ debugAuth3("Creating login", { appId, appName, serviceUrl, isCapacitor, isTauri });
4355
+ await initializeMetaLogin();
4356
+ const authUrl = `${serviceUrl}/auth/meta/login?mode=mobile&app=${encodeURIComponent(appId)}&name=${encodeURIComponent(appName)}`;
4357
+ if (isCapacitor) {
4358
+ debugAuth3("Opening mobile auth browser");
4359
+ const { Browser: Browser3 } = await getCapacitorPlugins3();
4360
+ await Browser3.open({ url: authUrl });
4361
+ return;
4362
+ }
4363
+ if (isTauri) {
4364
+ debugAuth3("Opening desktop auth window");
4365
+ const WebviewWindow2 = await getTauriWebviewWindow3();
4366
+ await closeAllTauriWebviews3();
4367
+ const url = `${serviceUrl}/auth/meta/login?mode=desktop&app=${encodeURIComponent(appId)}&name=${encodeURIComponent(appName)}`;
4368
+ const win = new WebviewWindow2("auth", {
4369
+ url,
4370
+ title: `${appName} Login`,
4371
+ width: 550,
4372
+ height: 500,
4373
+ resizable: true,
4374
+ center: true
4375
+ });
4376
+ authWindowRef3 = win;
4377
+ win.once("tauri://created", () => {
4378
+ debugAuth3("Auth window opened");
4379
+ });
4380
+ win.once("tauri://error", (e2) => {
4381
+ debugAuthError3("Auth window error", e2);
4382
+ });
4383
+ return;
4384
+ }
4385
+ const isLocalhost = true;
4386
+ const detectedAppId = typeof window !== "undefined" ? window.location.host : appId;
4387
+ const mode = isLocalhost ? "localhost" : "netlify";
4388
+ const finalUrl = `${serviceUrl}/auth/meta/login?mode=${mode}&app=${encodeURIComponent(
4389
+ detectedAppId
4390
+ )}&name=${encodeURIComponent(appName)}`;
4391
+ if (isLocalhost) {
4392
+ debugAuth3("Opening web auth popup", { mode, appId: detectedAppId });
4393
+ const popup = window.open(
4394
+ finalUrl,
4395
+ "metaLogin",
4396
+ "width=500,height=650"
4397
+ );
4398
+ if (!popup) {
4399
+ debugAuthError3("Popup blocked");
4400
+ throw new Error("Meta sign-in popup was blocked. Allow popups and try again.");
4401
+ }
4402
+ authWindowRef3 = popup;
4403
+ authMessageListener3 = async (event) => {
4404
+ const serviceOrigin = new URL(serviceUrl).origin;
4405
+ if (event.origin !== serviceOrigin) return;
4406
+ if (event.data?.type === "meta-auth") {
4407
+ debugAuth3("Received popup auth message", { origin: event.origin });
4408
+ const token = event.data?.token || null;
4409
+ const url = token ? `${window.location.href}${window.location.href.includes("?") ? "&" : "?"}token=${token}` : window.location.href;
4410
+ await handleCallback3(url);
4411
+ }
4412
+ };
4413
+ window.addEventListener("message", authMessageListener3);
4414
+ authCleanupTimer3 = setInterval(() => {
4415
+ if (popup.closed) {
4416
+ cleanupAuthWindow3().catch(() => {
4417
+ });
4418
+ }
4419
+ }, 500);
4420
+ return;
4421
+ }
4422
+ };
4423
+ }
4424
+ });
4425
+
3889
4426
  // src/services/useYocoPayment.js
3890
4427
  function emitPaymentStatus(status, err2 = null) {
3891
4428
  paymentStatusListeners.forEach((cb) => {
@@ -3903,18 +4440,18 @@ function subscribePaymentStatus(cb) {
3903
4440
  if (i4 !== -1) paymentStatusListeners.splice(i4, 1);
3904
4441
  };
3905
4442
  }
3906
- var capacitorPluginsPromise2, tauriWebviewWindowPromise2, getCapacitorPlugins2, getTauriWebviewWindow2, paymentInitialized, paymentStatusListeners, paymentWindowRef, logs, addLog, handlePaymentCallback, initializePayment, createPayment;
4443
+ var capacitorPluginsPromise4, tauriWebviewWindowPromise4, getCapacitorPlugins4, getTauriWebviewWindow4, paymentInitialized, paymentStatusListeners, paymentWindowRef, logs, addLog, handlePaymentCallback, initializePayment, createPayment;
3907
4444
  var init_useYocoPayment = __esm({
3908
4445
  "src/services/useYocoPayment.js"() {
3909
4446
  init_usePlatform();
3910
4447
  init_debug();
3911
- getCapacitorPlugins2 = () => {
3912
- capacitorPluginsPromise2 ??= Promise.all([Promise.resolve().then(() => (init_esm(), esm_exports)), Promise.resolve().then(() => (init_esm2(), esm_exports2))]).then(([appModule, browserModule]) => ({ App: appModule.App, Browser: browserModule.Browser }));
3913
- return capacitorPluginsPromise2;
4448
+ getCapacitorPlugins4 = () => {
4449
+ capacitorPluginsPromise4 ??= Promise.all([Promise.resolve().then(() => (init_esm(), esm_exports)), Promise.resolve().then(() => (init_esm2(), esm_exports2))]).then(([appModule, browserModule]) => ({ App: appModule.App, Browser: browserModule.Browser }));
4450
+ return capacitorPluginsPromise4;
3914
4451
  };
3915
- getTauriWebviewWindow2 = async () => {
3916
- tauriWebviewWindowPromise2 ??= Promise.resolve().then(() => (init_webviewWindow(), webviewWindow_exports)).then((module) => module.WebviewWindow);
3917
- return tauriWebviewWindowPromise2;
4452
+ getTauriWebviewWindow4 = async () => {
4453
+ tauriWebviewWindowPromise4 ??= Promise.resolve().then(() => (init_webviewWindow(), webviewWindow_exports)).then((module) => module.WebviewWindow);
4454
+ return tauriWebviewWindowPromise4;
3918
4455
  };
3919
4456
  paymentInitialized = false;
3920
4457
  paymentStatusListeners = [];
@@ -3956,7 +4493,7 @@ var init_useYocoPayment = __esm({
3956
4493
  if (paymentInitialized) return;
3957
4494
  paymentInitialized = true;
3958
4495
  if (isCapacitor) {
3959
- const { App: App2 } = await getCapacitorPlugins2();
4496
+ const { App: App2 } = await getCapacitorPlugins4();
3960
4497
  App2.addListener("appUrlOpen", (event) => {
3961
4498
  handlePaymentCallback(
3962
4499
  event.url,
@@ -3999,14 +4536,14 @@ var init_useYocoPayment = __esm({
3999
4536
  const paymentUrl = `${basePaymentUrl}?mode=mobile&amount=${cents}&app=${appId}&account=${payAccount}`;
4000
4537
  debugLog(basePaymentUrl, paymentUrl);
4001
4538
  if (isCapacitor) {
4002
- const { Browser: Browser3 } = await getCapacitorPlugins2();
4539
+ const { Browser: Browser3 } = await getCapacitorPlugins4();
4003
4540
  await Browser3.open({
4004
4541
  url: paymentUrl
4005
4542
  });
4006
4543
  return;
4007
4544
  }
4008
4545
  if (isTauri) {
4009
- const WebviewWindow2 = await getTauriWebviewWindow2();
4546
+ const WebviewWindow2 = await getTauriWebviewWindow4();
4010
4547
  const url = `${basePaymentUrl}?mode=desktop&amount=${cents}&app=${appId}&account=${payAccount}`;
4011
4548
  const win = new WebviewWindow2("payment", {
4012
4549
  url,
@@ -8174,13 +8711,13 @@ var require_html2canvas = __commonJS({
8174
8711
  var textList = toCodePoints$1(node2.data).map(function(i5) {
8175
8712
  return fromCodePoint$1(i5);
8176
8713
  });
8177
- var offset = 0;
8714
+ var offset2 = 0;
8178
8715
  var prev = {};
8179
8716
  var supports = textList.every(function(text2, i5) {
8180
- range.setStart(node2, offset);
8181
- range.setEnd(node2, offset + text2.length);
8717
+ range.setStart(node2, offset2);
8718
+ range.setEnd(node2, offset2 + text2.length);
8182
8719
  var rect = range.getBoundingClientRect();
8183
- offset += text2.length;
8720
+ offset2 += text2.length;
8184
8721
  var boundAhead = rect.x > prev.x || rect.y > prev.y;
8185
8722
  prev = rect;
8186
8723
  if (i5 === 0) {
@@ -8329,16 +8866,16 @@ var require_html2canvas = __commonJS({
8329
8866
  var parseTextBounds = function(context, value, styles, node2) {
8330
8867
  var textList = breakText(value, styles);
8331
8868
  var textBounds = [];
8332
- var offset = 0;
8869
+ var offset2 = 0;
8333
8870
  textList.forEach(function(text2) {
8334
8871
  if (styles.textDecorationLine.length || text2.trim().length > 0) {
8335
8872
  if (FEATURES.SUPPORT_RANGE_BOUNDS) {
8336
- var clientRects = createRange(node2, offset, text2.length).getClientRects();
8873
+ var clientRects = createRange(node2, offset2, text2.length).getClientRects();
8337
8874
  if (clientRects.length > 1) {
8338
8875
  var subSegments = segmentGraphemes(text2);
8339
8876
  var subOffset_1 = 0;
8340
8877
  subSegments.forEach(function(subSegment) {
8341
- textBounds.push(new TextBounds(subSegment, Bounds.fromDOMRectList(context, createRange(node2, subOffset_1 + offset, subSegment.length).getClientRects())));
8878
+ textBounds.push(new TextBounds(subSegment, Bounds.fromDOMRectList(context, createRange(node2, subOffset_1 + offset2, subSegment.length).getClientRects())));
8342
8879
  subOffset_1 += subSegment.length;
8343
8880
  });
8344
8881
  } else {
@@ -8352,7 +8889,7 @@ var require_html2canvas = __commonJS({
8352
8889
  } else if (!FEATURES.SUPPORT_RANGE_BOUNDS) {
8353
8890
  node2 = node2.splitText(text2.length);
8354
8891
  }
8355
- offset += text2.length;
8892
+ offset2 += text2.length;
8356
8893
  });
8357
8894
  return textBounds;
8358
8895
  };
@@ -8373,14 +8910,14 @@ var require_html2canvas = __commonJS({
8373
8910
  }
8374
8911
  return Bounds.EMPTY;
8375
8912
  };
8376
- var createRange = function(node2, offset, length) {
8913
+ var createRange = function(node2, offset2, length) {
8377
8914
  var ownerDocument = node2.ownerDocument;
8378
8915
  if (!ownerDocument) {
8379
8916
  throw new Error("Node has no owner document");
8380
8917
  }
8381
8918
  var range = ownerDocument.createRange();
8382
- range.setStart(node2, offset);
8383
- range.setEnd(node2, offset + length);
8919
+ range.setStart(node2, offset2);
8920
+ range.setEnd(node2, offset2 + length);
8384
8921
  return range;
8385
8922
  };
8386
8923
  var segmentGraphemes = function(value) {
@@ -20691,13 +21228,13 @@ var init_index_es = __esm({
20691
21228
  } else if (typeof ctx.mozDash !== "undefined" && !(gaps.length === 1 && gaps[0] === 0)) {
20692
21229
  ctx.mozDash = gaps;
20693
21230
  }
20694
- var offset = strokeDashoffsetProp.getPixels();
21231
+ var offset2 = strokeDashoffsetProp.getPixels();
20695
21232
  if (typeof ctx.lineDashOffset !== "undefined") {
20696
- ctx.lineDashOffset = offset;
21233
+ ctx.lineDashOffset = offset2;
20697
21234
  } else if (typeof ctx.webkitLineDashOffset !== "undefined") {
20698
- ctx.webkitLineDashOffset = offset;
21235
+ ctx.webkitLineDashOffset = offset2;
20699
21236
  } else if (typeof ctx.mozDashOffset !== "undefined") {
20700
- ctx.mozDashOffset = offset;
21237
+ ctx.mozDashOffset = offset2;
20701
21238
  }
20702
21239
  }
20703
21240
  }
@@ -22134,7 +22671,7 @@ var init_index_es = __esm({
22134
22671
  constructor(document2, node2, captureTextNodes) {
22135
22672
  super(document2, node2, captureTextNodes);
22136
22673
  this.type = "stop";
22137
- var offset = Math.max(0, Math.min(1, this.getAttribute("offset").getNumber()));
22674
+ var offset2 = Math.max(0, Math.min(1, this.getAttribute("offset").getNumber()));
22138
22675
  var stopOpacity = this.getStyle("stop-opacity");
22139
22676
  var stopColor = this.getStyle("stop-color", true);
22140
22677
  if (stopColor.getString() === "") {
@@ -22143,7 +22680,7 @@ var init_index_es = __esm({
22143
22680
  if (stopOpacity.hasValue()) {
22144
22681
  stopColor = stopColor.addOpacity(stopOpacity);
22145
22682
  }
22146
- this.offset = offset;
22683
+ this.offset = offset2;
22147
22684
  this.color = stopColor.getColor();
22148
22685
  }
22149
22686
  };
@@ -22542,17 +23079,17 @@ var init_index_es = __esm({
22542
23079
  return this.letterSpacingCache[idx] || 0;
22543
23080
  }
22544
23081
  findSegmentToFitChar(ctx, anchor, textFullWidth, fullPathWidth, spacesNumber, inputOffset, dy, c4, charI) {
22545
- var offset = inputOffset;
23082
+ var offset2 = inputOffset;
22546
23083
  var glyphWidth = this.measureText(ctx, c4);
22547
23084
  if (c4 === " " && anchor === "justify" && textFullWidth < fullPathWidth) {
22548
23085
  glyphWidth += (fullPathWidth - textFullWidth) / spacesNumber;
22549
23086
  }
22550
23087
  if (charI > -1) {
22551
- offset += this.getLetterSpacingAt(charI);
23088
+ offset2 += this.getLetterSpacingAt(charI);
22552
23089
  }
22553
23090
  var splineStep = this.textHeight / 20;
22554
- var p0 = this.getEquidistantPointOnPath(offset, splineStep, 0);
22555
- var p1 = this.getEquidistantPointOnPath(offset + glyphWidth, splineStep, 0);
23091
+ var p0 = this.getEquidistantPointOnPath(offset2, splineStep, 0);
23092
+ var p1 = this.getEquidistantPointOnPath(offset2 + glyphWidth, splineStep, 0);
22556
23093
  var segment = {
22557
23094
  p0,
22558
23095
  p1
@@ -22570,9 +23107,9 @@ var init_index_es = __esm({
22570
23107
  y: p1.y + dyY
22571
23108
  });
22572
23109
  }
22573
- offset += glyphWidth;
23110
+ offset2 += glyphWidth;
22574
23111
  return {
22575
- offset,
23112
+ offset: offset2,
22576
23113
  segment,
22577
23114
  rotation
22578
23115
  };
@@ -22626,21 +23163,21 @@ var init_index_es = __esm({
22626
23163
  this.glyphInfo = [];
22627
23164
  var fullPathWidth = this.getPathLength();
22628
23165
  var startOffset = this.getStyle("startOffset").getNumber(0) * fullPathWidth;
22629
- var offset = 0;
23166
+ var offset2 = 0;
22630
23167
  if (anchor === "middle" || anchor === "center") {
22631
- offset = -textFullWidth / 2;
23168
+ offset2 = -textFullWidth / 2;
22632
23169
  }
22633
23170
  if (anchor === "end" || anchor === "right") {
22634
- offset = -textFullWidth;
23171
+ offset2 = -textFullWidth;
22635
23172
  }
22636
- offset += startOffset;
23173
+ offset2 += startOffset;
22637
23174
  chars.forEach((char, i5) => {
22638
23175
  var {
22639
23176
  offset: nextOffset,
22640
23177
  segment,
22641
23178
  rotation
22642
- } = this.findSegmentToFitChar(ctx, anchor, textFullWidth, fullPathWidth, spacesNumber, offset, dy, char, i5);
22643
- offset = nextOffset;
23179
+ } = this.findSegmentToFitChar(ctx, anchor, textFullWidth, fullPathWidth, spacesNumber, offset2, dy, char, i5);
23180
+ offset2 = nextOffset;
22644
23181
  if (!segment.p0 || !segment.p1) {
22645
23182
  return;
22646
23183
  }
@@ -25268,10 +25805,10 @@ var init_dist_js2 = __esm({
25268
25805
  *
25269
25806
  * @since 2.0.0
25270
25807
  */
25271
- async seek(offset, whence) {
25808
+ async seek(offset2, whence) {
25272
25809
  return await invoke("plugin:fs|seek", {
25273
25810
  rid: this.rid,
25274
- offset,
25811
+ offset: offset2,
25275
25812
  whence
25276
25813
  });
25277
25814
  }
@@ -26939,6 +27476,8 @@ var init_esm6 = __esm({
26939
27476
 
26940
27477
  // src/index.js
26941
27478
  init_useGoogleAuth();
27479
+ init_useFacebookAuth();
27480
+ init_useMetaAuth();
26942
27481
  init_useYocoPayment();
26943
27482
  init_debug();
26944
27483
 
@@ -27610,12 +28149,12 @@ var IOBuffer = class _IOBuffer {
27610
28149
  dataIsGiven = true;
27611
28150
  this.lastWrittenByte = data.byteLength;
27612
28151
  }
27613
- const offset = options.offset ? options.offset >>> 0 : 0;
27614
- const byteLength = data.byteLength - offset;
27615
- let dvOffset = offset;
28152
+ const offset2 = options.offset ? options.offset >>> 0 : 0;
28153
+ const byteLength = data.byteLength - offset2;
28154
+ let dvOffset = offset2;
27616
28155
  if (ArrayBuffer.isView(data) || data instanceof _IOBuffer) {
27617
28156
  if (data.byteLength !== data.buffer.byteLength) {
27618
- dvOffset = data.byteOffset + offset;
28157
+ dvOffset = data.byteOffset + offset2;
27619
28158
  }
27620
28159
  data = data.buffer;
27621
28160
  }
@@ -27697,8 +28236,8 @@ var IOBuffer = class _IOBuffer {
27697
28236
  * @param offset - The offset to move to.
27698
28237
  * @returns This.
27699
28238
  */
27700
- seek(offset) {
27701
- this.offset = offset;
28239
+ seek(offset2) {
28240
+ this.offset = offset2;
27702
28241
  return this;
27703
28242
  }
27704
28243
  /**
@@ -27735,11 +28274,11 @@ var IOBuffer = class _IOBuffer {
27735
28274
  * @returns This.
27736
28275
  */
27737
28276
  popMark() {
27738
- const offset = this._marks.pop();
27739
- if (offset === void 0) {
28277
+ const offset2 = this._marks.pop();
28278
+ if (offset2 === void 0) {
27740
28279
  throw new Error("Mark stack empty");
27741
28280
  }
27742
- this.seek(offset);
28281
+ this.seek(offset2);
27743
28282
  return this;
27744
28283
  }
27745
28284
  /**
@@ -27817,10 +28356,10 @@ var IOBuffer = class _IOBuffer {
27817
28356
  */
27818
28357
  readArray(size2, type) {
27819
28358
  const bytes = typedArrays[type].BYTES_PER_ELEMENT * size2;
27820
- const offset = this.byteOffset + this.offset;
27821
- const slice = this.buffer.slice(offset, offset + bytes);
28359
+ const offset2 = this.byteOffset + this.offset;
28360
+ const slice = this.buffer.slice(offset2, offset2 + bytes);
27822
28361
  if (this.littleEndian === hostBigEndian && type !== "uint8" && type !== "int8") {
27823
- const slice2 = new Uint8Array(this.buffer.slice(offset, offset + bytes));
28362
+ const slice2 = new Uint8Array(this.buffer.slice(offset2, offset2 + bytes));
27824
28363
  slice2.reverse();
27825
28364
  const returnArray2 = new typedArrays[type](slice2.buffer);
27826
28365
  this.offset += bytes;
@@ -32524,7 +33063,7 @@ function decodeInterlaceAdam7(params) {
32524
33063
  ];
32525
33064
  const bytesPerPixel = Math.ceil(depth / 8) * channels;
32526
33065
  const resultData = new Uint8Array(height * width * bytesPerPixel);
32527
- let offset = 0;
33066
+ let offset2 = 0;
32528
33067
  for (let passIndex = 0; passIndex < 7; passIndex++) {
32529
33068
  const pass = passes[passIndex];
32530
33069
  const passWidth = Math.ceil((width - pass.x) / pass.xStep);
@@ -32534,9 +33073,9 @@ function decodeInterlaceAdam7(params) {
32534
33073
  const passLineBytes = passWidth * bytesPerPixel;
32535
33074
  const prevLine = new Uint8Array(passLineBytes);
32536
33075
  for (let y3 = 0; y3 < passHeight; y3++) {
32537
- const filterType = data[offset++];
32538
- const currentLine = data.subarray(offset, offset + passLineBytes);
32539
- offset += passLineBytes;
33076
+ const filterType = data[offset2++];
33077
+ const currentLine = data.subarray(offset2, offset2 + passLineBytes);
33078
+ offset2 += passLineBytes;
32540
33079
  const newLine = new Uint8Array(passLineBytes);
32541
33080
  applyUnfilter(filterType, currentLine, newLine, prevLine, passLineBytes, bytesPerPixel);
32542
33081
  prevLine.set(newLine);
@@ -32578,13 +33117,13 @@ function decodeInterlaceNull(params) {
32578
33117
  const bytesPerLine = Math.ceil(depth / 8 * channels * width);
32579
33118
  const newData = new Uint8Array(height * bytesPerLine);
32580
33119
  let prevLine = empty;
32581
- let offset = 0;
33120
+ let offset2 = 0;
32582
33121
  let currentLine;
32583
33122
  let newLine;
32584
33123
  for (let i4 = 0; i4 < height; i4++) {
32585
- currentLine = data.subarray(offset + 1, offset + 1 + bytesPerLine);
33124
+ currentLine = data.subarray(offset2 + 1, offset2 + 1 + bytesPerLine);
32586
33125
  newLine = newData.subarray(i4 * bytesPerLine, (i4 + 1) * bytesPerLine);
32587
- switch (data[offset]) {
33126
+ switch (data[offset2]) {
32588
33127
  case 0:
32589
33128
  unfilterNone(currentLine, newLine, bytesPerLine);
32590
33129
  break;
@@ -32601,10 +33140,10 @@ function decodeInterlaceNull(params) {
32601
33140
  unfilterPaeth(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel);
32602
33141
  break;
32603
33142
  default:
32604
- throw new Error(`Unsupported filter: ${data[offset]}`);
33143
+ throw new Error(`Unsupported filter: ${data[offset2]}`);
32605
33144
  }
32606
33145
  prevLine = newLine;
32607
- offset += bytesPerLine + 1;
33146
+ offset2 += bytesPerLine + 1;
32608
33147
  }
32609
33148
  if (depth === 16) {
32610
33149
  const uint16Data = new Uint16Array(newData.buffer);
@@ -32789,7 +33328,7 @@ var PngDecoder = class extends IOBuffer {
32789
33328
  }
32790
33329
  // https://www.w3.org/TR/PNG/#5Chunk-layout
32791
33330
  decodeChunk(length, type) {
32792
- const offset = this.offset;
33331
+ const offset2 = this.offset;
32793
33332
  switch (type) {
32794
33333
  // 11.2 Critical chunks
32795
33334
  case "IHDR":
@@ -32821,7 +33360,7 @@ var PngDecoder = class extends IOBuffer {
32821
33360
  this.skip(length);
32822
33361
  break;
32823
33362
  }
32824
- if (this.offset - offset !== length) {
33363
+ if (this.offset - offset2 !== length) {
32825
33364
  throw new Error(`Length mismatch while decoding chunk ${type}`);
32826
33365
  }
32827
33366
  if (this._checkCrc) {
@@ -32831,7 +33370,7 @@ var PngDecoder = class extends IOBuffer {
32831
33370
  }
32832
33371
  }
32833
33372
  decodeApngChunk(length, type) {
32834
- const offset = this.offset;
33373
+ const offset2 = this.offset;
32835
33374
  if (type !== "fdAT" && type !== "IDAT" && this._writingDataChunks) {
32836
33375
  this.pushDataToFrame();
32837
33376
  }
@@ -32847,10 +33386,10 @@ var PngDecoder = class extends IOBuffer {
32847
33386
  break;
32848
33387
  default:
32849
33388
  this.decodeChunk(length, type);
32850
- this.offset = offset + length;
33389
+ this.offset = offset2 + length;
32851
33390
  break;
32852
33391
  }
32853
- if (this.offset - offset !== length) {
33392
+ if (this.offset - offset2 !== length) {
32854
33393
  throw new Error(`Length mismatch while decoding chunk ${type}`);
32855
33394
  }
32856
33395
  if (this._checkCrc) {
@@ -40762,6 +41301,181 @@ function createPdfApi() {
40762
41301
  };
40763
41302
  }
40764
41303
 
41304
+ // src/services/agentNotifications.js
41305
+ var toList = (result) => Array.isArray(result) ? result : result?.data || [];
41306
+ var latestByTime = (records) => [...records].sort((a3, b2) => {
41307
+ const left = Number(a3.createdAt || a3.updatedAt || 0) || Date.parse(a3.createdAt || a3.updatedAt || 0) || 0;
41308
+ const right = Number(b2.createdAt || b2.updatedAt || 0) || Date.parse(b2.createdAt || b2.updatedAt || 0) || 0;
41309
+ return right - left;
41310
+ })[0] || null;
41311
+ function createAgentNotificationService(client) {
41312
+ let timer = null;
41313
+ let stopped = true;
41314
+ const seen = /* @__PURE__ */ new Map();
41315
+ const listeners2 = /* @__PURE__ */ new Set();
41316
+ const notify = (event) => listeners2.forEach((listener) => listener(event));
41317
+ const getSessionId = (session) => session.sessionId || session.session_id || session.id;
41318
+ const getMessages = async (sessionId, appId) => {
41319
+ const [bySessionId, byLegacySessionId] = await Promise.all([
41320
+ client.entities.ChatMessage.query({ filter: { appId, sessionId }, limit: 100 }),
41321
+ client.entities.ChatMessage.query({ filter: { appId, session_id: sessionId }, limit: 100 })
41322
+ ]);
41323
+ const seenMessages = /* @__PURE__ */ new Set();
41324
+ return [...toList(bySessionId), ...toList(byLegacySessionId)].filter((message2) => {
41325
+ const key = message2?.id || `${message2?.createdAt || ""}:${message2?.content || ""}`;
41326
+ if (seenMessages.has(key)) return false;
41327
+ seenMessages.add(key);
41328
+ return true;
41329
+ });
41330
+ };
41331
+ const publish = (sessionId, payload) => {
41332
+ const connection = client.realtime.room(sessionId, {}, { maxReconnects: 2 });
41333
+ connection.publish({ type: "chat_message", sessionId, session_id: sessionId, message: payload, payload });
41334
+ setTimeout(() => connection.close(), 1e3);
41335
+ };
41336
+ const publishStatus = (sessionId, status, session) => publish(sessionId, {
41337
+ id: `status_${status}_${Date.now()}`,
41338
+ type: "chat_status",
41339
+ status,
41340
+ sessionId,
41341
+ session_id: sessionId,
41342
+ visitor_name: session?.visitor_name || "",
41343
+ createdAt: Date.now()
41344
+ });
41345
+ const accept = async (session) => {
41346
+ const sessionId = getSessionId(session);
41347
+ await client.entities.ChatSession.update(session.id, {
41348
+ status: "agent_active",
41349
+ agent_email: client.agentIdentity || "agent",
41350
+ updatedAt: Date.now()
41351
+ });
41352
+ publishStatus(sessionId, "agent_active", session);
41353
+ notify({ type: "accepted", sessionId, session });
41354
+ };
41355
+ const reject = async (session) => {
41356
+ const sessionId = getSessionId(session);
41357
+ await client.entities.ChatSession.update(session.id, { status: "agent_rejected", updatedAt: Date.now() });
41358
+ publishStatus(sessionId, "agent_rejected", session);
41359
+ notify({ type: "rejected", sessionId, session });
41360
+ };
41361
+ const reply = async (session, content) => {
41362
+ const sessionId = getSessionId(session);
41363
+ if (!content?.trim()) throw new TypeError("A reply message is required.");
41364
+ const message2 = {
41365
+ id: `msg_${Date.now()}_${Math.random().toString(36).slice(2)}`,
41366
+ appId: session.appId || client.appId,
41367
+ userId: client.agentIdentity || "agent",
41368
+ sessionId,
41369
+ session_id: sessionId,
41370
+ role: "agent",
41371
+ content: content.trim(),
41372
+ createdAt: Date.now()
41373
+ };
41374
+ await client.entities.ChatMessage.create(message2);
41375
+ publish(sessionId, message2);
41376
+ notify({ type: "replied", sessionId, session, message: message2 });
41377
+ return message2;
41378
+ };
41379
+ const dispatchAction = async ({ action, sessionId, reply: text2 }) => {
41380
+ const appId = client.appId;
41381
+ const [bySessionId, byLegacySessionId] = await Promise.all([
41382
+ client.entities.ChatSession.query({ filter: { appId, sessionId }, limit: 1 }),
41383
+ client.entities.ChatSession.query({ filter: { appId, session_id: sessionId }, limit: 1 })
41384
+ ]);
41385
+ const session = toList(bySessionId)[0] || toList(byLegacySessionId)[0];
41386
+ if (!session) return;
41387
+ if (action === "open") return notify({ type: "open", sessionId, session });
41388
+ if (action === "accept") return accept(session);
41389
+ if (action === "reject") return reject(session);
41390
+ if (action === "reply") return reply(session, text2);
41391
+ };
41392
+ const showNative = (request) => client.notifications.show({
41393
+ id: `agent-request-${request.sessionId}`,
41394
+ title: request.title,
41395
+ body: request.body,
41396
+ data: { sessionId: request.sessionId, kind: request.kind || "agent_request" },
41397
+ channel: "agent_requests",
41398
+ style: request.style,
41399
+ actions: [
41400
+ ...request.kind === "agent_message" ? [] : [
41401
+ { id: "accept", title: "Accept" },
41402
+ { id: "reject", title: "Reject" }
41403
+ ],
41404
+ { id: "open", title: "Open" },
41405
+ { id: "reply", title: "Reply", input: true }
41406
+ ]
41407
+ });
41408
+ const check = async ({ appId = client.appId, notificationStyle } = {}) => {
41409
+ const sessions = toList(await client.entities.ChatSession.query({ filter: { appId, status: "escalated" }, limit: 100 }));
41410
+ for (const session of sessions) {
41411
+ const sessionId = getSessionId(session);
41412
+ if (!sessionId) continue;
41413
+ const latest = latestByTime(await getMessages(sessionId, appId));
41414
+ const fingerprint = `${session.updatedAt || session.lastMessageAt || session.createdAt}:${latest?.id || latest?.content || ""}`;
41415
+ if (seen.get(sessionId) === fingerprint) continue;
41416
+ seen.set(sessionId, fingerprint);
41417
+ const request = {
41418
+ sessionId,
41419
+ kind: "agent_request",
41420
+ title: `Support request from ${session.visitor_name || "a visitor"}`,
41421
+ body: latest?.content || "A visitor is requesting a human agent.",
41422
+ latestMessage: latest,
41423
+ session,
41424
+ style: notificationStyle
41425
+ };
41426
+ await showNative(request);
41427
+ notify({ type: "request", ...request });
41428
+ }
41429
+ if (client.agentIdentity) {
41430
+ const active = toList(await client.entities.ChatSession.query({ filter: { appId, status: "agent_active", agent_email: client.agentIdentity }, limit: 100 }));
41431
+ for (const session of active) {
41432
+ const sessionId = getSessionId(session);
41433
+ if (!sessionId) continue;
41434
+ const messages2 = await getMessages(sessionId, appId);
41435
+ const latestVisitor = latestByTime(messages2.filter((message2) => message2?.role === "visitor" || message2?.role === "user"));
41436
+ if (!latestVisitor) continue;
41437
+ const fingerprint = `message:${latestVisitor.id || latestVisitor.createdAt || latestVisitor.content}`;
41438
+ if (seen.get(`message:${sessionId}`) === fingerprint) continue;
41439
+ seen.set(`message:${sessionId}`, fingerprint);
41440
+ const request = {
41441
+ sessionId,
41442
+ kind: "agent_message",
41443
+ title: `New message from ${session.visitor_name || "visitor"}`,
41444
+ body: latestVisitor.content || "The visitor sent an attachment.",
41445
+ latestMessage: latestVisitor,
41446
+ session,
41447
+ style: notificationStyle
41448
+ };
41449
+ await showNative(request);
41450
+ notify({ type: "message", ...request });
41451
+ }
41452
+ }
41453
+ };
41454
+ const start = async ({ pollMs = 8e3, agentIdentity, ...options } = {}) => {
41455
+ if (agentIdentity) client.agentIdentity = agentIdentity;
41456
+ if (options.appId) client.appId = options.appId;
41457
+ stopped = false;
41458
+ await check(options);
41459
+ clearInterval(timer);
41460
+ timer = setInterval(() => !stopped && check(options).catch((error) => notify({ type: "error", error })), pollMs);
41461
+ };
41462
+ const stop = () => {
41463
+ stopped = true;
41464
+ clearInterval(timer);
41465
+ timer = null;
41466
+ };
41467
+ const onEvent = (listener) => {
41468
+ listeners2.add(listener);
41469
+ return () => listeners2.delete(listener);
41470
+ };
41471
+ client.notifications.onAction(({ action, data, reply: text2 }) => {
41472
+ if (data?.sessionId && String(data.kind || "").startsWith("agent_")) {
41473
+ dispatchAction({ action, sessionId: data.sessionId, reply: text2 }).catch((error) => notify({ type: "error", error }));
41474
+ }
41475
+ });
41476
+ return { start, stop, check, onEvent, accept, reject, reply, dispatchAction };
41477
+ }
41478
+
40765
41479
  // src/services/notifications.js
40766
41480
  var isBrowser = () => typeof window !== "undefined" && typeof Notification !== "undefined";
40767
41481
  function createNotificationService() {
@@ -40887,190 +41601,13 @@ function createNotificationService() {
40887
41601
  return { permission, requestPermission, show, schedule, cancel, cancelAll, onAction };
40888
41602
  }
40889
41603
 
40890
- // src/services/agentNotifications.js
40891
- var toList = (result) => Array.isArray(result) ? result : result?.data || [];
40892
- var latestByTime = (records) => [...records].sort((a3, b2) => {
40893
- const left = Number(a3.createdAt || a3.updatedAt || 0) || Date.parse(a3.createdAt || a3.updatedAt || 0) || 0;
40894
- const right = Number(b2.createdAt || b2.updatedAt || 0) || Date.parse(b2.createdAt || b2.updatedAt || 0) || 0;
40895
- return right - left;
40896
- })[0] || null;
40897
- function createAgentNotificationService(client) {
40898
- const notifications = client.notifications || createNotificationService();
40899
- let timer = null;
40900
- let stopped = true;
40901
- const seen = /* @__PURE__ */ new Map();
40902
- const listeners2 = /* @__PURE__ */ new Set();
40903
- const notify = (event) => listeners2.forEach((listener) => listener(event));
40904
- const getSessionId = (session) => session.sessionId || session.session_id || session.id;
40905
- const getMessages = async (sessionId, appId) => {
40906
- const [bySessionId, byLegacySessionId] = await Promise.all([
40907
- client.entities.ChatMessage.query({ filter: { appId, sessionId }, limit: 100 }),
40908
- client.entities.ChatMessage.query({ filter: { appId, session_id: sessionId }, limit: 100 })
40909
- ]);
40910
- const seenMessages = /* @__PURE__ */ new Set();
40911
- return [...toList(bySessionId), ...toList(byLegacySessionId)].filter((message2) => {
40912
- const key = message2?.id || `${message2?.createdAt || ""}:${message2?.content || ""}`;
40913
- if (seenMessages.has(key)) return false;
40914
- seenMessages.add(key);
40915
- return true;
40916
- });
40917
- };
40918
- const publish = (sessionId, payload) => {
40919
- const connection = client.realtime.room(sessionId, {}, { maxReconnects: 2 });
40920
- connection.publish({ type: "chat_message", sessionId, session_id: sessionId, message: payload, payload });
40921
- setTimeout(() => connection.close(), 1e3);
40922
- };
40923
- const publishStatus = (sessionId, status, session) => publish(sessionId, {
40924
- id: `status_${status}_${Date.now()}`,
40925
- type: "chat_status",
40926
- status,
40927
- sessionId,
40928
- session_id: sessionId,
40929
- visitor_name: session?.visitor_name || "",
40930
- createdAt: Date.now()
40931
- });
40932
- const accept = async (session) => {
40933
- const sessionId = getSessionId(session);
40934
- await client.entities.ChatSession.update(session.id, {
40935
- status: "agent_active",
40936
- agent_email: client.agentIdentity || "agent",
40937
- updatedAt: Date.now()
40938
- });
40939
- publishStatus(sessionId, "agent_active", session);
40940
- notify({ type: "accepted", sessionId, session });
40941
- };
40942
- const reject = async (session) => {
40943
- const sessionId = getSessionId(session);
40944
- await client.entities.ChatSession.update(session.id, { status: "agent_rejected", updatedAt: Date.now() });
40945
- publishStatus(sessionId, "agent_rejected", session);
40946
- notify({ type: "rejected", sessionId, session });
40947
- };
40948
- const reply = async (session, content) => {
40949
- const sessionId = getSessionId(session);
40950
- if (!content?.trim()) throw new TypeError("A reply message is required.");
40951
- const message2 = {
40952
- id: `msg_${Date.now()}_${Math.random().toString(36).slice(2)}`,
40953
- appId: session.appId || client.appId,
40954
- userId: client.agentIdentity || "agent",
40955
- sessionId,
40956
- session_id: sessionId,
40957
- role: "agent",
40958
- content: content.trim(),
40959
- createdAt: Date.now()
40960
- };
40961
- await client.entities.ChatMessage.create(message2);
40962
- publish(sessionId, message2);
40963
- notify({ type: "replied", sessionId, session, message: message2 });
40964
- return message2;
40965
- };
40966
- const dispatchAction = async ({ action, sessionId, reply: text2 }) => {
40967
- const appId = client.appId;
40968
- const [bySessionId, byLegacySessionId] = await Promise.all([
40969
- client.entities.ChatSession.query({ filter: { appId, sessionId }, limit: 1 }),
40970
- client.entities.ChatSession.query({ filter: { appId, session_id: sessionId }, limit: 1 })
40971
- ]);
40972
- const session = toList(bySessionId)[0] || toList(byLegacySessionId)[0];
40973
- if (!session) return;
40974
- if (action === "open") return notify({ type: "open", sessionId, session });
40975
- if (action === "accept") return accept(session);
40976
- if (action === "reject") return reject(session);
40977
- if (action === "reply") return reply(session, text2);
40978
- };
40979
- const showNative = (request) => notifications.show({
40980
- id: `agent-request-${request.sessionId}`,
40981
- title: request.title,
40982
- body: request.body,
40983
- data: { sessionId: request.sessionId, kind: request.kind || "agent_request" },
40984
- channel: "agent_requests",
40985
- style: request.style,
40986
- actions: [
40987
- ...request.kind === "agent_message" ? [] : [
40988
- { id: "accept", title: "Accept" },
40989
- { id: "reject", title: "Reject" }
40990
- ],
40991
- { id: "open", title: "Open" },
40992
- { id: "reply", title: "Reply", input: true }
40993
- ]
40994
- });
40995
- const check = async ({ appId = client.appId, notificationStyle } = {}) => {
40996
- const sessions = toList(await client.entities.ChatSession.query({ filter: { appId, status: "escalated" }, limit: 100 }));
40997
- for (const session of sessions) {
40998
- const sessionId = getSessionId(session);
40999
- if (!sessionId) continue;
41000
- const latest = latestByTime(await getMessages(sessionId, appId));
41001
- const fingerprint = `${session.updatedAt || session.lastMessageAt || session.createdAt}:${latest?.id || latest?.content || ""}`;
41002
- if (seen.get(sessionId) === fingerprint) continue;
41003
- seen.set(sessionId, fingerprint);
41004
- const request = {
41005
- sessionId,
41006
- kind: "agent_request",
41007
- title: `Support request from ${session.visitor_name || "a visitor"}`,
41008
- body: latest?.content || "A visitor is requesting a human agent.",
41009
- latestMessage: latest,
41010
- session,
41011
- style: notificationStyle
41012
- };
41013
- await showNative(request);
41014
- notify({ type: "request", ...request });
41015
- }
41016
- if (client.agentIdentity) {
41017
- const active = toList(await client.entities.ChatSession.query({ filter: { appId, status: "agent_active", agent_email: client.agentIdentity }, limit: 100 }));
41018
- for (const session of active) {
41019
- const sessionId = getSessionId(session);
41020
- if (!sessionId) continue;
41021
- const messages2 = await getMessages(sessionId, appId);
41022
- const latestVisitor = latestByTime(messages2.filter((message2) => message2?.role === "visitor" || message2?.role === "user"));
41023
- if (!latestVisitor) continue;
41024
- const fingerprint = `message:${latestVisitor.id || latestVisitor.createdAt || latestVisitor.content}`;
41025
- if (seen.get(`message:${sessionId}`) === fingerprint) continue;
41026
- seen.set(`message:${sessionId}`, fingerprint);
41027
- const request = {
41028
- sessionId,
41029
- kind: "agent_message",
41030
- title: `New message from ${session.visitor_name || "visitor"}`,
41031
- body: latestVisitor.content || "The visitor sent an attachment.",
41032
- latestMessage: latestVisitor,
41033
- session,
41034
- style: notificationStyle
41035
- };
41036
- await showNative(request);
41037
- notify({ type: "message", ...request });
41038
- }
41039
- }
41040
- };
41041
- const start = async ({ pollMs = 8e3, agentIdentity, ...options } = {}) => {
41042
- if (agentIdentity) client.agentIdentity = agentIdentity;
41043
- if (options.appId) client.appId = options.appId;
41044
- stopped = false;
41045
- await check(options);
41046
- clearInterval(timer);
41047
- timer = setInterval(() => !stopped && check(options).catch((error) => notify({ type: "error", error })), pollMs);
41048
- };
41049
- const stop = () => {
41050
- stopped = true;
41051
- clearInterval(timer);
41052
- timer = null;
41053
- };
41054
- const onEvent = (listener) => {
41055
- listeners2.add(listener);
41056
- return () => listeners2.delete(listener);
41057
- };
41058
- notifications.onAction(({ action, data, reply: text2 }) => {
41059
- if (data?.sessionId && String(data.kind || "").startsWith("agent_")) {
41060
- dispatchAction({ action, sessionId: data.sessionId, reply: text2 }).catch((error) => notify({ type: "error", error }));
41061
- }
41062
- });
41063
- return { start, stop, check, onEvent, accept, reject, reply, dispatchAction };
41064
- }
41065
-
41066
41604
  // src/services/chatNotifications.js
41067
41605
  function createChatNotificationService(client) {
41068
- const notifications = client.notifications || createNotificationService();
41069
41606
  const listeners2 = /* @__PURE__ */ new Set();
41070
41607
  const emit2 = (event) => listeners2.forEach((listener) => listener(event));
41071
41608
  const showMessage = async ({ sessionId, title = "New chat message", body = "", data = {}, style } = {}) => {
41072
41609
  if (!sessionId) return null;
41073
- return notifications.show({
41610
+ return client.notifications.show({
41074
41611
  id: `chat-message-${sessionId}-${Date.now()}`,
41075
41612
  title,
41076
41613
  body,
@@ -41085,7 +41622,7 @@ function createChatNotificationService(client) {
41085
41622
  };
41086
41623
  const showStatus = async ({ sessionId, title = "Chat update", body = "", data = {}, style } = {}) => {
41087
41624
  if (!sessionId) return null;
41088
- return notifications.show({
41625
+ return client.notifications.show({
41089
41626
  id: `chat-status-${sessionId}-${Date.now()}`,
41090
41627
  title,
41091
41628
  body,
@@ -41099,7 +41636,7 @@ function createChatNotificationService(client) {
41099
41636
  listeners2.add(listener);
41100
41637
  return () => listeners2.delete(listener);
41101
41638
  };
41102
- notifications.onAction(({ action, data, reply }) => {
41639
+ client.notifications.onAction(({ action, data, reply }) => {
41103
41640
  if (data?.sessionId && ["chat_message", "chat_status"].includes(data.kind)) {
41104
41641
  emit2({ type: action === "reply" ? "reply" : action, action, sessionId: data.sessionId, reply: reply || "", data });
41105
41642
  }
@@ -42110,6 +42647,20 @@ async function getGoogleModule() {
42110
42647
  }
42111
42648
  return googleModule;
42112
42649
  }
42650
+ var facebookModule = null;
42651
+ async function getFacebookModule() {
42652
+ if (!facebookModule) {
42653
+ facebookModule = await Promise.resolve().then(() => (init_useFacebookAuth(), useFacebookAuth_exports));
42654
+ }
42655
+ return facebookModule;
42656
+ }
42657
+ var metaModule = null;
42658
+ async function getMetaModule() {
42659
+ if (!metaModule) {
42660
+ metaModule = await Promise.resolve().then(() => (init_useMetaAuth(), useMetaAuth_exports));
42661
+ }
42662
+ return metaModule;
42663
+ }
42113
42664
  var TevrocError = class extends Error {
42114
42665
  constructor(message2, options = {}) {
42115
42666
  super(message2);
@@ -42172,10 +42723,12 @@ function createChatbotClient(options = {}) {
42172
42723
  var TevrocClient = class {
42173
42724
  constructor(options = {}) {
42174
42725
  const baseUrl = options.baseUrl ?? options.url;
42175
- const serviceUrl = options.serviceUrl ?? options.url;
42726
+ const serviceUrl = options.serviceUrl ?? options.url ?? baseUrl;
42727
+ const vpsUrl = options.vpsUrl ?? serviceUrl;
42176
42728
  if (!baseUrl) throw new TypeError("createClient requires a baseUrl");
42177
42729
  this.baseUrl = normalizeBaseUrl(baseUrl);
42178
42730
  this.serviceUrl = normalizeBaseUrl(serviceUrl);
42731
+ this.vpsUrl = normalizeBaseUrl(vpsUrl);
42179
42732
  this.appId = options.appId;
42180
42733
  this.appName = options.appName;
42181
42734
  this.payAccount = options.payAccount ?? "default";
@@ -42522,6 +43075,7 @@ function createAuthApi(client) {
42522
43075
  // base44
42523
43076
  loginWithProvider: async (provider, redirectTo, setToken = async () => {
42524
43077
  }) => {
43078
+ console.log(client, "loginWithProvider called", { provider, redirectTo });
42525
43079
  if (provider === "google") {
42526
43080
  const { createGoogleLogin: createGoogleLogin2, subscribeGoogleLogin: subscribeGoogleLogin2 } = await getGoogleModule();
42527
43081
  debugLog2(client, {
@@ -42529,7 +43083,7 @@ function createAuthApi(client) {
42529
43083
  appId: client.appId,
42530
43084
  appName: client.appName
42531
43085
  });
42532
- createGoogleLogin2({
43086
+ await createGoogleLogin2({
42533
43087
  serviceUrl: client.serviceUrl,
42534
43088
  appId: client.appId,
42535
43089
  appName: client.appName
@@ -42551,12 +43105,100 @@ function createAuthApi(client) {
42551
43105
  });
42552
43106
  }
42553
43107
  }
43108
+ if (provider === "facebook") {
43109
+ const { createFacebookLogin: createFacebookLogin2, subscribeFacebookLogin: subscribeFacebookLogin2 } = await getFacebookModule();
43110
+ debugLog2(client, {
43111
+ serviceUrl: client.serviceUrl,
43112
+ appId: client.appId,
43113
+ appName: client.appName
43114
+ });
43115
+ if (redirectTo) {
43116
+ const unsub = subscribeFacebookLogin2(async (user, err2) => {
43117
+ debugLog2(client, "Facebook callback:", user, err2);
43118
+ unsub();
43119
+ if (!user) return;
43120
+ const result = await client.request("/auth/facebook", {
43121
+ method: "POST",
43122
+ body: buildAuthPayload({ accessToken: user.accessToken }, client),
43123
+ auth: false
43124
+ });
43125
+ debugLog2(client, result);
43126
+ await setToken(result.token, result.user);
43127
+ debugLog2(client, "Redirecting to:", redirectTo);
43128
+ window.location.href = redirectTo;
43129
+ });
43130
+ try {
43131
+ await createFacebookLogin2({
43132
+ serviceUrl: client.serviceUrl,
43133
+ appId: client.appId,
43134
+ appName: client.appName
43135
+ });
43136
+ } catch (error) {
43137
+ unsub();
43138
+ throw error;
43139
+ }
43140
+ } else {
43141
+ await createFacebookLogin2({
43142
+ serviceUrl: client.serviceUrl,
43143
+ appId: client.appId,
43144
+ appName: client.appName
43145
+ });
43146
+ }
43147
+ }
43148
+ if (provider === "meta") {
43149
+ const { createMetaLogin: createMetaLogin2, subscribeMetaLogin: subscribeMetaLogin2 } = await getMetaModule();
43150
+ debugLog2(client, {
43151
+ serviceUrl: client.serviceUrl,
43152
+ appId: client.appId,
43153
+ appName: client.appName
43154
+ });
43155
+ if (redirectTo) {
43156
+ const unsub = subscribeMetaLogin2(async (user, err2) => {
43157
+ debugLog2(client, "Meta callback:", user, err2);
43158
+ unsub();
43159
+ if (!user) return;
43160
+ const result = await client.request("/auth/meta", {
43161
+ method: "POST",
43162
+ body: buildAuthPayload({ accessToken: user.accessToken }, client),
43163
+ auth: false
43164
+ });
43165
+ debugLog2(client, result);
43166
+ await setToken(result.token, result.user);
43167
+ debugLog2(client, "Redirecting to:", redirectTo);
43168
+ window.location.href = redirectTo;
43169
+ });
43170
+ try {
43171
+ await createMetaLogin2({
43172
+ serviceUrl: client.serviceUrl,
43173
+ appId: client.appId,
43174
+ appName: client.appName
43175
+ });
43176
+ } catch (error) {
43177
+ unsub();
43178
+ throw error;
43179
+ }
43180
+ } else {
43181
+ await createMetaLogin2({
43182
+ serviceUrl: client.serviceUrl,
43183
+ appId: client.appId,
43184
+ appName: client.appName
43185
+ });
43186
+ }
43187
+ }
42554
43188
  },
42555
43189
  // extra
42556
43190
  googleLogin: (params) => createGoogleLogin(params),
42557
43191
  onGoogleLogin: (callback) => {
42558
43192
  return subscribeGoogleLogin(callback);
42559
43193
  },
43194
+ facebookLogin: (params) => createFacebookLogin(params),
43195
+ onFacebookLogin: (callback) => {
43196
+ return subscribeFacebookLogin(callback);
43197
+ },
43198
+ metaLogin: (params) => createMetaLogin(params),
43199
+ onMetaLogin: (callback) => {
43200
+ return subscribeMetaLogin(callback);
43201
+ },
42560
43202
  //
42561
43203
  async login(input) {
42562
43204
  const body = buildAuthPayload(input, client);
@@ -42564,6 +43206,33 @@ function createAuthApi(client) {
42564
43206
  if (result.token) client.setToken(result.token);
42565
43207
  return result;
42566
43208
  },
43209
+ async loginWithGoogle(input) {
43210
+ const result = await client.request("/auth/google", {
43211
+ method: "POST",
43212
+ body: buildAuthPayload(input, client),
43213
+ auth: false
43214
+ });
43215
+ if (result.token) client.setToken(result.token);
43216
+ return result;
43217
+ },
43218
+ async loginWithFacebook(input) {
43219
+ const result = await client.request("/auth/facebook", {
43220
+ method: "POST",
43221
+ body: buildAuthPayload(input, client),
43222
+ auth: false
43223
+ });
43224
+ if (result.token) client.setToken(result.token);
43225
+ return result;
43226
+ },
43227
+ async loginWithMeta(input) {
43228
+ const result = await client.request("/auth/meta", {
43229
+ method: "POST",
43230
+ body: buildAuthPayload(input, client),
43231
+ auth: false
43232
+ });
43233
+ if (result.token) client.setToken(result.token);
43234
+ return result;
43235
+ },
42567
43236
  async logout() {
42568
43237
  const result = await client.request("/auth/logout", { method: "POST", body: buildAuthPayload({}, client) });
42569
43238
  client.clearToken();
@@ -43155,29 +43824,6 @@ function base64ToBlob(base64, contentType = "application/octet-stream") {
43155
43824
  }
43156
43825
  return new Blob([bytes], { type: contentType });
43157
43826
  }
43158
- function arrayBufferToBase64(buffer) {
43159
- let binary = "";
43160
- const bytes = new Uint8Array(buffer);
43161
- const chunkSize = 32768;
43162
- for (let i4 = 0; i4 < bytes.length; i4 += chunkSize) {
43163
- const chunk = bytes.subarray(i4, i4 + chunkSize);
43164
- binary += String.fromCharCode.apply(null, chunk);
43165
- }
43166
- return btoa(binary);
43167
- }
43168
- async function normalizeUploadBody(file) {
43169
- if (typeof Blob !== "undefined" && file instanceof Blob) {
43170
- return { data: await blobToBase643(file), contentType: file.type || "application/octet-stream", bodyIsBase64: true };
43171
- }
43172
- if (file && typeof file.arrayBuffer === "function") {
43173
- const buffer = await file.arrayBuffer();
43174
- return { data: arrayBufferToBase64(buffer), contentType: "application/octet-stream", bodyIsBase64: true };
43175
- }
43176
- if (typeof file === "string") {
43177
- return { data: file, contentType: "text/plain", bodyIsBase64: false };
43178
- }
43179
- return { data: JSON.stringify(file), contentType: "application/json", bodyIsBase64: false };
43180
- }
43181
43827
  function createFileApi(client) {
43182
43828
  return {
43183
43829
  url: async (key) => {
@@ -43313,34 +43959,174 @@ function createFileApi(client) {
43313
43959
  };
43314
43960
  }
43315
43961
  async function upload(client, path, file, options = {}) {
43316
- const headers = {};
43317
- if (options.filename) headers["x-filename"] = options.filename;
43318
- if (options.contentType) headers["content-type"] = options.contentType;
43319
- if (isNative && client.offline) {
43320
- const online = await client.offline.isOnline();
43321
- if (!online) {
43322
- const id = options.filename || `file_${Date.now()}`;
43323
- const normalized = await normalizeUploadBody(file);
43324
- const payload = {
43325
- path,
43962
+ const isElectron = await detectElectronEnvironment(client);
43963
+ if (isElectron) {
43964
+ return uploadViaElectronBridge(client, file, options);
43965
+ }
43966
+ return uploadViaGoogleStorage(client, file, { ...options, path });
43967
+ }
43968
+ async function detectElectronEnvironment(client) {
43969
+ try {
43970
+ const serviceUrl = String(client?.serviceUrl || "").replace(/\/$/, "");
43971
+ const response = await client.fetch(`${serviceUrl}/api/environment`, {
43972
+ method: "GET",
43973
+ headers: { Accept: "application/json" },
43974
+ cache: "no-store"
43975
+ });
43976
+ if (response && response.ok) {
43977
+ const data = await response.json();
43978
+ if (data && typeof data === "object" && "isElectron" in data) {
43979
+ return Boolean(data.isElectron);
43980
+ }
43981
+ }
43982
+ } catch (error) {
43983
+ console.debug("[tevrocsdk][env] /api/environment fallback", error);
43984
+ }
43985
+ if (typeof navigator !== "undefined") {
43986
+ const userAgent = navigator.userAgent || "";
43987
+ if (/electron/i.test(userAgent)) return true;
43988
+ }
43989
+ if (typeof window !== "undefined") {
43990
+ const bridge = window?.bridge || window?.electronBridge || window?.nativeBridge;
43991
+ if (bridge) return true;
43992
+ if (window.process && window.process.versions && window.process.versions.electron) return true;
43993
+ }
43994
+ return false;
43995
+ }
43996
+ async function uploadViaElectronBridge(client, file, options = {}) {
43997
+ const fileName = options.filename || "upload";
43998
+ const contentType = options.contentType || "application/octet-stream";
43999
+ const resolvedFile = file instanceof Blob ? file : new Blob([String(file ?? "")], { type: contentType });
44000
+ const dataUrl = resolvedFile instanceof Blob ? `data:${contentType};base64,${await blobToBase643(resolvedFile)}` : String(file);
44001
+ const packetSize = options.packetSize || 1024 * 1024;
44002
+ const packets = [];
44003
+ for (let offset2 = 0; offset2 < dataUrl.length; offset2 += packetSize) {
44004
+ const packetData2 = dataUrl.slice(offset2, offset2 + packetSize);
44005
+ packets.push({
44006
+ packetId: packets.length,
44007
+ packetData: encodeURIComponent(packetData2),
44008
+ isLastPacket: offset2 + packetSize >= dataUrl.length,
44009
+ filePanaroma: options.filePanaroma || "NO"
44010
+ });
44011
+ }
44012
+ if (!packets.length) throw new TevrocError("Cannot upload an empty file", { code: "empty_file" });
44013
+ let clientId = "";
44014
+ const endpoint = `${client.serviceUrl.replace(/\/$/, "")}/receivePacket`;
44015
+ for (const packet of packets) {
44016
+ const payload = {
44017
+ ...packet,
44018
+ clientId,
44019
+ tableName: options.tableName || "",
44020
+ tableIdx: options.tableIdx ?? "",
44021
+ tableGallery: options.gallery === true || options.gallery === "YES",
44022
+ fileName,
44023
+ fileSize: resolvedFile.size,
44024
+ fileMime: contentType,
44025
+ server: options.server || "test",
44026
+ session: options.session || client.token || ""
44027
+ };
44028
+ let result;
44029
+ const bridge = typeof window !== "undefined" ? window : null;
44030
+ if (bridge && typeof bridge.syncRequest === "function") {
44031
+ const rawResult = bridge.syncRequest(endpoint, "POST", payload);
44032
+ if (!rawResult) throw new TevrocError("Electron upload failed", { code: "electron_upload_failed" });
44033
+ try {
44034
+ result = JSON.parse(rawResult);
44035
+ } catch (error) {
44036
+ throw new TevrocError("Electron upload returned invalid JSON", { code: "electron_upload_failed" });
44037
+ }
44038
+ } else {
44039
+ const response = await client.fetch(endpoint, {
43326
44040
  method: "POST",
43327
- headers,
43328
- body: normalized.data,
43329
- contentType: normalized.contentType,
43330
- bodyIsBase64: normalized.bodyIsBase64,
43331
- filename: options.filename,
43332
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
43333
- };
43334
- const queued = await client.offline.queueOperation("files", "upload", id, payload);
43335
- debugLog2(client, "[tevrocsdk][files] upload queued offline", { path, id, queued });
43336
- return queued;
44041
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
44042
+ body: JSON.stringify(payload)
44043
+ });
44044
+ if (!response.ok) {
44045
+ const text2 = await response.text();
44046
+ throw new TevrocError(text2 || "Electron upload failed", { status: response.status, code: "electron_upload_failed" });
44047
+ }
44048
+ result = await response.json();
44049
+ }
44050
+ clientId = result.clientId || clientId;
44051
+ if (typeof options.onProgress === "function") {
44052
+ options.onProgress({ uploaded: Math.min(offset + packetData.length, dataUrl.length), total: dataUrl.length, progress: Math.round((offset + packetData.length) / dataUrl.length * 100) });
43337
44053
  }
43338
44054
  }
43339
- if (isNative && client.offline && typeof client.offline.syncPendingActions === "function") {
43340
- await client.offline.syncPendingActions();
44055
+ return { success: true, clientId, fileName, fileSize: resolvedFile.size, runtime: "electron" };
44056
+ }
44057
+ async function uploadViaGoogleStorage(client, file, options = {}) {
44058
+ const contentType = options.contentType || "application/octet-stream";
44059
+ const fileName = options.filename || "upload";
44060
+ const body = file instanceof Blob ? file : new Blob([String(file ?? "")], { type: contentType });
44061
+ const serviceUrl = client.serviceUrl.replace(/\/$/, "");
44062
+ const initResponse = await client.fetch(`${serviceUrl}/api/uploads/create`, {
44063
+ method: "POST",
44064
+ headers: {
44065
+ "Content-Type": "application/json",
44066
+ Accept: "application/json"
44067
+ },
44068
+ body: JSON.stringify({
44069
+ filename: fileName,
44070
+ contentType,
44071
+ size: body.size,
44072
+ userId: options.userId || "anon"
44073
+ })
44074
+ });
44075
+ if (!initResponse.ok) {
44076
+ const text2 = await initResponse.text();
44077
+ throw new TevrocError(text2 || "Create upload session failed", { status: initResponse.status, code: "gcs_create_failed" });
44078
+ }
44079
+ const init = await initResponse.json();
44080
+ const uploadUrl = init && init.uploadUrl ? init.uploadUrl : null;
44081
+ const uploadId = init && init.uploadId ? init.uploadId : null;
44082
+ if (!uploadUrl || !uploadId) {
44083
+ throw new TevrocError("Google storage upload session is missing uploadUrl or uploadId", { code: "gcs_invalid_session" });
44084
+ }
44085
+ const chunkSize = options.chunkSize || 10 * 1024 * 1024;
44086
+ for (let offset2 = 0; offset2 < body.size; offset2 += chunkSize) {
44087
+ const end = Math.min(offset2 + chunkSize, body.size) - 1;
44088
+ let uploadResponse;
44089
+ for (let attempt = 1; attempt <= (options.retries || 5); attempt += 1) {
44090
+ try {
44091
+ uploadResponse = await client.fetch(uploadUrl, {
44092
+ method: "PUT",
44093
+ body: body.slice(offset2, end + 1),
44094
+ headers: {
44095
+ "Content-Length": String(end - offset2 + 1),
44096
+ "Content-Range": `bytes ${offset2}-${end}/${body.size}`,
44097
+ "Content-Type": contentType
44098
+ }
44099
+ });
44100
+ if (uploadResponse.ok || uploadResponse.status === 308) break;
44101
+ throw new Error(`HTTP ${uploadResponse.status}`);
44102
+ } catch (error) {
44103
+ if (attempt === (options.retries || 5)) throw new TevrocError(error.message, { code: "gcs_upload_failed" });
44104
+ await new Promise((resolve3) => setTimeout(resolve3, 1e3 * attempt));
44105
+ }
44106
+ }
44107
+ if (!uploadResponse || !uploadResponse.ok && uploadResponse.status !== 308) {
44108
+ throw new TevrocError("Google storage upload failed", { code: "gcs_upload_failed" });
44109
+ }
44110
+ if (typeof options.onProgress === "function") options.onProgress({ uploaded: end + 1, total: body.size, progress: Math.round((end + 1) / body.size * 100) });
43341
44111
  }
43342
- const result = await client.request(path, { method: "POST", body: file, headers, skipSync: true });
43343
- return result;
44112
+ const finalizeResponse = await client.fetch(`${serviceUrl}/api/uploads/${encodeURIComponent(uploadId)}/complete`, {
44113
+ method: "POST",
44114
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
44115
+ body: JSON.stringify({ storageKey: init.storageKey, userId: options.userId || "anon" })
44116
+ });
44117
+ if (!finalizeResponse.ok) {
44118
+ const text2 = await finalizeResponse.text();
44119
+ throw new TevrocError(text2 || "Finalize upload failed", { status: finalizeResponse.status, code: "gcs_finalize_failed" });
44120
+ }
44121
+ const result = await finalizeResponse.json();
44122
+ if (options.tableName && options.tableIdx !== void 0) {
44123
+ await client.fetch(`${serviceUrl}/api/files/gcs-store`, {
44124
+ method: "POST",
44125
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
44126
+ body: JSON.stringify({ storageKey: result.storageKey || init.storageKey, tableName: options.tableName, tableIdx: options.tableIdx, fileName, fileSize: body.size, fileMime: contentType, gallery: options.gallery ? "YES" : "NO", filePanaroma: options.filePanaroma || "NO" })
44127
+ });
44128
+ }
44129
+ return { ...result, runtime: "gcs" };
43344
44130
  }
43345
44131
  async function parseResponse(response, parseAs) {
43346
44132
  if (parseAs === "response") return response;