t1y-sdk-js 5.0.0 → 5.0.2

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.mjs CHANGED
@@ -1,3 +1,3 @@
1
- var se=e=>{throw TypeError(e)};var I=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Ve=(e,t,n)=>t.has(e)||se("Cannot "+n);var ie=(e,t,n)=>t.has(e)?se("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n);var N=(e,t,n)=>(Ve(e,t,"access private method"),n);var ae="https://myapp.t1y.net";var j="YYYY-MM-DD HH:mm:ss";var _=/^[0-9a-fA-F]{24}$/;var h=class extends Error{constructor(t,n,r){super(n),this.name="T1YError",this.code=t,this.data=r}toJSON(){return{name:this.name,code:this.code,message:this.message,data:this.data}}},m=class extends Error{constructor(t){super(t),this.name="ValidationError"}};function Y(e){if(!Number.isInteger(e))throw new m("appId must be an integer");if(e<1001)throw new m(`appId must be >= ${1001}`)}function W(e){if(typeof e!="string")throw new m("apiKey must be a string");if(e.length!==32)throw new m(`apiKey must be exactly ${32} characters (got ${e.length})`)}function J(e){if(typeof e!="string")throw new m("secretKey must be a string");if(e.length!==32)throw new m(`secretKey must be exactly ${32} characters (got ${e.length})`)}function Z(e){if(!/^https?:\/\//.test(e))throw new m('baseUrl must start with "http://" or "https://"')}function B(e){if(e.baseUrl!==void 0&&Z(e.baseUrl),Y(e.appId),W(e.apiKey),J(e.secretKey),e.version!==void 0&&(!Number.isInteger(e.version)||e.version<0))throw new m("version must be a non-negative integer")}function T(e,t="ObjectID"){if(typeof e!="string")throw new m(`${t} must be a string`);if(!_.test(e))throw new m(`Invalid ${t} string: "${e}"`);return!0}function O(e){if(e instanceof Date)return`Date('${e.toISOString()}')`;if(typeof e=="number"){let t=String(e);return/^\d{10,}$/.test(t)?`Timestamp('${t}')`:e}if(Array.isArray(e))return e.map(t=>O(t));if(e&&typeof e=="object"){let t={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=O(e[n]));return t}return e}function g(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length>0}function w(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function M(e){return!Array.isArray(e)||e.length===0?!1:e.every(t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>0)}function fe(){try{if(typeof I<"u")return I}catch{}return null}function H(e){let t=fe();if(t)try{return t("node:crypto").createHash("sha256").update(e).digest("hex")}catch{}let n=Qe(e);return k(n)}function k(e){return Xe(e)}async function ye(e){let t=fe();if(t)try{return t("node:crypto").createHash("sha256").update(e).digest("hex")}catch{}let n=new TextEncoder,r=await crypto.subtle.digest("SHA-256",n.encode(e));return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}function Qe(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e);let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r<128)t.push(r);else if(r<2048)t.push(192|r>>6,128|r&63);else if(r<55296||r>=57344)t.push(224|r>>12,128|r>>6&63,128|r&63);else{n++;let o=e.charCodeAt(n),i=65536+((r&1023)<<10)+(o&1023);t.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63)}}return new Uint8Array(t)}function Xe(e){let t=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],n=e.length,r=n*8,o=(64-(n+9)%64)%64,i=n+1+o+8,c=new Uint8Array(i);c.set(e),c[n]=128;for(let a=0;a<8;a++)c[i-8+a]=Number(BigInt(r)>>BigInt((7-a)*8)&BigInt(255));let s=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];for(let a=0;a<i;a+=64){let u=new Array(64);for(let p=0;p<16;p++)u[p]=c[a+p*4]<<24|c[a+p*4+1]<<16|c[a+p*4+2]<<8|c[a+p*4+3];for(let p=16;p<64;p++){let d=(b(u[p-15],7)^b(u[p-15],18)^u[p-15]>>>3)>>>0,G=(b(u[p-2],17)^b(u[p-2],19)^u[p-2]>>>10)>>>0;u[p]=u[p-16]+d+u[p-7]+G>>>0}let[f,l,y,S,x,U,E,P]=s;for(let p=0;p<64;p++){let d=(b(x,6)^b(x,11)^b(x,25))>>>0,G=(x&U^~x&E)>>>0,oe=P+d+G+t[p]+u[p]>>>0,We=(b(f,2)^b(f,13)^b(f,22))>>>0,Je=(f&l^f&y^l&y)>>>0,Ze=We+Je>>>0;P=E,E=U,U=x,x=S+oe>>>0,S=y,y=l,l=f,f=oe+Ze>>>0}s[0]=s[0]+f>>>0,s[1]=s[1]+l>>>0,s[2]=s[2]+y>>>0,s[3]=s[3]+S>>>0,s[4]=s[4]+x>>>0,s[5]=s[5]+U>>>0,s[6]=s[6]+E>>>0,s[7]=s[7]+P>>>0}return s.map(a=>a.toString(16).padStart(8,"0")).join("")}function b(e,t){return e>>>t|e<<32-t}function ge(){try{if(typeof I<"u")return I}catch{}return null}function R(e,t){let n=ge();if(n)try{return n("node:crypto").createHmac("sha256",e).update(t).digest("hex")}catch{}return et(e,t)}async function he(e,t){let n=ge();if(n)try{return n("node:crypto").createHmac("sha256",e).update(t).digest("hex")}catch{}let r=new TextEncoder,o=await crypto.subtle.importKey("raw",r.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",o,r.encode(t));return Array.from(new Uint8Array(i)).map(c=>c.toString(16).padStart(2,"0")).join("")}function $(e,t,n){if(typeof n!="string")return!1;let r=R(e,t);return ze(r,n.toLowerCase())}function ze(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}function et(e,t){let r=le(e),o=le(t);r.length>64&&(r=de(k(r)));let i=new Uint8Array(64);i.set(r.subarray(0,Math.min(r.length,64)));let c=new Uint8Array(64);c.fill(54);let s=me(i,c),a=new Uint8Array(64+o.length);a.set(s),a.set(o,64);let u=de(k(a)),f=new Uint8Array(64);f.fill(92);let l=me(i,f),y=new Uint8Array(64+u.length);return y.set(l),y.set(u,64),k(y)}function me(e,t){let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]^t[r];return n}function le(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e);let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r<128)t.push(r);else if(r<2048)t.push(192|r>>6,128|r&63);else if(r<55296||r>=57344)t.push(224|r>>12,128|r>>6&63,128|r&63);else{n++;let o=e.charCodeAt(n),i=65536+((r&1023)<<10)+(o&1023);t.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63)}}return new Uint8Array(t)}function de(e){let t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.substring(n,n+2),16);return t}function we(){if(typeof globalThis<"u"){if(typeof globalThis.crypto<"u"&&globalThis.crypto.subtle)return globalThis.crypto;try{let e=globalThis.require?globalThis.require("node:crypto"):null;if(e?.webcrypto)return e.webcrypto}catch{}}throw new Error("Web Crypto API is not available in this environment")}var xe=16,tt=12;function V(e){let t="",n=e.byteLength;for(let r=0;r<n;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Q(e){let t=atob(e),n=t.length,r=new Uint8Array(n);for(let o=0;o<n;o++)r[o]=t.charCodeAt(o);return r}async function v(e,t){if(!(t instanceof Uint8Array))throw new Error("key must be Uint8Array");if(t.length!==32)throw new Error("key length must be 32 bytes for AES-256-GCM");let n=we(),r=await n.subtle.importKey("raw",t,"AES-GCM",!1,["encrypt"]),o=new Uint8Array(tt);n.getRandomValues(o);let i=new TextEncoder().encode(e),c=new Uint8Array(await n.subtle.encrypt({name:"AES-GCM",iv:o,tagLength:128},r,i)),s=c.slice(0,c.length-xe),a=c.slice(c.length-xe),u={n:V(o),j:V(s),t:V(a)};return JSON.stringify(u)}async function L(e,t){if(!(t instanceof Uint8Array))throw new Error("key must be Uint8Array");if(t.length!==32)throw new Error("key length must be 32 bytes for AES-256-GCM");let n=we(),{n:r,j:o,t:i}=JSON.parse(e),c=Q(r),s=Q(o),a=Q(i),u=new Uint8Array(s.length+a.length);u.set(s),u.set(a,s.length);let f=await n.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]),l=await n.subtle.decrypt({name:"AES-GCM",iv:c,tagLength:128},f,u);return new TextDecoder().decode(l)}function F(e){let{method:t,pathAndQuery:n,body:r,appId:o,timestamp:i,secretKey:c}=e,s=H(r),a=[t.toUpperCase(),n,s,String(o),String(i)].join(`
2
- `);return R(c,a)}function q(e){return String(Math.floor(Date.now()/1e3)+e)}function be(e){return e.replace(/\/+$/,"")}function Ae(e,t){for(let n of Object.keys(t)){let r=t[n];r!=null&&e.searchParams.set(n,typeof r=="string"?r:JSON.stringify(r))}}function nt(e,t){let n=new Date(e);if(isNaN(n.getTime()))return e;let r=o=>String(o).padStart(2,"0");return t.replace("YYYY",String(n.getFullYear())).replace("MM",r(n.getMonth()+1)).replace("DD",r(n.getDate())).replace("HH",r(n.getHours())).replace("mm",r(n.getMinutes())).replace("ss",r(n.getSeconds()))}function C(e,t=j){function n(r){if(Array.isArray(r))return r.map(n);if(r&&typeof r=="object"){let o={};for(let i in r)Object.prototype.hasOwnProperty.call(r,i)&&(i==="createdAt"||i==="updatedAt"?o[i]=nt(r[i],t):o[i]=n(r[i]));return o}return r}return n(e)}async function Te(e,t,n,r){let o,i=e.headers.get("content-type")||"",c=await e.text();if(i.includes("application/json"))try{o=JSON.parse(c)}catch{o=c}else o=c;if(t&&o&&typeof o=="object"&&"j"in o)try{let s=await L(JSON.stringify(o),new TextEncoder().encode(n));try{o=JSON.parse(s)}catch{o=s}}catch(s){throw new h(400,"AES-256-GCM decryption failed",s instanceof Error?s.message:null)}if(o&&typeof o=="object"&&"data"in o){let s=o;if(s.data=C(s.data,r),!e.ok)throw new h(s.code||e.status,s.message||e.statusText,s.data);return s}if(!e.ok)throw new h(e.status,e.statusText,o);return{code:0,message:"ok",data:C(o,r)}}function Ee(e){if(e&&typeof e=="object"&&"response"in e){let t=e;throw e}throw e instanceof h?e:e instanceof Error?e.name==="AbortError"?new h(408,"Request timeout",null):new h(0,e.message,null):new h(0,"Unknown error",e)}async function X(e,t){let{method:n,path:r,params:o,encryption:i,timeout:c}=t,s=be(e.baseUrl),a=i??e.isSafeMode,u=new URL(s+r),f=O(o),l,y="";if(n!=="GET")if(a&&f!==void 0){let d=await v(JSON.stringify(f),new TextEncoder().encode(e.secretKey));l=d,y=d}else if(f!==void 0){let d=JSON.stringify(f);l=d,y=d}else y="";else f&&typeof f=="object"&&Object.keys(f).length>0&&Ae(u,f);let S=Number(q(e.offset)),x=u.pathname+u.search,U=F({method:n,pathAndQuery:x,body:y,appId:e.appId,timestamp:S,secretKey:e.secretKey}),E=new AbortController,p=setTimeout(()=>E.abort(),c??3e5);try{let d=await fetch(u.toString(),{method:n,headers:{"X-T1Y-Application-ID":String(e.appId),"X-T1Y-API-Key":e.apiKey,"X-T1Y-Safe-Timestamp":String(S),"X-T1Y-Safe-Sign":U,"Content-Type":"application/json"},body:n!=="GET"?l:void 0,signal:E.signal});return clearTimeout(p),await Te(d,a,e.secretKey,e.timeFormat)}catch(d){return clearTimeout(p),Ee(d)}}var D=class{constructor(t,n){this.client=t,this.name=n}async insertOne(t){if(!g(t))throw new TypeError("insertOne data must be a non-empty plain object");return await this.client.request("POST",`/v5/classes/${this.name}`,t)}async deleteById(t){return T(t),await this.client.request("DELETE",`/v5/classes/${this.name}/${t}`)}async updateById(t,n){if(T(t),!g(n))throw new TypeError("update data must be a non-empty plain object");return await this.client.request("PUT",`/v5/classes/${this.name}/${t}`,n)}async findById(t){return T(t),await this.client.request("GET",`/v5/classes/${this.name}/${t}`)}async deleteOne(t){if(!g(t))throw new TypeError("deleteOne filter must be a non-empty plain object");return await this.client.request("DELETE",`/v5/classes/${this.name}/one`,t)}async updateOne(t,n){if(!g(t))throw new TypeError("updateOne filter must be a non-empty plain object");if(!g(n))throw new TypeError("updateOne body must be a non-empty plain object");return await this.client.request("PUT",`/v5/classes/${this.name}/one`,{filter:t,body:n})}async findOne(t){if(!g(t))throw new TypeError("findOne filter must be a non-empty plain object");return await this.client.request("POST",`/v5/classes/${this.name}/one`,t)}async insertMany(t){if(!M(t))throw new TypeError("insertMany dataList must be a non-empty array of non-empty plain objects");return await this.client.request("POST",`/v5/classes/${this.name}/many`,t)}async deleteMany(t){if(!w(t))throw new TypeError("deleteMany filter must be a plain object");return await this.client.request("DELETE",`/v5/classes/${this.name}/many`,t)}async updateMany(t,n){if(!w(t))throw new TypeError("updateMany filter must be a plain object");if(!g(n))throw new TypeError("updateMany body must be a non-empty plain object");return await this.client.request("PUT",`/v5/classes/${this.name}/many`,{filter:t,body:n})}async find(t=1,n=10,r={createdAt:-1},o={}){if(!Number.isInteger(t)||t<1)throw new TypeError("find page must be a positive integer");if(!Number.isInteger(n)||n<1)throw new TypeError("find size must be a positive integer");if(n>100&&(n=100),!g(r))throw new TypeError("find sort must be a non-empty plain object");if(!w(o))throw new TypeError("find filter must be a plain object");return await this.client.request("POST",`/v5/classes/${this.name}/find`,{page:t,size:n,sort:r,filter:o})}async aggregate(t){if(!Array.isArray(t))throw new TypeError("aggregate pipeline must be an array");return await this.client.request("POST",`/v5/classes/${this.name}/aggregate`,t)}async count(t={}){if(!w(t))throw new TypeError("count filter must be a plain object");return await this.client.request("POST",`/v5/classes/${this.name}/count`,t)}async distinct(t,n={}){if(typeof t!="string"||t.length===0)throw new TypeError("distinct fieldName must be a non-empty string");if(!w(n))throw new TypeError("distinct filter must be a plain object");return await this.client.request("POST",`/v5/classes/${this.name}/distinct/${encodeURIComponent(t)}`,n)}async create(){return await this.client.request("POST",`/v5/schemas/${encodeURIComponent(this.name)}`)}async clear(){return await this.client.request("PUT",`/v5/schemas/${encodeURIComponent(this.name)}`)}async drop(){return await this.client.request("DELETE",`/v5/schemas/${encodeURIComponent(this.name)}`)}};var A,Re,Se,Ue,Ie,K=class{constructor(t){ie(this,A);B(t),this.config={baseUrl:t.baseUrl??ae,appId:t.appId,apiKey:t.apiKey,secretKey:t.secretKey,version:t.version??0,isSafeMode:t.isSafeMode??!1,timeFormat:t.timeFormat??j,offset:t.offset??0},this.db={collection:n=>N(this,A,Re).call(this,n),toObjectID:n=>N(this,A,Ue).call(this,n),getCollections:()=>N(this,A,Se).call(this)}}async init(){try{let n=(await this.request("GET",`/init/${this.config.appId}`,void 0,!1)).data;this.config.isSafeMode=n.is_safe_mode,this.config.offset=n.unix-Math.floor(Date.now()/1e3)}catch(t){console.warn("Failed to get time offset from server, defaulting to 0. Error:",t),this.config.isSafeMode=!1,this.config.offset=0}}async getMeta(t){if(t!==void 0&&t!==""&&typeof t!="string")throw new TypeError("Meta field must be a string");let n=t?`?field=${encodeURIComponent(t)}`:"";return await this.request("GET",`/v5/meta${n}`)}async checkUpdate(){try{return(await this.request("GET","/v5/meta?field=version")).data.result>this.config.version}catch{return!1}}async callFunc(t,n=null,r){if(typeof t!="string")throw new TypeError("Function name must be a string");return await this.request("POST",`/${this.config.appId}/${N(this,A,Ie).call(this,t)}`,n,r)}async request(t,n,r,o){if(typeof n!="string")throw new TypeError("request path must be a string");return await X(this.config,{method:t,path:n,params:r,encryption:o??this.config.isSafeMode})}assertObjectID(t,n="ObjectID"){return T(t,n)}isNonEmptyObject(t){return g(t)}isPlainObject(t){return w(t)}isNonEmptyArrayWithNonEmptyObjects(t){return M(t)}hmacSHA256(t,n){return R(t,n)}verifyHmacSHA256(t,n,r){return $(t,n,r)}};A=new WeakSet,Re=function(t){if(typeof t!="string")throw new TypeError("Collection name must be a string");return new D(this,t)},Se=async function(){return await this.request("GET","/v5/schemas")},Ue=function(t){return T(t),`ObjectID('${t}')`},Ie=function(t){let n=t.startsWith("/")?t.slice(1):t,r=n.indexOf("#"),o=r!==-1?n.slice(r):"",i=r!==-1?n.slice(0,r):n,c=i.indexOf("?"),s=c!==-1?i.slice(c):"",a=c!==-1?i.slice(0,c):i;return a.endsWith("/")?a=a+"index.jsc":a.endsWith(".jsc")||(a.endsWith(".js")?a=a.replace(/\.js$/,".jsc"):a=a+".jsc"),a+s+o};var at=K;function Oe(e){if(!_.test(e))throw new Error(`Invalid ObjectID: "${e}" (must be 24 hex characters)`);return`ObjectID('${e}')`}function Me(e){return`Date('${e}')`}function Ne(e){return`DateTime('${e}')`}function ke(e){return`Timestamp('${String(e)}')`}function Ce(e){return`Boolean(${e})`}function De(e){return`Integer(${e})`}function Pe(e){return`Bigint(${Number(e)})`}function je(e){return`Float(${e})`}function _e(e){return`Double(${e})`}function Be(e){return`Array(${JSON.stringify(e)})`}function He(e){return`Map(${JSON.stringify(e)})`}function $e(e){return`Map[](${JSON.stringify(e)})`}var ve="Null",Le="None",Fe="Nil",qe="",Ke="UNDEFINED",Ge="Undefined";var z="time.Now()",ee="time.Now().Unix()",te="time.Now().UnixNano()",ne="time.Now().Weekday()",re="time.Now().Weekday().Chinese()",Ye={Now:()=>z,NowUnix:()=>ee,NowUnixNano:()=>te,NowWeekday:()=>ne,NowWeekdayChinese:()=>re};export{Be as Array,Pe as Bigint,Ce as Boolean,Me as Date,Ne as DateTime,_e as Double,qe as Empty,je as Float,De as Integer,He as Map,$e as MapArray,Fe as Nil,Le as None,ve as Null,Oe as ObjectID,D as T1Collection,h as T1YError,K as T1YOS,z as TimeNow,ee as TimeNowUnix,te as TimeNowUnixNano,ne as TimeNowWeekday,re as TimeNowWeekdayChinese,ke as Timestamp,Ke as UNDEFINED,Ge as Undefined,m as ValidationError,T as assertObjectID,O as convertDateTypes,F as createSignature,L as decryptAESGCM,at as default,v as encryptAESGCM,C as formatTimestampsToLocal,q as getSafeTimestamp,R as hmacSHA256Hex,he as hmacSHA256HexAsync,M as isNonEmptyArrayWithNonEmptyObjects,g as isNonEmptyObject,w as isPlainObject,H as sha256Hex,ye as sha256HexAsync,Ye as timeNow,W as validateApiKey,Y as validateAppId,Z as validateBaseUrl,B as validateInitConfig,J as validateSecretKey,$ as verifyHmacSHA256};
1
+ var Ae=t=>{throw TypeError(t)};var A=(t=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(t,{get:(e,n)=>(typeof require!="undefined"?require:e)[n]}):t)(function(t){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var kt=(t,e,n)=>e.has(t)||Ae("Cannot "+n);var Te=(t,e,n)=>e.has(t)?Ae("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n);var B=(t,e,n)=>(kt(t,e,"access private method"),n);var Ee="https://myapp.t1y.net";var G="YYYY-MM-DD HH:mm:ss";var L=/^[0-9a-fA-F]{24}$/;var E=class extends Error{constructor(e,n,r){super(n),this.name="T1YError",this.code=e,this.data=r}toJSON(){return{name:this.name,code:this.code,message:this.message,data:this.data}}},h=class extends Error{constructor(e){super(e),this.name="ValidationError"}};function oe(t){if(!Number.isInteger(t))throw new h("appId must be an integer");if(t<1001)throw new h(`appId must be >= ${1001}`)}function se(t){if(typeof t!="string")throw new h("apiKey must be a string");if(t.length!==32)throw new h(`apiKey must be exactly ${32} characters (got ${t.length})`)}function ie(t){if(typeof t!="string")throw new h("secretKey must be a string");if(t.length!==32)throw new h(`secretKey must be exactly ${32} characters (got ${t.length})`)}function ae(t){if(!/^https?:\/\//.test(t))throw new h('baseUrl must start with "http://" or "https://"')}function K(t){if(t.baseUrl!==void 0&&ae(t.baseUrl),oe(t.appId),se(t.apiKey),ie(t.secretKey),t.version!==void 0&&(!Number.isInteger(t.version)||t.version<0))throw new h("version must be a non-negative integer")}function P(t,e="ObjectID"){if(typeof t!="string")throw new h(`${e} must be a string`);if(!L.test(t))throw new h(`Invalid ${e} string: "${t}"`);return!0}function I(t){if(t instanceof Date)return`Date('${t.toISOString()}')`;if(typeof t=="number"){let e=String(t);return/^\d{10,}$/.test(e)?`Timestamp('${e}')`:t}if(Array.isArray(t))return t.map(e=>I(e));if(t&&typeof t=="object"){let e={};for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=I(t[n]));return e}return t}function T(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>0}function S(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function q(t){return!Array.isArray(t)||t.length===0?!1:t.every(e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length>0)}function ke(){try{if(typeof A!="undefined")return A}catch(t){}return null}function W(t){let e=ke();if(e)try{return e("node:crypto").createHash("sha256").update(t).digest("hex")}catch(r){}let n=Pt(t);return _(n)}function _(t){return Ot(t)}async function Pe(t){let e=ke();if(e)try{return e("node:crypto").createHash("sha256").update(t).digest("hex")}catch(a){}let n=new TextEncoder,r=await crypto.subtle.digest("SHA-256",n.encode(t));return Array.from(new Uint8Array(r)).map(a=>a.toString(16).padStart(2,"0")).join("")}function Pt(t){if(typeof TextEncoder!="undefined")return new TextEncoder().encode(t);let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);if(r<128)e.push(r);else if(r<2048)e.push(192|r>>6,128|r&63);else if(r<55296||r>=57344)e.push(224|r>>12,128|r>>6&63,128|r&63);else{n++;let a=t.charCodeAt(n),o=65536+((r&1023)<<10)+(a&1023);e.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|o&63)}}return new Uint8Array(e)}function Mt(t,e,n){let r=Math.floor(n/4294967296),a=n%4294967296;t[e]=r>>>24&255,t[e+1]=r>>>16&255,t[e+2]=r>>>8&255,t[e+3]=r&255,t[e+4]=a>>>24&255,t[e+5]=a>>>16&255,t[e+6]=a>>>8&255,t[e+7]=a&255}function Ot(t){let e=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],n=t.length,r=n*8,a=(64-(n+9)%64)%64,o=n+1+a+8,c=new Uint8Array(o);c.set(t),c[n]=128,Mt(c,o-8,r);let s=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];for(let i=0;i<o;i+=64){let u=new Array(64);for(let m=0;m<16;m++)u[m]=c[i+m*4]<<24|c[i+m*4+1]<<16|c[i+m*4+2]<<8|c[i+m*4+3];for(let m=16;m<64;m++){let ne=(U(u[m-15],7)^U(u[m-15],18)^u[m-15]>>>3)>>>0,re=(U(u[m-2],17)^U(u[m-2],19)^u[m-2]>>>10)>>>0;u[m]=u[m-16]+ne+u[m-7]+re>>>0}let[p,f,y,d,l,g,w,x]=s;for(let m=0;m<64;m++){let ne=(U(l,6)^U(l,11)^U(l,25))>>>0,re=(l&g^~l&w)>>>0,we=x+ne+re+e[m]+u[m]>>>0,Rt=(U(p,2)^U(p,13)^U(p,22))>>>0,St=(p&f^p&y^f&y)>>>0,Ut=Rt+St>>>0;x=w,w=g,g=l,l=d+we>>>0,d=y,y=f,f=p,p=we+Ut>>>0}s[0]=s[0]+p>>>0,s[1]=s[1]+f>>>0,s[2]=s[2]+y>>>0,s[3]=s[3]+d>>>0,s[4]=s[4]+l>>>0,s[5]=s[5]+g>>>0,s[6]=s[6]+w>>>0,s[7]=s[7]+x>>>0}return s.map(i=>i.toString(16).padStart(8,"0")).join("")}function U(t,e){return t>>>e|t<<32-e}function Ie(){try{if(typeof A!="undefined")return A}catch(t){}return null}function C(t,e){let n=Ie();if(n)try{return n("node:crypto").createHmac("sha256",t).update(e).digest("hex")}catch(r){}return It(t,e)}async function qe(t,e){let n=Ie();if(n)try{return n("node:crypto").createHmac("sha256",t).update(e).digest("hex")}catch(c){}let r=new TextEncoder,a=await crypto.subtle.importKey("raw",r.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",a,r.encode(e));return Array.from(new Uint8Array(o)).map(c=>c.toString(16).padStart(2,"0")).join("")}function Y(t,e,n){if(typeof n!="string")return!1;let r=C(t,e);return Ct(r,n.toLowerCase())}function Ct(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}function It(t,e){let r=Oe(t),a=Oe(e);r.length>64&&(r=Ce(_(r)));let o=new Uint8Array(64);o.set(r.subarray(0,Math.min(r.length,64)));let c=new Uint8Array(64);c.fill(54);let s=Me(o,c),i=new Uint8Array(64+a.length);i.set(s),i.set(a,64);let u=Ce(_(i)),p=new Uint8Array(64);p.fill(92);let f=Me(o,p),y=new Uint8Array(64+u.length);return y.set(f),y.set(u,64),_(y)}function Me(t,e){let n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t[r]^e[r];return n}function Oe(t){if(typeof TextEncoder!="undefined")return new TextEncoder().encode(t);let e=[];for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);if(r<128)e.push(r);else if(r<2048)e.push(192|r>>6,128|r&63);else if(r<55296||r>=57344)e.push(224|r>>12,128|r>>6&63,128|r&63);else{n++;let a=t.charCodeAt(n),o=65536+((r&1023)<<10)+(a&1023);e.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|o&63)}}return new Uint8Array(e)}function Ce(t){let e=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)e[n/2]=parseInt(t.substring(n,n+2),16);return e}var H=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],qt=[1,2,4,8,16,32,64,128,27,54];function fe(t){if(t.length!==32)throw new Error("AES-256 requires a 32-byte key");let e=8,n=14,a=4*(n+1),o=new Array(a);for(let s=0;s<e;s++)o[s]=t[4*s]<<24|t[4*s+1]<<16|t[4*s+2]<<8|t[4*s+3];for(let s=e;s<a;s++){let i=o[s-1];s%e===0?i=Ne(Nt(i))^qt[Math.floor(s/e)-1]<<24:e>6&&s%e===4&&(i=Ne(i)),o[s]=o[s-e]^i}let c=[];for(let s=0;s<=n;s++){let i=new Uint8Array(16);for(let u=0;u<4;u++){let p=o[s*4+u];i[4*u]=p>>>24&255,i[4*u+1]=p>>>16&255,i[4*u+2]=p>>>8&255,i[4*u+3]=p&255}c.push(i)}return c}function Nt(t){return(t<<8|t>>>24)>>>0}function Ne(t){return(H[t>>>24&255]<<24|H[t>>>16&255]<<16|H[t>>>8&255]<<8|H[t&255]<<0)>>>0}function pe(t,e){if(t.length!==16)throw new Error("AES block must be exactly 16 bytes");let n=[[],[],[],[]];for(let o=0;o<4;o++)for(let c=0;c<4;c++)n[c][o]=t[o*4+c];let r=14;ce(n,e[0]);for(let o=1;o<r;o++)De(n),je(n),Dt(n),ce(n,e[o]);De(n),je(n),ce(n,e[r]);let a=new Uint8Array(16);for(let o=0;o<4;o++)for(let c=0;c<4;c++)a[o*4+c]=n[c][o];return a}function De(t){for(let e=0;e<4;e++)for(let n=0;n<4;n++)t[e][n]=H[t[e][n]]}function je(t){for(let e=1;e<4;e++){let n=t[e];t[e]=[n[e%4],n[(e+1)%4],n[(e+2)%4],n[(e+3)%4]]}}function Dt(t){for(let e=0;e<4;e++){let n=[];for(let r=0;r<4;r++)n[r]=t[r][e];t[0][e]=M(2,n[0])^M(3,n[1])^n[2]^n[3],t[1][e]=n[0]^M(2,n[1])^M(3,n[2])^n[3],t[2][e]=n[0]^n[1]^M(2,n[2])^M(3,n[3]),t[3][e]=M(3,n[0])^n[1]^n[2]^M(2,n[3])}}function ce(t,e){for(let n=0;n<4;n++)for(let r=0;r<4;r++)t[r][n]=t[r][n]^e[n*4+r]}function M(t,e){let n=0,r=t,a=e;for(let o=0;o<8;o++){a&1&&(n^=r);let c=r&128;r=r<<1&255,c&&(r^=27),a>>=1}return n}function J(t,e,n){let r=fe(t),a=Math.ceil(n.length/16),o=new Uint8Array(n.length),c=new Uint8Array(e);for(let s=0;s<a;s++){let i=pe(c,r),u=Math.min(16,n.length-s*16);for(let p=0;p<u;p++)o[s*16+p]=n[s*16+p]^i[p];le(c)}return o}function le(t){for(let e=15;e>=12;e--){let n=t[e]+1;if(t[e]=n&255,n<=255)break}}function ve(t,e,n){let r=Math.floor(n/4294967296),a=n%4294967296;t[e]=r>>>24&255,t[e+1]=r>>>16&255,t[e+2]=r>>>8&255,t[e+3]=r&255,t[e+4]=a>>>24&255,t[e+5]=a>>>16&255,t[e+6]=a>>>8&255,t[e+7]=a&255}function Be(t,e,n){let a=Math.ceil(e.length/16),o=Math.ceil(n.length/16),c=a+o+1,s=new Uint8Array(16);for(let y=0;y<a;y++){let d=new Uint8Array(16),l=y*16,g=Math.min(16,e.length-l);for(let x=0;x<g;x++)d[x]=e[l+x];for(let x=0;x<16;x++)d[x]^=s[x];let w=ue(d,t);s.set(w)}for(let y=0;y<o;y++){let d=new Uint8Array(16),l=y*16,g=Math.min(16,n.length-l);for(let x=0;x<g;x++)d[x]=n[l+x];for(let x=0;x<16;x++)d[x]^=s[x];let w=ue(d,t);s.set(w)}let i=new Uint8Array(16),u=e.length*8,p=n.length*8;ve(i,0,u),ve(i,8,p);for(let y=0;y<16;y++)i[y]^=s[y];return ue(i,t)}function ue(t,e){let n=new Uint8Array(16),r=new Uint8Array(e);for(let a=0;a<16;a++)for(let o=0;o<8;o++){if(t[15-a]>>7-o&1)for(let s=0;s<16;s++)n[s]^=r[s];let c=r[15]&1;for(let s=15;s>0;s--)r[s]=r[s]>>1|(r[s-1]&1)<<7;r[0]=r[0]>>1,c&&(r[0]^=225)}return n}function _e(t,e,n,r=new Uint8Array(0)){if(e.length!==32)throw new Error("key length must be 32 bytes for AES-256-GCM");if(n.length!==12)throw new Error("nonce length must be 12 bytes for AES-256-GCM");let a=new Uint8Array(16);a.set(n),a[15]=1;let o=fe(e),c=new Uint8Array(16),s=pe(c,o),i=new Uint8Array(16);i.set(n),i[15]=1;let u=new Uint8Array(i);le(u);let p=J(e,u,t),f=Be(s,r,p),y=J(e,i,f),d=new Uint8Array(16);for(let l=0;l<16;l++)d[l]=f[l]^y[l];return{ciphertext:p,tag:d}}function He(t,e,n,r,a=new Uint8Array(0)){if(n.length!==32)throw new Error("key length must be 32 bytes for AES-256-GCM");if(r.length!==12)throw new Error("nonce length must be 12 bytes for AES-256-GCM");if(e.length!==16)throw new Error("tag length must be 16 bytes for AES-256-GCM");let o=fe(n),c=new Uint8Array(16),s=pe(c,o),i=new Uint8Array(16);i.set(r),i[15]=1;let u=Be(s,a,t),p=J(n,i,u),f=new Uint8Array(16);for(let l=0;l<16;l++)f[l]=u[l]^p[l];let y=0;for(let l=0;l<16;l++)y|=e[l]^f[l];if(y!==0)throw new Error("AES-256-GCM authentication failed: tag mismatch");let d=new Uint8Array(i);return le(d),J(n,d,t)}function j(){try{if(typeof globalThis!="undefined"){if(typeof globalThis.crypto!="undefined"&&globalThis.crypto.subtle)return globalThis.crypto;try{let t=typeof A!="undefined"?A:null;if(t){let e=t("node:crypto");if(e!=null&&e.webcrypto)return e.webcrypto}}catch(t){}}}catch(t){}return null}function $e(){return!0}function Ge(){return j()!==null}var Fe=16,Le=12;function jt(t){let e=j();if(e){let r=new Uint8Array(t);return e.getRandomValues(r),r}try{if(typeof wx!="undefined"&&typeof wx.getRandomValues=="function"){let r=new Uint8Array(t);return wx.getRandomValues(r),r}}catch(r){}let n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=Math.floor(Math.random()*256);return n}function N(t){let e="",n=t.byteLength;for(let r=0;r<n;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function D(t){let e=atob(t),n=e.length,r=new Uint8Array(n);for(let a=0;a<n;a++)r[a]=e.charCodeAt(a);return r}async function vt(t,e){let n=j();if(!n)throw new Error("Web Crypto API is not available");let r=await n.subtle.importKey("raw",e,"AES-GCM",!1,["encrypt"]),a=new Uint8Array(Le);n.getRandomValues(a);let o=new TextEncoder().encode(t),c=new Uint8Array(await n.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},r,o)),s=c.slice(0,c.length-Fe),i=c.slice(c.length-Fe),u={n:N(a),j:N(s),t:N(i)};return JSON.stringify(u)}async function Bt(t,e){let n=j();if(!n)throw new Error("Web Crypto API is not available");let{n:r,j:a,t:o}=JSON.parse(t),c=D(r),s=D(a),i=D(o),u=new Uint8Array(s.length+i.length);u.set(s),u.set(i,s.length);let p=await n.subtle.importKey("raw",e,"AES-GCM",!1,["decrypt"]),f=await n.subtle.decrypt({name:"AES-GCM",iv:c,tagLength:128},p,u);return new TextDecoder().decode(f)}function _t(t,e){let n=jt(Le),r=new TextEncoder().encode(t),{ciphertext:a,tag:o}=_e(r,e,n),c={n:N(n),j:N(a),t:N(o)};return JSON.stringify(c)}function Ht(t,e){let{n,j:r,t:a}=JSON.parse(t),o=D(n),c=D(r),s=D(a),i=He(c,s,e,o);return new TextDecoder().decode(i)}async function z(t,e){if(!(e instanceof Uint8Array))throw new Error("key must be Uint8Array");if(e.length!==32)throw new Error("key length must be 32 bytes for AES-256-GCM");return j()?await vt(t,e):_t(t,e)}async function Q(t,e){if(!(e instanceof Uint8Array))throw new Error("key must be Uint8Array");if(e.length!==32)throw new Error("key length must be 32 bytes for AES-256-GCM");return j()?await Bt(t,e):Ht(t,e)}function V(t){let{method:e,pathAndQuery:n,body:r,appId:a,timestamp:o,secretKey:c}=t,s=W(r),i=[e.toUpperCase(),n,s,String(a),String(o)].join(`
2
+ `);return C(c,i)}function Z(t){return String(Math.floor(Date.now()/1e3)+t)}function Ke(t){return t.replace(/\/+$/,"")}function We(t,e){for(let n of Object.keys(e)){let r=e[n];r!=null&&t.searchParams.set(n,typeof r=="string"?r:JSON.stringify(r))}}function Ft(t,e){let n=new Date(t);if(isNaN(n.getTime()))return t;let r=a=>String(a).padStart(2,"0");return e.replace("YYYY",String(n.getFullYear())).replace("MM",r(n.getMonth()+1)).replace("DD",r(n.getDate())).replace("HH",r(n.getHours())).replace("mm",r(n.getMinutes())).replace("ss",r(n.getSeconds()))}function F(t,e=G){function n(r){if(Array.isArray(r))return r.map(n);if(r&&typeof r=="object"){let a={};for(let o in r)Object.prototype.hasOwnProperty.call(r,o)&&(o==="createdAt"||o==="updatedAt"?a[o]=Ft(r[o],e):a[o]=n(r[o]));return a}return r}return n(t)}async function Ye(t,e,n,r){let a=t.headers["content-type"]||"",o,c=t.body;if(a.includes("application/json"))try{o=JSON.parse(c)}catch(i){o=c}else o=c;if(e&&o&&typeof o=="object"&&"j"in o)try{let i=await Q(JSON.stringify(o),new TextEncoder().encode(n));try{o=JSON.parse(i)}catch(u){o=i}}catch(i){throw new E(400,"AES-256-GCM decryption failed",i instanceof Error?i.message:null)}let s=t.status>=200&&t.status<300;if(o&&typeof o=="object"&&"data"in o){let i=o;if(i.data=F(i.data,r),!s)throw new E(i.code||t.status,i.message||t.statusText,i.data);return i}if(!s)throw new E(t.status,t.statusText,o);return{code:0,message:"ok",data:F(o,r)}}function Je(t){if(t instanceof E)throw t;if(t instanceof Error){let e=t.message||"Unknown error";throw e.includes("timeout")||e.includes("\u8D85\u65F6")||t.name==="AbortError"||e.includes("abort")?new E(408,"Request timeout",null):new E(0,e,null)}throw new E(0,"Unknown error",t)}var b=null,R=null;function v(){var t;if(b!==null)return b;if(typeof wx!="undefined"&&typeof wx.request=="function")return b="wx",b;if(typeof my!="undefined"&&typeof my.request=="function")return b="my",b;if(typeof window=="undefined"&&typeof document=="undefined"&&typeof global!="undefined"&&typeof global.require=="function")try{if(typeof A!="undefined"&&typeof A("@system.fetch")!="undefined")return b="hap",b}catch(e){}return typeof window!="undefined"&&typeof document!="undefined"?(b="h5",b):typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof((t=process.versions)==null?void 0:t.node)!="undefined"?(b="nodejs",b):(b="unknown",b)}function X(){return R!==null?R:v()!=="wx"?(R="unknown",R):typeof tt!="undefined"&&typeof tt.request=="function"?(R="toutiao",R):typeof qq!="undefined"&&typeof qq.request=="function"?(R="qq",R):(R="wechat",R)}function ee(){let t=v();if(t==="my")return my;if(t!=="wx")return null;switch(X()){case"toutiao":return tt;case"qq":return qq;default:return wx}}function ze(){b=null,R=null}var ye=async t=>{let{url:e,method:n,headers:r,body:a,signal:o}=t,c={method:n,headers:r,signal:o};a!==void 0&&n!=="GET"&&(c.body=a);let s=await fetch(e,c),i={};s.headers.forEach((p,f)=>{i[f.toLowerCase()]=p});let u=await s.text();return{status:s.status,statusText:s.statusText,headers:i,body:u}};var Qe=async t=>{let e=ee();if(!e||typeof e.request!="function")throw new Error("Mini program request API is not available");let n=e.request,{url:r,method:a,headers:o,body:c,timeout:s}=t;return new Promise((i,u)=>{let p=n({url:r,method:a,header:o,data:c,timeout:s!=null?s:3e5,dataType:"text",responseType:"text",success:f=>{var l;let y={};if(f.header)for(let g of Object.keys(f.header))y[g.toLowerCase()]=f.header[g];let d;typeof f.data=="string"?d=f.data:f.data!==void 0&&f.data!==null?d=JSON.stringify(f.data):d="",i({status:f.statusCode,statusText:(l=f.errMsg)!=null?l:"",headers:y,body:d})},fail:f=>{var d;let y=(d=f.errMsg)!=null?d:"Mini program request failed";y.includes("timeout")||y.includes("\u8D85\u65F6")?u(new Error("Request timeout")):u(new Error(y))}});if(t.signal){let f=()=>{typeof p.abort=="function"&&p.abort()};t.signal.addEventListener("abort",f,{once:!0})}})};var Ve=async t=>{let e=my;if(!e||typeof e.request!="function")throw new Error("Alipay mini program request API (my.request) is not available");let n=e.request,{url:r,method:a,headers:o,body:c,timeout:s}=t;return new Promise((i,u)=>{let p=n({url:r,method:a.toUpperCase(),headers:o,data:c!==void 0?c:void 0,timeout:s!=null?s:3e5,dataType:"text",success:f=>{var g,w;let y=(w=(g=f.status)!=null?g:f.statusCode)!=null?w:200,d={};if(f.headers)for(let x of Object.keys(f.headers))d[x.toLowerCase()]=f.headers[x];let l;typeof f.data=="string"?l=f.data:f.data!==void 0&&f.data!==null?l=JSON.stringify(f.data):l="",i({status:y,statusText:"",headers:d,body:l})},fail:f=>{var d,l;let y=(l=(d=f.errorMessage)!=null?d:f.errMsg)!=null?l:`Alipay request failed (error: ${f.error})`;u(new Error(y))},complete:()=>{}});if(t.signal){let f=()=>{p&&typeof p.abort=="function"&&p.abort()};t.signal.addEventListener("abort",f,{once:!0})}})};function $t(){try{return A("@system.fetch")}catch(t){return null}}var Ze=async t=>{let e=$t();if(!e)throw new Error("Quick App fetch module (@system.fetch) is not available. Ensure you are running inside a Quick App environment.");let{url:n,method:r,headers:a,body:o}=t;return new Promise((c,s)=>{e.fetch({url:n,method:r.toUpperCase(),header:a,data:o,responseType:"text",success:i=>{let u={};if(i.headers)for(let p of Object.keys(i.headers))u[p.toLowerCase()]=i.headers[p];c({status:i.code,statusText:"",headers:u,body:typeof i.data=="string"?i.data:JSON.stringify(i.data)})},fail:i=>{s(new Error(`Quick App request failed (code: ${i.code}, data: ${i.data})`))},complete:()=>{}})})};var O=null;function Xe(){if(O!==null)return O;switch(v()){case"h5":case"nodejs":O=ye;break;case"wx":O=Qe;break;case"my":O=Ve;break;case"hap":O=Ze;break;default:if(typeof fetch=="function")O=ye;else throw new Error("Unable to determine platform request adapter. The current environment does not have `fetch`, `wx.request`, `my.request`, or `@system.fetch` available. Please ensure you are running in a supported environment: Web browser, Node.js 18+, WeChat/QQ/Alipay/Toutiao/Douyin Mini Program, or Quick App.");break}return O}async function de(t,e){let{method:n,path:r,params:a,encryption:o,timeout:c}=e,s=Ke(t.baseUrl),i=o!=null?o:t.isSafeMode,u=new URL(s+r),p=I(a),f,y="";if(n!=="GET")if(i&&p!==void 0){let m=await z(JSON.stringify(p),new TextEncoder().encode(t.secretKey));f=m,y=m}else if(p!==void 0){let m=JSON.stringify(p);f=m,y=m}else y="";else p&&typeof p=="object"&&Object.keys(p).length>0&&We(u,p);let d=Number(Z(t.offset)),l=u.pathname+u.search,g=V({method:n,pathAndQuery:l,body:y,appId:t.appId,timestamp:d,secretKey:t.secretKey}),w=Xe(),x=c!=null?c:3e5;try{let m=await w({url:u.toString(),method:n,headers:{"X-T1Y-Application-ID":String(t.appId),"X-T1Y-API-Key":t.apiKey,"X-T1Y-Safe-Timestamp":String(d),"X-T1Y-Safe-Sign":g,"Content-Type":"application/json"},body:n!=="GET"?f:void 0,timeout:x});return await Ye(m,i,t.secretKey,t.timeFormat)}catch(m){return Je(m)}}var $=class{constructor(e,n){this.client=e,this.name=n}async insertOne(e){if(!T(e))throw new TypeError("insertOne data must be a non-empty plain object");return await this.client.request("POST",`/v5/classes/${this.name}`,e)}async deleteById(e){return P(e),await this.client.request("DELETE",`/v5/classes/${this.name}/${e}`)}async updateById(e,n){if(P(e),!T(n))throw new TypeError("update data must be a non-empty plain object");return await this.client.request("PUT",`/v5/classes/${this.name}/${e}`,n)}async findById(e){return P(e),await this.client.request("GET",`/v5/classes/${this.name}/${e}`)}async deleteOne(e){if(!T(e))throw new TypeError("deleteOne filter must be a non-empty plain object");return await this.client.request("DELETE",`/v5/classes/${this.name}/one`,e)}async updateOne(e,n){if(!T(e))throw new TypeError("updateOne filter must be a non-empty plain object");if(!T(n))throw new TypeError("updateOne body must be a non-empty plain object");return await this.client.request("PUT",`/v5/classes/${this.name}/one`,{filter:e,body:n})}async findOne(e){if(!T(e))throw new TypeError("findOne filter must be a non-empty plain object");return await this.client.request("POST",`/v5/classes/${this.name}/one`,e)}async insertMany(e){if(!q(e))throw new TypeError("insertMany dataList must be a non-empty array of non-empty plain objects");return await this.client.request("POST",`/v5/classes/${this.name}/many`,e)}async deleteMany(e){if(!S(e))throw new TypeError("deleteMany filter must be a plain object");return await this.client.request("DELETE",`/v5/classes/${this.name}/many`,e)}async updateMany(e,n){if(!S(e))throw new TypeError("updateMany filter must be a plain object");if(!T(n))throw new TypeError("updateMany body must be a non-empty plain object");return await this.client.request("PUT",`/v5/classes/${this.name}/many`,{filter:e,body:n})}async find(e=1,n=10,r={createdAt:-1},a={}){if(!Number.isInteger(e)||e<1)throw new TypeError("find page must be a positive integer");if(!Number.isInteger(n)||n<1)throw new TypeError("find size must be a positive integer");if(n>100&&(n=100),!T(r))throw new TypeError("find sort must be a non-empty plain object");if(!S(a))throw new TypeError("find filter must be a plain object");return await this.client.request("POST",`/v5/classes/${this.name}/find`,{page:e,size:n,sort:r,filter:a})}async aggregate(e){if(!Array.isArray(e))throw new TypeError("aggregate pipeline must be an array");return await this.client.request("POST",`/v5/classes/${this.name}/aggregate`,e)}async count(e={}){if(!S(e))throw new TypeError("count filter must be a plain object");return await this.client.request("POST",`/v5/classes/${this.name}/count`,e)}async distinct(e,n={}){if(typeof e!="string"||e.length===0)throw new TypeError("distinct fieldName must be a non-empty string");if(!S(n))throw new TypeError("distinct filter must be a plain object");return await this.client.request("POST",`/v5/classes/${this.name}/distinct/${encodeURIComponent(e)}`,n)}async create(){return await this.client.request("POST",`/v5/schemas/${encodeURIComponent(this.name)}`)}async clear(){return await this.client.request("PUT",`/v5/schemas/${encodeURIComponent(this.name)}`)}async drop(){return await this.client.request("DELETE",`/v5/schemas/${encodeURIComponent(this.name)}`)}};var k,et,nt,rt,ot,te=class{constructor(e){Te(this,k);var n,r,a,o,c;K(e),this.config={baseUrl:(n=e.baseUrl)!=null?n:Ee,appId:e.appId,apiKey:e.apiKey,secretKey:e.secretKey,version:(r=e.version)!=null?r:0,isSafeMode:(a=e.isSafeMode)!=null?a:!1,timeFormat:(o=e.timeFormat)!=null?o:G,offset:(c=e.offset)!=null?c:0},this.db={collection:s=>B(this,k,et).call(this,s),toObjectID:s=>B(this,k,rt).call(this,s),getCollections:()=>B(this,k,nt).call(this)}}async init(){try{let n=(await this.request("GET",`/init/${this.config.appId}`,void 0,!1)).data;this.config.isSafeMode=n.is_safe_mode,this.config.offset=n.unix-Math.floor(Date.now()/1e3)}catch(e){console.warn("Failed to get time offset from server, defaulting to 0. Error:",e),this.config.isSafeMode=!1,this.config.offset=0}}async getMeta(e){if(e!==void 0&&e!==""&&typeof e!="string")throw new TypeError("Meta field must be a string");let n=e?`?field=${encodeURIComponent(e)}`:"";return await this.request("GET",`/v5/meta${n}`)}async checkUpdate(){try{return(await this.request("GET","/v5/meta?field=version")).data.result>this.config.version}catch(e){return!1}}async callFunc(e,n=null,r){if(typeof e!="string")throw new TypeError("Function name must be a string");return await this.request("POST",`/${this.config.appId}/${B(this,k,ot).call(this,e)}`,n,r)}async request(e,n,r,a){if(typeof n!="string")throw new TypeError("request path must be a string");return await de(this.config,{method:e,path:n,params:r,encryption:a!=null?a:this.config.isSafeMode})}assertObjectID(e,n="ObjectID"){return P(e,n)}isNonEmptyObject(e){return T(e)}isPlainObject(e){return S(e)}isNonEmptyArrayWithNonEmptyObjects(e){return q(e)}hmacSHA256(e,n){return C(e,n)}verifyHmacSHA256(e,n,r){return Y(e,n,r)}};k=new WeakSet,et=function(e){if(typeof e!="string")throw new TypeError("Collection name must be a string");return new $(this,e)},nt=async function(){return await this.request("GET","/v5/schemas")},rt=function(e){return P(e),`ObjectID('${e}')`},ot=function(e){let n=e.startsWith("/")?e.slice(1):e,r=n.indexOf("#"),a=r!==-1?n.slice(r):"",o=r!==-1?n.slice(0,r):n,c=o.indexOf("?"),s=c!==-1?o.slice(c):"",i=c!==-1?o.slice(0,c):o;return i.endsWith("/")?i=i+"index.jsc":i.endsWith(".jsc")||(i.endsWith(".js")?i=i.replace(/\.js$/,".jsc"):i=i+".jsc"),i+s+a};var Yt=te;function st(t){if(!L.test(t))throw new Error(`Invalid ObjectID: "${t}" (must be 24 hex characters)`);return`ObjectID('${t}')`}function it(t){return`Date('${t}')`}function at(t){return`DateTime('${t}')`}function ct(t){return`Timestamp('${String(t)}')`}function ut(t){return`Boolean(${t})`}function ft(t){return`Integer(${t})`}function pt(t){return`Bigint(${Number(t)})`}function lt(t){return`Float(${t})`}function yt(t){return`Double(${t})`}function dt(t){return`Array(${JSON.stringify(t)})`}function mt(t){return`Map(${JSON.stringify(t)})`}function xt(t){return`Map[](${JSON.stringify(t)})`}var gt="Null",bt="None",ht="Nil",wt="",At="UNDEFINED",Tt="Undefined";var me="time.Now()",xe="time.Now().Unix()",ge="time.Now().UnixNano()",be="time.Now().Weekday()",he="time.Now().Weekday().Chinese()",Et={Now:()=>me,NowUnix:()=>xe,NowUnixNano:()=>ge,NowWeekday:()=>be,NowWeekdayChinese:()=>he};export{dt as Array,pt as Bigint,ut as Boolean,it as Date,at as DateTime,yt as Double,wt as Empty,lt as Float,ft as Integer,mt as Map,xt as MapArray,ht as Nil,bt as None,gt as Null,st as ObjectID,$ as T1Collection,E as T1YError,te as T1YOS,me as TimeNow,xe as TimeNowUnix,ge as TimeNowUnixNano,be as TimeNowWeekday,he as TimeNowWeekdayChinese,ct as Timestamp,At as UNDEFINED,Tt as Undefined,h as ValidationError,P as assertObjectID,I as convertDateTypes,V as createSignature,Q as decryptAESGCM,Yt as default,z as encryptAESGCM,F as formatTimestampsToLocal,ee as getMiniProgramAPI,X as getMiniProgramSubType,v as getPlatformType,Z as getSafeTimestamp,C as hmacSHA256Hex,qe as hmacSHA256HexAsync,$e as isAESGCMAvailable,q as isNonEmptyArrayWithNonEmptyObjects,T as isNonEmptyObject,S as isPlainObject,Ge as isWebCryptoAvailable,ze as resetPlatformDetection,W as sha256Hex,Pe as sha256HexAsync,Et as timeNow,se as validateApiKey,oe as validateAppId,ae as validateBaseUrl,K as validateInitConfig,ie as validateSecretKey,Y as verifyHmacSHA256};
3
3
  //# sourceMappingURL=index.mjs.map