@nvwa-app/sdk-web 6.19.0 → 6.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,4 +1,5 @@
1
- import { NvwaLocalStorage, NvwaFetch, INvwa, AuthClient, NvwaFileStorage, createPostgrestClient, NvwaEdgeFunctions, NvwaHttpClient, IntegrationProvidersConfig, IPaymentLauncher } from '@nvwa-app/sdk-core';
1
+ import { NvwaLocalStorage, AuthClient, SocialProviderDescriptor, NvwaFetch, INvwa, NvwaFileStorage, createPostgrestClient, NvwaEdgeFunctions, NvwaHttpClient, IntegrationProvidersConfig, IPaymentLauncher } from '@nvwa-app/sdk-core';
2
+ import { ReactNode } from 'react';
2
3
 
3
4
  declare class WebNvwaLocalStorage implements NvwaLocalStorage {
4
5
  private prefix;
@@ -31,6 +32,19 @@ declare function getIframeSourceLocation(iframe: HTMLIFrameElement | null, targe
31
32
  */
32
33
  declare function setupIframeSourceLocationListener(): (() => void) | undefined;
33
34
 
35
+ interface WebSocialLoginProps {
36
+ auth: AuthClient;
37
+ returnUrl?: string;
38
+ applicationCode?: string;
39
+ platformCode?: string;
40
+ className?: string;
41
+ providers?: SocialProviderDescriptor[];
42
+ onError?: (error: Error) => void;
43
+ onBeforeLogin?: (provider: SocialProviderDescriptor) => void;
44
+ onRenderButton?: (provider: SocialProviderDescriptor, defaultButton: ReactNode) => ReactNode;
45
+ }
46
+ declare function SocialLoginButtons(props: WebSocialLoginProps): ReactNode;
47
+
34
48
  /**
35
49
  * Web 平台的 fetch 适配器
36
50
  * 将浏览器原生 fetch 包装为符合 NvwaFetch 类型的函数
@@ -63,4 +77,4 @@ declare class Nvwa implements INvwa {
63
77
  constructor(init: NvwaWebInit);
64
78
  }
65
79
 
66
- export { type NvwaWebInit, Nvwa as default, disableIframeHoverInspector, enableIframeHoverInspector, getIframeSourceLocation, localStorage, setupIframeHoverInspector, setupIframeSourceLocationListener, webFetch };
80
+ export { type NvwaWebInit, SocialLoginButtons, type WebSocialLoginProps, Nvwa as default, disableIframeHoverInspector, enableIframeHoverInspector, getIframeSourceLocation, localStorage, setupIframeHoverInspector, setupIframeSourceLocationListener, webFetch };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { NvwaLocalStorage, NvwaFetch, INvwa, AuthClient, NvwaFileStorage, createPostgrestClient, NvwaEdgeFunctions, NvwaHttpClient, IntegrationProvidersConfig, IPaymentLauncher } from '@nvwa-app/sdk-core';
1
+ import { NvwaLocalStorage, AuthClient, SocialProviderDescriptor, NvwaFetch, INvwa, NvwaFileStorage, createPostgrestClient, NvwaEdgeFunctions, NvwaHttpClient, IntegrationProvidersConfig, IPaymentLauncher } from '@nvwa-app/sdk-core';
2
+ import { ReactNode } from 'react';
2
3
 
3
4
  declare class WebNvwaLocalStorage implements NvwaLocalStorage {
4
5
  private prefix;
@@ -31,6 +32,19 @@ declare function getIframeSourceLocation(iframe: HTMLIFrameElement | null, targe
31
32
  */
32
33
  declare function setupIframeSourceLocationListener(): (() => void) | undefined;
33
34
 
35
+ interface WebSocialLoginProps {
36
+ auth: AuthClient;
37
+ returnUrl?: string;
38
+ applicationCode?: string;
39
+ platformCode?: string;
40
+ className?: string;
41
+ providers?: SocialProviderDescriptor[];
42
+ onError?: (error: Error) => void;
43
+ onBeforeLogin?: (provider: SocialProviderDescriptor) => void;
44
+ onRenderButton?: (provider: SocialProviderDescriptor, defaultButton: ReactNode) => ReactNode;
45
+ }
46
+ declare function SocialLoginButtons(props: WebSocialLoginProps): ReactNode;
47
+
34
48
  /**
35
49
  * Web 平台的 fetch 适配器
36
50
  * 将浏览器原生 fetch 包装为符合 NvwaFetch 类型的函数
@@ -63,4 +77,4 @@ declare class Nvwa implements INvwa {
63
77
  constructor(init: NvwaWebInit);
64
78
  }
65
79
 
66
- export { type NvwaWebInit, Nvwa as default, disableIframeHoverInspector, enableIframeHoverInspector, getIframeSourceLocation, localStorage, setupIframeHoverInspector, setupIframeSourceLocationListener, webFetch };
80
+ export { type NvwaWebInit, SocialLoginButtons, type WebSocialLoginProps, Nvwa as default, disableIframeHoverInspector, enableIframeHoverInspector, getIframeSourceLocation, localStorage, setupIframeHoverInspector, setupIframeSourceLocationListener, webFetch };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";var _=Object.defineProperty;var te=Object.getOwnPropertyDescriptor;var re=Object.getOwnPropertyNames;var se=Object.prototype.hasOwnProperty;var ae=(t,e)=>{for(var r in e)_(t,r,{get:e[r],enumerable:!0})},ie=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of re(e))!se.call(t,a)&&a!==r&&_(t,a,{get:()=>e[a],enumerable:!(s=te(e,a))||s.enumerable});return t};var ne=t=>ie(_({},"__esModule",{value:!0}),t);var Ue={};ae(Ue,{default:()=>C,disableIframeHoverInspector:()=>xe,enableIframeHoverInspector:()=>Ie,getIframeSourceLocation:()=>Ne,localStorage:()=>A,setupIframeHoverInspector:()=>_e,setupIframeSourceLocationListener:()=>Ae,webFetch:()=>S});module.exports=ne(Ue);var y=class M{constructor(e){if(this.headerMap=new Map,e){if(e instanceof M)e.forEach((r,s)=>this.set(s,r));else if(Array.isArray(e))for(let[r,s]of e)this.set(r,String(s));else if(typeof e=="object")for(let r of Object.keys(e))this.set(r,String(e[r]))}}append(e,r){let s=e.toLowerCase(),a=this.headerMap.get(s);this.headerMap.set(s,a?`${a}, ${r}`:r)}set(e,r){this.headerMap.set(e.toLowerCase(),String(r))}get(e){return this.headerMap.get(e.toLowerCase())??null}has(e){return this.headerMap.has(e.toLowerCase())}delete(e){this.headerMap.delete(e.toLowerCase())}forEach(e){for(let[r,s]of this.headerMap.entries())e(s,r,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},oe=class W{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof W)this.params=new Map(e.params);else if(Array.isArray(e))for(let[r,s]of e)this.append(r,s);else if(e&&typeof e=="object")for(let[r,s]of Object.entries(e))this.set(r,s)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let r=e.split("&");for(let s of r)if(s){let[a,i]=s.split("=");a&&this.append(decodeURIComponent(a),i?decodeURIComponent(i):"")}}append(e,r){let s=this.params.get(e)||[];s.push(r),this.params.set(e,s)}delete(e){this.params.delete(e)}get(e){let r=this.params.get(e);return r?r[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,r){this.params.set(e,[r])}sort(){let e=Array.from(this.params.entries()).sort(([r],[s])=>r.localeCompare(s));this.params=new Map(e)}toString(){let e=[];for(let[r,s]of this.params.entries())for(let a of s)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(a)}`);return e.join("&")}forEach(e){for(let[r,s]of this.params.entries())for(let a of s)e(a,r,this)}keys(){return this.params.keys()}values(){let e=[];for(let r of this.params.values())e.push(...r);return e[Symbol.iterator]()}entries(){let e=[];for(let[r,s]of this.params.entries())for(let a of s)e.push([r,a]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},I=class x{constructor(e,r){let s;if(e instanceof x)s=e.href;else if(r){let i=r instanceof x?r.href:r;s=this.resolve(i,e)}else s=e;let a=this.parseUrl(s);this.href=s,this.origin=`${a.protocol}//${a.host}`,this.protocol=a.protocol,this.username=a.username,this.password=a.password,this.host=a.host,this.hostname=a.hostname,this.port=a.port,this.pathname=a.pathname,this.search=a.search,this.searchParams=new oe(a.search),this.hash=a.hash}resolve(e,r){if(r.startsWith("http://")||r.startsWith("https://"))return r;if(r.startsWith("//"))return`${this.parseUrl(e).protocol}${r}`;if(r.startsWith("/")){let i=this.parseUrl(e);return`${i.protocol}//${i.host}${r}`}let s=this.parseUrl(e),a=s.pathname.endsWith("/")?s.pathname:s.pathname+"/";return`${s.protocol}//${s.host}${a}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let s=r[2]||"",a=r[4]||"",i=r[5]||"/",n=r[7]?`?${r[7]}`:"",o=r[9]?`#${r[9]}`:"";if(!s&&!a&&!i.startsWith("/")&&!i.includes("/")&&!i.includes("."))throw new TypeError("Invalid URL");let c=a.match(/^([^@]*)@(.+)$/),h="",l="",u=a;if(c){let f=c[1];u=c[2];let w=f.match(/^([^:]*):?(.*)$/);w&&(h=w[1]||"",l=w[2]||"")}let d=u.match(/^([^:]+):?(\d*)$/),m=d?d[1]:u,p=d&&d[2]?d[2]:"";return{protocol:s?`${s}:`:"",username:h,password:l,host:u,hostname:m,port:p,pathname:i,search:n,hash:o}}toString(){let e=this.searchParams.toString(),r=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${r}${this.hash}`}toJSON(){return this.toString()}};var F=class{constructor(t,e){this.bodyData=t,this.status=e?.status??200,this.statusText=e?.statusText??"",this.headers=le(e?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let t=await this.text();return new TextEncoder().encode(t).buffer}};function le(t){return t?new y(t):new y}var he=class{constructor(){this._aborted=!1,this.listeners=new Set,this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let t of Array.from(this.listeners))try{t()}catch{}this.listeners.clear()}}addEventListener(t,e){if(this._aborted){try{e()}catch{}return}this.listeners.add(e)}removeEventListener(t,e){this.listeners.delete(e)}toString(){return"[object AbortSignal]"}},ce=class{constructor(){this._signal=new he}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}},q=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`;return await(await this.http.fetch(r,{method:e.method||"POST",body:e.body,headers:e.headers})).json()}},g="nvwa_current_jwt",v="nvwa_login_token",b="nvwa_user_profile",ue="set-auth-token",de=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},pe={google:{id:"google",name:"Google Login",description:"Sign in with Google account."},github:{id:"github",name:"GitHub Login",description:"Sign in with GitHub account."},"wechat-website":{id:"wechat-website",name:"WeChat QR Login",description:"Sign in with WeChat website QR code."}};function U(t,e){let r=t.socialLogin?.providers?.[e];return r?.enabled?r.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var G=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??de,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},typeof console<"u"&&(console.warn("[NvwaAuth] init baseUrl:",this.baseUrl||"(empty)"),(!this.baseUrl||!this.baseUrl.startsWith("http://")&&!this.baseUrl.startsWith("https://"))&&console.warn("[NvwaAuth] baseUrl \u5E94\u4E3A\u5B8C\u6574\u5730\u5740\uFF08\u5982 https://xxx.nvwa.app\uFF09\uFF0C\u5426\u5219\u5C0F\u7A0B\u5E8F request \u4F1A\u62A5 invalid url"))}async getSocialProviders(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>pe[r]??{id:r,name:r,description:""})}async currentUser(){if(this.storage){let r=await this.storage.get(b);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(b,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(g);if(e!=null)return e;let r=await this.storage.get(v),{data:s}=await this.getToken(r??void 0);return s?.token?(await this.storage.set(g,s.token),s.token):null}let{data:t}=await this.getToken();return t?.token??null}async persistLogin(t,e){if(!this.storage)return;let r=e?.headers.get(ue)?.trim()||t.token||t.session?.token;r&&await this.storage.set(v,r),t.user&&await this.storage.set(b,t.user);let s=r??await this.storage.get(v),{data:a}=await this.getToken(s??void 0);a?.token&&await this.storage.set(g,a.token)}async clearLogin(){this.storage&&(await this.storage.remove(v),await this.storage.remove(b),await this.storage.remove(g))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let s=U(this.integrationProviders,"google");return s&&r.set("oauth_credential_source",s),`${this.url("google/openplatform/login")}?${r.toString()}`}startGoogleOpenPlatformLogin(t,e){let r=this.getGoogleOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGoogleOpenPlatformLogin requires a browser environment with location")}async completeGoogleOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGoogleOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGoogleExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGoogleExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let i=await this.storage.get(g);i!=null&&(e.Authorization=`Bearer ${i}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):null;return!a?.token||!a.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}let e=await this.fetchImpl(this.url("google/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let s=r?JSON.parse(r):null;return s?.sub?{data:s}:{error:{message:"invalid_google_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getGithubOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let s=U(this.integrationProviders,"github");return s&&r.set("oauth_credential_source",s),`${this.url("github/openplatform/login")}?${r.toString()}`}startGithubOpenPlatformLogin(t,e){let r=this.getGithubOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGithubOpenPlatformLogin requires a browser environment with location")}async completeGithubOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGithubOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGithubExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGithubExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let i=await this.storage.get(g);i!=null&&(e.Authorization=`Bearer ${i}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):null;return!a?.token||!a.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}let e=await this.fetchImpl(this.url("github/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let s=r?JSON.parse(r):null;return s?.sub?{data:s}:{error:{message:"invalid_github_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getWechatWebsiteOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("wechat-website/openplatform/login")}?${e.toString()}`}startWechatWebsiteOpenPlatformLogin(t){let e=this.getWechatWebsiteOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;return}throw new Error("startWechatWebsiteOpenPlatformLogin requires a browser environment with location")}async completeWechatWebsiteOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeWechatWebsiteOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithWechatWebsiteExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithWechatWebsiteExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let i=await this.storage.get(g);i!=null&&(e.Authorization=`Bearer ${i}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}let e=await this.fetchImpl(this.url("wechat-website/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let s=r?JSON.parse(r):null;return s?.sub?{data:s}:{error:{message:"invalid_wechat_website_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}url(t){let e=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",e),!e.startsWith("http://")&&!e.startsWith("https://")&&console.warn("[NvwaAuth] URL \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F\u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 Nvwa \u6784\u9020\u65F6\u4F20\u5165\u7684 baseUrl")),e}async getSession(){try{let t={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("session"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return e.ok?{data:await e.json()}:{data:null,error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{data:null,error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signInWithEmail(t,e){try{let r=await this.fetchImpl(this.url("sign-in/email"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify({email:t,password:e})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):void 0;return a&&await this.persistLogin({user:a.user,session:a.session},r),{data:a}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return await this.clearLogin(),e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let i=await this.storage.get(v)??await this.storage.get(g);i!=null&&(e.Authorization=`Bearer ${i}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):void 0;return{data:a?.token!=null?{token:a.token}:void 0}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async signInWithUsername(t,e){let r=await this.postJson("sign-in/username",{username:t,password:e});return r.data&&await this.persistLogin(r.data,r.response),r}async signInWithPhoneNumber(t,e,r){let s=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return s.data&&await this.persistLogin(s.data,s.response),s}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let n=await this.storage.get(g);n!=null&&(r.Authorization=`Bearer ${n}`)}let s=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),a=await s.text();if(!s.ok)return{error:{message:a||s.statusText,status:s.status}};let i=a?JSON.parse(a):null;return!i?.token||!i.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(b,i.user)),{data:i})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let n=await this.storage.get(g);n!=null&&(r.Authorization=`Bearer ${n}`)}let s=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),a=await s.text();if(!s.ok)return{error:{message:a||s.statusText,status:s.status}};let i=a?JSON.parse(a):null;return!i?.token||!i.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(b,i.user)),{data:i})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let n=await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",s=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),a=await s.text();if(!s.ok)return{error:{message:a||s.statusText,status:s.status}};let i=a?JSON.parse(a):null;return!i?.openid||!i.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:i}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let n=await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",s=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),a=await s.text();if(!s.ok)return{error:{message:a||s.statusText,status:s.status}};let i=a?JSON.parse(a):null;return!i?.openid||!i.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:i}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):void 0;return{data:a?.data??a??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}},z=class{constructor(t,e,r){this.storage=t,this.customFetch=e,this.handleUnauthorized=r}async fetch(t,e){return await this.customFetch(t,e)}async fetchWithAuth(t,e){let r=await this.storage.get(g),s=new y(e?.headers);r&&s.set("Authorization",`Bearer ${r}`);let a=e?.method||"GET";if((a==="POST"||a==="PUT"||a==="PATCH")&&e?.body){let n=s.get("Content-Type");(!n||n.includes("text/plain"))&&s.set("Content-Type","application/json")}let i=await this.customFetch(t,{...e,headers:s});if(i.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return i}},me="/storage",ge=me+"/generateUploadUrl",D=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+ge,{method:"POST",body:{fileName:t.name||t.fileName,fileSize:t.size||t.fileSize,fileType:t.type||t.fileType}}),{url:r}=await e.json();if(!r)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");let s=await this.http.fetch(r,{method:"PUT",body:t,headers:new y({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:a}=await s.json();return{url:a.split("?")[0]}}},fe=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},ye=class{constructor(t){var e,r,s;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new y(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(s=t.urlLengthLimit)!==null&&s!==void 0?s:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new y(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let s=this.fetch,a=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{let n=null,o=null,c=null,h=i.status,l=i.statusText;if(i.ok){var u,d;if(r.method!=="HEAD"){var m;let w=await i.text();w===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&!((m=r.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text")?o=w:o=JSON.parse(w))}let p=(u=r.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),f=(d=i.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");p&&f&&f.length>1&&(c=parseInt(f[1])),r.isMaybeSingle&&Array.isArray(o)&&(o.length>1?(n={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,c=null,h=406,l="Not Acceptable"):o.length===1?o=o[0]:o=null)}else{let p=await i.text();try{n=JSON.parse(p),Array.isArray(n)&&i.status===404&&(o=[],n=null,h=200,l="OK")}catch{i.status===404&&p===""?(h=204,l="No Content"):n={message:p}}if(n&&r.shouldThrowOnError)throw new fe(n)}return{error:n,data:o,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(a=a.catch(i=>{var n;let o="",c="",h="",l=i?.cause;if(l){var u,d,m,p;let ee=(u=l?.message)!==null&&u!==void 0?u:"",k=(d=l?.code)!==null&&d!==void 0?d:"";o=`${(m=i?.name)!==null&&m!==void 0?m:"FetchError"}: ${i?.message}`,o+=`
1
+ "use strict";var I=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var ne=Object.getOwnPropertyNames;var oe=Object.prototype.hasOwnProperty;var le=(t,e)=>{for(var r in e)I(t,r,{get:e[r],enumerable:!0})},he=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ne(e))!oe.call(t,i)&&i!==r&&I(t,i,{get:()=>e[i],enumerable:!(s=ae(e,i))||s.enumerable});return t};var ce=t=>he(I({},"__esModule",{value:!0}),t);var De={};le(De,{SocialLoginButtons:()=>qe,default:()=>$,disableIframeHoverInspector:()=>ke,enableIframeHoverInspector:()=>Ae,getIframeSourceLocation:()=>Ue,localStorage:()=>U,setupIframeHoverInspector:()=>Ne,setupIframeSourceLocationListener:()=>Re,webFetch:()=>O});module.exports=ce(De);var y=class q{constructor(e){if(this.headerMap=new Map,e){if(e instanceof q)e.forEach((r,s)=>this.set(s,r));else if(Array.isArray(e))for(let[r,s]of e)this.set(r,String(s));else if(typeof e=="object")for(let r of Object.keys(e))this.set(r,String(e[r]))}}append(e,r){let s=e.toLowerCase(),i=this.headerMap.get(s);this.headerMap.set(s,i?`${i}, ${r}`:r)}set(e,r){this.headerMap.set(e.toLowerCase(),String(r))}get(e){return this.headerMap.get(e.toLowerCase())??null}has(e){return this.headerMap.has(e.toLowerCase())}delete(e){this.headerMap.delete(e.toLowerCase())}forEach(e){for(let[r,s]of this.headerMap.entries())e(s,r,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},ue=class D{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof D)this.params=new Map(e.params);else if(Array.isArray(e))for(let[r,s]of e)this.append(r,s);else if(e&&typeof e=="object")for(let[r,s]of Object.entries(e))this.set(r,s)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let r=e.split("&");for(let s of r)if(s){let[i,a]=s.split("=");i&&this.append(decodeURIComponent(i),a?decodeURIComponent(a):"")}}append(e,r){let s=this.params.get(e)||[];s.push(r),this.params.set(e,s)}delete(e){this.params.delete(e)}get(e){let r=this.params.get(e);return r?r[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,r){this.params.set(e,[r])}sort(){let e=Array.from(this.params.entries()).sort(([r],[s])=>r.localeCompare(s));this.params=new Map(e)}toString(){let e=[];for(let[r,s]of this.params.entries())for(let i of s)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(i)}`);return e.join("&")}forEach(e){for(let[r,s]of this.params.entries())for(let i of s)e(i,r,this)}keys(){return this.params.keys()}values(){let e=[];for(let r of this.params.values())e.push(...r);return e[Symbol.iterator]()}entries(){let e=[];for(let[r,s]of this.params.entries())for(let i of s)e.push([r,i]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},x=class N{constructor(e,r){let s;if(e instanceof N)s=e.href;else if(r){let a=r instanceof N?r.href:r;s=this.resolve(a,e)}else s=e;let i=this.parseUrl(s);this.href=s,this.origin=`${i.protocol}//${i.host}`,this.protocol=i.protocol,this.username=i.username,this.password=i.password,this.host=i.host,this.hostname=i.hostname,this.port=i.port,this.pathname=i.pathname,this.search=i.search,this.searchParams=new ue(i.search),this.hash=i.hash}resolve(e,r){if(r.startsWith("http://")||r.startsWith("https://"))return r;if(r.startsWith("//"))return`${this.parseUrl(e).protocol}${r}`;if(r.startsWith("/")){let a=this.parseUrl(e);return`${a.protocol}//${a.host}${r}`}let s=this.parseUrl(e),i=s.pathname.endsWith("/")?s.pathname:s.pathname+"/";return`${s.protocol}//${s.host}${i}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let s=r[2]||"",i=r[4]||"",a=r[5]||"/",o=r[7]?`?${r[7]}`:"",n=r[9]?`#${r[9]}`:"";if(!s&&!i&&!a.startsWith("/")&&!a.includes("/")&&!a.includes("."))throw new TypeError("Invalid URL");let c=i.match(/^([^@]*)@(.+)$/),h="",l="",u=i;if(c){let f=c[1];u=c[2];let w=f.match(/^([^:]*):?(.*)$/);w&&(h=w[1]||"",l=w[2]||"")}let d=u.match(/^([^:]+):?(\d*)$/),m=d?d[1]:u,p=d&&d[2]?d[2]:"";return{protocol:s?`${s}:`:"",username:h,password:l,host:u,hostname:m,port:p,pathname:a,search:o,hash:n}}toString(){let e=this.searchParams.toString(),r=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${r}${this.hash}`}toJSON(){return this.toString()}};var G=class{constructor(t,e){this.bodyData=t,this.status=e?.status??200,this.statusText=e?.statusText??"",this.headers=de(e?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let t=await this.text();return new TextEncoder().encode(t).buffer}};function de(t){return t?new y(t):new y}var pe=class{constructor(){this._aborted=!1,this.listeners=new Set,this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let t of Array.from(this.listeners))try{t()}catch{}this.listeners.clear()}}addEventListener(t,e){if(this._aborted){try{e()}catch{}return}this.listeners.add(e)}removeEventListener(t,e){this.listeners.delete(e)}toString(){return"[object AbortSignal]"}},me=class{constructor(){this._signal=new pe}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}},B=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`;return await(await this.http.fetch(r,{method:e.method||"POST",body:e.body,headers:e.headers})).json()}},g="nvwa_current_jwt",v="nvwa_login_token",b="nvwa_user_profile",ge="set-auth-token",fe=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},z={google:{id:"google",name:"Google Login",description:"Sign in with Google account."},github:{id:"github",name:"GitHub Login",description:"Sign in with GitHub account."},"wechat-website":{id:"wechat-website",name:"WeChat QR Login",description:"Sign in with WeChat website QR code."},"wechat-miniprogram":{id:"wechat-miniprogram",name:"WeChat Mini Program Login",description:"Sign in with WeChat mini program code."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program Login",description:"Sign in with Alipay mini program code."},"douyin-miniprogram":{id:"douyin-miniprogram",name:"Douyin Mini Program Login",description:"Sign in with Douyin mini program code."}};function j(t){let e=z[t]??{id:t,name:t,description:""},r="unsupported";switch(t){case"google":r="google_openplatform";break;case"github":r="github_openplatform";break;case"wechat-website":r="wechat_website_openplatform";break;case"wechat-miniprogram":r="wechat_miniprogram_code";break;case"alipay-miniprogram":r="alipay_miniprogram_code";break;case"douyin-miniprogram":r="douyin_miniprogram_code";break;default:break}return{id:e.id,type:e.id,name:e.name,description:e.description,loginKind:r}}function H(t,e){let r=t.socialLogin?.providers?.[e];return r?.enabled?r.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var J=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??fe,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},typeof console<"u"&&(console.warn("[NvwaAuth] init baseUrl:",this.baseUrl||"(empty)"),(!this.baseUrl||!this.baseUrl.startsWith("http://")&&!this.baseUrl.startsWith("https://"))&&console.warn("[NvwaAuth] baseUrl \u5E94\u4E3A\u5B8C\u6574\u5730\u5740\uFF08\u5982 https://xxx.nvwa.app\uFF09\uFF0C\u5426\u5219\u5C0F\u7A0B\u5E8F request \u4F1A\u62A5 invalid url"))}async getSocialProviders(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>{let s=z[r]??{id:r,name:r,description:""};return{...s,type:s.id}})}async getSocialProviderDescriptors(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>!!r?.enabled).map(([r])=>j(r))}async getAvailableProviders(t){return this.getSocialProviders(t)}async startSocialLogin(t,e){let r=j(t),s=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!s)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(s,{applicationCode:e?.applicationCode,platformCode:e?.platformCode});return;case"github_openplatform":if(!s)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(s,{applicationCode:e?.applicationCode,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!s)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(s);return;case"wechat_miniprogram_code":if(!e?.miniProgramCode?.trim()||!e.applicationCode?.trim())throw new Error("startSocialLogin requires miniProgramCode and applicationCode for wechat-miniprogram");await this.loginWithWeChatCode(e.miniProgramCode.trim(),e.applicationCode.trim());return;case"alipay_miniprogram_code":if(!e?.miniProgramCode?.trim()||!e.applicationCode?.trim())throw new Error("startSocialLogin requires miniProgramCode and applicationCode for alipay-miniprogram");await this.loginWithAlipayCode(e.miniProgramCode.trim(),e.applicationCode.trim());return;case"douyin_miniprogram_code":throw new Error("startSocialLogin does not support douyin-miniprogram yet");default:throw new Error(`startSocialLogin unsupported provider: ${t}`)}}async currentUser(){if(this.storage){let r=await this.storage.get(b);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(b,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(g);if(e!=null)return e;let r=await this.storage.get(v),{data:s}=await this.getToken(r??void 0);return s?.token?(await this.storage.set(g,s.token),s.token):null}let{data:t}=await this.getToken();return t?.token??null}async persistLogin(t,e){if(!this.storage)return;let r=e?.headers.get(ge)?.trim()||t.token||t.session?.token;r&&await this.storage.set(v,r),t.user&&await this.storage.set(b,t.user);let s=r??await this.storage.get(v),{data:i}=await this.getToken(s??void 0);i?.token&&await this.storage.set(g,i.token)}async clearLogin(){this.storage&&(await this.storage.remove(v),await this.storage.remove(b),await this.storage.remove(g))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let s=H(this.integrationProviders,"google");return s&&r.set("oauth_credential_source",s),`${this.url("google/openplatform/login")}?${r.toString()}`}startGoogleOpenPlatformLogin(t,e){let r=this.getGoogleOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGoogleOpenPlatformLogin requires a browser environment with location")}async completeGoogleOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGoogleOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGoogleExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGoogleExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let i=s?JSON.parse(s):null;return!i?.token||!i.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(b,i.user)),{data:i})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let i=await this.storage.get(g);i!=null&&(t.Authorization=`Bearer ${i}`)}let e=await this.fetchImpl(this.url("google/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let s=r?JSON.parse(r):null;return s?.sub?{data:s}:{error:{message:"invalid_google_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getGithubOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let s=H(this.integrationProviders,"github");return s&&r.set("oauth_credential_source",s),`${this.url("github/openplatform/login")}?${r.toString()}`}startGithubOpenPlatformLogin(t,e){let r=this.getGithubOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGithubOpenPlatformLogin requires a browser environment with location")}async completeGithubOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGithubOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGithubExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGithubExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let i=s?JSON.parse(s):null;return!i?.token||!i.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(b,i.user)),{data:i})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let i=await this.storage.get(g);i!=null&&(t.Authorization=`Bearer ${i}`)}let e=await this.fetchImpl(this.url("github/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let s=r?JSON.parse(r):null;return s?.sub?{data:s}:{error:{message:"invalid_github_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getWechatWebsiteOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("wechat-website/openplatform/login")}?${e.toString()}`}startWechatWebsiteOpenPlatformLogin(t){let e=this.getWechatWebsiteOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;return}throw new Error("startWechatWebsiteOpenPlatformLogin requires a browser environment with location")}async completeWechatWebsiteOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeWechatWebsiteOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithWechatWebsiteExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithWechatWebsiteExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let i=s?JSON.parse(s):null;return!i?.token||!i.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(b,i.user)),{data:i})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let i=await this.storage.get(g);i!=null&&(t.Authorization=`Bearer ${i}`)}let e=await this.fetchImpl(this.url("wechat-website/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let s=r?JSON.parse(r):null;return s?.sub?{data:s}:{error:{message:"invalid_wechat_website_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}url(t){let e=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",e),!e.startsWith("http://")&&!e.startsWith("https://")&&console.warn("[NvwaAuth] URL \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F\u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 Nvwa \u6784\u9020\u65F6\u4F20\u5165\u7684 baseUrl")),e}async getSession(){try{let t={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("session"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return e.ok?{data:await e.json()}:{data:null,error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{data:null,error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signInWithEmail(t,e){try{let r=await this.fetchImpl(this.url("sign-in/email"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify({email:t,password:e})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let i=s?JSON.parse(s):void 0;return i&&await this.persistLogin({user:i.user,session:i.session},r),{data:i}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return await this.clearLogin(),e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let a=await this.storage.get(v)??await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let i=s?JSON.parse(s):void 0;return{data:i?.token!=null?{token:i.token}:void 0}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async signInWithUsername(t,e){let r=await this.postJson("sign-in/username",{username:t,password:e});return r.data&&await this.persistLogin(r.data,r.response),r}async signInWithPhoneNumber(t,e,r){let s=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return s.data&&await this.persistLogin(s.data,s.response),s}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(g);o!=null&&(r.Authorization=`Bearer ${o}`)}let s=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),i=await s.text();if(!s.ok)return{error:{message:i||s.statusText,status:s.status}};let a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(g);o!=null&&(r.Authorization=`Bearer ${o}`)}let s=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),i=await s.text();if(!s.ok)return{error:{message:i||s.statusText,status:s.status}};let a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(g);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",s=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await s.text();if(!s.ok)return{error:{message:i||s.statusText,status:s.status}};let a=i?JSON.parse(i):null;return!a?.openid||!a.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(g);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",s=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await s.text();if(!s.ok)return{error:{message:i||s.statusText,status:s.status}};let a=i?JSON.parse(i):null;return!a?.openid||!a.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let i=s?JSON.parse(s):void 0;return{data:i?.data??i??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}},K=class{constructor(t,e,r){this.storage=t,this.customFetch=e,this.handleUnauthorized=r}async fetch(t,e){return await this.customFetch(t,e)}async fetchWithAuth(t,e){let r=await this.storage.get(g),s=new y(e?.headers);r&&s.set("Authorization",`Bearer ${r}`);let i=e?.method||"GET";if((i==="POST"||i==="PUT"||i==="PATCH")&&e?.body){let o=s.get("Content-Type");(!o||o.includes("text/plain"))&&s.set("Content-Type","application/json")}let a=await this.customFetch(t,{...e,headers:s});if(a.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return a}},ye="/storage",we=ye+"/generateUploadUrl",V=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+we,{method:"POST",body:{fileName:t.name||t.fileName,fileSize:t.size||t.fileSize,fileType:t.type||t.fileType}}),{url:r}=await e.json();if(!r)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");let s=await this.http.fetch(r,{method:"PUT",body:t,headers:new y({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:i}=await s.json();return{url:i.split("?")[0]}}},ve=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},be=class{constructor(t){var e,r,s;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new y(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(s=t.urlLengthLimit)!==null&&s!==void 0?s:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new y(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let s=this.fetch,i=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async a=>{let o=null,n=null,c=null,h=a.status,l=a.statusText;if(a.ok){var u,d;if(r.method!=="HEAD"){var m;let w=await a.text();w===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&!((m=r.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text")?n=w:n=JSON.parse(w))}let p=(u=r.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),f=(d=a.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");p&&f&&f.length>1&&(c=parseInt(f[1])),r.isMaybeSingle&&Array.isArray(n)&&(n.length>1?(o={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,c=null,h=406,l="Not Acceptable"):n.length===1?n=n[0]:n=null)}else{let p=await a.text();try{o=JSON.parse(p),Array.isArray(o)&&a.status===404&&(n=[],o=null,h=200,l="OK")}catch{a.status===404&&p===""?(h=204,l="No Content"):o={message:p}}if(o&&r.shouldThrowOnError)throw new ve(o)}return{error:o,data:n,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(i=i.catch(a=>{var o;let n="",c="",h="",l=a?.cause;if(l){var u,d,m,p;let ie=(u=l?.message)!==null&&u!==void 0?u:"",R=(d=l?.code)!==null&&d!==void 0?d:"";n=`${(m=a?.name)!==null&&m!==void 0?m:"FetchError"}: ${a?.message}`,n+=`
2
2
 
3
- Caused by: ${(p=l?.name)!==null&&p!==void 0?p:"Error"}: ${ee}`,k&&(o+=` (${k})`),l?.stack&&(o+=`
4
- ${l.stack}`)}else{var f;o=(f=i?.stack)!==null&&f!==void 0?f:""}let w=this.url.toString().length;return i?.name==="AbortError"||i?.code==="ABORT_ERR"?(h="",c="Request was aborted (timeout or manual cancellation)",w>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${w} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(l?.name==="HeadersOverflowError"||l?.code==="UND_ERR_HEADERS_OVERFLOW")&&(h="",c="HTTP headers exceeded server limits (typically 16KB)",w>this.urlLengthLimit&&(c+=`. Your request URL is ${w} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(n=i?.name)!==null&&n!==void 0?n:"FetchError"}: ${i?.message}`,details:o,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),a.then(t,e)}returns(){return this}overrideTypes(){return this}},we=class extends ye{select(t){let e=!1,r=(t??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:s,referencedTable:a=s}={}){let i=a?`${a}.order`:"order",n=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${n?`${n},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){let a=typeof s>"u"?"offset":`${s}.offset`,i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(a,`${t}`),this.url.searchParams.set(i,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:s=!1,wal:a=!1,format:i="text"}={}){var n;let o=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,a?"wal":null].filter(Boolean).join("|"),c=(n=this.headers.get("Accept"))!==null&&n!==void 0?n:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${c}"; options=${o};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},R=new RegExp("[,()]"),E=class extends we{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(s=>typeof s=="string"&&R.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(s=>typeof s=="string"&&R.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:s}={}){let a="";s==="plain"?a="pl":s==="phrase"?a="ph":s==="websearch"&&(a="w");let i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${a}fts${i}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},ve=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:a=8e3}){this.url=t,this.headers=new y(e),this.schema=r,this.fetch=s,this.urlLengthLimit=a}cloneRequestState(){return{url:new I(this.url.toString()),headers:new y(this.headers)}}select(t,e){let{head:r=!1,count:s}=e??{},a=r?"HEAD":"GET",i=!1,n=(t??"*").split("").map(h=>/\s/.test(h)&&!i?"":(h==='"'&&(i=!i),h)).join(""),{url:o,headers:c}=this.cloneRequestState();return o.searchParams.set("select",n),s&&c.append("Prefer",`count=${s}`),new E({method:a,url:o,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;let a="POST",{url:i,headers:n}=this.cloneRequestState();if(e&&n.append("Prefer",`count=${e}`),r||n.append("Prefer","missing=default"),Array.isArray(t)){let o=t.reduce((c,h)=>c.concat(Object.keys(h)),[]);if(o.length>0){let c=[...new Set(o)].map(h=>`"${h}"`);i.searchParams.set("columns",c.join(","))}}return new E({method:a,url:i,headers:n,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:a=!0}={}){var i;let n="POST",{url:o,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),s&&c.append("Prefer",`count=${s}`),a||c.append("Prefer","missing=default"),Array.isArray(t)){let h=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(h.length>0){let l=[...new Set(h)].map(u=>`"${u}"`);o.searchParams.set("columns",l.join(","))}}return new E({method:n,url:o,headers:c,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let s="PATCH",{url:a,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new E({method:s,url:a,headers:i,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;let r="DELETE",{url:s,headers:a}=this.cloneRequestState();return t&&a.append("Prefer",`count=${t}`),new E({method:r,url:s,headers:a,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function P(t){"@babel/helpers - typeof";return P=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},P(t)}function be(t,e){if(P(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(P(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ee(t){var e=be(t,"string");return P(e)=="symbol"?e:e+""}function Pe(t,e,r){return(e=Ee(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function j(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),r.push.apply(r,s)}return r}function L(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?j(Object(r),!0).forEach(function(s){Pe(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):j(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var Oe=class J{constructor(e,{headers:r={},schema:s,fetch:a,timeout:i,urlLengthLimit:n=8e3}={}){this.url=e,this.headers=new y(r),this.schemaName=s,this.urlLengthLimit=n;let o=a??globalThis.fetch;i!==void 0&&i>0?this.fetch=(c,h)=>{let l=new ce,u=setTimeout(()=>l.abort(),i),d=h?.signal;if(d){if(d.aborted)return clearTimeout(u),o(c,h);let m=()=>{clearTimeout(u),l.abort()};return d.addEventListener("abort",m,{once:!0}),o(c,L(L({},h),{},{signal:l.signal})).finally(()=>{clearTimeout(u),d.removeEventListener("abort",m)})}return o(c,L(L({},h),{},{signal:l.signal})).finally(()=>clearTimeout(u))}:this.fetch=o}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new ve(new I(`${this.url}/${e}`),{headers:new y(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new J(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:s=!1,get:a=!1,count:i}={}){var n;let o,c=new I(`${this.url}/rpc/${e}`),h,l=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(l)),u=s&&Object.values(r).some(l);u?(o="POST",h=r):s||a?(o=s?"HEAD":"GET",Object.entries(r).filter(([m,p])=>p!==void 0).map(([m,p])=>[m,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([m,p])=>{c.searchParams.append(m,p)})):(o="POST",h=r);let d=new y(this.headers);return u?d.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&d.set("Prefer",`count=${i}`),new E({method:o,url:c,headers:d,schema:this.schemaName,body:h,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}},Se="/entities",B=(t,e)=>new Oe(t+Se,{fetch:e.fetchWithAuth.bind(e)}),K=class{constructor(){this.hoverOverlay=null,this.selectedOverlay=null,this.tooltip=null,this.hoverElement=null,this.selectedElement=null,this.hoverUpdateHandler=null,this.selectedUpdateHandler=null,this.createStyles()}createStyles(){if(document.getElementById("__nvwa-inspector-overlay-style"))return;let t=document.createElement("style");t.id="__nvwa-inspector-overlay-style",t.textContent=`
3
+ Caused by: ${(p=l?.name)!==null&&p!==void 0?p:"Error"}: ${ie}`,R&&(n+=` (${R})`),l?.stack&&(n+=`
4
+ ${l.stack}`)}else{var f;n=(f=a?.stack)!==null&&f!==void 0?f:""}let w=this.url.toString().length;return a?.name==="AbortError"||a?.code==="ABORT_ERR"?(h="",c="Request was aborted (timeout or manual cancellation)",w>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${w} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(l?.name==="HeadersOverflowError"||l?.code==="UND_ERR_HEADERS_OVERFLOW")&&(h="",c="HTTP headers exceeded server limits (typically 16KB)",w>this.urlLengthLimit&&(c+=`. Your request URL is ${w} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(o=a?.name)!==null&&o!==void 0?o:"FetchError"}: ${a?.message}`,details:n,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),i.then(t,e)}returns(){return this}overrideTypes(){return this}},Ee=class extends be{select(t){let e=!1,r=(t??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:s,referencedTable:i=s}={}){let a=i?`${i}.order`:"order",o=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){let i=typeof s>"u"?"offset":`${s}.offset`,a=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${t}`),this.url.searchParams.set(a,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:s=!1,wal:i=!1,format:a="text"}={}){var o;let n=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),c=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${a}; for="${c}"; options=${n};`),a==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},W=new RegExp("[,()]"),P=class extends Ee{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(s=>typeof s=="string"&&W.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(s=>typeof s=="string"&&W.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:s}={}){let i="";s==="plain"?i="pl":s==="phrase"?i="ph":s==="websearch"&&(i="w");let a=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${i}fts${a}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Pe=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:i=8e3}){this.url=t,this.headers=new y(e),this.schema=r,this.fetch=s,this.urlLengthLimit=i}cloneRequestState(){return{url:new x(this.url.toString()),headers:new y(this.headers)}}select(t,e){let{head:r=!1,count:s}=e??{},i=r?"HEAD":"GET",a=!1,o=(t??"*").split("").map(h=>/\s/.test(h)&&!a?"":(h==='"'&&(a=!a),h)).join(""),{url:n,headers:c}=this.cloneRequestState();return n.searchParams.set("select",o),s&&c.append("Prefer",`count=${s}`),new P({method:i,url:n,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;let i="POST",{url:a,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),r||o.append("Prefer","missing=default"),Array.isArray(t)){let n=t.reduce((c,h)=>c.concat(Object.keys(h)),[]);if(n.length>0){let c=[...new Set(n)].map(h=>`"${h}"`);a.searchParams.set("columns",c.join(","))}}return new P({method:i,url:a,headers:o,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:i=!0}={}){var a;let o="POST",{url:n,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&n.searchParams.set("on_conflict",e),s&&c.append("Prefer",`count=${s}`),i||c.append("Prefer","missing=default"),Array.isArray(t)){let h=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(h.length>0){let l=[...new Set(h)].map(u=>`"${u}"`);n.searchParams.set("columns",l.join(","))}}return new P({method:o,url:n,headers:c,schema:this.schema,body:t,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let s="PATCH",{url:i,headers:a}=this.cloneRequestState();return e&&a.append("Prefer",`count=${e}`),new P({method:s,url:i,headers:a,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;let r="DELETE",{url:s,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new P({method:r,url:s,headers:i,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function L(t){"@babel/helpers - typeof";return L=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},L(t)}function Se(t,e){if(L(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(L(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Le(t){var e=Se(t,"string");return L(e)=="symbol"?e:e+""}function Oe(t,e,r){return(e=Le(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function M(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,s)}return r}function C(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?M(Object(r),!0).forEach(function(s){Oe(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):M(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var Ce=class Y{constructor(e,{headers:r={},schema:s,fetch:i,timeout:a,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new y(r),this.schemaName=s,this.urlLengthLimit=o;let n=i??globalThis.fetch;a!==void 0&&a>0?this.fetch=(c,h)=>{let l=new me,u=setTimeout(()=>l.abort(),a),d=h?.signal;if(d){if(d.aborted)return clearTimeout(u),n(c,h);let m=()=>{clearTimeout(u),l.abort()};return d.addEventListener("abort",m,{once:!0}),n(c,C(C({},h),{},{signal:l.signal})).finally(()=>{clearTimeout(u),d.removeEventListener("abort",m)})}return n(c,C(C({},h),{},{signal:l.signal})).finally(()=>clearTimeout(u))}:this.fetch=n}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Pe(new x(`${this.url}/${e}`),{headers:new y(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Y(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:s=!1,get:i=!1,count:a}={}){var o;let n,c=new x(`${this.url}/rpc/${e}`),h,l=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(l)),u=s&&Object.values(r).some(l);u?(n="POST",h=r):s||i?(n=s?"HEAD":"GET",Object.entries(r).filter(([m,p])=>p!==void 0).map(([m,p])=>[m,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([m,p])=>{c.searchParams.append(m,p)})):(n="POST",h=r);let d=new y(this.headers);return u?d.set("Prefer",a?`count=${a},return=minimal`:"return=minimal"):a&&d.set("Prefer",`count=${a}`),new P({method:n,url:c,headers:d,schema:this.schemaName,body:h,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}},Te="/entities",Q=(t,e)=>new Ce(t+Te,{fetch:e.fetchWithAuth.bind(e)}),X=class{constructor(){this.hoverOverlay=null,this.selectedOverlay=null,this.tooltip=null,this.hoverElement=null,this.selectedElement=null,this.hoverUpdateHandler=null,this.selectedUpdateHandler=null,this.createStyles()}createStyles(){if(document.getElementById("__nvwa-inspector-overlay-style"))return;let t=document.createElement("style");t.id="__nvwa-inspector-overlay-style",t.textContent=`
5
5
  .__nvwa-inspector-overlay {
6
6
  position: absolute;
7
7
  pointer-events: none;
@@ -33,4 +33,4 @@ ${l.stack}`)}else{var f;o=(f=i?.stack)!==null&&f!==void 0?f:""}let w=this.url.to
33
33
  max-width: 400px;
34
34
  word-break: break-all;
35
35
  }
36
- `,document.head.appendChild(t)}createTooltip(){return this.tooltip?this.tooltip:(this.tooltip=document.createElement("div"),this.tooltip.id="__nvwa-inspector-tooltip",document.body.appendChild(this.tooltip),this.tooltip)}createOverlay(t){let e=document.createElement("div");return e.className=`__nvwa-inspector-overlay __nvwa-inspector-overlay-${t}`,document.body.appendChild(e),e}updateOverlayPosition(t,e){if(!e.isConnected)return;let r=e.getBoundingClientRect(),s=window.scrollX||window.pageXOffset,a=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+s}px`,t.style.top=`${r.top+a}px`,t.style.width=`${r.width}px`,t.style.height=`${r.height}px`,t.style.display="block"):t.style.display="none"}removeOverlay(t){t&&t.parentNode&&t.parentNode.removeChild(t)}highlightElement(t,e){if(!t.isConnected)return;if(this.hoverElement===t&&this.hoverOverlay){this.updateOverlayPosition(this.hoverOverlay,t);let n=this.createTooltip();e?n.textContent=e:n.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,n.style.display="block";let o=t.getBoundingClientRect();n.style.left=`${o.left+window.scrollX}px`,n.style.top=`${o.top+window.scrollY-n.offsetHeight-8}px`,o.top<n.offsetHeight+8&&(n.style.top=`${o.bottom+window.scrollY+8}px`);return}this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null);let r=this.createOverlay("hover");this.updateOverlayPosition(r,t),this.hoverOverlay=r,this.hoverElement=t;let s=()=>{this.hoverOverlay&&this.hoverElement&&this.hoverElement.isConnected&&this.updateOverlayPosition(this.hoverOverlay,this.hoverElement)};this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler)),this.hoverUpdateHandler=s,window.addEventListener("scroll",s,!0),window.addEventListener("resize",s);let a=this.createTooltip();e?a.textContent=e:a.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,a.style.display="block";let i=t.getBoundingClientRect();a.style.left=`${i.left+window.scrollX}px`,a.style.top=`${i.top+window.scrollY-a.offsetHeight-8}px`,i.top<a.offsetHeight+8&&(a.style.top=`${i.bottom+window.scrollY+8}px`)}selectElement(t,e){if(!t.isConnected)return;if(this.selectedElement===t&&this.selectedOverlay){this.updateOverlayPosition(this.selectedOverlay,t);return}this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null);let r=this.createOverlay("selected");this.updateOverlayPosition(r,t),this.selectedOverlay=r,this.selectedElement=t;let s=()=>{this.selectedOverlay&&this.selectedElement&&this.selectedElement.isConnected&&this.updateOverlayPosition(this.selectedOverlay,this.selectedElement)};this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler)),this.selectedUpdateHandler=s,window.addEventListener("scroll",s,!0),window.addEventListener("resize",s)}removeHighlight(){this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null),this.hoverElement&&(this.hoverElement=null),this.tooltip&&(this.tooltip.style.display="none"),this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler),this.hoverUpdateHandler=null)}clearSelection(){this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null),this.selectedElement&&(this.selectedElement=null),this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler),this.selectedUpdateHandler=null)}cleanup(){this.removeHighlight(),this.clearSelection(),this.tooltip&&this.tooltip.parentNode&&(this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null);let t=document.getElementById("__nvwa-inspector-overlay-style");t&&t.parentNode&&t.parentNode.removeChild(t)}};function V(t="root"){if(typeof document>"u")return null;let e=document.getElementById(t)||document.body;if(!e)return null;let r=e.querySelector("[data-source-location]");if(r){let s=r.getAttribute("data-source-location");if(s)return s}if(e.firstElementChild){let s=e.firstElementChild.getAttribute("data-source-location");if(s)return s}return null}var Le={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},wechat_partner:{id:"wechat_partner",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},alipay:{id:"alipay",name:"Alipay",description:"Alipay payment."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function Y(t){let e=t;if(typeof e.kind=="string")return e;if(typeof e.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:e.tradeNO};if(typeof e.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:e.clientSecret};if(typeof e.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:e.redirectUrl};if(typeof e.formHtml=="string")return{kind:"alipay_page",formHtml:e.formHtml};if(typeof e.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:e.codeUrl};let r=e.jsapiPayParams??e;return typeof r.timeStamp=="string"&&typeof r.nonceStr=="string"&&typeof r.package=="string"&&typeof r.paySign=="string"&&typeof r.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:r.appId,timeStamp:r.timeStamp,nonceStr:r.nonceStr,package:r.package,signType:r.signType??"RSA",paySign:r.paySign}}:null}async function Q(t,e){let r=t.payment?.providers??{};return Object.entries(r).filter(([,s])=>s.enabled).map(([s])=>Le[s]??{id:s,name:s,description:""})}function T(t){return t&&typeof t=="object"?t:{}}function Te(t){let e=T(t),r=e.enabled===!0,s=String(e.oauthCredentialSource??"").toLowerCase();return s?{enabled:r,oauthCredentialSource:s==="custom"?"custom":"nvwa_default"}:{enabled:r}}function H(t){let e=T(t),r=T(e.providers),s={};for(let[a,i]of Object.entries(r))s[a]=Te(i);return{providers:s}}function X(t){let e=T(t);return{socialLogin:H(e.socialLogin),payment:H(e.payment)}}var $=class{constructor(){this.prefix="nvwa_"}getKey(e){return`${this.prefix}${e}`}async get(e){try{let r=this.getKey(e),s=localStorage.getItem(r);if(!s)return null;let a=JSON.parse(s);return a.expires&&Date.now()>a.expires?(await this.remove(e),null):a.value}catch(r){return console.error("WebStorageService get error:",r),null}}async set(e,r,s){try{let a=this.getKey(e),i={value:r,expires:s?Date.now()+s*1e3:null,timestamp:Date.now()};localStorage.setItem(a,JSON.stringify(i))}catch(a){throw console.error("WebStorageService set error:",a),a}}async remove(e){try{let r=this.getKey(e);localStorage.removeItem(r)}catch(r){throw console.error("WebStorageService remove error:",r),r}}async clear(){try{Object.keys(localStorage).filter(s=>s.startsWith(this.prefix)).forEach(s=>{localStorage.removeItem(s)})}catch(e){throw console.error("WebStorageService clear error:",e),e}}};var $e=(t,e)=>{let r;if(typeof t=="string")r=t;else if(t&&typeof t.toString=="function")r=t.toString();else if(t?.url)r=t.url;else throw new Error("Invalid input for webFetch");let s;if(e?.headers){let i=e.headers;if(i instanceof y){let n={};i.forEach((o,c)=>{n[c]=o}),s=n}else if(Array.isArray(i)){let n=[];for(let o of i)Array.isArray(o)&&o.length>=2&&n.push([String(o[0]),String(o[1])]);s=n}else typeof i=="object"&&(s=i)}let a={method:e?.method||"GET",headers:s,body:e?.body,credentials:e?.credentials};return e?.signal&&(a.signal=e.signal),globalThis.fetch(r,a).then(async i=>{let n=i.headers.get("content-type")||"",o;if(n.includes("application/json"))o=await i.json();else{let h=await i.text();try{o=JSON.parse(h)}catch{o=h}}let c=new y;return i.headers.forEach((h,l)=>{c.set(l,h)}),new F(o,{status:i.status,statusText:i.statusText,headers:c})})},S=$e;function Ce(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}var N={async requestPayment(t,e){let r=Y(t);if(r?.kind==="redirect_url"){window.location.href=r.redirectUrl;return}if(r?.kind==="wechat_native_qr"){let a=Ce(r.codeUrl);window.open(a,"_blank","noopener,noreferrer");return}if(r?.kind==="alipay_page"){let a=window.open("","_blank");a&&(a.document.write(r.formHtml),a.document.close());return}let s=new Error("requestPayment: unsupported payParams for Desktop-web");throw e?.onFailure?.(s),s}};function Z(t){let e=async r=>await Q(t,r);return{...N,getAvailableProviders:e,getProviders:e}}function _e(){if(typeof window>"u"||window===window.parent)return;let t=!1,e=new K;function r(h){if(!h)return!1;let l=h.toLowerCase();return l.includes("/components/")||l.includes("\\components\\")}function s(h){let l=h,u=null;for(;l;){let d=l.getAttribute("data-source-location");if(d)if(r(d)){u||(u=d),l=l.parentElement;continue}else return d;l=l.parentElement}return u}let a=null;function i(h){t&&(a!==null&&cancelAnimationFrame(a),a=requestAnimationFrame(()=>{let l=h.target;if(!l||l===document.body||l===document.documentElement){e.removeHighlight();return}if(l.tagName.toLowerCase()==="img"){let p=s(l);e.highlightElement(l,p);let f={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:p,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(f,"*");return}let u=l,d=s(l);if(!d){let p=l.parentElement;for(;p&&p!==document.body&&p!==document.documentElement;){let f=s(p);if(f){u=p,d=f;break}p=p.parentElement}}e.highlightElement(u,d);let m={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:d,elementInfo:{tagName:u.tagName.toLowerCase(),className:u.className||"",id:u.id||""}};window.parent.postMessage(m,"*")}))}function n(){if(!t)return;e.removeHighlight();let h={type:"HOVER_INSPECTOR_ELEMENT_LEAVE"};window.parent.postMessage(h,"*")}function o(h){if(!t)return;h.preventDefault(),h.stopPropagation();let l=h.target;if(!l||l===document.body||l===document.documentElement)return;let u=s(l);e.selectElement(l,u);let d={type:"HOVER_INSPECTOR_ELEMENT_SELECT",sourceLocation:u,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(d,"*")}function c(h){h.data?.type==="HOVER_INSPECTOR_ENABLE"?(t=!0,document.addEventListener("mousemove",i),document.addEventListener("mouseleave",n),document.addEventListener("click",o,!0)):h.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",i),document.removeEventListener("mouseleave",n),document.removeEventListener("click",o,!0),e.removeHighlight(),e.clearSelection())}return window.addEventListener("message",c),()=>{window.removeEventListener("message",c),document.removeEventListener("mousemove",i),document.removeEventListener("mouseleave",n),document.removeEventListener("click",o,!0),e.cleanup()}}function Ie(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function xe(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function Ne(t,e,r=5e3){return new Promise((s,a)=>{if(!t||!t.contentWindow){a(new Error("Invalid iframe element"));return}let i=`source-location-${Date.now()}-${Math.random()}`,n=setTimeout(()=>{window.removeEventListener("message",o),a(new Error("Request timeout"))},r),o=h=>{h.origin===e&&h.data?.type==="GET_SOURCE_LOCATION_RESPONSE"&&h.data?.requestId===i&&(clearTimeout(n),window.removeEventListener("message",o),h.data.error?a(new Error(h.data.error)):s(h.data.sourceLocation||null))};window.addEventListener("message",o);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:i};try{t.contentWindow.postMessage(c,e)}catch(h){clearTimeout(n),window.removeEventListener("message",o),a(h)}})}function Ae(){if(typeof window>"u"||window===window.parent)return;let t=e=>{if(e.data?.type==="GET_SOURCE_LOCATION_REQUEST")try{let s={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:ke(),requestId:e.data.requestId};window.parent.postMessage(s,e.origin)}catch(r){let s={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:null,error:r instanceof Error?r.message:"Unknown error",requestId:e.data.requestId};window.parent.postMessage(s,e.origin)}};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}}function ke(){return V("root")}var A=new $,C=class{constructor(e){this.endpointType="Desktop-web";this.payment=N;let{baseUrl:r,handleUnauthorized:s,applicationCode:a,platformType:i,integrationProviders:n}=e,o=a.trim();if(!o)throw new Error("Nvwa: applicationCode \u4E0D\u80FD\u4E3A\u7A7A");this.applicationCode=o;let c=i.trim();if(!c)throw new Error("Nvwa: platformType \u4E0D\u80FD\u4E3A\u7A7A");this.platformType=c,this.integrationProviders=X(n),this.auth=new G(r,{fetchImpl:S,storage:A,integrationProviders:this.integrationProviders}),this.httpClient=new z(A,S,s),this.fileStorage=new D(r,this.httpClient),this.entities=B(r,this.httpClient),this.functions=new q(this.httpClient,r),this.payment=Z(this.integrationProviders)}};0&&(module.exports={disableIframeHoverInspector,enableIframeHoverInspector,getIframeSourceLocation,localStorage,setupIframeHoverInspector,setupIframeSourceLocationListener,webFetch});
36
+ `,document.head.appendChild(t)}createTooltip(){return this.tooltip?this.tooltip:(this.tooltip=document.createElement("div"),this.tooltip.id="__nvwa-inspector-tooltip",document.body.appendChild(this.tooltip),this.tooltip)}createOverlay(t){let e=document.createElement("div");return e.className=`__nvwa-inspector-overlay __nvwa-inspector-overlay-${t}`,document.body.appendChild(e),e}updateOverlayPosition(t,e){if(!e.isConnected)return;let r=e.getBoundingClientRect(),s=window.scrollX||window.pageXOffset,i=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+s}px`,t.style.top=`${r.top+i}px`,t.style.width=`${r.width}px`,t.style.height=`${r.height}px`,t.style.display="block"):t.style.display="none"}removeOverlay(t){t&&t.parentNode&&t.parentNode.removeChild(t)}highlightElement(t,e){if(!t.isConnected)return;if(this.hoverElement===t&&this.hoverOverlay){this.updateOverlayPosition(this.hoverOverlay,t);let o=this.createTooltip();e?o.textContent=e:o.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,o.style.display="block";let n=t.getBoundingClientRect();o.style.left=`${n.left+window.scrollX}px`,o.style.top=`${n.top+window.scrollY-o.offsetHeight-8}px`,n.top<o.offsetHeight+8&&(o.style.top=`${n.bottom+window.scrollY+8}px`);return}this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null);let r=this.createOverlay("hover");this.updateOverlayPosition(r,t),this.hoverOverlay=r,this.hoverElement=t;let s=()=>{this.hoverOverlay&&this.hoverElement&&this.hoverElement.isConnected&&this.updateOverlayPosition(this.hoverOverlay,this.hoverElement)};this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler)),this.hoverUpdateHandler=s,window.addEventListener("scroll",s,!0),window.addEventListener("resize",s);let i=this.createTooltip();e?i.textContent=e:i.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,i.style.display="block";let a=t.getBoundingClientRect();i.style.left=`${a.left+window.scrollX}px`,i.style.top=`${a.top+window.scrollY-i.offsetHeight-8}px`,a.top<i.offsetHeight+8&&(i.style.top=`${a.bottom+window.scrollY+8}px`)}selectElement(t,e){if(!t.isConnected)return;if(this.selectedElement===t&&this.selectedOverlay){this.updateOverlayPosition(this.selectedOverlay,t);return}this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null);let r=this.createOverlay("selected");this.updateOverlayPosition(r,t),this.selectedOverlay=r,this.selectedElement=t;let s=()=>{this.selectedOverlay&&this.selectedElement&&this.selectedElement.isConnected&&this.updateOverlayPosition(this.selectedOverlay,this.selectedElement)};this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler)),this.selectedUpdateHandler=s,window.addEventListener("scroll",s,!0),window.addEventListener("resize",s)}removeHighlight(){this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null),this.hoverElement&&(this.hoverElement=null),this.tooltip&&(this.tooltip.style.display="none"),this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler),this.hoverUpdateHandler=null)}clearSelection(){this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null),this.selectedElement&&(this.selectedElement=null),this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler),this.selectedUpdateHandler=null)}cleanup(){this.removeHighlight(),this.clearSelection(),this.tooltip&&this.tooltip.parentNode&&(this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null);let t=document.getElementById("__nvwa-inspector-overlay-style");t&&t.parentNode&&t.parentNode.removeChild(t)}};function Z(t="root"){if(typeof document>"u")return null;let e=document.getElementById(t)||document.body;if(!e)return null;let r=e.querySelector("[data-source-location]");if(r){let s=r.getAttribute("data-source-location");if(s)return s}if(e.firstElementChild){let s=e.firstElementChild.getAttribute("data-source-location");if(s)return s}return null}var _e={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},wechat_partner:{id:"wechat_partner",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},alipay:{id:"alipay",name:"Alipay",description:"Alipay payment."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function ee(t){let e=t;if(typeof e.kind=="string")return e;if(typeof e.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:e.tradeNO};if(typeof e.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:e.clientSecret};if(typeof e.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:e.redirectUrl};if(typeof e.formHtml=="string")return{kind:"alipay_page",formHtml:e.formHtml};if(typeof e.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:e.codeUrl};let r=e.jsapiPayParams??e;return typeof r.timeStamp=="string"&&typeof r.nonceStr=="string"&&typeof r.package=="string"&&typeof r.paySign=="string"&&typeof r.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:r.appId,timeStamp:r.timeStamp,nonceStr:r.nonceStr,package:r.package,signType:r.signType??"RSA",paySign:r.paySign}}:null}async function te(t,e){let r=t.payment?.providers??{};return Object.entries(r).filter(([,s])=>s.enabled).map(([s])=>{let i=_e[s]??{id:s,name:s,description:""};return{...i,type:i.id}})}function T(t){return t&&typeof t=="object"?t:{}}function $e(t){let e=T(t),r=e.enabled===!0,s=String(e.oauthCredentialSource??"").toLowerCase();return s?{enabled:r,oauthCredentialSource:s==="custom"?"custom":"nvwa_default"}:{enabled:r}}function F(t){let e=T(t),r=T(e.providers),s={};for(let[i,a]of Object.entries(r))s[i]=$e(a);return{providers:s}}function re(t){let e=T(t);return{socialLogin:F(e.socialLogin),payment:F(e.payment)}}var _=class{constructor(){this.prefix="nvwa_"}getKey(e){return`${this.prefix}${e}`}async get(e){try{let r=this.getKey(e),s=localStorage.getItem(r);if(!s)return null;let i=JSON.parse(s);return i.expires&&Date.now()>i.expires?(await this.remove(e),null):i.value}catch(r){return console.error("WebStorageService get error:",r),null}}async set(e,r,s){try{let i=this.getKey(e),a={value:r,expires:s?Date.now()+s*1e3:null,timestamp:Date.now()};localStorage.setItem(i,JSON.stringify(a))}catch(i){throw console.error("WebStorageService set error:",i),i}}async remove(e){try{let r=this.getKey(e);localStorage.removeItem(r)}catch(r){throw console.error("WebStorageService remove error:",r),r}}async clear(){try{Object.keys(localStorage).filter(s=>s.startsWith(this.prefix)).forEach(s=>{localStorage.removeItem(s)})}catch(e){throw console.error("WebStorageService clear error:",e),e}}};var Ie=(t,e)=>{let r;if(typeof t=="string")r=t;else if(t&&typeof t.toString=="function")r=t.toString();else if(t?.url)r=t.url;else throw new Error("Invalid input for webFetch");let s;if(e?.headers){let a=e.headers;if(a instanceof y){let o={};a.forEach((n,c)=>{o[c]=n}),s=o}else if(Array.isArray(a)){let o=[];for(let n of a)Array.isArray(n)&&n.length>=2&&o.push([String(n[0]),String(n[1])]);s=o}else typeof a=="object"&&(s=a)}let i={method:e?.method||"GET",headers:s,body:e?.body,credentials:e?.credentials};return e?.signal&&(i.signal=e.signal),globalThis.fetch(r,i).then(async a=>{let o=a.headers.get("content-type")||"",n;if(o.includes("application/json"))n=await a.json();else{let h=await a.text();try{n=JSON.parse(h)}catch{n=h}}let c=new y;return a.headers.forEach((h,l)=>{c.set(l,h)}),new G(n,{status:a.status,statusText:a.statusText,headers:c})})},O=Ie;function xe(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}var A={async requestPayment(t,e){let r=ee(t);if(r?.kind==="redirect_url"){window.location.href=r.redirectUrl;return}if(r?.kind==="wechat_native_qr"){let i=xe(r.codeUrl);window.open(i,"_blank","noopener,noreferrer");return}if(r?.kind==="alipay_page"){let i=window.open("","_blank");i&&(i.document.write(r.formHtml),i.document.close());return}let s=new Error("requestPayment: unsupported payParams for Desktop-web");throw e?.onFailure?.(s),s}};function se(t){let e=async r=>await te(t,r);return{...A,getAvailableProviders:e,getProviders:e}}function Ne(){if(typeof window>"u"||window===window.parent)return;let t=!1,e=new X;function r(h){if(!h)return!1;let l=h.toLowerCase();return l.includes("/components/")||l.includes("\\components\\")}function s(h){let l=h,u=null;for(;l;){let d=l.getAttribute("data-source-location");if(d)if(r(d)){u||(u=d),l=l.parentElement;continue}else return d;l=l.parentElement}return u}let i=null;function a(h){t&&(i!==null&&cancelAnimationFrame(i),i=requestAnimationFrame(()=>{let l=h.target;if(!l||l===document.body||l===document.documentElement){e.removeHighlight();return}if(l.tagName.toLowerCase()==="img"){let p=s(l);e.highlightElement(l,p);let f={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:p,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(f,"*");return}let u=l,d=s(l);if(!d){let p=l.parentElement;for(;p&&p!==document.body&&p!==document.documentElement;){let f=s(p);if(f){u=p,d=f;break}p=p.parentElement}}e.highlightElement(u,d);let m={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:d,elementInfo:{tagName:u.tagName.toLowerCase(),className:u.className||"",id:u.id||""}};window.parent.postMessage(m,"*")}))}function o(){if(!t)return;e.removeHighlight();let h={type:"HOVER_INSPECTOR_ELEMENT_LEAVE"};window.parent.postMessage(h,"*")}function n(h){if(!t)return;h.preventDefault(),h.stopPropagation();let l=h.target;if(!l||l===document.body||l===document.documentElement)return;let u=s(l);e.selectElement(l,u);let d={type:"HOVER_INSPECTOR_ELEMENT_SELECT",sourceLocation:u,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(d,"*")}function c(h){h.data?.type==="HOVER_INSPECTOR_ENABLE"?(t=!0,document.addEventListener("mousemove",a),document.addEventListener("mouseleave",o),document.addEventListener("click",n,!0)):h.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",a),document.removeEventListener("mouseleave",o),document.removeEventListener("click",n,!0),e.removeHighlight(),e.clearSelection())}return window.addEventListener("message",c),()=>{window.removeEventListener("message",c),document.removeEventListener("mousemove",a),document.removeEventListener("mouseleave",o),document.removeEventListener("click",n,!0),e.cleanup()}}function Ae(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function ke(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function Ue(t,e,r=5e3){return new Promise((s,i)=>{if(!t||!t.contentWindow){i(new Error("Invalid iframe element"));return}let a=`source-location-${Date.now()}-${Math.random()}`,o=setTimeout(()=>{window.removeEventListener("message",n),i(new Error("Request timeout"))},r),n=h=>{h.origin===e&&h.data?.type==="GET_SOURCE_LOCATION_RESPONSE"&&h.data?.requestId===a&&(clearTimeout(o),window.removeEventListener("message",n),h.data.error?i(new Error(h.data.error)):s(h.data.sourceLocation||null))};window.addEventListener("message",n);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:a};try{t.contentWindow.postMessage(c,e)}catch(h){clearTimeout(o),window.removeEventListener("message",n),i(h)}})}function Re(){if(typeof window>"u"||window===window.parent)return;let t=e=>{if(e.data?.type==="GET_SOURCE_LOCATION_REQUEST")try{let s={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:je(),requestId:e.data.requestId};window.parent.postMessage(s,e.origin)}catch(r){let s={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:null,error:r instanceof Error?r.message:"Unknown error",requestId:e.data.requestId};window.parent.postMessage(s,e.origin)}};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}}function je(){return Z("root")}var E=require("react"),k=require("react"),He="nvwa-social-login-list",We="nvwa-social-login-button";async function Me(t){return await t.getSocialProviderDescriptors()}function Fe(t){return t?.trim()?t.trim():typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:""}function qe(t){let[e,r]=(0,E.useState)(t.providers??[]),[s,i]=(0,E.useState)(!t.providers);(0,E.useEffect)(()=>{if(t.providers){r(t.providers),i(!1);return}let n=!1;return i(!0),Me(t.auth).then(c=>{n||r(c)}).catch(c=>{n||t.onError?.(c instanceof Error?c:new Error(String(c)))}).finally(()=>{n||i(!1)}),()=>{n=!0}},[t.auth,t.providers,t.onError]);let a=(0,E.useMemo)(()=>Fe(t.returnUrl),[t.returnUrl]),o=(0,E.useMemo)(()=>e.filter(n=>n.loginKind!=="unsupported"),[e]);return s||o.length===0?null:(0,k.createElement)("div",{className:t.className??He},...o.map(n=>{let c=async()=>{try{t.onBeforeLogin?.(n),await t.auth.startSocialLogin(n.id,{returnUrl:a,applicationCode:t.applicationCode,platformCode:t.platformCode})}catch(l){t.onError?.(l instanceof Error?l:new Error(String(l)))}},h=(0,k.createElement)("button",{key:n.id,type:"button",className:We,onClick:c},n.name);return t.onRenderButton?t.onRenderButton(n,h):h}))}var U=new _,$=class{constructor(e){this.endpointType="Desktop-web";this.payment=A;let{baseUrl:r,handleUnauthorized:s,applicationCode:i,platformType:a,integrationProviders:o}=e,n=i.trim();if(!n)throw new Error("Nvwa: applicationCode \u4E0D\u80FD\u4E3A\u7A7A");this.applicationCode=n;let c=a.trim();if(!c)throw new Error("Nvwa: platformType \u4E0D\u80FD\u4E3A\u7A7A");this.platformType=c,this.integrationProviders=re(o),this.auth=new J(r,{fetchImpl:O,storage:U,integrationProviders:this.integrationProviders}),this.httpClient=new K(U,O,s),this.fileStorage=new V(r,this.httpClient),this.entities=Q(r,this.httpClient),this.functions=new B(this.httpClient,r),this.payment=se(this.integrationProviders)}};0&&(module.exports={SocialLoginButtons,disableIframeHoverInspector,enableIframeHoverInspector,getIframeSourceLocation,localStorage,setupIframeHoverInspector,setupIframeSourceLocationListener,webFetch});
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- var y=class H{constructor(e){if(this.headerMap=new Map,e){if(e instanceof H)e.forEach((r,s)=>this.set(s,r));else if(Array.isArray(e))for(let[r,s]of e)this.set(r,String(s));else if(typeof e=="object")for(let r of Object.keys(e))this.set(r,String(e[r]))}}append(e,r){let s=e.toLowerCase(),a=this.headerMap.get(s);this.headerMap.set(s,a?`${a}, ${r}`:r)}set(e,r){this.headerMap.set(e.toLowerCase(),String(r))}get(e){return this.headerMap.get(e.toLowerCase())??null}has(e){return this.headerMap.has(e.toLowerCase())}delete(e){this.headerMap.delete(e.toLowerCase())}forEach(e){for(let[r,s]of this.headerMap.entries())e(s,r,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},te=class M{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof M)this.params=new Map(e.params);else if(Array.isArray(e))for(let[r,s]of e)this.append(r,s);else if(e&&typeof e=="object")for(let[r,s]of Object.entries(e))this.set(r,s)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let r=e.split("&");for(let s of r)if(s){let[a,i]=s.split("=");a&&this.append(decodeURIComponent(a),i?decodeURIComponent(i):"")}}append(e,r){let s=this.params.get(e)||[];s.push(r),this.params.set(e,s)}delete(e){this.params.delete(e)}get(e){let r=this.params.get(e);return r?r[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,r){this.params.set(e,[r])}sort(){let e=Array.from(this.params.entries()).sort(([r],[s])=>r.localeCompare(s));this.params=new Map(e)}toString(){let e=[];for(let[r,s]of this.params.entries())for(let a of s)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(a)}`);return e.join("&")}forEach(e){for(let[r,s]of this.params.entries())for(let a of s)e(a,r,this)}keys(){return this.params.keys()}values(){let e=[];for(let r of this.params.values())e.push(...r);return e[Symbol.iterator]()}entries(){let e=[];for(let[r,s]of this.params.entries())for(let a of s)e.push([r,a]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},_=class I{constructor(e,r){let s;if(e instanceof I)s=e.href;else if(r){let i=r instanceof I?r.href:r;s=this.resolve(i,e)}else s=e;let a=this.parseUrl(s);this.href=s,this.origin=`${a.protocol}//${a.host}`,this.protocol=a.protocol,this.username=a.username,this.password=a.password,this.host=a.host,this.hostname=a.hostname,this.port=a.port,this.pathname=a.pathname,this.search=a.search,this.searchParams=new te(a.search),this.hash=a.hash}resolve(e,r){if(r.startsWith("http://")||r.startsWith("https://"))return r;if(r.startsWith("//"))return`${this.parseUrl(e).protocol}${r}`;if(r.startsWith("/")){let i=this.parseUrl(e);return`${i.protocol}//${i.host}${r}`}let s=this.parseUrl(e),a=s.pathname.endsWith("/")?s.pathname:s.pathname+"/";return`${s.protocol}//${s.host}${a}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let s=r[2]||"",a=r[4]||"",i=r[5]||"/",n=r[7]?`?${r[7]}`:"",o=r[9]?`#${r[9]}`:"";if(!s&&!a&&!i.startsWith("/")&&!i.includes("/")&&!i.includes("."))throw new TypeError("Invalid URL");let c=a.match(/^([^@]*)@(.+)$/),h="",l="",u=a;if(c){let f=c[1];u=c[2];let w=f.match(/^([^:]*):?(.*)$/);w&&(h=w[1]||"",l=w[2]||"")}let d=u.match(/^([^:]+):?(\d*)$/),m=d?d[1]:u,p=d&&d[2]?d[2]:"";return{protocol:s?`${s}:`:"",username:h,password:l,host:u,hostname:m,port:p,pathname:i,search:n,hash:o}}toString(){let e=this.searchParams.toString(),r=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${r}${this.hash}`}toJSON(){return this.toString()}};var W=class{constructor(t,e){this.bodyData=t,this.status=e?.status??200,this.statusText=e?.statusText??"",this.headers=re(e?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let t=await this.text();return new TextEncoder().encode(t).buffer}};function re(t){return t?new y(t):new y}var se=class{constructor(){this._aborted=!1,this.listeners=new Set,this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let t of Array.from(this.listeners))try{t()}catch{}this.listeners.clear()}}addEventListener(t,e){if(this._aborted){try{e()}catch{}return}this.listeners.add(e)}removeEventListener(t,e){this.listeners.delete(e)}toString(){return"[object AbortSignal]"}},ae=class{constructor(){this._signal=new se}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}},F=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`;return await(await this.http.fetch(r,{method:e.method||"POST",body:e.body,headers:e.headers})).json()}},g="nvwa_current_jwt",v="nvwa_login_token",b="nvwa_user_profile",ie="set-auth-token",ne=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},oe={google:{id:"google",name:"Google Login",description:"Sign in with Google account."},github:{id:"github",name:"GitHub Login",description:"Sign in with GitHub account."},"wechat-website":{id:"wechat-website",name:"WeChat QR Login",description:"Sign in with WeChat website QR code."}};function k(t,e){let r=t.socialLogin?.providers?.[e];return r?.enabled?r.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var q=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??ne,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},typeof console<"u"&&(console.warn("[NvwaAuth] init baseUrl:",this.baseUrl||"(empty)"),(!this.baseUrl||!this.baseUrl.startsWith("http://")&&!this.baseUrl.startsWith("https://"))&&console.warn("[NvwaAuth] baseUrl \u5E94\u4E3A\u5B8C\u6574\u5730\u5740\uFF08\u5982 https://xxx.nvwa.app\uFF09\uFF0C\u5426\u5219\u5C0F\u7A0B\u5E8F request \u4F1A\u62A5 invalid url"))}async getSocialProviders(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>oe[r]??{id:r,name:r,description:""})}async currentUser(){if(this.storage){let r=await this.storage.get(b);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(b,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(g);if(e!=null)return e;let r=await this.storage.get(v),{data:s}=await this.getToken(r??void 0);return s?.token?(await this.storage.set(g,s.token),s.token):null}let{data:t}=await this.getToken();return t?.token??null}async persistLogin(t,e){if(!this.storage)return;let r=e?.headers.get(ie)?.trim()||t.token||t.session?.token;r&&await this.storage.set(v,r),t.user&&await this.storage.set(b,t.user);let s=r??await this.storage.get(v),{data:a}=await this.getToken(s??void 0);a?.token&&await this.storage.set(g,a.token)}async clearLogin(){this.storage&&(await this.storage.remove(v),await this.storage.remove(b),await this.storage.remove(g))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let s=k(this.integrationProviders,"google");return s&&r.set("oauth_credential_source",s),`${this.url("google/openplatform/login")}?${r.toString()}`}startGoogleOpenPlatformLogin(t,e){let r=this.getGoogleOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGoogleOpenPlatformLogin requires a browser environment with location")}async completeGoogleOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGoogleOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGoogleExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGoogleExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let i=await this.storage.get(g);i!=null&&(e.Authorization=`Bearer ${i}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):null;return!a?.token||!a.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}let e=await this.fetchImpl(this.url("google/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let s=r?JSON.parse(r):null;return s?.sub?{data:s}:{error:{message:"invalid_google_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getGithubOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let s=k(this.integrationProviders,"github");return s&&r.set("oauth_credential_source",s),`${this.url("github/openplatform/login")}?${r.toString()}`}startGithubOpenPlatformLogin(t,e){let r=this.getGithubOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGithubOpenPlatformLogin requires a browser environment with location")}async completeGithubOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGithubOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGithubExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGithubExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let i=await this.storage.get(g);i!=null&&(e.Authorization=`Bearer ${i}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):null;return!a?.token||!a.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}let e=await this.fetchImpl(this.url("github/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let s=r?JSON.parse(r):null;return s?.sub?{data:s}:{error:{message:"invalid_github_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getWechatWebsiteOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("wechat-website/openplatform/login")}?${e.toString()}`}startWechatWebsiteOpenPlatformLogin(t){let e=this.getWechatWebsiteOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;return}throw new Error("startWechatWebsiteOpenPlatformLogin requires a browser environment with location")}async completeWechatWebsiteOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeWechatWebsiteOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithWechatWebsiteExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithWechatWebsiteExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let i=await this.storage.get(g);i!=null&&(e.Authorization=`Bearer ${i}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}let e=await this.fetchImpl(this.url("wechat-website/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let s=r?JSON.parse(r):null;return s?.sub?{data:s}:{error:{message:"invalid_wechat_website_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}url(t){let e=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",e),!e.startsWith("http://")&&!e.startsWith("https://")&&console.warn("[NvwaAuth] URL \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F\u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 Nvwa \u6784\u9020\u65F6\u4F20\u5165\u7684 baseUrl")),e}async getSession(){try{let t={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("session"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return e.ok?{data:await e.json()}:{data:null,error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{data:null,error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signInWithEmail(t,e){try{let r=await this.fetchImpl(this.url("sign-in/email"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify({email:t,password:e})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):void 0;return a&&await this.persistLogin({user:a.user,session:a.session},r),{data:a}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return await this.clearLogin(),e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let i=await this.storage.get(v)??await this.storage.get(g);i!=null&&(e.Authorization=`Bearer ${i}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):void 0;return{data:a?.token!=null?{token:a.token}:void 0}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async signInWithUsername(t,e){let r=await this.postJson("sign-in/username",{username:t,password:e});return r.data&&await this.persistLogin(r.data,r.response),r}async signInWithPhoneNumber(t,e,r){let s=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return s.data&&await this.persistLogin(s.data,s.response),s}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let n=await this.storage.get(g);n!=null&&(r.Authorization=`Bearer ${n}`)}let s=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),a=await s.text();if(!s.ok)return{error:{message:a||s.statusText,status:s.status}};let i=a?JSON.parse(a):null;return!i?.token||!i.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(b,i.user)),{data:i})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let n=await this.storage.get(g);n!=null&&(r.Authorization=`Bearer ${n}`)}let s=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),a=await s.text();if(!s.ok)return{error:{message:a||s.statusText,status:s.status}};let i=a?JSON.parse(a):null;return!i?.token||!i.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(b,i.user)),{data:i})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let n=await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",s=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),a=await s.text();if(!s.ok)return{error:{message:a||s.statusText,status:s.status}};let i=a?JSON.parse(a):null;return!i?.openid||!i.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:i}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let n=await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",s=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),a=await s.text();if(!s.ok)return{error:{message:a||s.statusText,status:s.status}};let i=a?JSON.parse(a):null;return!i?.openid||!i.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:i}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let a=s?JSON.parse(s):void 0;return{data:a?.data??a??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}},G=class{constructor(t,e,r){this.storage=t,this.customFetch=e,this.handleUnauthorized=r}async fetch(t,e){return await this.customFetch(t,e)}async fetchWithAuth(t,e){let r=await this.storage.get(g),s=new y(e?.headers);r&&s.set("Authorization",`Bearer ${r}`);let a=e?.method||"GET";if((a==="POST"||a==="PUT"||a==="PATCH")&&e?.body){let n=s.get("Content-Type");(!n||n.includes("text/plain"))&&s.set("Content-Type","application/json")}let i=await this.customFetch(t,{...e,headers:s});if(i.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return i}},le="/storage",he=le+"/generateUploadUrl",z=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+he,{method:"POST",body:{fileName:t.name||t.fileName,fileSize:t.size||t.fileSize,fileType:t.type||t.fileType}}),{url:r}=await e.json();if(!r)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");let s=await this.http.fetch(r,{method:"PUT",body:t,headers:new y({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:a}=await s.json();return{url:a.split("?")[0]}}},ce=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},ue=class{constructor(t){var e,r,s;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new y(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(s=t.urlLengthLimit)!==null&&s!==void 0?s:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new y(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let s=this.fetch,a=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{let n=null,o=null,c=null,h=i.status,l=i.statusText;if(i.ok){var u,d;if(r.method!=="HEAD"){var m;let w=await i.text();w===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&!((m=r.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text")?o=w:o=JSON.parse(w))}let p=(u=r.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),f=(d=i.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");p&&f&&f.length>1&&(c=parseInt(f[1])),r.isMaybeSingle&&Array.isArray(o)&&(o.length>1?(n={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,c=null,h=406,l="Not Acceptable"):o.length===1?o=o[0]:o=null)}else{let p=await i.text();try{n=JSON.parse(p),Array.isArray(n)&&i.status===404&&(o=[],n=null,h=200,l="OK")}catch{i.status===404&&p===""?(h=204,l="No Content"):n={message:p}}if(n&&r.shouldThrowOnError)throw new ce(n)}return{error:n,data:o,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(a=a.catch(i=>{var n;let o="",c="",h="",l=i?.cause;if(l){var u,d,m,p;let ee=(u=l?.message)!==null&&u!==void 0?u:"",A=(d=l?.code)!==null&&d!==void 0?d:"";o=`${(m=i?.name)!==null&&m!==void 0?m:"FetchError"}: ${i?.message}`,o+=`
1
+ var y=class W{constructor(e){if(this.headerMap=new Map,e){if(e instanceof W)e.forEach((r,s)=>this.set(s,r));else if(Array.isArray(e))for(let[r,s]of e)this.set(r,String(s));else if(typeof e=="object")for(let r of Object.keys(e))this.set(r,String(e[r]))}}append(e,r){let s=e.toLowerCase(),i=this.headerMap.get(s);this.headerMap.set(s,i?`${i}, ${r}`:r)}set(e,r){this.headerMap.set(e.toLowerCase(),String(r))}get(e){return this.headerMap.get(e.toLowerCase())??null}has(e){return this.headerMap.has(e.toLowerCase())}delete(e){this.headerMap.delete(e.toLowerCase())}forEach(e){for(let[r,s]of this.headerMap.entries())e(s,r,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},ne=class M{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof M)this.params=new Map(e.params);else if(Array.isArray(e))for(let[r,s]of e)this.append(r,s);else if(e&&typeof e=="object")for(let[r,s]of Object.entries(e))this.set(r,s)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let r=e.split("&");for(let s of r)if(s){let[i,a]=s.split("=");i&&this.append(decodeURIComponent(i),a?decodeURIComponent(a):"")}}append(e,r){let s=this.params.get(e)||[];s.push(r),this.params.set(e,s)}delete(e){this.params.delete(e)}get(e){let r=this.params.get(e);return r?r[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,r){this.params.set(e,[r])}sort(){let e=Array.from(this.params.entries()).sort(([r],[s])=>r.localeCompare(s));this.params=new Map(e)}toString(){let e=[];for(let[r,s]of this.params.entries())for(let i of s)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(i)}`);return e.join("&")}forEach(e){for(let[r,s]of this.params.entries())for(let i of s)e(i,r,this)}keys(){return this.params.keys()}values(){let e=[];for(let r of this.params.values())e.push(...r);return e[Symbol.iterator]()}entries(){let e=[];for(let[r,s]of this.params.entries())for(let i of s)e.push([r,i]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},$=class I{constructor(e,r){let s;if(e instanceof I)s=e.href;else if(r){let a=r instanceof I?r.href:r;s=this.resolve(a,e)}else s=e;let i=this.parseUrl(s);this.href=s,this.origin=`${i.protocol}//${i.host}`,this.protocol=i.protocol,this.username=i.username,this.password=i.password,this.host=i.host,this.hostname=i.hostname,this.port=i.port,this.pathname=i.pathname,this.search=i.search,this.searchParams=new ne(i.search),this.hash=i.hash}resolve(e,r){if(r.startsWith("http://")||r.startsWith("https://"))return r;if(r.startsWith("//"))return`${this.parseUrl(e).protocol}${r}`;if(r.startsWith("/")){let a=this.parseUrl(e);return`${a.protocol}//${a.host}${r}`}let s=this.parseUrl(e),i=s.pathname.endsWith("/")?s.pathname:s.pathname+"/";return`${s.protocol}//${s.host}${i}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let s=r[2]||"",i=r[4]||"",a=r[5]||"/",o=r[7]?`?${r[7]}`:"",n=r[9]?`#${r[9]}`:"";if(!s&&!i&&!a.startsWith("/")&&!a.includes("/")&&!a.includes("."))throw new TypeError("Invalid URL");let c=i.match(/^([^@]*)@(.+)$/),h="",l="",u=i;if(c){let f=c[1];u=c[2];let w=f.match(/^([^:]*):?(.*)$/);w&&(h=w[1]||"",l=w[2]||"")}let d=u.match(/^([^:]+):?(\d*)$/),m=d?d[1]:u,p=d&&d[2]?d[2]:"";return{protocol:s?`${s}:`:"",username:h,password:l,host:u,hostname:m,port:p,pathname:a,search:o,hash:n}}toString(){let e=this.searchParams.toString(),r=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${r}${this.hash}`}toJSON(){return this.toString()}};var F=class{constructor(t,e){this.bodyData=t,this.status=e?.status??200,this.statusText=e?.statusText??"",this.headers=oe(e?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let t=await this.text();return new TextEncoder().encode(t).buffer}};function oe(t){return t?new y(t):new y}var le=class{constructor(){this._aborted=!1,this.listeners=new Set,this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let t of Array.from(this.listeners))try{t()}catch{}this.listeners.clear()}}addEventListener(t,e){if(this._aborted){try{e()}catch{}return}this.listeners.add(e)}removeEventListener(t,e){this.listeners.delete(e)}toString(){return"[object AbortSignal]"}},he=class{constructor(){this._signal=new le}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}},q=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`;return await(await this.http.fetch(r,{method:e.method||"POST",body:e.body,headers:e.headers})).json()}},g="nvwa_current_jwt",v="nvwa_login_token",b="nvwa_user_profile",ce="set-auth-token",ue=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},D={google:{id:"google",name:"Google Login",description:"Sign in with Google account."},github:{id:"github",name:"GitHub Login",description:"Sign in with GitHub account."},"wechat-website":{id:"wechat-website",name:"WeChat QR Login",description:"Sign in with WeChat website QR code."},"wechat-miniprogram":{id:"wechat-miniprogram",name:"WeChat Mini Program Login",description:"Sign in with WeChat mini program code."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program Login",description:"Sign in with Alipay mini program code."},"douyin-miniprogram":{id:"douyin-miniprogram",name:"Douyin Mini Program Login",description:"Sign in with Douyin mini program code."}};function k(t){let e=D[t]??{id:t,name:t,description:""},r="unsupported";switch(t){case"google":r="google_openplatform";break;case"github":r="github_openplatform";break;case"wechat-website":r="wechat_website_openplatform";break;case"wechat-miniprogram":r="wechat_miniprogram_code";break;case"alipay-miniprogram":r="alipay_miniprogram_code";break;case"douyin-miniprogram":r="douyin_miniprogram_code";break;default:break}return{id:e.id,type:e.id,name:e.name,description:e.description,loginKind:r}}function U(t,e){let r=t.socialLogin?.providers?.[e];return r?.enabled?r.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var G=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??ue,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},typeof console<"u"&&(console.warn("[NvwaAuth] init baseUrl:",this.baseUrl||"(empty)"),(!this.baseUrl||!this.baseUrl.startsWith("http://")&&!this.baseUrl.startsWith("https://"))&&console.warn("[NvwaAuth] baseUrl \u5E94\u4E3A\u5B8C\u6574\u5730\u5740\uFF08\u5982 https://xxx.nvwa.app\uFF09\uFF0C\u5426\u5219\u5C0F\u7A0B\u5E8F request \u4F1A\u62A5 invalid url"))}async getSocialProviders(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>{let s=D[r]??{id:r,name:r,description:""};return{...s,type:s.id}})}async getSocialProviderDescriptors(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>!!r?.enabled).map(([r])=>k(r))}async getAvailableProviders(t){return this.getSocialProviders(t)}async startSocialLogin(t,e){let r=k(t),s=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!s)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(s,{applicationCode:e?.applicationCode,platformCode:e?.platformCode});return;case"github_openplatform":if(!s)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(s,{applicationCode:e?.applicationCode,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!s)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(s);return;case"wechat_miniprogram_code":if(!e?.miniProgramCode?.trim()||!e.applicationCode?.trim())throw new Error("startSocialLogin requires miniProgramCode and applicationCode for wechat-miniprogram");await this.loginWithWeChatCode(e.miniProgramCode.trim(),e.applicationCode.trim());return;case"alipay_miniprogram_code":if(!e?.miniProgramCode?.trim()||!e.applicationCode?.trim())throw new Error("startSocialLogin requires miniProgramCode and applicationCode for alipay-miniprogram");await this.loginWithAlipayCode(e.miniProgramCode.trim(),e.applicationCode.trim());return;case"douyin_miniprogram_code":throw new Error("startSocialLogin does not support douyin-miniprogram yet");default:throw new Error(`startSocialLogin unsupported provider: ${t}`)}}async currentUser(){if(this.storage){let r=await this.storage.get(b);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(b,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(g);if(e!=null)return e;let r=await this.storage.get(v),{data:s}=await this.getToken(r??void 0);return s?.token?(await this.storage.set(g,s.token),s.token):null}let{data:t}=await this.getToken();return t?.token??null}async persistLogin(t,e){if(!this.storage)return;let r=e?.headers.get(ce)?.trim()||t.token||t.session?.token;r&&await this.storage.set(v,r),t.user&&await this.storage.set(b,t.user);let s=r??await this.storage.get(v),{data:i}=await this.getToken(s??void 0);i?.token&&await this.storage.set(g,i.token)}async clearLogin(){this.storage&&(await this.storage.remove(v),await this.storage.remove(b),await this.storage.remove(g))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let s=U(this.integrationProviders,"google");return s&&r.set("oauth_credential_source",s),`${this.url("google/openplatform/login")}?${r.toString()}`}startGoogleOpenPlatformLogin(t,e){let r=this.getGoogleOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGoogleOpenPlatformLogin requires a browser environment with location")}async completeGoogleOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGoogleOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGoogleExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGoogleExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let i=s?JSON.parse(s):null;return!i?.token||!i.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(b,i.user)),{data:i})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let i=await this.storage.get(g);i!=null&&(t.Authorization=`Bearer ${i}`)}let e=await this.fetchImpl(this.url("google/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let s=r?JSON.parse(r):null;return s?.sub?{data:s}:{error:{message:"invalid_google_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getGithubOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let s=U(this.integrationProviders,"github");return s&&r.set("oauth_credential_source",s),`${this.url("github/openplatform/login")}?${r.toString()}`}startGithubOpenPlatformLogin(t,e){let r=this.getGithubOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGithubOpenPlatformLogin requires a browser environment with location")}async completeGithubOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGithubOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGithubExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGithubExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let i=s?JSON.parse(s):null;return!i?.token||!i.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(b,i.user)),{data:i})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let i=await this.storage.get(g);i!=null&&(t.Authorization=`Bearer ${i}`)}let e=await this.fetchImpl(this.url("github/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let s=r?JSON.parse(r):null;return s?.sub?{data:s}:{error:{message:"invalid_github_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getWechatWebsiteOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("wechat-website/openplatform/login")}?${e.toString()}`}startWechatWebsiteOpenPlatformLogin(t){let e=this.getWechatWebsiteOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;return}throw new Error("startWechatWebsiteOpenPlatformLogin requires a browser environment with location")}async completeWechatWebsiteOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeWechatWebsiteOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithWechatWebsiteExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithWechatWebsiteExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let i=s?JSON.parse(s):null;return!i?.token||!i.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(b,i.user)),{data:i})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let i=await this.storage.get(g);i!=null&&(t.Authorization=`Bearer ${i}`)}let e=await this.fetchImpl(this.url("wechat-website/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let s=r?JSON.parse(r):null;return s?.sub?{data:s}:{error:{message:"invalid_wechat_website_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}url(t){let e=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",e),!e.startsWith("http://")&&!e.startsWith("https://")&&console.warn("[NvwaAuth] URL \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F\u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 Nvwa \u6784\u9020\u65F6\u4F20\u5165\u7684 baseUrl")),e}async getSession(){try{let t={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("session"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return e.ok?{data:await e.json()}:{data:null,error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{data:null,error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signInWithEmail(t,e){try{let r=await this.fetchImpl(this.url("sign-in/email"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify({email:t,password:e})}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let i=s?JSON.parse(s):void 0;return i&&await this.persistLogin({user:i.user,session:i.session},r),{data:i}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return await this.clearLogin(),e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let a=await this.storage.get(v)??await this.storage.get(g);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let i=s?JSON.parse(s):void 0;return{data:i?.token!=null?{token:i.token}:void 0}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async signInWithUsername(t,e){let r=await this.postJson("sign-in/username",{username:t,password:e});return r.data&&await this.persistLogin(r.data,r.response),r}async signInWithPhoneNumber(t,e,r){let s=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return s.data&&await this.persistLogin(s.data,s.response),s}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(g);o!=null&&(r.Authorization=`Bearer ${o}`)}let s=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),i=await s.text();if(!s.ok)return{error:{message:i||s.statusText,status:s.status}};let a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(g);o!=null&&(r.Authorization=`Bearer ${o}`)}let s=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),i=await s.text();if(!s.ok)return{error:{message:i||s.statusText,status:s.status}};let a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(g);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",s=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await s.text();if(!s.ok)return{error:{message:i||s.statusText,status:s.status}};let a=i?JSON.parse(i):null;return!a?.openid||!a.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(g);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",s=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await s.text();if(!s.ok)return{error:{message:i||s.statusText,status:s.status}};let a=i?JSON.parse(i):null;return!a?.openid||!a.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),s=await r.text();if(!r.ok)return{error:{message:s||r.statusText,status:r.status}};let i=s?JSON.parse(s):void 0;return{data:i?.data??i??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}},B=class{constructor(t,e,r){this.storage=t,this.customFetch=e,this.handleUnauthorized=r}async fetch(t,e){return await this.customFetch(t,e)}async fetchWithAuth(t,e){let r=await this.storage.get(g),s=new y(e?.headers);r&&s.set("Authorization",`Bearer ${r}`);let i=e?.method||"GET";if((i==="POST"||i==="PUT"||i==="PATCH")&&e?.body){let o=s.get("Content-Type");(!o||o.includes("text/plain"))&&s.set("Content-Type","application/json")}let a=await this.customFetch(t,{...e,headers:s});if(a.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return a}},de="/storage",pe=de+"/generateUploadUrl",z=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+pe,{method:"POST",body:{fileName:t.name||t.fileName,fileSize:t.size||t.fileSize,fileType:t.type||t.fileType}}),{url:r}=await e.json();if(!r)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");let s=await this.http.fetch(r,{method:"PUT",body:t,headers:new y({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:i}=await s.json();return{url:i.split("?")[0]}}},me=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},ge=class{constructor(t){var e,r,s;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new y(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(s=t.urlLengthLimit)!==null&&s!==void 0?s:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new y(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let s=this.fetch,i=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async a=>{let o=null,n=null,c=null,h=a.status,l=a.statusText;if(a.ok){var u,d;if(r.method!=="HEAD"){var m;let w=await a.text();w===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&!((m=r.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text")?n=w:n=JSON.parse(w))}let p=(u=r.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),f=(d=a.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");p&&f&&f.length>1&&(c=parseInt(f[1])),r.isMaybeSingle&&Array.isArray(n)&&(n.length>1?(o={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,c=null,h=406,l="Not Acceptable"):n.length===1?n=n[0]:n=null)}else{let p=await a.text();try{o=JSON.parse(p),Array.isArray(o)&&a.status===404&&(n=[],o=null,h=200,l="OK")}catch{a.status===404&&p===""?(h=204,l="No Content"):o={message:p}}if(o&&r.shouldThrowOnError)throw new me(o)}return{error:o,data:n,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(i=i.catch(a=>{var o;let n="",c="",h="",l=a?.cause;if(l){var u,d,m,p;let ae=(u=l?.message)!==null&&u!==void 0?u:"",A=(d=l?.code)!==null&&d!==void 0?d:"";n=`${(m=a?.name)!==null&&m!==void 0?m:"FetchError"}: ${a?.message}`,n+=`
2
2
 
3
- Caused by: ${(p=l?.name)!==null&&p!==void 0?p:"Error"}: ${ee}`,A&&(o+=` (${A})`),l?.stack&&(o+=`
4
- ${l.stack}`)}else{var f;o=(f=i?.stack)!==null&&f!==void 0?f:""}let w=this.url.toString().length;return i?.name==="AbortError"||i?.code==="ABORT_ERR"?(h="",c="Request was aborted (timeout or manual cancellation)",w>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${w} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(l?.name==="HeadersOverflowError"||l?.code==="UND_ERR_HEADERS_OVERFLOW")&&(h="",c="HTTP headers exceeded server limits (typically 16KB)",w>this.urlLengthLimit&&(c+=`. Your request URL is ${w} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(n=i?.name)!==null&&n!==void 0?n:"FetchError"}: ${i?.message}`,details:o,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),a.then(t,e)}returns(){return this}overrideTypes(){return this}},de=class extends ue{select(t){let e=!1,r=(t??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:s,referencedTable:a=s}={}){let i=a?`${a}.order`:"order",n=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${n?`${n},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){let a=typeof s>"u"?"offset":`${s}.offset`,i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(a,`${t}`),this.url.searchParams.set(i,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:s=!1,wal:a=!1,format:i="text"}={}){var n;let o=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,a?"wal":null].filter(Boolean).join("|"),c=(n=this.headers.get("Accept"))!==null&&n!==void 0?n:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${c}"; options=${o};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},U=new RegExp("[,()]"),E=class extends de{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(s=>typeof s=="string"&&U.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(s=>typeof s=="string"&&U.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:s}={}){let a="";s==="plain"?a="pl":s==="phrase"?a="ph":s==="websearch"&&(a="w");let i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${a}fts${i}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},pe=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:a=8e3}){this.url=t,this.headers=new y(e),this.schema=r,this.fetch=s,this.urlLengthLimit=a}cloneRequestState(){return{url:new _(this.url.toString()),headers:new y(this.headers)}}select(t,e){let{head:r=!1,count:s}=e??{},a=r?"HEAD":"GET",i=!1,n=(t??"*").split("").map(h=>/\s/.test(h)&&!i?"":(h==='"'&&(i=!i),h)).join(""),{url:o,headers:c}=this.cloneRequestState();return o.searchParams.set("select",n),s&&c.append("Prefer",`count=${s}`),new E({method:a,url:o,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;let a="POST",{url:i,headers:n}=this.cloneRequestState();if(e&&n.append("Prefer",`count=${e}`),r||n.append("Prefer","missing=default"),Array.isArray(t)){let o=t.reduce((c,h)=>c.concat(Object.keys(h)),[]);if(o.length>0){let c=[...new Set(o)].map(h=>`"${h}"`);i.searchParams.set("columns",c.join(","))}}return new E({method:a,url:i,headers:n,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:a=!0}={}){var i;let n="POST",{url:o,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),s&&c.append("Prefer",`count=${s}`),a||c.append("Prefer","missing=default"),Array.isArray(t)){let h=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(h.length>0){let l=[...new Set(h)].map(u=>`"${u}"`);o.searchParams.set("columns",l.join(","))}}return new E({method:n,url:o,headers:c,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let s="PATCH",{url:a,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new E({method:s,url:a,headers:i,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;let r="DELETE",{url:s,headers:a}=this.cloneRequestState();return t&&a.append("Prefer",`count=${t}`),new E({method:r,url:s,headers:a,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function P(t){"@babel/helpers - typeof";return P=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},P(t)}function me(t,e){if(P(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(P(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ge(t){var e=me(t,"string");return P(e)=="symbol"?e:e+""}function fe(t,e,r){return(e=ge(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function R(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),r.push.apply(r,s)}return r}function L(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?R(Object(r),!0).forEach(function(s){fe(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):R(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var ye=class D{constructor(e,{headers:r={},schema:s,fetch:a,timeout:i,urlLengthLimit:n=8e3}={}){this.url=e,this.headers=new y(r),this.schemaName=s,this.urlLengthLimit=n;let o=a??globalThis.fetch;i!==void 0&&i>0?this.fetch=(c,h)=>{let l=new ae,u=setTimeout(()=>l.abort(),i),d=h?.signal;if(d){if(d.aborted)return clearTimeout(u),o(c,h);let m=()=>{clearTimeout(u),l.abort()};return d.addEventListener("abort",m,{once:!0}),o(c,L(L({},h),{},{signal:l.signal})).finally(()=>{clearTimeout(u),d.removeEventListener("abort",m)})}return o(c,L(L({},h),{},{signal:l.signal})).finally(()=>clearTimeout(u))}:this.fetch=o}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new pe(new _(`${this.url}/${e}`),{headers:new y(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new D(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:s=!1,get:a=!1,count:i}={}){var n;let o,c=new _(`${this.url}/rpc/${e}`),h,l=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(l)),u=s&&Object.values(r).some(l);u?(o="POST",h=r):s||a?(o=s?"HEAD":"GET",Object.entries(r).filter(([m,p])=>p!==void 0).map(([m,p])=>[m,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([m,p])=>{c.searchParams.append(m,p)})):(o="POST",h=r);let d=new y(this.headers);return u?d.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&d.set("Prefer",`count=${i}`),new E({method:o,url:c,headers:d,schema:this.schemaName,body:h,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}},we="/entities",J=(t,e)=>new ye(t+we,{fetch:e.fetchWithAuth.bind(e)}),B=class{constructor(){this.hoverOverlay=null,this.selectedOverlay=null,this.tooltip=null,this.hoverElement=null,this.selectedElement=null,this.hoverUpdateHandler=null,this.selectedUpdateHandler=null,this.createStyles()}createStyles(){if(document.getElementById("__nvwa-inspector-overlay-style"))return;let t=document.createElement("style");t.id="__nvwa-inspector-overlay-style",t.textContent=`
3
+ Caused by: ${(p=l?.name)!==null&&p!==void 0?p:"Error"}: ${ae}`,A&&(n+=` (${A})`),l?.stack&&(n+=`
4
+ ${l.stack}`)}else{var f;n=(f=a?.stack)!==null&&f!==void 0?f:""}let w=this.url.toString().length;return a?.name==="AbortError"||a?.code==="ABORT_ERR"?(h="",c="Request was aborted (timeout or manual cancellation)",w>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${w} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(l?.name==="HeadersOverflowError"||l?.code==="UND_ERR_HEADERS_OVERFLOW")&&(h="",c="HTTP headers exceeded server limits (typically 16KB)",w>this.urlLengthLimit&&(c+=`. Your request URL is ${w} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(o=a?.name)!==null&&o!==void 0?o:"FetchError"}: ${a?.message}`,details:n,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),i.then(t,e)}returns(){return this}overrideTypes(){return this}},fe=class extends ge{select(t){let e=!1,r=(t??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:s,referencedTable:i=s}={}){let a=i?`${i}.order`:"order",o=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){let i=typeof s>"u"?"offset":`${s}.offset`,a=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${t}`),this.url.searchParams.set(a,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:s=!1,wal:i=!1,format:a="text"}={}){var o;let n=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),c=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${a}; for="${c}"; options=${n};`),a==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},R=new RegExp("[,()]"),E=class extends fe{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(s=>typeof s=="string"&&R.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(s=>typeof s=="string"&&R.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:s}={}){let i="";s==="plain"?i="pl":s==="phrase"?i="ph":s==="websearch"&&(i="w");let a=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${i}fts${a}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},ye=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:i=8e3}){this.url=t,this.headers=new y(e),this.schema=r,this.fetch=s,this.urlLengthLimit=i}cloneRequestState(){return{url:new $(this.url.toString()),headers:new y(this.headers)}}select(t,e){let{head:r=!1,count:s}=e??{},i=r?"HEAD":"GET",a=!1,o=(t??"*").split("").map(h=>/\s/.test(h)&&!a?"":(h==='"'&&(a=!a),h)).join(""),{url:n,headers:c}=this.cloneRequestState();return n.searchParams.set("select",o),s&&c.append("Prefer",`count=${s}`),new E({method:i,url:n,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;let i="POST",{url:a,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),r||o.append("Prefer","missing=default"),Array.isArray(t)){let n=t.reduce((c,h)=>c.concat(Object.keys(h)),[]);if(n.length>0){let c=[...new Set(n)].map(h=>`"${h}"`);a.searchParams.set("columns",c.join(","))}}return new E({method:i,url:a,headers:o,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:i=!0}={}){var a;let o="POST",{url:n,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&n.searchParams.set("on_conflict",e),s&&c.append("Prefer",`count=${s}`),i||c.append("Prefer","missing=default"),Array.isArray(t)){let h=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(h.length>0){let l=[...new Set(h)].map(u=>`"${u}"`);n.searchParams.set("columns",l.join(","))}}return new E({method:o,url:n,headers:c,schema:this.schema,body:t,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let s="PATCH",{url:i,headers:a}=this.cloneRequestState();return e&&a.append("Prefer",`count=${e}`),new E({method:s,url:i,headers:a,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;let r="DELETE",{url:s,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new E({method:r,url:s,headers:i,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function L(t){"@babel/helpers - typeof";return L=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},L(t)}function we(t,e){if(L(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(L(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ve(t){var e=we(t,"string");return L(e)=="symbol"?e:e+""}function be(t,e,r){return(e=ve(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function j(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,s)}return r}function O(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?j(Object(r),!0).forEach(function(s){be(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):j(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var Ee=class J{constructor(e,{headers:r={},schema:s,fetch:i,timeout:a,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new y(r),this.schemaName=s,this.urlLengthLimit=o;let n=i??globalThis.fetch;a!==void 0&&a>0?this.fetch=(c,h)=>{let l=new he,u=setTimeout(()=>l.abort(),a),d=h?.signal;if(d){if(d.aborted)return clearTimeout(u),n(c,h);let m=()=>{clearTimeout(u),l.abort()};return d.addEventListener("abort",m,{once:!0}),n(c,O(O({},h),{},{signal:l.signal})).finally(()=>{clearTimeout(u),d.removeEventListener("abort",m)})}return n(c,O(O({},h),{},{signal:l.signal})).finally(()=>clearTimeout(u))}:this.fetch=n}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new ye(new $(`${this.url}/${e}`),{headers:new y(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new J(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:s=!1,get:i=!1,count:a}={}){var o;let n,c=new $(`${this.url}/rpc/${e}`),h,l=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(l)),u=s&&Object.values(r).some(l);u?(n="POST",h=r):s||i?(n=s?"HEAD":"GET",Object.entries(r).filter(([m,p])=>p!==void 0).map(([m,p])=>[m,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([m,p])=>{c.searchParams.append(m,p)})):(n="POST",h=r);let d=new y(this.headers);return u?d.set("Prefer",a?`count=${a},return=minimal`:"return=minimal"):a&&d.set("Prefer",`count=${a}`),new E({method:n,url:c,headers:d,schema:this.schemaName,body:h,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}},Pe="/entities",K=(t,e)=>new Ee(t+Pe,{fetch:e.fetchWithAuth.bind(e)}),V=class{constructor(){this.hoverOverlay=null,this.selectedOverlay=null,this.tooltip=null,this.hoverElement=null,this.selectedElement=null,this.hoverUpdateHandler=null,this.selectedUpdateHandler=null,this.createStyles()}createStyles(){if(document.getElementById("__nvwa-inspector-overlay-style"))return;let t=document.createElement("style");t.id="__nvwa-inspector-overlay-style",t.textContent=`
5
5
  .__nvwa-inspector-overlay {
6
6
  position: absolute;
7
7
  pointer-events: none;
@@ -33,4 +33,4 @@ ${l.stack}`)}else{var f;o=(f=i?.stack)!==null&&f!==void 0?f:""}let w=this.url.to
33
33
  max-width: 400px;
34
34
  word-break: break-all;
35
35
  }
36
- `,document.head.appendChild(t)}createTooltip(){return this.tooltip?this.tooltip:(this.tooltip=document.createElement("div"),this.tooltip.id="__nvwa-inspector-tooltip",document.body.appendChild(this.tooltip),this.tooltip)}createOverlay(t){let e=document.createElement("div");return e.className=`__nvwa-inspector-overlay __nvwa-inspector-overlay-${t}`,document.body.appendChild(e),e}updateOverlayPosition(t,e){if(!e.isConnected)return;let r=e.getBoundingClientRect(),s=window.scrollX||window.pageXOffset,a=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+s}px`,t.style.top=`${r.top+a}px`,t.style.width=`${r.width}px`,t.style.height=`${r.height}px`,t.style.display="block"):t.style.display="none"}removeOverlay(t){t&&t.parentNode&&t.parentNode.removeChild(t)}highlightElement(t,e){if(!t.isConnected)return;if(this.hoverElement===t&&this.hoverOverlay){this.updateOverlayPosition(this.hoverOverlay,t);let n=this.createTooltip();e?n.textContent=e:n.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,n.style.display="block";let o=t.getBoundingClientRect();n.style.left=`${o.left+window.scrollX}px`,n.style.top=`${o.top+window.scrollY-n.offsetHeight-8}px`,o.top<n.offsetHeight+8&&(n.style.top=`${o.bottom+window.scrollY+8}px`);return}this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null);let r=this.createOverlay("hover");this.updateOverlayPosition(r,t),this.hoverOverlay=r,this.hoverElement=t;let s=()=>{this.hoverOverlay&&this.hoverElement&&this.hoverElement.isConnected&&this.updateOverlayPosition(this.hoverOverlay,this.hoverElement)};this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler)),this.hoverUpdateHandler=s,window.addEventListener("scroll",s,!0),window.addEventListener("resize",s);let a=this.createTooltip();e?a.textContent=e:a.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,a.style.display="block";let i=t.getBoundingClientRect();a.style.left=`${i.left+window.scrollX}px`,a.style.top=`${i.top+window.scrollY-a.offsetHeight-8}px`,i.top<a.offsetHeight+8&&(a.style.top=`${i.bottom+window.scrollY+8}px`)}selectElement(t,e){if(!t.isConnected)return;if(this.selectedElement===t&&this.selectedOverlay){this.updateOverlayPosition(this.selectedOverlay,t);return}this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null);let r=this.createOverlay("selected");this.updateOverlayPosition(r,t),this.selectedOverlay=r,this.selectedElement=t;let s=()=>{this.selectedOverlay&&this.selectedElement&&this.selectedElement.isConnected&&this.updateOverlayPosition(this.selectedOverlay,this.selectedElement)};this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler)),this.selectedUpdateHandler=s,window.addEventListener("scroll",s,!0),window.addEventListener("resize",s)}removeHighlight(){this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null),this.hoverElement&&(this.hoverElement=null),this.tooltip&&(this.tooltip.style.display="none"),this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler),this.hoverUpdateHandler=null)}clearSelection(){this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null),this.selectedElement&&(this.selectedElement=null),this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler),this.selectedUpdateHandler=null)}cleanup(){this.removeHighlight(),this.clearSelection(),this.tooltip&&this.tooltip.parentNode&&(this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null);let t=document.getElementById("__nvwa-inspector-overlay-style");t&&t.parentNode&&t.parentNode.removeChild(t)}};function K(t="root"){if(typeof document>"u")return null;let e=document.getElementById(t)||document.body;if(!e)return null;let r=e.querySelector("[data-source-location]");if(r){let s=r.getAttribute("data-source-location");if(s)return s}if(e.firstElementChild){let s=e.firstElementChild.getAttribute("data-source-location");if(s)return s}return null}var ve={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},wechat_partner:{id:"wechat_partner",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},alipay:{id:"alipay",name:"Alipay",description:"Alipay payment."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function V(t){let e=t;if(typeof e.kind=="string")return e;if(typeof e.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:e.tradeNO};if(typeof e.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:e.clientSecret};if(typeof e.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:e.redirectUrl};if(typeof e.formHtml=="string")return{kind:"alipay_page",formHtml:e.formHtml};if(typeof e.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:e.codeUrl};let r=e.jsapiPayParams??e;return typeof r.timeStamp=="string"&&typeof r.nonceStr=="string"&&typeof r.package=="string"&&typeof r.paySign=="string"&&typeof r.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:r.appId,timeStamp:r.timeStamp,nonceStr:r.nonceStr,package:r.package,signType:r.signType??"RSA",paySign:r.paySign}}:null}async function Y(t,e){let r=t.payment?.providers??{};return Object.entries(r).filter(([,s])=>s.enabled).map(([s])=>ve[s]??{id:s,name:s,description:""})}function T(t){return t&&typeof t=="object"?t:{}}function be(t){let e=T(t),r=e.enabled===!0,s=String(e.oauthCredentialSource??"").toLowerCase();return s?{enabled:r,oauthCredentialSource:s==="custom"?"custom":"nvwa_default"}:{enabled:r}}function j(t){let e=T(t),r=T(e.providers),s={};for(let[a,i]of Object.entries(r))s[a]=be(i);return{providers:s}}function Q(t){let e=T(t);return{socialLogin:j(e.socialLogin),payment:j(e.payment)}}var $=class{constructor(){this.prefix="nvwa_"}getKey(e){return`${this.prefix}${e}`}async get(e){try{let r=this.getKey(e),s=localStorage.getItem(r);if(!s)return null;let a=JSON.parse(s);return a.expires&&Date.now()>a.expires?(await this.remove(e),null):a.value}catch(r){return console.error("WebStorageService get error:",r),null}}async set(e,r,s){try{let a=this.getKey(e),i={value:r,expires:s?Date.now()+s*1e3:null,timestamp:Date.now()};localStorage.setItem(a,JSON.stringify(i))}catch(a){throw console.error("WebStorageService set error:",a),a}}async remove(e){try{let r=this.getKey(e);localStorage.removeItem(r)}catch(r){throw console.error("WebStorageService remove error:",r),r}}async clear(){try{Object.keys(localStorage).filter(s=>s.startsWith(this.prefix)).forEach(s=>{localStorage.removeItem(s)})}catch(e){throw console.error("WebStorageService clear error:",e),e}}};var Ee=(t,e)=>{let r;if(typeof t=="string")r=t;else if(t&&typeof t.toString=="function")r=t.toString();else if(t?.url)r=t.url;else throw new Error("Invalid input for webFetch");let s;if(e?.headers){let i=e.headers;if(i instanceof y){let n={};i.forEach((o,c)=>{n[c]=o}),s=n}else if(Array.isArray(i)){let n=[];for(let o of i)Array.isArray(o)&&o.length>=2&&n.push([String(o[0]),String(o[1])]);s=n}else typeof i=="object"&&(s=i)}let a={method:e?.method||"GET",headers:s,body:e?.body,credentials:e?.credentials};return e?.signal&&(a.signal=e.signal),globalThis.fetch(r,a).then(async i=>{let n=i.headers.get("content-type")||"",o;if(n.includes("application/json"))o=await i.json();else{let h=await i.text();try{o=JSON.parse(h)}catch{o=h}}let c=new y;return i.headers.forEach((h,l)=>{c.set(l,h)}),new W(o,{status:i.status,statusText:i.statusText,headers:c})})},C=Ee;function Pe(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}var x={async requestPayment(t,e){let r=V(t);if(r?.kind==="redirect_url"){window.location.href=r.redirectUrl;return}if(r?.kind==="wechat_native_qr"){let a=Pe(r.codeUrl);window.open(a,"_blank","noopener,noreferrer");return}if(r?.kind==="alipay_page"){let a=window.open("","_blank");a&&(a.document.write(r.formHtml),a.document.close());return}let s=new Error("requestPayment: unsupported payParams for Desktop-web");throw e?.onFailure?.(s),s}};function X(t){let e=async r=>await Y(t,r);return{...x,getAvailableProviders:e,getProviders:e}}function Ze(){if(typeof window>"u"||window===window.parent)return;let t=!1,e=new B;function r(h){if(!h)return!1;let l=h.toLowerCase();return l.includes("/components/")||l.includes("\\components\\")}function s(h){let l=h,u=null;for(;l;){let d=l.getAttribute("data-source-location");if(d)if(r(d)){u||(u=d),l=l.parentElement;continue}else return d;l=l.parentElement}return u}let a=null;function i(h){t&&(a!==null&&cancelAnimationFrame(a),a=requestAnimationFrame(()=>{let l=h.target;if(!l||l===document.body||l===document.documentElement){e.removeHighlight();return}if(l.tagName.toLowerCase()==="img"){let p=s(l);e.highlightElement(l,p);let f={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:p,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(f,"*");return}let u=l,d=s(l);if(!d){let p=l.parentElement;for(;p&&p!==document.body&&p!==document.documentElement;){let f=s(p);if(f){u=p,d=f;break}p=p.parentElement}}e.highlightElement(u,d);let m={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:d,elementInfo:{tagName:u.tagName.toLowerCase(),className:u.className||"",id:u.id||""}};window.parent.postMessage(m,"*")}))}function n(){if(!t)return;e.removeHighlight();let h={type:"HOVER_INSPECTOR_ELEMENT_LEAVE"};window.parent.postMessage(h,"*")}function o(h){if(!t)return;h.preventDefault(),h.stopPropagation();let l=h.target;if(!l||l===document.body||l===document.documentElement)return;let u=s(l);e.selectElement(l,u);let d={type:"HOVER_INSPECTOR_ELEMENT_SELECT",sourceLocation:u,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(d,"*")}function c(h){h.data?.type==="HOVER_INSPECTOR_ENABLE"?(t=!0,document.addEventListener("mousemove",i),document.addEventListener("mouseleave",n),document.addEventListener("click",o,!0)):h.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",i),document.removeEventListener("mouseleave",n),document.removeEventListener("click",o,!0),e.removeHighlight(),e.clearSelection())}return window.addEventListener("message",c),()=>{window.removeEventListener("message",c),document.removeEventListener("mousemove",i),document.removeEventListener("mouseleave",n),document.removeEventListener("click",o,!0),e.cleanup()}}function et(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function tt(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function rt(t,e,r=5e3){return new Promise((s,a)=>{if(!t||!t.contentWindow){a(new Error("Invalid iframe element"));return}let i=`source-location-${Date.now()}-${Math.random()}`,n=setTimeout(()=>{window.removeEventListener("message",o),a(new Error("Request timeout"))},r),o=h=>{h.origin===e&&h.data?.type==="GET_SOURCE_LOCATION_RESPONSE"&&h.data?.requestId===i&&(clearTimeout(n),window.removeEventListener("message",o),h.data.error?a(new Error(h.data.error)):s(h.data.sourceLocation||null))};window.addEventListener("message",o);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:i};try{t.contentWindow.postMessage(c,e)}catch(h){clearTimeout(n),window.removeEventListener("message",o),a(h)}})}function st(){if(typeof window>"u"||window===window.parent)return;let t=e=>{if(e.data?.type==="GET_SOURCE_LOCATION_REQUEST")try{let s={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:Oe(),requestId:e.data.requestId};window.parent.postMessage(s,e.origin)}catch(r){let s={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:null,error:r instanceof Error?r.message:"Unknown error",requestId:e.data.requestId};window.parent.postMessage(s,e.origin)}};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}}function Oe(){return K("root")}var Z=new $,N=class{constructor(e){this.endpointType="Desktop-web";this.payment=x;let{baseUrl:r,handleUnauthorized:s,applicationCode:a,platformType:i,integrationProviders:n}=e,o=a.trim();if(!o)throw new Error("Nvwa: applicationCode \u4E0D\u80FD\u4E3A\u7A7A");this.applicationCode=o;let c=i.trim();if(!c)throw new Error("Nvwa: platformType \u4E0D\u80FD\u4E3A\u7A7A");this.platformType=c,this.integrationProviders=Q(n),this.auth=new q(r,{fetchImpl:C,storage:Z,integrationProviders:this.integrationProviders}),this.httpClient=new G(Z,C,s),this.fileStorage=new z(r,this.httpClient),this.entities=J(r,this.httpClient),this.functions=new F(this.httpClient,r),this.payment=X(this.integrationProviders)}};export{N as default,tt as disableIframeHoverInspector,et as enableIframeHoverInspector,rt as getIframeSourceLocation,Z as localStorage,Ze as setupIframeHoverInspector,st as setupIframeSourceLocationListener,C as webFetch};
36
+ `,document.head.appendChild(t)}createTooltip(){return this.tooltip?this.tooltip:(this.tooltip=document.createElement("div"),this.tooltip.id="__nvwa-inspector-tooltip",document.body.appendChild(this.tooltip),this.tooltip)}createOverlay(t){let e=document.createElement("div");return e.className=`__nvwa-inspector-overlay __nvwa-inspector-overlay-${t}`,document.body.appendChild(e),e}updateOverlayPosition(t,e){if(!e.isConnected)return;let r=e.getBoundingClientRect(),s=window.scrollX||window.pageXOffset,i=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+s}px`,t.style.top=`${r.top+i}px`,t.style.width=`${r.width}px`,t.style.height=`${r.height}px`,t.style.display="block"):t.style.display="none"}removeOverlay(t){t&&t.parentNode&&t.parentNode.removeChild(t)}highlightElement(t,e){if(!t.isConnected)return;if(this.hoverElement===t&&this.hoverOverlay){this.updateOverlayPosition(this.hoverOverlay,t);let o=this.createTooltip();e?o.textContent=e:o.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,o.style.display="block";let n=t.getBoundingClientRect();o.style.left=`${n.left+window.scrollX}px`,o.style.top=`${n.top+window.scrollY-o.offsetHeight-8}px`,n.top<o.offsetHeight+8&&(o.style.top=`${n.bottom+window.scrollY+8}px`);return}this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null);let r=this.createOverlay("hover");this.updateOverlayPosition(r,t),this.hoverOverlay=r,this.hoverElement=t;let s=()=>{this.hoverOverlay&&this.hoverElement&&this.hoverElement.isConnected&&this.updateOverlayPosition(this.hoverOverlay,this.hoverElement)};this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler)),this.hoverUpdateHandler=s,window.addEventListener("scroll",s,!0),window.addEventListener("resize",s);let i=this.createTooltip();e?i.textContent=e:i.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,i.style.display="block";let a=t.getBoundingClientRect();i.style.left=`${a.left+window.scrollX}px`,i.style.top=`${a.top+window.scrollY-i.offsetHeight-8}px`,a.top<i.offsetHeight+8&&(i.style.top=`${a.bottom+window.scrollY+8}px`)}selectElement(t,e){if(!t.isConnected)return;if(this.selectedElement===t&&this.selectedOverlay){this.updateOverlayPosition(this.selectedOverlay,t);return}this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null);let r=this.createOverlay("selected");this.updateOverlayPosition(r,t),this.selectedOverlay=r,this.selectedElement=t;let s=()=>{this.selectedOverlay&&this.selectedElement&&this.selectedElement.isConnected&&this.updateOverlayPosition(this.selectedOverlay,this.selectedElement)};this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler)),this.selectedUpdateHandler=s,window.addEventListener("scroll",s,!0),window.addEventListener("resize",s)}removeHighlight(){this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null),this.hoverElement&&(this.hoverElement=null),this.tooltip&&(this.tooltip.style.display="none"),this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler),this.hoverUpdateHandler=null)}clearSelection(){this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null),this.selectedElement&&(this.selectedElement=null),this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler),this.selectedUpdateHandler=null)}cleanup(){this.removeHighlight(),this.clearSelection(),this.tooltip&&this.tooltip.parentNode&&(this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null);let t=document.getElementById("__nvwa-inspector-overlay-style");t&&t.parentNode&&t.parentNode.removeChild(t)}};function Y(t="root"){if(typeof document>"u")return null;let e=document.getElementById(t)||document.body;if(!e)return null;let r=e.querySelector("[data-source-location]");if(r){let s=r.getAttribute("data-source-location");if(s)return s}if(e.firstElementChild){let s=e.firstElementChild.getAttribute("data-source-location");if(s)return s}return null}var Se={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},wechat_partner:{id:"wechat_partner",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},alipay:{id:"alipay",name:"Alipay",description:"Alipay payment."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function Q(t){let e=t;if(typeof e.kind=="string")return e;if(typeof e.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:e.tradeNO};if(typeof e.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:e.clientSecret};if(typeof e.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:e.redirectUrl};if(typeof e.formHtml=="string")return{kind:"alipay_page",formHtml:e.formHtml};if(typeof e.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:e.codeUrl};let r=e.jsapiPayParams??e;return typeof r.timeStamp=="string"&&typeof r.nonceStr=="string"&&typeof r.package=="string"&&typeof r.paySign=="string"&&typeof r.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:r.appId,timeStamp:r.timeStamp,nonceStr:r.nonceStr,package:r.package,signType:r.signType??"RSA",paySign:r.paySign}}:null}async function X(t,e){let r=t.payment?.providers??{};return Object.entries(r).filter(([,s])=>s.enabled).map(([s])=>{let i=Se[s]??{id:s,name:s,description:""};return{...i,type:i.id}})}function C(t){return t&&typeof t=="object"?t:{}}function Le(t){let e=C(t),r=e.enabled===!0,s=String(e.oauthCredentialSource??"").toLowerCase();return s?{enabled:r,oauthCredentialSource:s==="custom"?"custom":"nvwa_default"}:{enabled:r}}function H(t){let e=C(t),r=C(e.providers),s={};for(let[i,a]of Object.entries(r))s[i]=Le(a);return{providers:s}}function Z(t){let e=C(t);return{socialLogin:H(e.socialLogin),payment:H(e.payment)}}var T=class{constructor(){this.prefix="nvwa_"}getKey(e){return`${this.prefix}${e}`}async get(e){try{let r=this.getKey(e),s=localStorage.getItem(r);if(!s)return null;let i=JSON.parse(s);return i.expires&&Date.now()>i.expires?(await this.remove(e),null):i.value}catch(r){return console.error("WebStorageService get error:",r),null}}async set(e,r,s){try{let i=this.getKey(e),a={value:r,expires:s?Date.now()+s*1e3:null,timestamp:Date.now()};localStorage.setItem(i,JSON.stringify(a))}catch(i){throw console.error("WebStorageService set error:",i),i}}async remove(e){try{let r=this.getKey(e);localStorage.removeItem(r)}catch(r){throw console.error("WebStorageService remove error:",r),r}}async clear(){try{Object.keys(localStorage).filter(s=>s.startsWith(this.prefix)).forEach(s=>{localStorage.removeItem(s)})}catch(e){throw console.error("WebStorageService clear error:",e),e}}};var Oe=(t,e)=>{let r;if(typeof t=="string")r=t;else if(t&&typeof t.toString=="function")r=t.toString();else if(t?.url)r=t.url;else throw new Error("Invalid input for webFetch");let s;if(e?.headers){let a=e.headers;if(a instanceof y){let o={};a.forEach((n,c)=>{o[c]=n}),s=o}else if(Array.isArray(a)){let o=[];for(let n of a)Array.isArray(n)&&n.length>=2&&o.push([String(n[0]),String(n[1])]);s=o}else typeof a=="object"&&(s=a)}let i={method:e?.method||"GET",headers:s,body:e?.body,credentials:e?.credentials};return e?.signal&&(i.signal=e.signal),globalThis.fetch(r,i).then(async a=>{let o=a.headers.get("content-type")||"",n;if(o.includes("application/json"))n=await a.json();else{let h=await a.text();try{n=JSON.parse(h)}catch{n=h}}let c=new y;return a.headers.forEach((h,l)=>{c.set(l,h)}),new F(n,{status:a.status,statusText:a.statusText,headers:c})})},_=Oe;function Ce(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}var x={async requestPayment(t,e){let r=Q(t);if(r?.kind==="redirect_url"){window.location.href=r.redirectUrl;return}if(r?.kind==="wechat_native_qr"){let i=Ce(r.codeUrl);window.open(i,"_blank","noopener,noreferrer");return}if(r?.kind==="alipay_page"){let i=window.open("","_blank");i&&(i.document.write(r.formHtml),i.document.close());return}let s=new Error("requestPayment: unsupported payParams for Desktop-web");throw e?.onFailure?.(s),s}};function ee(t){let e=async r=>await X(t,r);return{...x,getAvailableProviders:e,getProviders:e}}function lt(){if(typeof window>"u"||window===window.parent)return;let t=!1,e=new V;function r(h){if(!h)return!1;let l=h.toLowerCase();return l.includes("/components/")||l.includes("\\components\\")}function s(h){let l=h,u=null;for(;l;){let d=l.getAttribute("data-source-location");if(d)if(r(d)){u||(u=d),l=l.parentElement;continue}else return d;l=l.parentElement}return u}let i=null;function a(h){t&&(i!==null&&cancelAnimationFrame(i),i=requestAnimationFrame(()=>{let l=h.target;if(!l||l===document.body||l===document.documentElement){e.removeHighlight();return}if(l.tagName.toLowerCase()==="img"){let p=s(l);e.highlightElement(l,p);let f={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:p,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(f,"*");return}let u=l,d=s(l);if(!d){let p=l.parentElement;for(;p&&p!==document.body&&p!==document.documentElement;){let f=s(p);if(f){u=p,d=f;break}p=p.parentElement}}e.highlightElement(u,d);let m={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:d,elementInfo:{tagName:u.tagName.toLowerCase(),className:u.className||"",id:u.id||""}};window.parent.postMessage(m,"*")}))}function o(){if(!t)return;e.removeHighlight();let h={type:"HOVER_INSPECTOR_ELEMENT_LEAVE"};window.parent.postMessage(h,"*")}function n(h){if(!t)return;h.preventDefault(),h.stopPropagation();let l=h.target;if(!l||l===document.body||l===document.documentElement)return;let u=s(l);e.selectElement(l,u);let d={type:"HOVER_INSPECTOR_ELEMENT_SELECT",sourceLocation:u,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(d,"*")}function c(h){h.data?.type==="HOVER_INSPECTOR_ENABLE"?(t=!0,document.addEventListener("mousemove",a),document.addEventListener("mouseleave",o),document.addEventListener("click",n,!0)):h.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",a),document.removeEventListener("mouseleave",o),document.removeEventListener("click",n,!0),e.removeHighlight(),e.clearSelection())}return window.addEventListener("message",c),()=>{window.removeEventListener("message",c),document.removeEventListener("mousemove",a),document.removeEventListener("mouseleave",o),document.removeEventListener("click",n,!0),e.cleanup()}}function ht(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function ct(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function ut(t,e,r=5e3){return new Promise((s,i)=>{if(!t||!t.contentWindow){i(new Error("Invalid iframe element"));return}let a=`source-location-${Date.now()}-${Math.random()}`,o=setTimeout(()=>{window.removeEventListener("message",n),i(new Error("Request timeout"))},r),n=h=>{h.origin===e&&h.data?.type==="GET_SOURCE_LOCATION_RESPONSE"&&h.data?.requestId===a&&(clearTimeout(o),window.removeEventListener("message",n),h.data.error?i(new Error(h.data.error)):s(h.data.sourceLocation||null))};window.addEventListener("message",n);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:a};try{t.contentWindow.postMessage(c,e)}catch(h){clearTimeout(o),window.removeEventListener("message",n),i(h)}})}function dt(){if(typeof window>"u"||window===window.parent)return;let t=e=>{if(e.data?.type==="GET_SOURCE_LOCATION_REQUEST")try{let s={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:Te(),requestId:e.data.requestId};window.parent.postMessage(s,e.origin)}catch(r){let s={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:null,error:r instanceof Error?r.message:"Unknown error",requestId:e.data.requestId};window.parent.postMessage(s,e.origin)}};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}}function Te(){return Y("root")}import{useEffect as _e,useMemo as te,useState as re}from"react";import{createElement as se}from"react";var $e="nvwa-social-login-list",Ie="nvwa-social-login-button";async function xe(t){return await t.getSocialProviderDescriptors()}function Ne(t){return t?.trim()?t.trim():typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:""}function yt(t){let[e,r]=re(t.providers??[]),[s,i]=re(!t.providers);_e(()=>{if(t.providers){r(t.providers),i(!1);return}let n=!1;return i(!0),xe(t.auth).then(c=>{n||r(c)}).catch(c=>{n||t.onError?.(c instanceof Error?c:new Error(String(c)))}).finally(()=>{n||i(!1)}),()=>{n=!0}},[t.auth,t.providers,t.onError]);let a=te(()=>Ne(t.returnUrl),[t.returnUrl]),o=te(()=>e.filter(n=>n.loginKind!=="unsupported"),[e]);return s||o.length===0?null:se("div",{className:t.className??$e},...o.map(n=>{let c=async()=>{try{t.onBeforeLogin?.(n),await t.auth.startSocialLogin(n.id,{returnUrl:a,applicationCode:t.applicationCode,platformCode:t.platformCode})}catch(l){t.onError?.(l instanceof Error?l:new Error(String(l)))}},h=se("button",{key:n.id,type:"button",className:Ie,onClick:c},n.name);return t.onRenderButton?t.onRenderButton(n,h):h}))}var ie=new T,N=class{constructor(e){this.endpointType="Desktop-web";this.payment=x;let{baseUrl:r,handleUnauthorized:s,applicationCode:i,platformType:a,integrationProviders:o}=e,n=i.trim();if(!n)throw new Error("Nvwa: applicationCode \u4E0D\u80FD\u4E3A\u7A7A");this.applicationCode=n;let c=a.trim();if(!c)throw new Error("Nvwa: platformType \u4E0D\u80FD\u4E3A\u7A7A");this.platformType=c,this.integrationProviders=Z(o),this.auth=new G(r,{fetchImpl:_,storage:ie,integrationProviders:this.integrationProviders}),this.httpClient=new B(ie,_,s),this.fileStorage=new z(r,this.httpClient),this.entities=K(r,this.httpClient),this.functions=new q(this.httpClient,r),this.payment=ee(this.integrationProviders)}};export{yt as SocialLoginButtons,N as default,ct as disableIframeHoverInspector,ht as enableIframeHoverInspector,ut as getIframeSourceLocation,ie as localStorage,lt as setupIframeHoverInspector,dt as setupIframeSourceLocationListener,_ as webFetch};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nvwa-app/sdk-web",
3
- "version": "6.19.0",
3
+ "version": "6.24.0",
4
4
  "description": "NVWA跨端通用工具类Web端实现",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -29,10 +29,13 @@
29
29
  "directory": "packages/sdk/web"
30
30
  },
31
31
  "peerDependencies": {
32
- "@nvwa-app/sdk-core": "workspace:*"
32
+ "@nvwa-app/sdk-core": "workspace:*",
33
+ "react": "^19.0.0"
33
34
  },
34
35
  "devDependencies": {
35
36
  "@types/node": "^24.3.0",
37
+ "@types/react": "^19.1.13",
38
+ "react": "^19.2.4",
36
39
  "tsup": "^8.1.0",
37
40
  "typescript": "^5.9.2"
38
41
  },