@nvwa-app/sdk-web 6.10.0 → 6.12.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 +1 -2
- package/dist/index.d.ts +1 -2
- package/dist/index.js +4 -4
- package/dist/index.mjs +4 -4
- package/package.json +1 -2
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { NvwaLocalStorage, INvwa, AuthClient, NvwaFileStorage, createPostgrestClient, NvwaEdgeFunctions, NvwaHttpClient, IPaymentLauncher } from '@nvwa-app/sdk-core';
|
|
2
|
-
import { NvwaFetch } from '@nvwa-app/nvwa-http-polyfill';
|
|
1
|
+
import { NvwaLocalStorage, NvwaFetch, INvwa, AuthClient, NvwaFileStorage, createPostgrestClient, NvwaEdgeFunctions, NvwaHttpClient, IPaymentLauncher } from '@nvwa-app/sdk-core';
|
|
3
2
|
|
|
4
3
|
declare class WebNvwaLocalStorage implements NvwaLocalStorage {
|
|
5
4
|
private prefix;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { NvwaLocalStorage, INvwa, AuthClient, NvwaFileStorage, createPostgrestClient, NvwaEdgeFunctions, NvwaHttpClient, IPaymentLauncher } from '@nvwa-app/sdk-core';
|
|
2
|
-
import { NvwaFetch } from '@nvwa-app/nvwa-http-polyfill';
|
|
1
|
+
import { NvwaLocalStorage, NvwaFetch, INvwa, AuthClient, NvwaFileStorage, createPostgrestClient, NvwaEdgeFunctions, NvwaHttpClient, IPaymentLauncher } from '@nvwa-app/sdk-core';
|
|
3
2
|
|
|
4
3
|
declare class WebNvwaLocalStorage implements NvwaLocalStorage {
|
|
5
4
|
private prefix;
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";var x=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var V=Object.prototype.hasOwnProperty;var Y=(t,e)=>{for(var r in e)x(t,r,{get:e[r],enumerable:!0})},X=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of K(e))!V.call(t,a)&&a!==r&&x(t,a,{get:()=>e[a],enumerable:!(s=D(e,a))||s.enumerable});return t};var Q=t=>X(x({},"__esModule",{value:!0}),t);var Ee={};Y(Ee,{default:()=>$,disableIframeHoverInspector:()=>fe,enableIframeHoverInspector:()=>ge,getIframeSourceLocation:()=>ye,localStorage:()=>C,setupIframeHoverInspector:()=>me,setupIframeSourceLocationListener:()=>we,webFetch:()=>S});module.exports=Q(Ee);var H=require("@nvwa-app/nvwa-http-polyfill"),j=require("@nvwa-app/nvwa-http-polyfill"),f=require("@nvwa-app/nvwa-http-polyfill"),A=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()}},m="nvwa_current_jwt",w="nvwa_login_token",v="nvwa_user_profile",Z="set-auth-token",ee=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},U=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??ee,this.storage=e.storage??null,this.credentials=e.credentials??"omit",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 currentUser(){if(this.storage){let r=await this.storage.get(v);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(v,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(m);if(e!=null)return e;let r=await this.storage.get(w),{data:s}=await this.getToken(r??void 0);return s?.token?(await this.storage.set(m,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(Z)?.trim()||t.token||t.session?.token;r&&await this.storage.set(w,r),t.user&&await this.storage.set(v,t.user);let s=r??await this.storage.get(w),{data:a}=await this.getToken(s??void 0);a?.token&&await this.storage.set(m,a.token)}async clearLogin(){this.storage&&(await this.storage.remove(w),await this.storage.remove(v),await this.storage.remove(m))}getGoogleOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("google/openplatform/login")}?${e.toString()}`}startGoogleOpenPlatformLogin(t){let e=this.getGoogleOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;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 n=await this.storage.get(m);n!=null&&(e.Authorization=`Bearer ${n}`)}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(m,a.token),await this.storage.set(w,a.token),await this.storage.set(v,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(m);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){let e=new URLSearchParams({return_url:t});return`${this.url("github/openplatform/login")}?${e.toString()}`}startGithubOpenPlatformLogin(t){let e=this.getGithubOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;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 n=await this.storage.get(m);n!=null&&(e.Authorization=`Bearer ${n}`)}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(m,a.token),await this.storage.set(w,a.token),await this.storage.set(v,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(m);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 n=await this.storage.get(m);n!=null&&(e.Authorization=`Bearer ${n}`)}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(m,a.token),await this.storage.set(w,a.token),await this.storage.set(v,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(m);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(w)??await this.storage.get(m);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(w)??await this.storage.get(m);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 n=await this.storage.get(w)??await this.storage.get(m);n!=null&&(e.Authorization=`Bearer ${n}`)}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 i=await this.storage.get(m);i!=null&&(r.Authorization=`Bearer ${i}`)}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 n=a?JSON.parse(a):null;return!n?.token||!n.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(m,n.token),await this.storage.set(w,n.token),await this.storage.set(v,n.user)),{data:n})}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 i=await this.storage.get(m);i!=null&&(r.Authorization=`Bearer ${i}`)}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 n=a?JSON.parse(a):null;return!n?.token||!n.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(m,n.token),await this.storage.set(w,n.token),await this.storage.set(v,n.user)),{data:n})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let i=await this.storage.get(m);i!=null&&(e.Authorization=`Bearer ${i}`)}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 n=a?JSON.parse(a):null;return!n?.openid||!n.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:n}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let i=await this.storage.get(m);i!=null&&(e.Authorization=`Bearer ${i}`)}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 n=a?JSON.parse(a):null;return!n?.openid||!n.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:n}}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}}}}},R=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(m),s=new H.Headers(e?.headers);r&&s.set("Authorization",`Bearer ${r}`);let a=e?.method||"GET";if((a==="POST"||a==="PUT"||a==="PATCH")&&e?.body){let i=s.get("Content-Type");(!i||i.includes("text/plain"))&&s.set("Content-Type","application/json")}let n=await this.customFetch(t,{...e,headers:s});if(n.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return n}},te="/storage",re=te+"/generateUploadUrl",F=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+re,{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 j.Headers({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:a}=await s.json();return{url:a.split("?")[0]}}},se=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},ae=class{constructor(t){var e,r,s;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new f.Headers(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 f.Headers(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 n=>{let i=null,o=null,c=null,h=n.status,l=n.statusText;if(n.ok){var u,d;if(r.method!=="HEAD"){var g;let E=await n.text();E===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&!((g=r.headers.get("Accept"))===null||g===void 0)&&g.includes("application/vnd.pgrst.plan+text")?o=E:o=JSON.parse(E))}let p=(u=r.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),y=(d=n.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");p&&y&&y.length>1&&(c=parseInt(y[1])),r.isMaybeSingle&&Array.isArray(o)&&(o.length>1?(i={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 n.text();try{i=JSON.parse(p),Array.isArray(i)&&n.status===404&&(o=[],i=null,h=200,l="OK")}catch{n.status===404&&p===""?(h=204,l="No Content"):i={message:p}}if(i&&r.shouldThrowOnError)throw new se(i)}return{error:i,data:o,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(a=a.catch(n=>{var i;let o="",c="",h="",l=n?.cause;if(l){var u,d,g,p;let J=(u=l?.message)!==null&&u!==void 0?u:"",N=(d=l?.code)!==null&&d!==void 0?d:"";o=`${(g=n?.name)!==null&&g!==void 0?g:"FetchError"}: ${n?.message}`,o+=`
|
|
1
|
+
"use strict";var _=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames;var X=Object.prototype.hasOwnProperty;var Q=(t,e)=>{for(var r in e)_(t,r,{get:e[r],enumerable:!0})},Z=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Y(e))!X.call(t,a)&&a!==r&&_(t,a,{get:()=>e[a],enumerable:!(s=V(e,a))||s.enumerable});return t};var ee=t=>Z(_({},"__esModule",{value:!0}),t);var Te={};Q(Te,{default:()=>$,disableIframeHoverInspector:()=>Oe,enableIframeHoverInspector:()=>Ee,getIframeSourceLocation:()=>Se,localStorage:()=>I,setupIframeHoverInspector:()=>be,setupIframeSourceLocationListener:()=>Pe,webFetch:()=>P});module.exports=ee(Te);var y=class U{constructor(e){if(this.headerMap=new Map,e){if(e instanceof U)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 R{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof R)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}},x=class C{constructor(e,r){let s;if(e instanceof C)s=e.href;else if(r){let i=r instanceof C?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 u=a.match(/^([^@]*)@(.+)$/),h="",l="",c=a;if(u){let f=u[1];c=u[2];let w=f.match(/^([^:]*):?(.*)$/);w&&(h=w[1]||"",l=w[2]||"")}let d=c.match(/^([^:]+):?(\d*)$/),m=d?d[1]:c,p=d&&d[2]?d[2]:"";return{protocol:s?`${s}:`:"",username:h,password:l,host:c,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 H=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]"}},j=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")},M=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",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 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){let e=new URLSearchParams({return_url:t});return`${this.url("google/openplatform/login")}?${e.toString()}`}startGoogleOpenPlatformLogin(t){let e=this.getGoogleOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;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){let e=new URLSearchParams({return_url:t});return`${this.url("github/openplatform/login")}?${e.toString()}`}startGithubOpenPlatformLogin(t){let e=this.getGithubOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;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}}}}},F=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}},oe="/storage",le=oe+"/generateUploadUrl",W=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+le,{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]}}},he=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,u=null,h=i.status,l=i.statusText;if(i.ok){var c,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=(c=r.headers.get("Prefer"))===null||c===void 0?void 0:c.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&&(u=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,u=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 he(n)}return{error:n,data:o,count:u,status:h,statusText:l}});return this.shouldThrowOnError||(a=a.catch(i=>{var n;let o="",u="",h="",l=i?.cause;if(l){var c,d,m,p;let K=(c=l?.message)!==null&&c!==void 0?c:"",N=(d=l?.code)!==null&&d!==void 0?d:"";o=`${(m=i?.name)!==null&&m!==void 0?m:"FetchError"}: ${i?.message}`,o+=`
|
|
2
2
|
|
|
3
|
-
Caused by: ${(p=l?.name)!==null&&p!==void 0?p:"Error"}: ${
|
|
4
|
-
${l.stack}`)}else{var y;o=(y=n?.stack)!==null&&y!==void 0?y:""}let E=this.url.toString().length;return n?.name==="AbortError"||n?.code==="ABORT_ERR"?(h="",c="Request was aborted (timeout or manual cancellation)",E>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${E} 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)",E>this.urlLengthLimit&&(c+=`. Your request URL is ${E} 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:`${(i=n?.name)!==null&&i!==void 0?i:"FetchError"}: ${n?.message}`,details:o,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),a.then(t,e)}returns(){return this}overrideTypes(){return this}},ne=class extends ae{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 n=a?`${a}.order`:"order",i=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${i?`${i},`:""}${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`,n=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(a,`${t}`),this.url.searchParams.set(n,`${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:n="text"}={}){var i;let o=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,a?"wal":null].filter(Boolean).join("|"),c=(i=this.headers.get("Accept"))!==null&&i!==void 0?i:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${c}"; options=${o};`),n==="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}},I=new RegExp("[,()]"),b=class extends ne{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"&&I.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"&&I.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 n=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${a}fts${n}.${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}},ie=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:a=8e3}){this.url=t,this.headers=new f.Headers(e),this.schema=r,this.fetch=s,this.urlLengthLimit=a}cloneRequestState(){return{url:new f.URL(this.url.toString()),headers:new f.Headers(this.headers)}}select(t,e){let{head:r=!1,count:s}=e??{},a=r?"HEAD":"GET",n=!1,i=(t??"*").split("").map(h=>/\s/.test(h)&&!n?"":(h==='"'&&(n=!n),h)).join(""),{url:o,headers:c}=this.cloneRequestState();return o.searchParams.set("select",i),s&&c.append("Prefer",`count=${s}`),new b({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:n,headers:i}=this.cloneRequestState();if(e&&i.append("Prefer",`count=${e}`),r||i.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}"`);n.searchParams.set("columns",c.join(","))}}return new b({method:a,url:n,headers:i,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 n;let i="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 b({method:i,url:o,headers:c,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let s="PATCH",{url:a,headers:n}=this.cloneRequestState();return e&&n.append("Prefer",`count=${e}`),new b({method:s,url:a,headers:n,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 b({method:r,url:s,headers:a,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function O(t){"@babel/helpers - typeof";return O=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},O(t)}function oe(t,e){if(O(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(O(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function le(t){var e=oe(t,"string");return O(e)=="symbol"?e:e+""}function he(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 k(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 T(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?k(Object(r),!0).forEach(function(s){he(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):k(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var ce=class M{constructor(e,{headers:r={},schema:s,fetch:a,timeout:n,urlLengthLimit:i=8e3}={}){this.url=e,this.headers=new f.Headers(r),this.schemaName=s,this.urlLengthLimit=i;let o=a??globalThis.fetch;n!==void 0&&n>0?this.fetch=(c,h)=>{let l=new f.AbortController,u=setTimeout(()=>l.abort(),n),d=h?.signal;if(d){if(d.aborted)return clearTimeout(u),o(c,h);let g=()=>{clearTimeout(u),l.abort()};return d.addEventListener("abort",g,{once:!0}),o(c,T(T({},h),{},{signal:l.signal})).finally(()=>{clearTimeout(u),d.removeEventListener("abort",g)})}return o(c,T(T({},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 ie(new f.URL(`${this.url}/${e}`),{headers:new f.Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new M(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:s=!1,get:a=!1,count:n}={}){var i;let o,c=new f.URL(`${this.url}/rpc/${e}`),h,l=g=>g!==null&&typeof g=="object"&&(!Array.isArray(g)||g.some(l)),u=s&&Object.values(r).some(l);u?(o="POST",h=r):s||a?(o=s?"HEAD":"GET",Object.entries(r).filter(([g,p])=>p!==void 0).map(([g,p])=>[g,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([g,p])=>{c.searchParams.append(g,p)})):(o="POST",h=r);let d=new f.Headers(this.headers);return u?d.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&d.set("Prefer",`count=${n}`),new b({method:o,url:c,headers:d,schema:this.schemaName,body:h,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}},ue="/entities",q=(t,e)=>new ce(t+ue,{fetch:e.fetchWithAuth.bind(e)}),W=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"}: ${K}`,N&&(o+=` (${N})`),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="",u="Request was aborted (timeout or manual cancellation)",w>this.urlLengthLimit&&(u+=`. 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="",u="HTTP headers exceeded server limits (typically 16KB)",w>this.urlLengthLimit&&(u+=`. 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:u,code:h},data:null,count:null,status:0,statusText:""}})),a.then(t,e)}returns(){return this}overrideTypes(){return this}},ce=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("|"),u=(n=this.headers.get("Accept"))!==null&&n!==void 0?n:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${u}"; 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}},k=new RegExp("[,()]"),E=class extends ce{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"&&k.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"&&k.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}},de=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 x(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:u}=this.cloneRequestState();return o.searchParams.set("select",n),s&&u.append("Prefer",`count=${s}`),new E({method:a,url:o,headers:u,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((u,h)=>u.concat(Object.keys(h)),[]);if(o.length>0){let u=[...new Set(o)].map(h=>`"${h}"`);i.searchParams.set("columns",u.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:u}=this.cloneRequestState();if(u.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),s&&u.append("Prefer",`count=${s}`),a||u.append("Prefer","missing=default"),Array.isArray(t)){let h=t.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(h.length>0){let l=[...new Set(h)].map(c=>`"${c}"`);o.searchParams.set("columns",l.join(","))}}return new E({method:n,url:o,headers:u,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 O(t){"@babel/helpers - typeof";return O=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},O(t)}function pe(t,e){if(O(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(O(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function me(t){var e=pe(t,"string");return O(e)=="symbol"?e:e+""}function ge(t,e,r){return(e=me(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function A(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?A(Object(r),!0).forEach(function(s){ge(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):A(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var fe=class q{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=(u,h)=>{let l=new ae,c=setTimeout(()=>l.abort(),i),d=h?.signal;if(d){if(d.aborted)return clearTimeout(c),o(u,h);let m=()=>{clearTimeout(c),l.abort()};return d.addEventListener("abort",m,{once:!0}),o(u,L(L({},h),{},{signal:l.signal})).finally(()=>{clearTimeout(c),d.removeEventListener("abort",m)})}return o(u,L(L({},h),{},{signal:l.signal})).finally(()=>clearTimeout(c))}: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 de(new x(`${this.url}/${e}`),{headers:new y(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new q(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,u=new x(`${this.url}/rpc/${e}`),h,l=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(l)),c=s&&Object.values(r).some(l);c?(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])=>{u.searchParams.append(m,p)})):(o="POST",h=r);let d=new y(this.headers);return c?d.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&d.set("Prefer",`count=${i}`),new E({method:o,url:u,headers:d,schema:this.schemaName,body:h,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}},ye="/entities",D=(t,e)=>new fe(t+ye,{fetch:e.fetchWithAuth.bind(e)}),G=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 y;o=(y=n?.stack)!==null&&y!==void 0?y:""}let E=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 i=this.createTooltip();e?i.textContent=e:i.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,i.style.display="block";let o=t.getBoundingClientRect();i.style.left=`${o.left+window.scrollX}px`,i.style.top=`${o.top+window.scrollY-i.offsetHeight-8}px`,o.top<i.offsetHeight+8&&(i.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 n=t.getBoundingClientRect();a.style.left=`${n.left+window.scrollX}px`,a.style.top=`${n.top+window.scrollY-a.offsetHeight-8}px`,n.top<a.offsetHeight+8&&(a.style.top=`${n.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 G(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}function z(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}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),n={value:r,expires:s?Date.now()+s*1e3:null,timestamp:Date.now()};localStorage.setItem(a,JSON.stringify(n))}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 L=require("@nvwa-app/nvwa-http-polyfill"),de=(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 n=e.headers;if(n instanceof L.Headers){let i={};n.forEach((o,c)=>{i[c]=o}),s=i}else if(Array.isArray(n)){let i=[];for(let o of n)Array.isArray(o)&&o.length>=2&&i.push([String(o[0]),String(o[1])]);s=i}else typeof n=="object"&&(s=n)}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 n=>{let i=n.headers.get("content-type")||"",o;if(i.includes("application/json"))o=await n.json();else{let h=await n.text();try{o=JSON.parse(h)}catch{o=h}}let c=new L.Headers;return n.headers.forEach((h,l)=>{c.set(l,h)}),new L.Response(o,{status:n.status,statusText:n.statusText,headers:c})})},S=de;function pe(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}var B={async requestPayment(t,e){let r=z(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 me(){if(typeof window>"u"||window===window.parent)return;let t=!1,e=new W;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 n(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 y={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:p,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(y,"*");return}let u=l,d=s(l);if(!d){let p=l.parentElement;for(;p&&p!==document.body&&p!==document.documentElement;){let y=s(p);if(y){u=p,d=y;break}p=p.parentElement}}e.highlightElement(u,d);let g={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:d,elementInfo:{tagName:u.tagName.toLowerCase(),className:u.className||"",id:u.id||""}};window.parent.postMessage(g,"*")}))}function i(){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",n),document.addEventListener("mouseleave",i),document.addEventListener("click",o,!0)):h.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",n),document.removeEventListener("mouseleave",i),document.removeEventListener("click",o,!0),e.removeHighlight(),e.clearSelection())}return window.addEventListener("message",c),()=>{window.removeEventListener("message",c),document.removeEventListener("mousemove",n),document.removeEventListener("mouseleave",i),document.removeEventListener("click",o,!0),e.cleanup()}}function ge(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function fe(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function ye(t,e,r=5e3){return new Promise((s,a)=>{if(!t||!t.contentWindow){a(new Error("Invalid iframe element"));return}let n=`source-location-${Date.now()}-${Math.random()}`,i=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===n&&(clearTimeout(i),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:n};try{t.contentWindow.postMessage(c,e)}catch(h){clearTimeout(i),window.removeEventListener("message",o),a(h)}})}function we(){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:ve(),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 ve(){return G("root")}var C=new _,$=class{constructor(e,r){this.endpointType="Desktop-web";this.payment=B;this.auth=new U(e,{fetchImpl:S,storage:C}),this.httpClient=new R(C,S,r),this.fileStorage=new F(e,this.httpClient),this.entities=q(e,this.httpClient),this.functions=new A(this.httpClient,e)}};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,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 J(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}function z(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}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 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 we=(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,u)=>{n[u]=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 u=new y;return i.headers.forEach((h,l)=>{u.set(l,h)}),new H(o,{status:i.status,statusText:i.statusText,headers:u})})},P=we;function ve(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}var B={async requestPayment(t,e){let r=z(t);if(r?.kind==="redirect_url"){window.location.href=r.redirectUrl;return}if(r?.kind==="wechat_native_qr"){let a=ve(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 be(){if(typeof window>"u"||window===window.parent)return;let t=!1,e=new G;function r(h){if(!h)return!1;let l=h.toLowerCase();return l.includes("/components/")||l.includes("\\components\\")}function s(h){let l=h,c=null;for(;l;){let d=l.getAttribute("data-source-location");if(d)if(r(d)){c||(c=d),l=l.parentElement;continue}else return d;l=l.parentElement}return c}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 c=l,d=s(l);if(!d){let p=l.parentElement;for(;p&&p!==document.body&&p!==document.documentElement;){let f=s(p);if(f){c=p,d=f;break}p=p.parentElement}}e.highlightElement(c,d);let m={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:d,elementInfo:{tagName:c.tagName.toLowerCase(),className:c.className||"",id:c.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 c=s(l);e.selectElement(l,c);let d={type:"HOVER_INSPECTOR_ELEMENT_SELECT",sourceLocation:c,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(d,"*")}function u(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",u),()=>{window.removeEventListener("message",u),document.removeEventListener("mousemove",i),document.removeEventListener("mouseleave",n),document.removeEventListener("click",o,!0),e.cleanup()}}function Ee(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function Oe(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function Se(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 u={type:"GET_SOURCE_LOCATION_REQUEST",requestId:i};try{t.contentWindow.postMessage(u,e)}catch(h){clearTimeout(n),window.removeEventListener("message",o),a(h)}})}function Pe(){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:Le(),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 Le(){return J("root")}var I=new T,$=class{constructor(e,r){this.endpointType="Desktop-web";this.payment=B;this.auth=new M(e,{fetchImpl:P,storage:I}),this.httpClient=new F(I,P,r),this.fileStorage=new W(e,this.httpClient),this.entities=D(e,this.httpClient),this.functions=new j(this.httpClient,e)}};0&&(module.exports={disableIframeHoverInspector,enableIframeHoverInspector,getIframeSourceLocation,localStorage,setupIframeHoverInspector,setupIframeSourceLocationListener,webFetch});
|
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{Headers as K}from"@nvwa-app/nvwa-http-polyfill";import{Headers as V}from"@nvwa-app/nvwa-http-polyfill";import{AbortController as Q,Headers as E,URL as $}from"@nvwa-app/nvwa-http-polyfill";var k=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()}},m="nvwa_current_jwt",y="nvwa_login_token",w="nvwa_user_profile",J="set-auth-token",D=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},A=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??D,this.storage=e.storage??null,this.credentials=e.credentials??"omit",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 currentUser(){if(this.storage){let r=await this.storage.get(w);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(w,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(m);if(e!=null)return e;let r=await this.storage.get(y),{data:s}=await this.getToken(r??void 0);return s?.token?(await this.storage.set(m,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(J)?.trim()||t.token||t.session?.token;r&&await this.storage.set(y,r),t.user&&await this.storage.set(w,t.user);let s=r??await this.storage.get(y),{data:a}=await this.getToken(s??void 0);a?.token&&await this.storage.set(m,a.token)}async clearLogin(){this.storage&&(await this.storage.remove(y),await this.storage.remove(w),await this.storage.remove(m))}getGoogleOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("google/openplatform/login")}?${e.toString()}`}startGoogleOpenPlatformLogin(t){let e=this.getGoogleOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;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 n=await this.storage.get(m);n!=null&&(e.Authorization=`Bearer ${n}`)}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(m,a.token),await this.storage.set(y,a.token),await this.storage.set(w,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(m);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){let e=new URLSearchParams({return_url:t});return`${this.url("github/openplatform/login")}?${e.toString()}`}startGithubOpenPlatformLogin(t){let e=this.getGithubOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;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 n=await this.storage.get(m);n!=null&&(e.Authorization=`Bearer ${n}`)}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(m,a.token),await this.storage.set(y,a.token),await this.storage.set(w,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(m);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 n=await this.storage.get(m);n!=null&&(e.Authorization=`Bearer ${n}`)}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(m,a.token),await this.storage.set(y,a.token),await this.storage.set(w,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(m);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(y)??await this.storage.get(m);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(y)??await this.storage.get(m);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 n=await this.storage.get(y)??await this.storage.get(m);n!=null&&(e.Authorization=`Bearer ${n}`)}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 i=await this.storage.get(m);i!=null&&(r.Authorization=`Bearer ${i}`)}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 n=a?JSON.parse(a):null;return!n?.token||!n.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(m,n.token),await this.storage.set(y,n.token),await this.storage.set(w,n.user)),{data:n})}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 i=await this.storage.get(m);i!=null&&(r.Authorization=`Bearer ${i}`)}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 n=a?JSON.parse(a):null;return!n?.token||!n.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(m,n.token),await this.storage.set(y,n.token),await this.storage.set(w,n.user)),{data:n})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let i=await this.storage.get(m);i!=null&&(e.Authorization=`Bearer ${i}`)}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 n=a?JSON.parse(a):null;return!n?.openid||!n.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:n}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let i=await this.storage.get(m);i!=null&&(e.Authorization=`Bearer ${i}`)}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 n=a?JSON.parse(a):null;return!n?.openid||!n.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:n}}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}}}}},U=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(m),s=new K(e?.headers);r&&s.set("Authorization",`Bearer ${r}`);let a=e?.method||"GET";if((a==="POST"||a==="PUT"||a==="PATCH")&&e?.body){let i=s.get("Content-Type");(!i||i.includes("text/plain"))&&s.set("Content-Type","application/json")}let n=await this.customFetch(t,{...e,headers:s});if(n.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return n}},Y="/storage",X=Y+"/generateUploadUrl",H=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+X,{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 V({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:a}=await s.json();return{url:a.split("?")[0]}}},Z=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},ee=class{constructor(t){var e,r,s;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new E(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 E(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 n=>{let i=null,o=null,c=null,h=n.status,l=n.statusText;if(n.ok){var u,d;if(r.method!=="HEAD"){var g;let v=await n.text();v===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&!((g=r.headers.get("Accept"))===null||g===void 0)&&g.includes("application/vnd.pgrst.plan+text")?o=v:o=JSON.parse(v))}let p=(u=r.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),f=(d=n.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?(i={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 n.text();try{i=JSON.parse(p),Array.isArray(i)&&n.status===404&&(o=[],i=null,h=200,l="OK")}catch{n.status===404&&p===""?(h=204,l="No Content"):i={message:p}}if(i&&r.shouldThrowOnError)throw new Z(i)}return{error:i,data:o,count:c,status:h,statusText:l}});return this.shouldThrowOnError||(a=a.catch(n=>{var i;let o="",c="",h="",l=n?.cause;if(l){var u,d,g,p;let B=(u=l?.message)!==null&&u!==void 0?u:"",C=(d=l?.code)!==null&&d!==void 0?d:"";o=`${(g=n?.name)!==null&&g!==void 0?g:"FetchError"}: ${n?.message}`,o+=`
|
|
1
|
+
var y=class A{constructor(e){if(this.headerMap=new Map,e){if(e instanceof A)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()}},V=class U{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof U)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 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 V(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 u=a.match(/^([^@]*)@(.+)$/),h="",l="",c=a;if(u){let f=u[1];c=u[2];let w=f.match(/^([^:]*):?(.*)$/);w&&(h=w[1]||"",l=w[2]||"")}let d=c.match(/^([^:]+):?(\d*)$/),m=d?d[1]:c,p=d&&d[2]?d[2]:"";return{protocol:s?`${s}:`:"",username:h,password:l,host:c,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 R=class{constructor(t,e){this.bodyData=t,this.status=e?.status??200,this.statusText=e?.statusText??"",this.headers=Y(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 Y(t){return t?new y(t):new y}var X=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]"}},Q=class{constructor(){this._signal=new X}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}},H=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",Z="set-auth-token",ee=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},j=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??ee,this.storage=e.storage??null,this.credentials=e.credentials??"omit",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 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(Z)?.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){let e=new URLSearchParams({return_url:t});return`${this.url("google/openplatform/login")}?${e.toString()}`}startGoogleOpenPlatformLogin(t){let e=this.getGoogleOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;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){let e=new URLSearchParams({return_url:t});return`${this.url("github/openplatform/login")}?${e.toString()}`}startGithubOpenPlatformLogin(t){let e=this.getGithubOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;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}}}}},M=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}},te="/storage",re=te+"/generateUploadUrl",F=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+re,{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]}}},se=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},ae=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,u=null,h=i.status,l=i.statusText;if(i.ok){var c,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=(c=r.headers.get("Prefer"))===null||c===void 0?void 0:c.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&&(u=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,u=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 se(n)}return{error:n,data:o,count:u,status:h,statusText:l}});return this.shouldThrowOnError||(a=a.catch(i=>{var n;let o="",u="",h="",l=i?.cause;if(l){var c,d,m,p;let K=(c=l?.message)!==null&&c!==void 0?c:"",I=(d=l?.code)!==null&&d!==void 0?d:"";o=`${(m=i?.name)!==null&&m!==void 0?m:"FetchError"}: ${i?.message}`,o+=`
|
|
2
2
|
|
|
3
|
-
Caused by: ${(p=l?.name)!==null&&p!==void 0?p:"Error"}: ${
|
|
4
|
-
${l.stack}`)}else{var f;o=(f=n?.stack)!==null&&f!==void 0?f:""}let v=this.url.toString().length;return n?.name==="AbortError"||n?.code==="ABORT_ERR"?(h="",c="Request was aborted (timeout or manual cancellation)",v>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${v} 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)",v>this.urlLengthLimit&&(c+=`. Your request URL is ${v} 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:`${(i=n?.name)!==null&&i!==void 0?i:"FetchError"}: ${n?.message}`,details:o,hint:c,code:h},data:null,count:null,status:0,statusText:""}})),a.then(t,e)}returns(){return this}overrideTypes(){return this}},te=class extends ee{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 n=a?`${a}.order`:"order",i=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${i?`${i},`:""}${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`,n=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(a,`${t}`),this.url.searchParams.set(n,`${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:n="text"}={}){var i;let o=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,a?"wal":null].filter(Boolean).join("|"),c=(i=this.headers.get("Accept"))!==null&&i!==void 0?i:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${c}"; options=${o};`),n==="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}},N=new RegExp("[,()]"),b=class extends te{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"&&N.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"&&N.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 n=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${a}fts${n}.${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}},re=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:a=8e3}){this.url=t,this.headers=new E(e),this.schema=r,this.fetch=s,this.urlLengthLimit=a}cloneRequestState(){return{url:new $(this.url.toString()),headers:new E(this.headers)}}select(t,e){let{head:r=!1,count:s}=e??{},a=r?"HEAD":"GET",n=!1,i=(t??"*").split("").map(h=>/\s/.test(h)&&!n?"":(h==='"'&&(n=!n),h)).join(""),{url:o,headers:c}=this.cloneRequestState();return o.searchParams.set("select",i),s&&c.append("Prefer",`count=${s}`),new b({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:n,headers:i}=this.cloneRequestState();if(e&&i.append("Prefer",`count=${e}`),r||i.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}"`);n.searchParams.set("columns",c.join(","))}}return new b({method:a,url:n,headers:i,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 n;let i="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 b({method:i,url:o,headers:c,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let s="PATCH",{url:a,headers:n}=this.cloneRequestState();return e&&n.append("Prefer",`count=${e}`),new b({method:s,url:a,headers:n,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 b({method:r,url:s,headers:a,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function O(t){"@babel/helpers - typeof";return O=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},O(t)}function se(t,e){if(O(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(O(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ae(t){var e=se(t,"string");return O(e)=="symbol"?e:e+""}function ne(t,e,r){return(e=ae(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function I(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 S(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?I(Object(r),!0).forEach(function(s){ne(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):I(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var ie=class R{constructor(e,{headers:r={},schema:s,fetch:a,timeout:n,urlLengthLimit:i=8e3}={}){this.url=e,this.headers=new E(r),this.schemaName=s,this.urlLengthLimit=i;let o=a??globalThis.fetch;n!==void 0&&n>0?this.fetch=(c,h)=>{let l=new Q,u=setTimeout(()=>l.abort(),n),d=h?.signal;if(d){if(d.aborted)return clearTimeout(u),o(c,h);let g=()=>{clearTimeout(u),l.abort()};return d.addEventListener("abort",g,{once:!0}),o(c,S(S({},h),{},{signal:l.signal})).finally(()=>{clearTimeout(u),d.removeEventListener("abort",g)})}return o(c,S(S({},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 re(new $(`${this.url}/${e}`),{headers:new E(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new R(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:s=!1,get:a=!1,count:n}={}){var i;let o,c=new $(`${this.url}/rpc/${e}`),h,l=g=>g!==null&&typeof g=="object"&&(!Array.isArray(g)||g.some(l)),u=s&&Object.values(r).some(l);u?(o="POST",h=r):s||a?(o=s?"HEAD":"GET",Object.entries(r).filter(([g,p])=>p!==void 0).map(([g,p])=>[g,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([g,p])=>{c.searchParams.append(g,p)})):(o="POST",h=r);let d=new E(this.headers);return u?d.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&d.set("Prefer",`count=${n}`),new b({method:o,url:c,headers:d,schema:this.schemaName,body:h,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}},oe="/entities",j=(t,e)=>new ie(t+oe,{fetch:e.fetchWithAuth.bind(e)}),F=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"}: ${K}`,I&&(o+=` (${I})`),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="",u="Request was aborted (timeout or manual cancellation)",w>this.urlLengthLimit&&(u+=`. 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="",u="HTTP headers exceeded server limits (typically 16KB)",w>this.urlLengthLimit&&(u+=`. 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:u,code:h},data:null,count:null,status:0,statusText:""}})),a.then(t,e)}returns(){return this}overrideTypes(){return this}},ie=class extends ae{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("|"),u=(n=this.headers.get("Accept"))!==null&&n!==void 0?n:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${u}"; 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}},N=new RegExp("[,()]"),E=class extends ie{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"&&N.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"&&N.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}},ne=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:u}=this.cloneRequestState();return o.searchParams.set("select",n),s&&u.append("Prefer",`count=${s}`),new E({method:a,url:o,headers:u,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((u,h)=>u.concat(Object.keys(h)),[]);if(o.length>0){let u=[...new Set(o)].map(h=>`"${h}"`);i.searchParams.set("columns",u.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:u}=this.cloneRequestState();if(u.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),s&&u.append("Prefer",`count=${s}`),a||u.append("Prefer","missing=default"),Array.isArray(t)){let h=t.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(h.length>0){let l=[...new Set(h)].map(c=>`"${c}"`);o.searchParams.set("columns",l.join(","))}}return new E({method:n,url:o,headers:u,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 O(t){"@babel/helpers - typeof";return O=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},O(t)}function oe(t,e){if(O(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(O(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function le(t){var e=oe(t,"string");return O(e)=="symbol"?e:e+""}function he(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 k(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?k(Object(r),!0).forEach(function(s){he(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):k(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var ue=class W{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=(u,h)=>{let l=new Q,c=setTimeout(()=>l.abort(),i),d=h?.signal;if(d){if(d.aborted)return clearTimeout(c),o(u,h);let m=()=>{clearTimeout(c),l.abort()};return d.addEventListener("abort",m,{once:!0}),o(u,L(L({},h),{},{signal:l.signal})).finally(()=>{clearTimeout(c),d.removeEventListener("abort",m)})}return o(u,L(L({},h),{},{signal:l.signal})).finally(()=>clearTimeout(c))}: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 ne(new _(`${this.url}/${e}`),{headers:new y(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new W(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,u=new _(`${this.url}/rpc/${e}`),h,l=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(l)),c=s&&Object.values(r).some(l);c?(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])=>{u.searchParams.append(m,p)})):(o="POST",h=r);let d=new y(this.headers);return c?d.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&d.set("Prefer",`count=${i}`),new E({method:o,url:u,headers:d,schema:this.schemaName,body:h,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}},ce="/entities",q=(t,e)=>new ue(t+ce,{fetch:e.fetchWithAuth.bind(e)}),D=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=n?.stack)!==null&&f!==void 0?f:""}let v=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 i=this.createTooltip();e?i.textContent=e:i.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,i.style.display="block";let o=t.getBoundingClientRect();i.style.left=`${o.left+window.scrollX}px`,i.style.top=`${o.top+window.scrollY-i.offsetHeight-8}px`,o.top<i.offsetHeight+8&&(i.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 n=t.getBoundingClientRect();a.style.left=`${n.left+window.scrollX}px`,a.style.top=`${n.top+window.scrollY-a.offsetHeight-8}px`,n.top<a.offsetHeight+8&&(a.style.top=`${n.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 M(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}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}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 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),n={value:r,expires:s?Date.now()+s*1e3:null,timestamp:Date.now()};localStorage.setItem(a,JSON.stringify(n))}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}}};import{Headers as W,Response as le}from"@nvwa-app/nvwa-http-polyfill";var he=(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 n=e.headers;if(n instanceof W){let i={};n.forEach((o,c)=>{i[c]=o}),s=i}else if(Array.isArray(n)){let i=[];for(let o of n)Array.isArray(o)&&o.length>=2&&i.push([String(o[0]),String(o[1])]);s=i}else typeof n=="object"&&(s=n)}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 n=>{let i=n.headers.get("content-type")||"",o;if(i.includes("application/json"))o=await n.json();else{let h=await n.text();try{o=JSON.parse(h)}catch{o=h}}let c=new W;return n.headers.forEach((h,l)=>{c.set(l,h)}),new le(o,{status:n.status,statusText:n.statusText,headers:c})})},_=he;function ce(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}var G={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 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 qe(){if(typeof window>"u"||window===window.parent)return;let t=!1,e=new F;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 n(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 g={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:d,elementInfo:{tagName:u.tagName.toLowerCase(),className:u.className||"",id:u.id||""}};window.parent.postMessage(g,"*")}))}function i(){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",n),document.addEventListener("mouseleave",i),document.addEventListener("click",o,!0)):h.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",n),document.removeEventListener("mouseleave",i),document.removeEventListener("click",o,!0),e.removeHighlight(),e.clearSelection())}return window.addEventListener("message",c),()=>{window.removeEventListener("message",c),document.removeEventListener("mousemove",n),document.removeEventListener("mouseleave",i),document.removeEventListener("click",o,!0),e.cleanup()}}function We(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function Ge(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function ze(t,e,r=5e3){return new Promise((s,a)=>{if(!t||!t.contentWindow){a(new Error("Invalid iframe element"));return}let n=`source-location-${Date.now()}-${Math.random()}`,i=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===n&&(clearTimeout(i),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:n};try{t.contentWindow.postMessage(c,e)}catch(h){clearTimeout(i),window.removeEventListener("message",o),a(h)}})}function Be(){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:ue(),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 ue(){return M("root")}var z=new T,x=class{constructor(e,r){this.endpointType="Desktop-web";this.payment=G;this.auth=new A(e,{fetchImpl:_,storage:z}),this.httpClient=new U(z,_,r),this.fileStorage=new H(e,this.httpClient),this.entities=j(e,this.httpClient),this.functions=new k(this.httpClient,e)}};export{x as default,Ge as disableIframeHoverInspector,We as enableIframeHoverInspector,ze as getIframeSourceLocation,z as localStorage,qe as setupIframeHoverInspector,Be as setupIframeSourceLocationListener,_ 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,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 G(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}function J(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}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 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 de=(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,u)=>{n[u]=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 u=new y;return i.headers.forEach((h,l)=>{u.set(l,h)}),new R(o,{status:i.status,statusText:i.statusText,headers:u})})},$=de;function pe(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}var z={async requestPayment(t,e){let r=J(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 Ge(){if(typeof window>"u"||window===window.parent)return;let t=!1,e=new D;function r(h){if(!h)return!1;let l=h.toLowerCase();return l.includes("/components/")||l.includes("\\components\\")}function s(h){let l=h,c=null;for(;l;){let d=l.getAttribute("data-source-location");if(d)if(r(d)){c||(c=d),l=l.parentElement;continue}else return d;l=l.parentElement}return c}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 c=l,d=s(l);if(!d){let p=l.parentElement;for(;p&&p!==document.body&&p!==document.documentElement;){let f=s(p);if(f){c=p,d=f;break}p=p.parentElement}}e.highlightElement(c,d);let m={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:d,elementInfo:{tagName:c.tagName.toLowerCase(),className:c.className||"",id:c.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 c=s(l);e.selectElement(l,c);let d={type:"HOVER_INSPECTOR_ELEMENT_SELECT",sourceLocation:c,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(d,"*")}function u(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",u),()=>{window.removeEventListener("message",u),document.removeEventListener("mousemove",i),document.removeEventListener("mouseleave",n),document.removeEventListener("click",o,!0),e.cleanup()}}function Je(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function ze(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function Be(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 u={type:"GET_SOURCE_LOCATION_REQUEST",requestId:i};try{t.contentWindow.postMessage(u,e)}catch(h){clearTimeout(n),window.removeEventListener("message",o),a(h)}})}function Ke(){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:me(),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 me(){return G("root")}var B=new T,C=class{constructor(e,r){this.endpointType="Desktop-web";this.payment=z;this.auth=new j(e,{fetchImpl:$,storage:B}),this.httpClient=new M(B,$,r),this.fileStorage=new F(e,this.httpClient),this.entities=q(e,this.httpClient),this.functions=new H(this.httpClient,e)}};export{C as default,ze as disableIframeHoverInspector,Je as enableIframeHoverInspector,Be as getIframeSourceLocation,B as localStorage,Ge as setupIframeHoverInspector,Ke as setupIframeSourceLocationListener,$ as webFetch};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nvwa-app/sdk-web",
|
|
3
|
-
"version": "6.
|
|
3
|
+
"version": "6.12.0",
|
|
4
4
|
"description": "NVWA跨端通用工具类Web端实现",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -29,7 +29,6 @@
|
|
|
29
29
|
"directory": "packages/sdk/web"
|
|
30
30
|
},
|
|
31
31
|
"peerDependencies": {
|
|
32
|
-
"@nvwa-app/nvwa-http-polyfill": "0.1.0",
|
|
33
32
|
"@nvwa-app/sdk-core": "workspace:*"
|
|
34
33
|
},
|
|
35
34
|
"devDependencies": {
|