@vaiftech/client 1.0.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/LICENSE +21 -0
- package/README.md +202 -0
- package/dist/index.d.mts +5929 -0
- package/dist/index.d.ts +5929 -0
- package/dist/index.js +1 -0
- package/dist/index.mjs +1 -0
- package/package.json +64 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var E=class i extends Error{constructor(n,e){super(n),this.name="VaifError",this.code=e.code,this.statusCode=e.statusCode,this.requestId=e.requestId,this.details=e.details;let t=Error;t.captureStackTrace&&t.captureStackTrace(this,i);}toJSON(){return {name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,requestId:this.requestId,details:this.details}}},M=class extends E{constructor(n,e){super(n,{code:e?.code??"AUTH_ERROR",statusCode:e?.statusCode??401,requestId:e?.requestId}),this.name="VaifAuthError";}},U=class extends E{constructor(n,e){super(n,{code:"VALIDATION_ERROR",statusCode:400,requestId:e?.requestId,details:e?.details??e?.fieldErrors}),this.name="VaifValidationError",this.fieldErrors=e?.fieldErrors;}},x=class extends E{constructor(n,e){super(n,{code:"NETWORK_ERROR"}),this.name="VaifNetworkError",this.cause=e;}},F=class extends E{constructor(n,e){super(n,{code:"RATE_LIMITED",statusCode:429}),this.name="VaifRateLimitError",this.retryAfter=e;}},j=class extends E{constructor(n,e){super(n,{code:"NOT_FOUND",statusCode:404,requestId:e}),this.name="VaifNotFoundError";}};function pe(i){return i instanceof E}async function me(i){let n;try{n=await i.json();}catch{}let e=n?.message??n?.error??i.statusText??"Request failed",t=n?.requestId;switch(i.status){case 400:return new U(e,{details:n?.details,requestId:t});case 401:return new M(e,{code:"UNAUTHORIZED",statusCode:401,requestId:t});case 403:return new M(e,{code:"FORBIDDEN",statusCode:403,requestId:t});case 404:return new j(e,t);case 429:{let r=i.headers.get("Retry-After"),s=r?parseInt(r,10):void 0;return new F(e,s)}default:return new E(e,{code:n?.error??"HTTP_ERROR",statusCode:i.status,requestId:t,details:n?.details})}}async function ye(i,n){let{timeout:e=3e4,fetchFn:t,...r}=n,s=new AbortController,a=setTimeout(()=>s.abort(),e);try{let l=await t(i,{...r,signal:s.signal});if(clearTimeout(a),!l.ok)throw await me(l);if(l.status===204)return;let o=await l.text();return o?JSON.parse(o):void 0}catch(l){throw clearTimeout(a),l instanceof E?l:l instanceof Error&&l.name==="AbortError"?new x("Request timed out"):l instanceof Error?new x(l.message,l):new x("Network request failed")}}function p(i){let{baseUrl:n,apiKey:e,apiKeyHeader:t,accessToken:r,fetch:s,timeout:a}=i;return async function(o,c={}){let g=`${n}${o}`,m={"Content-Type":"application/json",...c.headers??{}};if(e&&(m[t]=e),r){let h=typeof r=="function"?await r():r;m.Authorization=`Bearer ${h}`;}return ye(g,{...c,headers:m,timeout:a,fetchFn:s})}}function v(i){let n=new URLSearchParams;for(let[t,r]of Object.entries(i))r!==void 0&&n.set(t,String(r));let e=n.toString();return e?`?${e}`:""}function be(i){return JSON.stringify(i)}function L(i,n,e={}){let t={...e},r=()=>{let o={};if(t.limit!==void 0&&(o.limit=t.limit),t.offset!==void 0&&(o.offset=t.offset),t.where&&(o.where=be(t.where)),t.orderBy){let c=Array.isArray(t.orderBy)?t.orderBy:[t.orderBy];o.orderBy=JSON.stringify(c);}return t.select&&t.select.length>0&&(o.select=t.select.join(",")),t.include&&t.include.length>0&&(o.include=JSON.stringify(t.include)),t.distinct&&t.distinct.length>0&&(o.distinct=t.distinct.join(",")),o},s=()=>v(r()),a=o=>L(i,n,{...t,...o}),l={async list(o){o&&(t={...t,...o});let c=s();return n(`/generated/${i}${c}`)},async get(o){let c={};t.select&&t.select.length>0&&(c.select=t.select.join(",")),t.include&&t.include.length>0&&(c.include=JSON.stringify(t.include));let g=v(c);return n(`/generated/${i}/${encodeURIComponent(o)}${g}`)},async first(){let o=await l.limit(1).list();return o.data.length>0?o.data[0]:null},async firstOrFail(){let o=await l.first();if(!o)throw new Error(`No record found in table '${i}' matching the query`);return o},async create(o){return n(`/generated/${i}`,{method:"POST",body:JSON.stringify(o)})},async update(o,c){return n(`/generated/${i}/${encodeURIComponent(o)}`,{method:"PATCH",body:JSON.stringify(c)})},async delete(o){return n(`/generated/${i}/${encodeURIComponent(o)}`,{method:"DELETE"})},async createMany(o,c){return n(`/generated/${i}/batch`,{method:"POST",body:JSON.stringify({records:o,skipOnConflict:c?.skipOnConflict,returnRecords:c?.returnRecords})})},async updateMany(o,c){r();return n(`/generated/${i}/batch`,{method:"PATCH",body:JSON.stringify({data:o,where:t.where,returnRecords:c?.returnRecords})})},async deleteMany(){return n(`/generated/${i}/batch`,{method:"DELETE",body:JSON.stringify({where:t.where})})},async upsert(o,c){return n(`/generated/${i}/upsert`,{method:"POST",body:JSON.stringify({data:o,conflictFields:c.conflictFields,updateFields:c.updateFields})})},async count(){let o=r(),c=v(o);return (await n(`/generated/${i}/count${c}`)).count},async sum(o){let c=r(),g=v({...c,field:o});return (await n(`/generated/${i}/sum${g}`)).sum},async avg(o){let c=r(),g=v({...c,field:o});return (await n(`/generated/${i}/avg${g}`)).avg},async min(o){let c=r(),g=v({...c,field:o});return (await n(`/generated/${i}/min${g}`)).min},async max(o){let c=r(),g=v({...c,field:o});return (await n(`/generated/${i}/max${g}`)).max},async aggregate(o,c){return n(`/generated/${i}/aggregate`,{method:"POST",body:JSON.stringify({aggregates:o,where:c?.where||t.where,groupBy:c?.groupBy,having:c?.having})})},async paginate(o){let c=o.page||1,g=o.pageSize||20,m=(c-1)*g,h=r();h.limit=g,h.offset=m,h.includeCount=true;let S=v(h),I=await n(`/generated/${i}${S}`),R=I.total||I.data.length,b=Math.ceil(R/g);return {data:I.data,pageInfo:{total:R,page:c,pageSize:g,pageCount:b,hasNextPage:c<b,hasPrevPage:c>1}}},async cursorPaginate(o){let c=r();c.limit=o.limit||20,o.cursor&&(c.cursor=o.cursor);let g=v(c),m=await n(`/generated/${i}/cursor${g}`);return {data:m.data,nextCursor:m.nextCursor,prevCursor:m.prevCursor,hasMore:m.hasMore}},where(o){if(t.where){let c=t.where;return a({where:{AND:[...Array.isArray(c)?c:[c],o]}})}return a({where:o})},orderBy(o,c="asc"){let g={field:o,direction:c};if(t.orderBy){let m=Array.isArray(t.orderBy)?t.orderBy:[t.orderBy];return a({orderBy:[...m,g]})}return a({orderBy:g})},select(...o){return a({select:o})},limit(o){return a({limit:o})},offset(o){return a({offset:o})},include(o){let c=t.include||[];return a({include:[...c,o]})},distinct(...o){return a({distinct:o})}};return l}function V(i){let n=p(i);return {from(e){return L(e,n)},async raw(e,t){return n("/generated/raw",{method:"POST",body:JSON.stringify({query:e,params:t})})},async transaction(e,t){return n("/generated/transaction",{method:"POST",body:JSON.stringify({operations:e,isolationLevel:t?.isolationLevel,timeout:t?.timeout})})},async withTransaction(e,t){let s=(await n("/generated/transaction/start",{method:"POST",body:JSON.stringify({isolationLevel:t?.isolationLevel,timeout:t?.timeout})})).transactionId,a=(o,c)=>{let g=new Headers(c?.headers);return g.set("X-Transaction-Id",s),n(o,{...c,headers:g})},l={from(o){return L(o,a)},async raw(o,c){return a("/generated/raw",{method:"POST",body:JSON.stringify({query:o,params:c})})},async transaction(){throw new Error("Nested transactions are not supported")},async withTransaction(){throw new Error("Nested transactions are not supported")}};try{let o=await e(l);return await n("/generated/transaction/commit",{method:"POST",body:JSON.stringify({transactionId:s})}),o}catch(o){throw await n("/generated/transaction/rollback",{method:"POST",body:JSON.stringify({transactionId:s})}).catch(()=>{}),o}}}}function q(i){let n=p(i);return {async signUp(e,t,r){return n("/auth/signup",{method:"POST",body:JSON.stringify({email:e,password:t,name:r?.name,phone:r?.phone,metadata:r?.metadata,redirectUrl:r?.redirectUrl})})},async login(e,t,r){return n("/auth/login",{method:"POST",body:JSON.stringify({email:e,password:t,mfaCode:r?.mfaCode,rememberMe:r?.rememberMe})})},async logout(){await n("/auth/logout",{method:"POST"});},async logoutAll(){await n("/auth/logout-all",{method:"POST"});},async getUser(){return (await n("/auth/me")).user},async updateProfile(e){return (await n("/users/me",{method:"PATCH",body:JSON.stringify(e)})).user},async changePassword(e){return n("/users/me/change-password",{method:"POST",body:JSON.stringify(e)})},async requestPasswordReset(e){return n("/auth/forgot-password",{method:"POST",body:JSON.stringify(e)})},async confirmPasswordReset(e){return n("/auth/reset-password",{method:"POST",body:JSON.stringify(e)})},async requestEmailVerification(e){return n("/auth/verify-email/send",{method:"POST",body:JSON.stringify(e||{})})},async confirmEmailVerification(e){return n("/auth/verify-email/confirm",{method:"POST",body:JSON.stringify(e)})},async getOAuthSignInUrl(e){return n("/auth/oauth/authorize",{method:"POST",body:JSON.stringify(e)})},async handleOAuthCallback(e){return n("/auth/oauth/callback",{method:"POST",body:JSON.stringify(e)})},async linkOAuthProvider(e){return n("/auth/oauth/link",{method:"POST",body:JSON.stringify(e)})},async unlinkOAuthProvider(e){return n(`/auth/oauth/unlink/${e}`,{method:"POST"})},async listLinkedProviders(){return n("/auth/oauth/providers")},async requestMagicLink(e){return n("/auth/magic-link/send",{method:"POST",body:JSON.stringify(e)})},async verifyMagicLink(e){return n("/auth/magic-link/verify",{method:"POST",body:JSON.stringify(e)})},async requestPhoneVerification(e){return n("/auth/phone/send",{method:"POST",body:JSON.stringify(e)})},async confirmPhoneVerification(e){return n("/auth/phone/verify",{method:"POST",body:JSON.stringify(e)})},async setupMFA(e){return n("/auth/mfa/setup",{method:"POST",body:JSON.stringify({method:e})})},async enableMFA(e){return n("/auth/mfa/enable",{method:"POST",body:JSON.stringify({code:e})})},async disableMFA(e){return n("/auth/mfa/disable",{method:"POST",body:JSON.stringify({code:e})})},async verifyMFA(e,t){return n("/auth/mfa/verify",{method:"POST",body:JSON.stringify({mfaToken:e,code:t})})},async regenerateBackupCodes(){return n("/auth/mfa/backup-codes",{method:"POST"})},async refreshToken(e){return n("/auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:e})})},async listSessions(){return n("/auth/sessions")},async revokeSession(e){return n(`/auth/sessions/${e}`,{method:"DELETE"})},async revokeOtherSessions(){return n("/auth/sessions/revoke-others",{method:"POST"})}}}function J(i){return new Promise(n=>setTimeout(n,i))}function H(i){let n=p(i);async function e(t,r,s){let a=s?.retry||{},l=a.maxRetries??0,o=a.initialDelay??1e3,c=a.maxDelay??3e4,g=a.backoffMultiplier??2,m=a.retryOnStatus??[429,500,502,503,504],h=a.retryOnNetworkError??true,S=null,I=o;for(let R=0;R<=l;R++)try{let b={};s?.version!==void 0&&(b.version=s.version),s?.includeLogs&&(b.includeLogs=!0);let C=v(b),D=await n(`/functions/${t}/invoke${C}`,{method:"POST",body:JSON.stringify(r??{}),headers:s?.headers});if(m.includes(D.status)&&R<l){S=new Error(`Function returned status ${D.status}`),await J(I),I=Math.min(I*g,c);continue}return D}catch(b){S=b;let C=b instanceof TypeError||b.message?.includes("network")||b.message?.includes("fetch");if(h&&C&&R<l){await J(I),I=Math.min(I*g,c);continue}throw b}throw S||new Error("Function invocation failed after retries")}return {invoke:e,async invokeByName(t,r,s){let a={};s?.version!==void 0&&(a.version=s.version),s?.includeLogs&&(a.includeLogs=true);let l=v(a);return n(`/functions/name/${encodeURIComponent(t)}/invoke${l}`,{method:"POST",body:JSON.stringify(r??{}),headers:s?.headers})},async batchInvoke(t,r){let a=(await Promise.allSettled(t.map(l=>this.invoke(l.functionId,l.input,r)))).map((l,o)=>l.status==="fulfilled"?{functionId:t[o].functionId,success:true,result:l.value}:{functionId:t[o].functionId,success:false,error:l.reason?.message||"Unknown error"});return {results:a,successCount:a.filter(l=>l.success).length,errorCount:a.filter(l=>!l.success).length}},rpc(t,r){let s=this,a=async(l,o)=>{let c={...r,...o};return (await e(t,{body:l},c)).data};return Object.defineProperty(a,"id",{value:t,writable:false}),a.getInfo=()=>s.get(t),a.getInvocations=l=>s.getInvocations({...l,functionId:t}),a},async list(t){let r={envId:t.envId,enabled:t.enabled,limit:t.limit,offset:t.offset},s=v(r);return n(`/functions/project/${t.projectId}${s}`)},async get(t){return n(`/functions/${t}`)},async getByName(t,r){return n(`/functions/project/${r}/name/${encodeURIComponent(t)}`)},async create(t){return n("/functions",{method:"POST",body:JSON.stringify(t)})},async update(t,r){return n(`/functions/${t}`,{method:"PATCH",body:JSON.stringify(r)})},async delete(t){return n(`/functions/${t}`,{method:"DELETE"})},async enable(t){return this.update(t,{enabled:true})},async disable(t){return this.update(t,{enabled:false})},async deploy(t,r,s){return n(`/functions/${t}/deploy`,{method:"POST",body:JSON.stringify({sourceCode:r,createVersion:s?.createVersion,versionDescription:s?.versionDescription,envVars:s?.envVars,secrets:s?.secrets})})},async getSource(t,r){let s=r!==void 0?`?version=${r}`:"";return n(`/functions/${t}/source${s}`)},async listVersions(t){return (await n(`/functions/${t}/versions`)).versions},async rollback(t,r){return n(`/functions/${t}/rollback`,{method:"POST",body:JSON.stringify({version:r})})},async getEnvVars(t){return (await n(`/functions/${t}/env`)).envVars},async setEnvVars(t,r){return n(`/functions/${t}/env`,{method:"PUT",body:JSON.stringify({envVars:r})})},async deleteEnvVar(t,r){return n(`/functions/${t}/env/${encodeURIComponent(r)}`,{method:"DELETE"})},async bindSecrets(t,r){return n(`/functions/${t}/secrets`,{method:"PUT",body:JSON.stringify({secrets:r})})},async setSchedule(t,r){return n(`/functions/${t}/schedule`,{method:"PUT",body:JSON.stringify(r)})},async removeSchedule(t){return n(`/functions/${t}/schedule`,{method:"DELETE"})},async getInvocations(t){let r={functionId:t.functionId,projectId:t.projectId,status:t.status,since:t.since,until:t.until,limit:t.limit,offset:t.offset},s=v(r);return (await n(`/functions/invocations${s}`)).invocations},async getInvocation(t){return n(`/functions/invocations/${t}`)},async getLogs(t,r){let s={since:r?.since,until:r?.until,level:r?.level,limit:r?.limit},a=v(s);return (await n(`/functions/${t}/logs${a}`)).logs}}}function K(i){let n=p(i),e="default";return {async getUploadUrl(t,r){return n("/storage/upload-url",{method:"POST",body:JSON.stringify({key:t,bucket:r?.bucket||e,contentType:r?.contentType,sizeBytes:r?.sizeBytes,metadata:r?.metadata,isPublic:r?.isPublic,cacheControl:r?.cacheControl,contentDisposition:r?.contentDisposition,upsert:r?.upsert})})},async getDownloadUrl(t,r){return n("/storage/download-url",{method:"POST",body:JSON.stringify({key:t,bucket:r?.bucket||e,expiresIn:r?.expiresIn,download:r?.download,transform:r?.transform})})},async createSignedUrl(t,r=3600,s){return (await this.getDownloadUrl(t,{...s,expiresIn:r})).url},async createSignedUrls(t,r=3600,s){return await Promise.all(t.map(async l=>({key:l,url:await this.createSignedUrl(l,r,s)})))},async upload(t,r,s){let a=r instanceof Blob?r:new Blob([r]),l=a.size,o=s?.contentType||(r instanceof File?r.type:void 0)||"application/octet-stream",c=await this.getUploadUrl(t,{...s,contentType:o,sizeBytes:l}),g=await i.fetch(c.url,{method:"PUT",body:a,headers:{"Content-Type":o,...s?.cacheControl&&{"Cache-Control":s.cacheControl},...s?.contentDisposition&&{"Content-Disposition":s.contentDisposition}}});if(!g.ok)throw new Error(`Upload failed: ${g.statusText}`);let m=s?.bucket||e,h=c.url.split("?")[0];return {ok:true,key:t,bucket:m,url:h,publicUrl:s?.isPublic?this.getPublicUrl(t,{bucket:m}):void 0,size:l,contentType:o}},async uploadFromUrl(t,r,s){return n("/storage/upload-from-url",{method:"POST",body:JSON.stringify({key:t,url:r,bucket:s?.bucket||e,contentType:s?.contentType,metadata:s?.metadata,isPublic:s?.isPublic,timeout:s?.timeout})})},async download(t,r){let s=await this.getDownloadUrl(t,r),a=await i.fetch(s.url);if(!a.ok)throw new Error(`Download failed: ${a.statusText}`);return a.blob()},async list(t){let r={bucket:t?.bucket||e,prefix:t?.prefix,delimiter:t?.delimiter,limit:t?.limit,cursor:t?.cursor,includeUrls:t?.includeUrls},s=v(r);return n(`/storage/files${s}`)},async getMetadata(t,r){let s=r?.bucket||e;return n(`/storage/files/${encodeURIComponent(s)}/${encodeURIComponent(t)}/metadata`)},async updateMetadata(t,r,s){let a=s?.bucket||e;return n(`/storage/files/${encodeURIComponent(a)}/${encodeURIComponent(t)}/metadata`,{method:"PATCH",body:JSON.stringify(r)})},async exists(t,r){try{return await this.getMetadata(t,r),!0}catch{return false}},async copy(t,r,s){return n("/storage/files/copy",{method:"POST",body:JSON.stringify({sourceKey:t,sourceBucket:s?.sourceBucket||e,destinationKey:r,destinationBucket:s?.destinationBucket||s?.sourceBucket||e,metadata:s?.metadata})})},async move(t,r,s){return n("/storage/files/move",{method:"POST",body:JSON.stringify({sourceKey:t,sourceBucket:s?.sourceBucket||e,destinationKey:r,destinationBucket:s?.destinationBucket||s?.sourceBucket||e,metadata:s?.metadata})})},async delete(t,r){let s=r?.bucket||e;await n(`/storage/files/${encodeURIComponent(s)}/${encodeURIComponent(t)}`,{method:"DELETE"});},async deleteMany(t,r){return n("/storage/files/delete-batch",{method:"POST",body:JSON.stringify({keys:t,bucket:r?.bucket||e})})},getPublicUrl(t,r){let s=r?.bucket||e;return `${i.baseUrl.replace("/api","")}/storage/${encodeURIComponent(s)}/${encodeURIComponent(t)}`},async createBucket(t,r){return n("/storage/buckets",{method:"POST",body:JSON.stringify({name:t,isPublic:r?.isPublic,allowedMimeTypes:r?.allowedMimeTypes,maxFileSize:r?.maxFileSize,fileSizeLimit:r?.fileSizeLimit})})},async getBucket(t){return n(`/storage/buckets/${encodeURIComponent(t)}`)},async updateBucket(t,r){return n(`/storage/buckets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(r)})},async listBuckets(){return (await n("/storage/buckets")).buckets},async deleteBucket(t){await n(`/storage/buckets/${encodeURIComponent(t)}`,{method:"DELETE"});},async emptyBucket(t){return n(`/storage/buckets/${encodeURIComponent(t)}/empty`,{method:"POST"})},async createMultipartUpload(t,r){return n("/storage/multipart/create",{method:"POST",body:JSON.stringify({key:t,bucket:r?.bucket||e,contentType:r?.contentType,metadata:r?.metadata,partSize:r?.partSize})})},async uploadPart(t,r,s){let a=s instanceof Blob?s:new Blob([s]),{url:l}=await n(`/storage/multipart/${t}/part-url`,{method:"POST",body:JSON.stringify({partNumber:r})}),o=await i.fetch(l,{method:"PUT",body:a});if(!o.ok)throw new Error(`Part upload failed: ${o.statusText}`);let c=o.headers.get("etag")||"";return {partNumber:r,etag:c}},async completeMultipartUpload(t,r){return n(`/storage/multipart/${t}/complete`,{method:"POST",body:JSON.stringify({parts:r})})},async abortMultipartUpload(t){await n(`/storage/multipart/${t}/abort`,{method:"POST"});}}}function z(i){let n=p(i);return {async list(){return n("/projects")},async get(e){return n(`/projects/${e}`)},async create(e){return n("/projects",{method:"POST",body:JSON.stringify(e)})},async getApiKeys(e){return n(`/projects/${e}/api-keys`)},async createApiKey(e,t){return n(`/projects/${e}/api-keys`,{method:"POST",body:JSON.stringify(t??{})})},async revokeApiKey(e,t){return n(`/projects/${e}/api-keys/${t}/revoke`,{method:"POST"})},async rotateApiKey(e,t){return n(`/projects/${e}/api-keys/${t}/rotate`,{method:"POST"})}}}function _(i){let n=p(i);return {async list(){return n("/orgs")},async create(e){return n("/orgs",{method:"POST",body:JSON.stringify(e)})},async getProfile(e){return (await n(`/orgs/${e}/profile`)).profile||{}},async updateProfile(e,t){return (await n(`/orgs/${e}/profile`,{method:"PATCH",body:JSON.stringify(t)})).profile},async listBillingContacts(e){return (await n(`/orgs/${e}/billing-contacts`)).contacts},async addBillingContact(e,t){return n(`/orgs/${e}/billing-contacts`,{method:"POST",body:JSON.stringify(t)})},async removeBillingContact(e,t){return n(`/orgs/${e}/billing-contacts/${t}`,{method:"DELETE"})},async listMembers(e){return (await n(`/orgs/${e}/members`)).members},async inviteMember(e,t){return n(`/orgs/${e}/members/invite`,{method:"POST",body:JSON.stringify(t)})},async listInvites(e){return (await n(`/orgs/${e}/invites`)).invites},async cancelInvite(e,t){return n(`/orgs/${e}/invites/${t}`,{method:"DELETE"})},async removeMember(e,t){return n(`/orgs/${e}/members/${t}`,{method:"DELETE"})},async updateMemberRole(e,t,r){return n(`/orgs/${e}/members/${t}/role`,{method:"PATCH",body:JSON.stringify({role:r})})}}}function W(i){let n=p(i);return {async preview(e){return n("/schema-engine/preview",{method:"POST",body:JSON.stringify(e)})},async apply(e){return n("/schema-engine/apply",{method:"POST",body:JSON.stringify(e)})},async getMigrations(e,t){let r=t?`/schema-engine/migrations/project/${e}?limit=${t}`:`/schema-engine/migrations/project/${e}`;return n(r)},async saveSchema(e){return n("/schemas/",{method:"POST",body:JSON.stringify(e)})},async getSchemas(e){return n(`/schemas/project/${e}`)}}}function G(i){let n=p(i);return {async create(e){return n("/functions/secrets",{method:"POST",body:JSON.stringify(e)})},async list(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let s=r.toString(),a=`/functions/secrets/project/${e}${s?`?${s}`:""}`;return n(a)},async reveal(e){return n(`/functions/secrets/${e}/value`)},async update(e,t){return n(`/functions/secrets/${e}`,{method:"PUT",body:JSON.stringify({value:t})})},async delete(e){return n(`/functions/secrets/${e}`,{method:"DELETE"})}}}function Q(i){let n=p(i);return {async list(e,t){let r=new URLSearchParams;t&&r.set("env",t);let s=r.toString(),a=`/deployments/project/${e}${s?`?${s}`:""}`;return (await n(a)).deployments},async get(e){let t=await n(`/deployments/${e}`);return {...t.deployment,steps:t.steps}},async getSteps(e){return (await n(`/deployments/${e}/steps`)).steps},async promote(e){let t={projectId:e.projectId,fromEnv:e.sourceEnv,toEnv:e.targetEnv},r=await n("/deployments/promote",{method:"POST",body:JSON.stringify(t)}),s=await n(`/deployments/${r.deploymentId}`);return {deployment:{...s.deployment,steps:s.steps}}},async rollback(e){return n(`/deployments/${e}/rollback`,{method:"POST"})},async listTokens(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let s=r.toString(),a=`/deployments/tokens/project/${encodeURIComponent(e)}${s?`?${s}`:""}`;return (await n(a)).tokens},async createToken(e){return n("/deployments/tokens",{method:"POST",body:JSON.stringify(e)})},async revokeToken(e){return n(`/deployments/tokens/${encodeURIComponent(e)}/revoke`,{method:"POST"})}}}function X(i){let n=p(i);return {async getStats(e){return n(`/realtime/stats/project/${e}`)},async getConnections(e){return (await n(`/realtime/connections/project/${e}`)).connections},async getSubscriptions(e){return (await n(`/realtime/subscriptions/project/${e}`)).subscriptions},async getEvents(e,t){let r=new URLSearchParams;t&&r.set("limit",String(t));let s=r.toString(),a=`/realtime/events/project/${e}${s?`?${s}`:""}`;return (await n(a)).events},async getStatus(e){return n(`/realtime/status/project/${e}`)},async install(e){return n("/realtime/install",{method:"POST",body:JSON.stringify(e)})},async enableAll(e){return n("/realtime/enable-all",{method:"POST",body:JSON.stringify(e)})}}}function Z(i){let n=p(i);return {async listBuckets(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let s=r.toString(),a=`/buckets/project/${e}${s?`?${s}`:""}`;return (await n(a)).buckets},async getBucket(e){return (await n(`/buckets/${e}`)).bucket},async createBucket(e){return (await n("/buckets",{method:"POST",body:JSON.stringify(e)})).bucket},async updateBucket(e,t){return (await n(`/buckets/${e}`,{method:"PUT",body:JSON.stringify(t)})).bucket},async deleteBucket(e){return n(`/buckets/${e}`,{method:"DELETE"})},async listFiles(e,t){let r=new URLSearchParams;t?.prefix&&r.set("prefix",t.prefix),t?.maxKeys&&r.set("maxKeys",String(t.maxKeys)),t?.continuationToken&&r.set("continuationToken",t.continuationToken);let s=r.toString(),a=`/buckets/${e}/files${s?`?${s}`:""}`;return n(a)},async deleteFile(e,t){return n(`/buckets/${e}/files?key=${encodeURIComponent(t)}`,{method:"DELETE"})},async getSignedUrl(e,t,r){return n(`/buckets/${e}/signed-url`,{method:"POST",body:JSON.stringify({key:t,expiresIn:r})})},async getUploadUrl(e,t,r){return n(`/buckets/${e}/upload-url`,{method:"POST",body:JSON.stringify({key:t,...r})})},async uploadFile(e,t,r,s){let a=s?.prefix?`${s.prefix}${t}`:t,l=s?.contentType??(r instanceof Blob?r.type:"application/octet-stream"),o=new URLSearchParams;return o.set("key",a),l&&o.set("contentType",l),n(`/buckets/${e}/upload?${o.toString()}`,{method:"POST",body:r,headers:{"Content-Type":l||"application/octet-stream"}})}}}function Y(i){let n=p(i);return {async list(e,t){let r={type:t?.type,enabled:t?.enabled},s=v(r);return (await n(`/integrations/subscriptions/project/${e}${s}`)).subscriptions},async get(e){return n(`/integrations/subscriptions/${e}`)},async create(e){return (await n("/integrations/subscriptions",{method:"POST",body:JSON.stringify(e)})).subscription},async update(e,t){return (await n(`/integrations/subscriptions/${e}`,{method:"PATCH",body:JSON.stringify(t)})).subscription},async delete(e){return n(`/integrations/subscriptions/${e}`,{method:"DELETE"})},async enable(e){return this.update(e,{enabled:true})},async disable(e){return this.update(e,{enabled:false})},async test(e){return n(`/integrations/subscriptions/${e}/test`,{method:"POST"})},async publish(e){return n("/integrations/events/publish",{method:"POST",body:JSON.stringify(e)})},async publishBatch(e){return (await n("/integrations/events/publish-batch",{method:"POST",body:JSON.stringify({events:e})})).results},async listEvents(e){let t={envId:e.envId,source:e.source,name:e.name,since:e.since,until:e.until,limit:e.limit,offset:e.offset},r=v(t);return (await n(`/integrations/events/project/${e.projectId}${r}`)).events},async getEvent(e){return n(`/integrations/events/${e}`)},async getDeliveries(e){let t={subscriptionId:e.subscriptionId,eventId:e.eventId,status:e.status,since:e.since,until:e.until,limit:e.limit,offset:e.offset},r=v(t);return (await n(`/integrations/deliveries${r}`)).deliveries},async getDelivery(e){return n(`/integrations/deliveries/${e}`)},async retryDelivery(e){return n(`/integrations/deliveries/${e}/retry`,{method:"POST"})},async retryAllFailed(e){return n(`/integrations/subscriptions/${e}/retry-failed`,{method:"POST"})},async getDlq(e,t){let r={limit:t?.limit,offset:t?.offset},s=v(r);return (await n(`/integrations/dlq/project/${e}${s}`)).deliveries},async purgeDlq(e,t){return n(`/integrations/dlq/project/${e}/purge`,{method:"POST",body:JSON.stringify({olderThan:t.olderThan})})},async replayDlq(e,t){return n(`/integrations/dlq/project/${e}/replay`,{method:"POST",body:JSON.stringify(t)})},verifySignature(e){let t=e.tolerance??300;try{let r=e.signature.split(","),s=r.find(b=>b.startsWith("t=")),a=r.find(b=>b.startsWith("v1="));if(!s||!a)return !1;let l=parseInt(s.slice(2),10),o=a.slice(3),c=Math.floor(Date.now()/1e3);if(Math.abs(c-l)>t)return !1;let g=`${l}.${e.payload}`,m=new TextEncoder,h=m.encode(e.secret),S=m.encode(g),I=Array.from(h).concat(Array.from(S)).reduce((b,C)=>b+C,0).toString(16);if(o.length!==I.length)return !1;let R=0;for(let b=0;b<o.length;b++)R|=o.charCodeAt(b)^I.charCodeAt(b);return R===0}catch{return false}},generateSecret(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="whsec_";for(let r=0;r<32;r++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}}}function ee(i){let n=p(i);return {async getSummary(e){return n(`/billing/org/${e}/summary`)},async getEntitlements(e){return n(`/entitlements/org/${e}`)},async checkEntitlement(e,t){return n(`/entitlements/org/${e}/check`,{method:"POST",body:JSON.stringify(t)})},async getPlans(){return (await n("/pricing/plans")).plans},async createCheckout(e){return n("/billing/checkout",{method:"POST",body:JSON.stringify(e)})},async openPortal(e){return n(`/billing/org/${e.orgId}/portal`,{method:"POST",body:JSON.stringify({returnUrl:e.returnUrl})})}}}function te(i){let n=p(i);return {async getOverview(){return n("/admin/overview")},async listUsers(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/users${r?`?${r}`:""}`)},async getUser(e){return n(`/admin/users/${e}`)},async updateUserStatus(e,t){return n(`/admin/users/${e}/status`,{method:"PATCH",body:JSON.stringify({status:t})})},async updateUserAdmin(e,t){return n(`/admin/users/${e}/admin`,{method:"PATCH",body:JSON.stringify({isAdmin:t})})},async listOrganizations(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.plan&&t.set("plan",e.plan),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/organizations${r?`?${r}`:""}`)},async getOrganization(e){return n(`/admin/organizations/${e}`)},async updateOrganization(e,t){return n(`/admin/organizations/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async listProjects(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.orgId&&t.set("orgId",e.orgId),e?.region&&t.set("region",e.region),e?.tenancy&&t.set("tenancy",e.tenancy),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/projects${r?`?${r}`:""}`)},async getProject(e){return n(`/admin/projects/${e}`)},async updateProject(e,t){return n(`/admin/projects/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async getProjectResources(e){return n(`/admin/resources/project/${e}`)},async setDedicatedDb(e){return n(`/admin/resources/project/${e.projectId}/db`,{method:"POST",body:JSON.stringify({connectionString:e.connectionString})})},async listIncidents(e="open"){return (await n(`/admin/incidents?status=${e}`)).incidents},async createIncident(e){return n("/admin/incidents",{method:"POST",body:JSON.stringify(e)})},async acknowledgeIncident(e){return n(`/admin/incidents/${e}/ack`,{method:"POST"})},async resolveIncident(e){return n(`/admin/incidents/${e}/resolve`,{method:"POST"})},async listRegions(){return n("/admin/regions")},async updateRegion(e,t){return n(`/admin/regions/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async getHealthComponents(){return n("/admin/health/components")},async updateHealthComponent(e,t){return n(`/admin/health/components/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async listQueues(){return n("/admin/queues")},async listDlqMessages(e){let t=new URLSearchParams;e?.queue&&t.set("queue",e.queue),e?.search&&t.set("search",e.search),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/dlq${r?`?${r}`:""}`)},async retryDlqMessage(e){return n(`/admin/dlq/${e}/retry`,{method:"POST"})},async archiveDlqMessage(e){return n(`/admin/dlq/${e}`,{method:"DELETE"})}}}function ne(i){let n=p(i);return {async list(){return (await n("/flags")).flags},async create(e){return n("/flags",{method:"POST",body:JSON.stringify(e)})},async update(e,t){return n(`/flags/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(t)})},async delete(e){return n(`/flags/${encodeURIComponent(e)}`,{method:"DELETE"})}}}function re(i){let n=p(i);return {async getOverview(e){return (await n(`/security/overview/${encodeURIComponent(e)}`)).overview},async getAuditLogs(e,t){let r=new URLSearchParams;t?.limit&&r.set("limit",String(t.limit)),t?.offset&&r.set("offset",String(t.offset));let s=r.toString(),a=`/security/audit/${encodeURIComponent(e)}${s?`?${s}`:""}`;return n(a)},async listEnvVars(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let s=r.toString(),a=`/projects/${encodeURIComponent(e)}/env-vars${s?`?${s}`:""}`;return (await n(a)).envVars},async createEnvVar(e,t){return (await n(`/projects/${encodeURIComponent(e)}/env-vars`,{method:"POST",body:JSON.stringify(t)})).envVar},async updateEnvVar(e,t,r){return (await n(`/projects/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(r)})).envVar},async deleteEnvVar(e,t){return n(`/projects/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(t)}`,{method:"DELETE"})},async getEnvVarValue(e,t){return n(`/projects/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(t)}/value`)}}}function se(i){let n=p(i);return {async generatePlan(e){return n("/ai/plan",{method:"POST",body:JSON.stringify({projectId:e.projectId,prompt:e.prompt,context:e.context,taskType:e.taskType,mode:e.mode})})},async explainPlan(e){return n("/ai/explain",{method:"POST",body:JSON.stringify({plan:e.plan,projectId:e.projectId,taskType:e.taskType,mode:e.mode})})},async getOrgSettings(e){return n(`/ai/settings/org/${encodeURIComponent(e)}`)},async updateOrgSettings(e,t){return n(`/ai/settings/org/${encodeURIComponent(e)}`,{method:"POST",body:JSON.stringify(t)})},async getProjectOverrides(e){return n(`/ai/settings/project/${encodeURIComponent(e)}`)},async updateProjectOverrides(e,t){return n(`/ai/settings/project/${encodeURIComponent(e)}`,{method:"POST",body:JSON.stringify(t)})},async getUsage(e,t){let r=new URLSearchParams;t&&r.set("month",t);let s=r.toString(),a=`/ai/usage/org/${encodeURIComponent(e)}${s?`?${s}`:""}`;return n(a)},async getBudgetStatus(e){let[t,r]=await Promise.all([this.getOrgSettings(e),this.getUsage(e)]),s=t?.monthlyBudgetCents??1e4,a=r.costCents,l=Math.max(0,s-a),o=s>0?Math.round(a/s*100):0;return {spent:a,budget:s,remaining:l,hardStop:t?.hardStopEnabled??false,percentUsed:o}},async generateFunction(e){return n("/ai/generate-function",{method:"POST",body:JSON.stringify({projectId:e.projectId,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema,language:e.language??"typescript",mode:e.mode})})},async generateEndpoint(e){return n("/ai/generate-endpoint",{method:"POST",body:JSON.stringify({projectId:e.projectId,description:e.description,method:e.method??"GET",authRequired:e.authRequired??true,mode:e.mode})})},async exportCode(e){return n("/ai/export-code",{method:"POST",body:JSON.stringify({projectId:e.projectId,targetLanguage:e.targetLanguage,includeSchema:e.includeSchema??true,includeFunctions:e.includeFunctions??true,includeEndpoints:e.includeEndpoints??true})})},async createConversation(e,t){return n("/ai/conversations",{method:"POST",body:JSON.stringify({projectId:e,title:t?.title,context:t?.context})})},async sendMessage(e,t){return n(`/ai/conversations/${encodeURIComponent(e)}/messages`,{method:"POST",body:JSON.stringify({content:t.content,taskType:t.taskType})})},async getConversation(e){return n(`/ai/conversations/${encodeURIComponent(e)}`)},async listConversations(e){return (await n(`/ai/conversations/project/${encodeURIComponent(e)}`)).conversations},async deleteConversation(e){return n(`/ai/conversations/${encodeURIComponent(e)}`,{method:"DELETE"})}}}function oe(i){let n=p(i);return {async load(){return n("/bootstrap")}}}function ie(i){let n=p(i);return {async list(e){let t=new URLSearchParams;e?.visibility&&t.set("visibility",e.visibility),e?.category&&t.set("category",e.category),e?.orgId&&t.set("orgId",e.orgId);let r=t.toString(),s=`/templates${r?`?${r}`:""}`;return (await n(s)).templates},async get(e){return n(`/templates/${e}`)},async previewInstall(e){return n("/templates/install/preview",{method:"POST",body:JSON.stringify(e)})},async applyInstall(e){return n("/templates/install/apply",{method:"POST",body:JSON.stringify(e)})},async rollback(e){return n(`/templates/install/${e}/rollback`,{method:"POST"})},async createProject(e){return n("/templates/create-project",{method:"POST",body:JSON.stringify(e)})}}}function ae(i){let n=p(i);return {async list(e){return (await n(`/oauth/org/${e}`)).connections},async configure(e,t){return n(`/oauth/org/${e}/configure`,{method:"POST",body:JSON.stringify(t)})},async enable(e){return n(`/oauth/connections/${e}/enable`,{method:"POST"})},async disable(e){return n(`/oauth/connections/${e}/disable`,{method:"POST"})},async delete(e){return n(`/oauth/connections/${e}`,{method:"DELETE"})}}}function ce(i){let n=p(i);return {async listPages(e){let t=e?`?category=${encodeURIComponent(e)}`:"";return (await n(`/docs/pages${t}`)).pages},async getPage(e){return (await n(`/docs/pages/${encodeURIComponent(e)}`)).page},async createPage(e){return (await n("/docs/pages",{method:"POST",body:JSON.stringify(e)})).page},async updatePage(e,t){return (await n(`/docs/pages/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).page},async deletePage(e){return n(`/docs/pages/${encodeURIComponent(e)}`,{method:"DELETE"})},async listSdks(){return (await n("/docs/sdks")).sdks},async getSdk(e){return (await n(`/docs/sdks/${encodeURIComponent(e)}`)).sdk},async createSdk(e){return (await n("/docs/sdks",{method:"POST",body:JSON.stringify(e)})).sdk},async updateSdk(e,t){return (await n(`/docs/sdks/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).sdk},async deleteSdk(e){return n(`/docs/sdks/${encodeURIComponent(e)}`,{method:"DELETE"})},async listSdkExamples(e,t){let r=t?`?topic=${encodeURIComponent(t)}`:"";return (await n(`/docs/sdks/${encodeURIComponent(e)}/examples${r}`)).examples},async createSdkExample(e){return (await n("/docs/sdk-examples",{method:"POST",body:JSON.stringify(e)})).example},async deleteSdkExample(e){return n(`/docs/sdk-examples/${encodeURIComponent(e)}`,{method:"DELETE"})},async listEndpoints(e){let t=e?`?category=${encodeURIComponent(e)}`:"";return (await n(`/docs/api-endpoints${t}`)).endpoints},async getEndpoint(e){return (await n(`/docs/api-endpoints/${encodeURIComponent(e)}`)).endpoint},async createEndpoint(e){return (await n("/docs/api-endpoints",{method:"POST",body:JSON.stringify(e)})).endpoint},async updateEndpoint(e,t){return (await n(`/docs/api-endpoints/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).endpoint},async deleteEndpoint(e){return n(`/docs/api-endpoints/${encodeURIComponent(e)}`,{method:"DELETE"})},async listExamples(e){let t=e!==void 0?`?featured=${e}`:"";return (await n(`/docs/examples${t}`)).examples},async getExample(e){return (await n(`/docs/examples/${encodeURIComponent(e)}`)).example},async createExample(e){return (await n("/docs/examples",{method:"POST",body:JSON.stringify(e)})).example},async updateExample(e,t){return (await n(`/docs/examples/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).example},async deleteExample(e){return n(`/docs/examples/${encodeURIComponent(e)}`,{method:"DELETE"})},async listChangelog(){return (await n("/docs/changelog")).entries},async getChangelogEntry(e){return (await n(`/docs/changelog/${encodeURIComponent(e)}`)).entry},async createChangelogEntry(e){return (await n("/docs/changelog",{method:"POST",body:JSON.stringify(e)})).entry},async updateChangelogEntry(e,t){return (await n(`/docs/changelog/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).entry},async deleteChangelogEntry(e){return n(`/docs/changelog/${encodeURIComponent(e)}`,{method:"DELETE"})},async search(e){return (await n(`/docs/search?q=${encodeURIComponent(e)}`)).results}}}function fe(i,n,e,t){let r=n.type||"public",s="unsubscribed",a=new Map,l=[],o={},c=null,g=null,m=new Set,h=new Set,S=new Set,I=u=>{if(u.event){let f=a.get(u.event);f&&f.forEach(T=>T(u.payload));}},R=u=>{o=u.state||{},m.forEach(f=>f(o));},b=u=>{let f=u.key||"",T=u.currentPresences||[],d=u.joinedPresences||[],y=u.leftPresences||[];d.length>0&&(o[f]=T,h.forEach(P=>P(f,T,d))),y.length>0&&(T.length===0?delete o[f]:o[f]=T,S.forEach(P=>P(f,T,y))),m.forEach(P=>P(o));},C=u=>{let f={type:"db_change",projectId:u.projectId||"",schema:u.schema||"",table:u.table||"",operation:u.op,new:u.record,old:u.old_record,timestamp:u.ts||new Date().toISOString(),partial:u.partial};l.forEach(({options:T,handler:d})=>{if(T.table===f.table){let y=T.event||"*";(y==="*"||(Array.isArray(y)?y.includes(f.operation):y===f.operation))&&d(f);}});},k={get name(){return i},get type(){return r},get status(){return s},_handleMessage:u=>{switch(u.type){case "broadcast":I(u);break;case "presence_state":R(u);break;case "presence":b(u);break;case "db_change":C(u);break;case "subscribed":s="subscribed";break;case "error":s="error";break}},onDbChange(u,f){return l.push({options:u,handler:f}),s==="subscribed"&&e({type:"subscribe",channel:i,options:{table:u.table,filter:u.filter,event:u.event,columns:u.columns}}),k},on(u,f){return a.has(u)||a.set(u,new Set),a.get(u).add(f),k},off(u,f){return f?a.get(u)?.delete(f):a.delete(u),k},async broadcast(u){if(s!=="subscribed")throw new Error("Channel must be subscribed before broadcasting");e({type:"broadcast",channel:i,event:u.event,payload:u.payload,includeSelf:u.includeSelf});},presence:{async track(u){if(r!=="presence")throw new Error("Presence tracking is only available on presence channels");c=u.key||t()||"anonymous",g=u.state,e({type:"presence_track",channel:i,key:c,state:g});},async update(u){if(!g)throw new Error("Must call track() before update()");g={...g,...u},e({type:"presence_update",channel:i,key:c,state:g});},async untrack(){c&&(e({type:"presence_untrack",channel:i,key:c}),c=null,g=null);},state(){return {...o}},onSync(u){return m.add(u),k},onJoin(u){return h.add(u),k},onLeave(u){return S.add(u),k}},async subscribe(){return s==="subscribed"||(s="subscribing",e({type:"subscribe",channel:i}),l.forEach(({options:u})=>{e({type:"subscribe",channel:i,options:{table:u.table,filter:u.filter,event:u.event,columns:u.columns}});}),n.presenceState&&r==="presence"&&await k.presence.track({state:n.presenceState})),k},async unsubscribe(){s!=="unsubscribed"&&(c&&await k.presence.untrack(),e({type:"unsubscribe",channel:i}),s="unsubscribed",o={},a.clear(),l.length=0);}};return k}function le(i,n){let{wsUrl:e=i.baseUrl.replace(/^http/,"ws")+"/realtime/ws",autoReconnect:t=true,reconnectDelay:r=1e3,maxReconnectAttempts:s=10}=n??{},a=null,l="disconnected",o=null,c=null,g=0,m=null,h=null,S=new Map,I=new Map,R=new Set,b={connect:new Set,disconnect:new Set,error:new Set,reconnect:new Set},C=d=>{b[d].forEach(y=>y());},D=d=>{let y=`table:${d.table}`;if(d.filter){let O=(Array.isArray(d.filter)?d.filter:[d.filter]).map(w=>`${w.field}${w.operator||"eq"}${w.value}`).join("&");y+=`?${O}`;}return y},k=d=>{a?.readyState===WebSocket.OPEN&&a.send(JSON.stringify(d));},u=d=>{if(d.channel){let y=S.get(d.channel);if(y){y._handleMessage(d);return}}switch(d.type){case "db_change":{let y={type:"db_change",projectId:d.projectId??"",schema:d.schema??"",table:d.table??"",operation:d.op,new:d.record,old:d.old_record,timestamp:d.ts??new Date().toISOString(),partial:d.partial},P=`table:${d.table}`;I.forEach((O,w)=>{(w===P||w.startsWith(P+"?"))&&O.forEach(B=>B(y));});break}case "presence":{let y={type:"presence",event:d.event,key:d.key||d.connectionId||"",connectionId:d.connectionId??"",projectId:d.projectId??"",currentPresences:d.currentPresences||[],leftPresences:d.leftPresences||[],joinedPresences:d.joinedPresences||[]};R.forEach(P=>P(y));break}case "welcome":o=d.connectionId||null;break;case "error":{console.error("[vaif/realtime] Server error:",d.message),C("error");break}}},f=()=>new Promise((d,y)=>{let P=new URLSearchParams;i.apiKey&&P.set(i.apiKeyHeader,i.apiKey),c&&P.set("token",c);let O=P.toString(),w=O?`${e}?${O}`:e;try{a=new WebSocket(w);}catch{y(new x("Failed to create WebSocket connection"));return}let B=()=>{l="connected",g=0,C("connect"),S.forEach(A=>{(A.status==="subscribed"||A.status==="subscribing")&&A.subscribe();}),I.forEach((A,N)=>{k({type:"subscribe",channel:N});}),h=setInterval(()=>{k({type:"ping"});},3e4),d();},ue=A=>{try{let N=JSON.parse(A.data);u(N);}catch{}},de=()=>{if(l="disconnected",o=null,a=null,h&&(clearInterval(h),h=null),C("disconnect"),t&&g<s){l="reconnecting";let A=r*Math.pow(2,g);m=setTimeout(()=>{g++,C("reconnect"),f().catch(()=>{});},Math.min(A,3e4));}},ge=()=>{C("error"),y(new x("WebSocket connection error"));};a.addEventListener("open",B),a.addEventListener("message",ue),a.addEventListener("close",de),a.addEventListener("error",ge);}),T=()=>{m&&(clearTimeout(m),m=null),h&&(clearInterval(h),h=null),g=s;};return {channel(d,y={}){let P=S.get(d);if(P)return P;let O=fe(d,y,k,()=>o);return S.set(d,O),O},async removeChannel(d){let y=S.get(d.name);y&&(await y.unsubscribe(),S.delete(d.name));},getChannels(){return Array.from(S.values())},subscribe(d,y){let P=D(d);return I.has(P)||I.set(P,new Set),I.get(P).add(y),a?.readyState===WebSocket.OPEN&&k({type:"subscribe",channel:P}),()=>{let O=I.get(P);O&&(O.delete(y),O.size===0&&(I.delete(P),a?.readyState===WebSocket.OPEN&&k({type:"unsubscribe",channel:P})));}},subscribeToPresence(d){return R.add(d),()=>{R.delete(d);}},async connect(){if(l!=="connected"){if(!i.apiKey)throw new M("API key is required for realtime connections");l="connecting",await f();}},disconnect(){T(),S.forEach(d=>{d.unsubscribe();}),S.clear(),a&&(a.close(),a=null),l="disconnected",o=null;},get isConnected(){return l==="connected"},get connectionState(){return l},get connectionId(){return o},on(d,y){b[d].add(y);},off(d,y){b[d].delete(y);},setAuth(d){c=d;}}}var $={apiKeyHeader:"x-vaif-key",timeout:3e4,retry:{maxRetries:3,retryDelay:1e3,retryOn:[429,500,502,503,504]}};function Pe(i){return {baseUrl:i.baseUrl.replace(/\/$/,""),apiKey:i.apiKey,apiKeyHeader:i.apiKeyHeader??$.apiKeyHeader,accessToken:i.accessToken,fetch:i.fetch??globalThis.fetch.bind(globalThis),timeout:i.timeout??$.timeout,retry:{maxRetries:i.retry?.maxRetries??$.retry.maxRetries,retryDelay:i.retry?.retryDelay??$.retry.retryDelay,retryOn:i.retry?.retryOn??[...$.retry.retryOn]}}}function he(i){let n=Pe(i),e=V(n),t=q(n),r=H(n),s=K(n),a=z(n),l=_(n),o=W(n),c=G(n),g=Q(n),m=X(n),h=Z(n),S=Y(n),I=ee(n),R=te(n),b=ne(n),C=re(n),D=se(n),k=oe(n),u=ie(n),f=ae(n),T=ce(n);return {from:e.from,auth:t,functions:r,storage:s,projects:a,orgs:l,schema:o,secrets:c,deployments:g,realtimeMonitoring:m,storageDashboard:h,integrations:S,billing:I,admin:R,flags:b,security:C,ai:D,bootstrap:k,templates:u,oauth:f,docs:T,realtime:d=>le(n,d)}}exports.VaifAuthError=M;exports.VaifError=E;exports.VaifNetworkError=x;exports.VaifNotFoundError=j;exports.VaifRateLimitError=F;exports.VaifValidationError=U;exports.createVaifClient=he;exports.isVaifError=pe;
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var E=class i extends Error{constructor(n,e){super(n),this.name="VaifError",this.code=e.code,this.statusCode=e.statusCode,this.requestId=e.requestId,this.details=e.details;let t=Error;t.captureStackTrace&&t.captureStackTrace(this,i);}toJSON(){return {name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,requestId:this.requestId,details:this.details}}},M=class extends E{constructor(n,e){super(n,{code:e?.code??"AUTH_ERROR",statusCode:e?.statusCode??401,requestId:e?.requestId}),this.name="VaifAuthError";}},U=class extends E{constructor(n,e){super(n,{code:"VALIDATION_ERROR",statusCode:400,requestId:e?.requestId,details:e?.details??e?.fieldErrors}),this.name="VaifValidationError",this.fieldErrors=e?.fieldErrors;}},x=class extends E{constructor(n,e){super(n,{code:"NETWORK_ERROR"}),this.name="VaifNetworkError",this.cause=e;}},F=class extends E{constructor(n,e){super(n,{code:"RATE_LIMITED",statusCode:429}),this.name="VaifRateLimitError",this.retryAfter=e;}},j=class extends E{constructor(n,e){super(n,{code:"NOT_FOUND",statusCode:404,requestId:e}),this.name="VaifNotFoundError";}};function pe(i){return i instanceof E}async function me(i){let n;try{n=await i.json();}catch{}let e=n?.message??n?.error??i.statusText??"Request failed",t=n?.requestId;switch(i.status){case 400:return new U(e,{details:n?.details,requestId:t});case 401:return new M(e,{code:"UNAUTHORIZED",statusCode:401,requestId:t});case 403:return new M(e,{code:"FORBIDDEN",statusCode:403,requestId:t});case 404:return new j(e,t);case 429:{let r=i.headers.get("Retry-After"),s=r?parseInt(r,10):void 0;return new F(e,s)}default:return new E(e,{code:n?.error??"HTTP_ERROR",statusCode:i.status,requestId:t,details:n?.details})}}async function ye(i,n){let{timeout:e=3e4,fetchFn:t,...r}=n,s=new AbortController,a=setTimeout(()=>s.abort(),e);try{let l=await t(i,{...r,signal:s.signal});if(clearTimeout(a),!l.ok)throw await me(l);if(l.status===204)return;let o=await l.text();return o?JSON.parse(o):void 0}catch(l){throw clearTimeout(a),l instanceof E?l:l instanceof Error&&l.name==="AbortError"?new x("Request timed out"):l instanceof Error?new x(l.message,l):new x("Network request failed")}}function p(i){let{baseUrl:n,apiKey:e,apiKeyHeader:t,accessToken:r,fetch:s,timeout:a}=i;return async function(o,c={}){let g=`${n}${o}`,m={"Content-Type":"application/json",...c.headers??{}};if(e&&(m[t]=e),r){let h=typeof r=="function"?await r():r;m.Authorization=`Bearer ${h}`;}return ye(g,{...c,headers:m,timeout:a,fetchFn:s})}}function v(i){let n=new URLSearchParams;for(let[t,r]of Object.entries(i))r!==void 0&&n.set(t,String(r));let e=n.toString();return e?`?${e}`:""}function be(i){return JSON.stringify(i)}function L(i,n,e={}){let t={...e},r=()=>{let o={};if(t.limit!==void 0&&(o.limit=t.limit),t.offset!==void 0&&(o.offset=t.offset),t.where&&(o.where=be(t.where)),t.orderBy){let c=Array.isArray(t.orderBy)?t.orderBy:[t.orderBy];o.orderBy=JSON.stringify(c);}return t.select&&t.select.length>0&&(o.select=t.select.join(",")),t.include&&t.include.length>0&&(o.include=JSON.stringify(t.include)),t.distinct&&t.distinct.length>0&&(o.distinct=t.distinct.join(",")),o},s=()=>v(r()),a=o=>L(i,n,{...t,...o}),l={async list(o){o&&(t={...t,...o});let c=s();return n(`/generated/${i}${c}`)},async get(o){let c={};t.select&&t.select.length>0&&(c.select=t.select.join(",")),t.include&&t.include.length>0&&(c.include=JSON.stringify(t.include));let g=v(c);return n(`/generated/${i}/${encodeURIComponent(o)}${g}`)},async first(){let o=await l.limit(1).list();return o.data.length>0?o.data[0]:null},async firstOrFail(){let o=await l.first();if(!o)throw new Error(`No record found in table '${i}' matching the query`);return o},async create(o){return n(`/generated/${i}`,{method:"POST",body:JSON.stringify(o)})},async update(o,c){return n(`/generated/${i}/${encodeURIComponent(o)}`,{method:"PATCH",body:JSON.stringify(c)})},async delete(o){return n(`/generated/${i}/${encodeURIComponent(o)}`,{method:"DELETE"})},async createMany(o,c){return n(`/generated/${i}/batch`,{method:"POST",body:JSON.stringify({records:o,skipOnConflict:c?.skipOnConflict,returnRecords:c?.returnRecords})})},async updateMany(o,c){r();return n(`/generated/${i}/batch`,{method:"PATCH",body:JSON.stringify({data:o,where:t.where,returnRecords:c?.returnRecords})})},async deleteMany(){return n(`/generated/${i}/batch`,{method:"DELETE",body:JSON.stringify({where:t.where})})},async upsert(o,c){return n(`/generated/${i}/upsert`,{method:"POST",body:JSON.stringify({data:o,conflictFields:c.conflictFields,updateFields:c.updateFields})})},async count(){let o=r(),c=v(o);return (await n(`/generated/${i}/count${c}`)).count},async sum(o){let c=r(),g=v({...c,field:o});return (await n(`/generated/${i}/sum${g}`)).sum},async avg(o){let c=r(),g=v({...c,field:o});return (await n(`/generated/${i}/avg${g}`)).avg},async min(o){let c=r(),g=v({...c,field:o});return (await n(`/generated/${i}/min${g}`)).min},async max(o){let c=r(),g=v({...c,field:o});return (await n(`/generated/${i}/max${g}`)).max},async aggregate(o,c){return n(`/generated/${i}/aggregate`,{method:"POST",body:JSON.stringify({aggregates:o,where:c?.where||t.where,groupBy:c?.groupBy,having:c?.having})})},async paginate(o){let c=o.page||1,g=o.pageSize||20,m=(c-1)*g,h=r();h.limit=g,h.offset=m,h.includeCount=true;let S=v(h),I=await n(`/generated/${i}${S}`),R=I.total||I.data.length,b=Math.ceil(R/g);return {data:I.data,pageInfo:{total:R,page:c,pageSize:g,pageCount:b,hasNextPage:c<b,hasPrevPage:c>1}}},async cursorPaginate(o){let c=r();c.limit=o.limit||20,o.cursor&&(c.cursor=o.cursor);let g=v(c),m=await n(`/generated/${i}/cursor${g}`);return {data:m.data,nextCursor:m.nextCursor,prevCursor:m.prevCursor,hasMore:m.hasMore}},where(o){if(t.where){let c=t.where;return a({where:{AND:[...Array.isArray(c)?c:[c],o]}})}return a({where:o})},orderBy(o,c="asc"){let g={field:o,direction:c};if(t.orderBy){let m=Array.isArray(t.orderBy)?t.orderBy:[t.orderBy];return a({orderBy:[...m,g]})}return a({orderBy:g})},select(...o){return a({select:o})},limit(o){return a({limit:o})},offset(o){return a({offset:o})},include(o){let c=t.include||[];return a({include:[...c,o]})},distinct(...o){return a({distinct:o})}};return l}function V(i){let n=p(i);return {from(e){return L(e,n)},async raw(e,t){return n("/generated/raw",{method:"POST",body:JSON.stringify({query:e,params:t})})},async transaction(e,t){return n("/generated/transaction",{method:"POST",body:JSON.stringify({operations:e,isolationLevel:t?.isolationLevel,timeout:t?.timeout})})},async withTransaction(e,t){let s=(await n("/generated/transaction/start",{method:"POST",body:JSON.stringify({isolationLevel:t?.isolationLevel,timeout:t?.timeout})})).transactionId,a=(o,c)=>{let g=new Headers(c?.headers);return g.set("X-Transaction-Id",s),n(o,{...c,headers:g})},l={from(o){return L(o,a)},async raw(o,c){return a("/generated/raw",{method:"POST",body:JSON.stringify({query:o,params:c})})},async transaction(){throw new Error("Nested transactions are not supported")},async withTransaction(){throw new Error("Nested transactions are not supported")}};try{let o=await e(l);return await n("/generated/transaction/commit",{method:"POST",body:JSON.stringify({transactionId:s})}),o}catch(o){throw await n("/generated/transaction/rollback",{method:"POST",body:JSON.stringify({transactionId:s})}).catch(()=>{}),o}}}}function q(i){let n=p(i);return {async signUp(e,t,r){return n("/auth/signup",{method:"POST",body:JSON.stringify({email:e,password:t,name:r?.name,phone:r?.phone,metadata:r?.metadata,redirectUrl:r?.redirectUrl})})},async login(e,t,r){return n("/auth/login",{method:"POST",body:JSON.stringify({email:e,password:t,mfaCode:r?.mfaCode,rememberMe:r?.rememberMe})})},async logout(){await n("/auth/logout",{method:"POST"});},async logoutAll(){await n("/auth/logout-all",{method:"POST"});},async getUser(){return (await n("/auth/me")).user},async updateProfile(e){return (await n("/users/me",{method:"PATCH",body:JSON.stringify(e)})).user},async changePassword(e){return n("/users/me/change-password",{method:"POST",body:JSON.stringify(e)})},async requestPasswordReset(e){return n("/auth/forgot-password",{method:"POST",body:JSON.stringify(e)})},async confirmPasswordReset(e){return n("/auth/reset-password",{method:"POST",body:JSON.stringify(e)})},async requestEmailVerification(e){return n("/auth/verify-email/send",{method:"POST",body:JSON.stringify(e||{})})},async confirmEmailVerification(e){return n("/auth/verify-email/confirm",{method:"POST",body:JSON.stringify(e)})},async getOAuthSignInUrl(e){return n("/auth/oauth/authorize",{method:"POST",body:JSON.stringify(e)})},async handleOAuthCallback(e){return n("/auth/oauth/callback",{method:"POST",body:JSON.stringify(e)})},async linkOAuthProvider(e){return n("/auth/oauth/link",{method:"POST",body:JSON.stringify(e)})},async unlinkOAuthProvider(e){return n(`/auth/oauth/unlink/${e}`,{method:"POST"})},async listLinkedProviders(){return n("/auth/oauth/providers")},async requestMagicLink(e){return n("/auth/magic-link/send",{method:"POST",body:JSON.stringify(e)})},async verifyMagicLink(e){return n("/auth/magic-link/verify",{method:"POST",body:JSON.stringify(e)})},async requestPhoneVerification(e){return n("/auth/phone/send",{method:"POST",body:JSON.stringify(e)})},async confirmPhoneVerification(e){return n("/auth/phone/verify",{method:"POST",body:JSON.stringify(e)})},async setupMFA(e){return n("/auth/mfa/setup",{method:"POST",body:JSON.stringify({method:e})})},async enableMFA(e){return n("/auth/mfa/enable",{method:"POST",body:JSON.stringify({code:e})})},async disableMFA(e){return n("/auth/mfa/disable",{method:"POST",body:JSON.stringify({code:e})})},async verifyMFA(e,t){return n("/auth/mfa/verify",{method:"POST",body:JSON.stringify({mfaToken:e,code:t})})},async regenerateBackupCodes(){return n("/auth/mfa/backup-codes",{method:"POST"})},async refreshToken(e){return n("/auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:e})})},async listSessions(){return n("/auth/sessions")},async revokeSession(e){return n(`/auth/sessions/${e}`,{method:"DELETE"})},async revokeOtherSessions(){return n("/auth/sessions/revoke-others",{method:"POST"})}}}function J(i){return new Promise(n=>setTimeout(n,i))}function H(i){let n=p(i);async function e(t,r,s){let a=s?.retry||{},l=a.maxRetries??0,o=a.initialDelay??1e3,c=a.maxDelay??3e4,g=a.backoffMultiplier??2,m=a.retryOnStatus??[429,500,502,503,504],h=a.retryOnNetworkError??true,S=null,I=o;for(let R=0;R<=l;R++)try{let b={};s?.version!==void 0&&(b.version=s.version),s?.includeLogs&&(b.includeLogs=!0);let C=v(b),D=await n(`/functions/${t}/invoke${C}`,{method:"POST",body:JSON.stringify(r??{}),headers:s?.headers});if(m.includes(D.status)&&R<l){S=new Error(`Function returned status ${D.status}`),await J(I),I=Math.min(I*g,c);continue}return D}catch(b){S=b;let C=b instanceof TypeError||b.message?.includes("network")||b.message?.includes("fetch");if(h&&C&&R<l){await J(I),I=Math.min(I*g,c);continue}throw b}throw S||new Error("Function invocation failed after retries")}return {invoke:e,async invokeByName(t,r,s){let a={};s?.version!==void 0&&(a.version=s.version),s?.includeLogs&&(a.includeLogs=true);let l=v(a);return n(`/functions/name/${encodeURIComponent(t)}/invoke${l}`,{method:"POST",body:JSON.stringify(r??{}),headers:s?.headers})},async batchInvoke(t,r){let a=(await Promise.allSettled(t.map(l=>this.invoke(l.functionId,l.input,r)))).map((l,o)=>l.status==="fulfilled"?{functionId:t[o].functionId,success:true,result:l.value}:{functionId:t[o].functionId,success:false,error:l.reason?.message||"Unknown error"});return {results:a,successCount:a.filter(l=>l.success).length,errorCount:a.filter(l=>!l.success).length}},rpc(t,r){let s=this,a=async(l,o)=>{let c={...r,...o};return (await e(t,{body:l},c)).data};return Object.defineProperty(a,"id",{value:t,writable:false}),a.getInfo=()=>s.get(t),a.getInvocations=l=>s.getInvocations({...l,functionId:t}),a},async list(t){let r={envId:t.envId,enabled:t.enabled,limit:t.limit,offset:t.offset},s=v(r);return n(`/functions/project/${t.projectId}${s}`)},async get(t){return n(`/functions/${t}`)},async getByName(t,r){return n(`/functions/project/${r}/name/${encodeURIComponent(t)}`)},async create(t){return n("/functions",{method:"POST",body:JSON.stringify(t)})},async update(t,r){return n(`/functions/${t}`,{method:"PATCH",body:JSON.stringify(r)})},async delete(t){return n(`/functions/${t}`,{method:"DELETE"})},async enable(t){return this.update(t,{enabled:true})},async disable(t){return this.update(t,{enabled:false})},async deploy(t,r,s){return n(`/functions/${t}/deploy`,{method:"POST",body:JSON.stringify({sourceCode:r,createVersion:s?.createVersion,versionDescription:s?.versionDescription,envVars:s?.envVars,secrets:s?.secrets})})},async getSource(t,r){let s=r!==void 0?`?version=${r}`:"";return n(`/functions/${t}/source${s}`)},async listVersions(t){return (await n(`/functions/${t}/versions`)).versions},async rollback(t,r){return n(`/functions/${t}/rollback`,{method:"POST",body:JSON.stringify({version:r})})},async getEnvVars(t){return (await n(`/functions/${t}/env`)).envVars},async setEnvVars(t,r){return n(`/functions/${t}/env`,{method:"PUT",body:JSON.stringify({envVars:r})})},async deleteEnvVar(t,r){return n(`/functions/${t}/env/${encodeURIComponent(r)}`,{method:"DELETE"})},async bindSecrets(t,r){return n(`/functions/${t}/secrets`,{method:"PUT",body:JSON.stringify({secrets:r})})},async setSchedule(t,r){return n(`/functions/${t}/schedule`,{method:"PUT",body:JSON.stringify(r)})},async removeSchedule(t){return n(`/functions/${t}/schedule`,{method:"DELETE"})},async getInvocations(t){let r={functionId:t.functionId,projectId:t.projectId,status:t.status,since:t.since,until:t.until,limit:t.limit,offset:t.offset},s=v(r);return (await n(`/functions/invocations${s}`)).invocations},async getInvocation(t){return n(`/functions/invocations/${t}`)},async getLogs(t,r){let s={since:r?.since,until:r?.until,level:r?.level,limit:r?.limit},a=v(s);return (await n(`/functions/${t}/logs${a}`)).logs}}}function K(i){let n=p(i),e="default";return {async getUploadUrl(t,r){return n("/storage/upload-url",{method:"POST",body:JSON.stringify({key:t,bucket:r?.bucket||e,contentType:r?.contentType,sizeBytes:r?.sizeBytes,metadata:r?.metadata,isPublic:r?.isPublic,cacheControl:r?.cacheControl,contentDisposition:r?.contentDisposition,upsert:r?.upsert})})},async getDownloadUrl(t,r){return n("/storage/download-url",{method:"POST",body:JSON.stringify({key:t,bucket:r?.bucket||e,expiresIn:r?.expiresIn,download:r?.download,transform:r?.transform})})},async createSignedUrl(t,r=3600,s){return (await this.getDownloadUrl(t,{...s,expiresIn:r})).url},async createSignedUrls(t,r=3600,s){return await Promise.all(t.map(async l=>({key:l,url:await this.createSignedUrl(l,r,s)})))},async upload(t,r,s){let a=r instanceof Blob?r:new Blob([r]),l=a.size,o=s?.contentType||(r instanceof File?r.type:void 0)||"application/octet-stream",c=await this.getUploadUrl(t,{...s,contentType:o,sizeBytes:l}),g=await i.fetch(c.url,{method:"PUT",body:a,headers:{"Content-Type":o,...s?.cacheControl&&{"Cache-Control":s.cacheControl},...s?.contentDisposition&&{"Content-Disposition":s.contentDisposition}}});if(!g.ok)throw new Error(`Upload failed: ${g.statusText}`);let m=s?.bucket||e,h=c.url.split("?")[0];return {ok:true,key:t,bucket:m,url:h,publicUrl:s?.isPublic?this.getPublicUrl(t,{bucket:m}):void 0,size:l,contentType:o}},async uploadFromUrl(t,r,s){return n("/storage/upload-from-url",{method:"POST",body:JSON.stringify({key:t,url:r,bucket:s?.bucket||e,contentType:s?.contentType,metadata:s?.metadata,isPublic:s?.isPublic,timeout:s?.timeout})})},async download(t,r){let s=await this.getDownloadUrl(t,r),a=await i.fetch(s.url);if(!a.ok)throw new Error(`Download failed: ${a.statusText}`);return a.blob()},async list(t){let r={bucket:t?.bucket||e,prefix:t?.prefix,delimiter:t?.delimiter,limit:t?.limit,cursor:t?.cursor,includeUrls:t?.includeUrls},s=v(r);return n(`/storage/files${s}`)},async getMetadata(t,r){let s=r?.bucket||e;return n(`/storage/files/${encodeURIComponent(s)}/${encodeURIComponent(t)}/metadata`)},async updateMetadata(t,r,s){let a=s?.bucket||e;return n(`/storage/files/${encodeURIComponent(a)}/${encodeURIComponent(t)}/metadata`,{method:"PATCH",body:JSON.stringify(r)})},async exists(t,r){try{return await this.getMetadata(t,r),!0}catch{return false}},async copy(t,r,s){return n("/storage/files/copy",{method:"POST",body:JSON.stringify({sourceKey:t,sourceBucket:s?.sourceBucket||e,destinationKey:r,destinationBucket:s?.destinationBucket||s?.sourceBucket||e,metadata:s?.metadata})})},async move(t,r,s){return n("/storage/files/move",{method:"POST",body:JSON.stringify({sourceKey:t,sourceBucket:s?.sourceBucket||e,destinationKey:r,destinationBucket:s?.destinationBucket||s?.sourceBucket||e,metadata:s?.metadata})})},async delete(t,r){let s=r?.bucket||e;await n(`/storage/files/${encodeURIComponent(s)}/${encodeURIComponent(t)}`,{method:"DELETE"});},async deleteMany(t,r){return n("/storage/files/delete-batch",{method:"POST",body:JSON.stringify({keys:t,bucket:r?.bucket||e})})},getPublicUrl(t,r){let s=r?.bucket||e;return `${i.baseUrl.replace("/api","")}/storage/${encodeURIComponent(s)}/${encodeURIComponent(t)}`},async createBucket(t,r){return n("/storage/buckets",{method:"POST",body:JSON.stringify({name:t,isPublic:r?.isPublic,allowedMimeTypes:r?.allowedMimeTypes,maxFileSize:r?.maxFileSize,fileSizeLimit:r?.fileSizeLimit})})},async getBucket(t){return n(`/storage/buckets/${encodeURIComponent(t)}`)},async updateBucket(t,r){return n(`/storage/buckets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(r)})},async listBuckets(){return (await n("/storage/buckets")).buckets},async deleteBucket(t){await n(`/storage/buckets/${encodeURIComponent(t)}`,{method:"DELETE"});},async emptyBucket(t){return n(`/storage/buckets/${encodeURIComponent(t)}/empty`,{method:"POST"})},async createMultipartUpload(t,r){return n("/storage/multipart/create",{method:"POST",body:JSON.stringify({key:t,bucket:r?.bucket||e,contentType:r?.contentType,metadata:r?.metadata,partSize:r?.partSize})})},async uploadPart(t,r,s){let a=s instanceof Blob?s:new Blob([s]),{url:l}=await n(`/storage/multipart/${t}/part-url`,{method:"POST",body:JSON.stringify({partNumber:r})}),o=await i.fetch(l,{method:"PUT",body:a});if(!o.ok)throw new Error(`Part upload failed: ${o.statusText}`);let c=o.headers.get("etag")||"";return {partNumber:r,etag:c}},async completeMultipartUpload(t,r){return n(`/storage/multipart/${t}/complete`,{method:"POST",body:JSON.stringify({parts:r})})},async abortMultipartUpload(t){await n(`/storage/multipart/${t}/abort`,{method:"POST"});}}}function z(i){let n=p(i);return {async list(){return n("/projects")},async get(e){return n(`/projects/${e}`)},async create(e){return n("/projects",{method:"POST",body:JSON.stringify(e)})},async getApiKeys(e){return n(`/projects/${e}/api-keys`)},async createApiKey(e,t){return n(`/projects/${e}/api-keys`,{method:"POST",body:JSON.stringify(t??{})})},async revokeApiKey(e,t){return n(`/projects/${e}/api-keys/${t}/revoke`,{method:"POST"})},async rotateApiKey(e,t){return n(`/projects/${e}/api-keys/${t}/rotate`,{method:"POST"})}}}function _(i){let n=p(i);return {async list(){return n("/orgs")},async create(e){return n("/orgs",{method:"POST",body:JSON.stringify(e)})},async getProfile(e){return (await n(`/orgs/${e}/profile`)).profile||{}},async updateProfile(e,t){return (await n(`/orgs/${e}/profile`,{method:"PATCH",body:JSON.stringify(t)})).profile},async listBillingContacts(e){return (await n(`/orgs/${e}/billing-contacts`)).contacts},async addBillingContact(e,t){return n(`/orgs/${e}/billing-contacts`,{method:"POST",body:JSON.stringify(t)})},async removeBillingContact(e,t){return n(`/orgs/${e}/billing-contacts/${t}`,{method:"DELETE"})},async listMembers(e){return (await n(`/orgs/${e}/members`)).members},async inviteMember(e,t){return n(`/orgs/${e}/members/invite`,{method:"POST",body:JSON.stringify(t)})},async listInvites(e){return (await n(`/orgs/${e}/invites`)).invites},async cancelInvite(e,t){return n(`/orgs/${e}/invites/${t}`,{method:"DELETE"})},async removeMember(e,t){return n(`/orgs/${e}/members/${t}`,{method:"DELETE"})},async updateMemberRole(e,t,r){return n(`/orgs/${e}/members/${t}/role`,{method:"PATCH",body:JSON.stringify({role:r})})}}}function W(i){let n=p(i);return {async preview(e){return n("/schema-engine/preview",{method:"POST",body:JSON.stringify(e)})},async apply(e){return n("/schema-engine/apply",{method:"POST",body:JSON.stringify(e)})},async getMigrations(e,t){let r=t?`/schema-engine/migrations/project/${e}?limit=${t}`:`/schema-engine/migrations/project/${e}`;return n(r)},async saveSchema(e){return n("/schemas/",{method:"POST",body:JSON.stringify(e)})},async getSchemas(e){return n(`/schemas/project/${e}`)}}}function G(i){let n=p(i);return {async create(e){return n("/functions/secrets",{method:"POST",body:JSON.stringify(e)})},async list(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let s=r.toString(),a=`/functions/secrets/project/${e}${s?`?${s}`:""}`;return n(a)},async reveal(e){return n(`/functions/secrets/${e}/value`)},async update(e,t){return n(`/functions/secrets/${e}`,{method:"PUT",body:JSON.stringify({value:t})})},async delete(e){return n(`/functions/secrets/${e}`,{method:"DELETE"})}}}function Q(i){let n=p(i);return {async list(e,t){let r=new URLSearchParams;t&&r.set("env",t);let s=r.toString(),a=`/deployments/project/${e}${s?`?${s}`:""}`;return (await n(a)).deployments},async get(e){let t=await n(`/deployments/${e}`);return {...t.deployment,steps:t.steps}},async getSteps(e){return (await n(`/deployments/${e}/steps`)).steps},async promote(e){let t={projectId:e.projectId,fromEnv:e.sourceEnv,toEnv:e.targetEnv},r=await n("/deployments/promote",{method:"POST",body:JSON.stringify(t)}),s=await n(`/deployments/${r.deploymentId}`);return {deployment:{...s.deployment,steps:s.steps}}},async rollback(e){return n(`/deployments/${e}/rollback`,{method:"POST"})},async listTokens(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let s=r.toString(),a=`/deployments/tokens/project/${encodeURIComponent(e)}${s?`?${s}`:""}`;return (await n(a)).tokens},async createToken(e){return n("/deployments/tokens",{method:"POST",body:JSON.stringify(e)})},async revokeToken(e){return n(`/deployments/tokens/${encodeURIComponent(e)}/revoke`,{method:"POST"})}}}function X(i){let n=p(i);return {async getStats(e){return n(`/realtime/stats/project/${e}`)},async getConnections(e){return (await n(`/realtime/connections/project/${e}`)).connections},async getSubscriptions(e){return (await n(`/realtime/subscriptions/project/${e}`)).subscriptions},async getEvents(e,t){let r=new URLSearchParams;t&&r.set("limit",String(t));let s=r.toString(),a=`/realtime/events/project/${e}${s?`?${s}`:""}`;return (await n(a)).events},async getStatus(e){return n(`/realtime/status/project/${e}`)},async install(e){return n("/realtime/install",{method:"POST",body:JSON.stringify(e)})},async enableAll(e){return n("/realtime/enable-all",{method:"POST",body:JSON.stringify(e)})}}}function Z(i){let n=p(i);return {async listBuckets(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let s=r.toString(),a=`/buckets/project/${e}${s?`?${s}`:""}`;return (await n(a)).buckets},async getBucket(e){return (await n(`/buckets/${e}`)).bucket},async createBucket(e){return (await n("/buckets",{method:"POST",body:JSON.stringify(e)})).bucket},async updateBucket(e,t){return (await n(`/buckets/${e}`,{method:"PUT",body:JSON.stringify(t)})).bucket},async deleteBucket(e){return n(`/buckets/${e}`,{method:"DELETE"})},async listFiles(e,t){let r=new URLSearchParams;t?.prefix&&r.set("prefix",t.prefix),t?.maxKeys&&r.set("maxKeys",String(t.maxKeys)),t?.continuationToken&&r.set("continuationToken",t.continuationToken);let s=r.toString(),a=`/buckets/${e}/files${s?`?${s}`:""}`;return n(a)},async deleteFile(e,t){return n(`/buckets/${e}/files?key=${encodeURIComponent(t)}`,{method:"DELETE"})},async getSignedUrl(e,t,r){return n(`/buckets/${e}/signed-url`,{method:"POST",body:JSON.stringify({key:t,expiresIn:r})})},async getUploadUrl(e,t,r){return n(`/buckets/${e}/upload-url`,{method:"POST",body:JSON.stringify({key:t,...r})})},async uploadFile(e,t,r,s){let a=s?.prefix?`${s.prefix}${t}`:t,l=s?.contentType??(r instanceof Blob?r.type:"application/octet-stream"),o=new URLSearchParams;return o.set("key",a),l&&o.set("contentType",l),n(`/buckets/${e}/upload?${o.toString()}`,{method:"POST",body:r,headers:{"Content-Type":l||"application/octet-stream"}})}}}function Y(i){let n=p(i);return {async list(e,t){let r={type:t?.type,enabled:t?.enabled},s=v(r);return (await n(`/integrations/subscriptions/project/${e}${s}`)).subscriptions},async get(e){return n(`/integrations/subscriptions/${e}`)},async create(e){return (await n("/integrations/subscriptions",{method:"POST",body:JSON.stringify(e)})).subscription},async update(e,t){return (await n(`/integrations/subscriptions/${e}`,{method:"PATCH",body:JSON.stringify(t)})).subscription},async delete(e){return n(`/integrations/subscriptions/${e}`,{method:"DELETE"})},async enable(e){return this.update(e,{enabled:true})},async disable(e){return this.update(e,{enabled:false})},async test(e){return n(`/integrations/subscriptions/${e}/test`,{method:"POST"})},async publish(e){return n("/integrations/events/publish",{method:"POST",body:JSON.stringify(e)})},async publishBatch(e){return (await n("/integrations/events/publish-batch",{method:"POST",body:JSON.stringify({events:e})})).results},async listEvents(e){let t={envId:e.envId,source:e.source,name:e.name,since:e.since,until:e.until,limit:e.limit,offset:e.offset},r=v(t);return (await n(`/integrations/events/project/${e.projectId}${r}`)).events},async getEvent(e){return n(`/integrations/events/${e}`)},async getDeliveries(e){let t={subscriptionId:e.subscriptionId,eventId:e.eventId,status:e.status,since:e.since,until:e.until,limit:e.limit,offset:e.offset},r=v(t);return (await n(`/integrations/deliveries${r}`)).deliveries},async getDelivery(e){return n(`/integrations/deliveries/${e}`)},async retryDelivery(e){return n(`/integrations/deliveries/${e}/retry`,{method:"POST"})},async retryAllFailed(e){return n(`/integrations/subscriptions/${e}/retry-failed`,{method:"POST"})},async getDlq(e,t){let r={limit:t?.limit,offset:t?.offset},s=v(r);return (await n(`/integrations/dlq/project/${e}${s}`)).deliveries},async purgeDlq(e,t){return n(`/integrations/dlq/project/${e}/purge`,{method:"POST",body:JSON.stringify({olderThan:t.olderThan})})},async replayDlq(e,t){return n(`/integrations/dlq/project/${e}/replay`,{method:"POST",body:JSON.stringify(t)})},verifySignature(e){let t=e.tolerance??300;try{let r=e.signature.split(","),s=r.find(b=>b.startsWith("t=")),a=r.find(b=>b.startsWith("v1="));if(!s||!a)return !1;let l=parseInt(s.slice(2),10),o=a.slice(3),c=Math.floor(Date.now()/1e3);if(Math.abs(c-l)>t)return !1;let g=`${l}.${e.payload}`,m=new TextEncoder,h=m.encode(e.secret),S=m.encode(g),I=Array.from(h).concat(Array.from(S)).reduce((b,C)=>b+C,0).toString(16);if(o.length!==I.length)return !1;let R=0;for(let b=0;b<o.length;b++)R|=o.charCodeAt(b)^I.charCodeAt(b);return R===0}catch{return false}},generateSecret(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="whsec_";for(let r=0;r<32;r++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}}}function ee(i){let n=p(i);return {async getSummary(e){return n(`/billing/org/${e}/summary`)},async getEntitlements(e){return n(`/entitlements/org/${e}`)},async checkEntitlement(e,t){return n(`/entitlements/org/${e}/check`,{method:"POST",body:JSON.stringify(t)})},async getPlans(){return (await n("/pricing/plans")).plans},async createCheckout(e){return n("/billing/checkout",{method:"POST",body:JSON.stringify(e)})},async openPortal(e){return n(`/billing/org/${e.orgId}/portal`,{method:"POST",body:JSON.stringify({returnUrl:e.returnUrl})})}}}function te(i){let n=p(i);return {async getOverview(){return n("/admin/overview")},async listUsers(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/users${r?`?${r}`:""}`)},async getUser(e){return n(`/admin/users/${e}`)},async updateUserStatus(e,t){return n(`/admin/users/${e}/status`,{method:"PATCH",body:JSON.stringify({status:t})})},async updateUserAdmin(e,t){return n(`/admin/users/${e}/admin`,{method:"PATCH",body:JSON.stringify({isAdmin:t})})},async listOrganizations(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.plan&&t.set("plan",e.plan),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/organizations${r?`?${r}`:""}`)},async getOrganization(e){return n(`/admin/organizations/${e}`)},async updateOrganization(e,t){return n(`/admin/organizations/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async listProjects(e){let t=new URLSearchParams;e?.search&&t.set("search",e.search),e?.orgId&&t.set("orgId",e.orgId),e?.region&&t.set("region",e.region),e?.tenancy&&t.set("tenancy",e.tenancy),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/projects${r?`?${r}`:""}`)},async getProject(e){return n(`/admin/projects/${e}`)},async updateProject(e,t){return n(`/admin/projects/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async getProjectResources(e){return n(`/admin/resources/project/${e}`)},async setDedicatedDb(e){return n(`/admin/resources/project/${e.projectId}/db`,{method:"POST",body:JSON.stringify({connectionString:e.connectionString})})},async listIncidents(e="open"){return (await n(`/admin/incidents?status=${e}`)).incidents},async createIncident(e){return n("/admin/incidents",{method:"POST",body:JSON.stringify(e)})},async acknowledgeIncident(e){return n(`/admin/incidents/${e}/ack`,{method:"POST"})},async resolveIncident(e){return n(`/admin/incidents/${e}/resolve`,{method:"POST"})},async listRegions(){return n("/admin/regions")},async updateRegion(e,t){return n(`/admin/regions/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async getHealthComponents(){return n("/admin/health/components")},async updateHealthComponent(e,t){return n(`/admin/health/components/${e}`,{method:"PATCH",body:JSON.stringify(t)})},async listQueues(){return n("/admin/queues")},async listDlqMessages(e){let t=new URLSearchParams;e?.queue&&t.set("queue",e.queue),e?.search&&t.set("search",e.search),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let r=t.toString();return n(`/admin/dlq${r?`?${r}`:""}`)},async retryDlqMessage(e){return n(`/admin/dlq/${e}/retry`,{method:"POST"})},async archiveDlqMessage(e){return n(`/admin/dlq/${e}`,{method:"DELETE"})}}}function ne(i){let n=p(i);return {async list(){return (await n("/flags")).flags},async create(e){return n("/flags",{method:"POST",body:JSON.stringify(e)})},async update(e,t){return n(`/flags/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(t)})},async delete(e){return n(`/flags/${encodeURIComponent(e)}`,{method:"DELETE"})}}}function re(i){let n=p(i);return {async getOverview(e){return (await n(`/security/overview/${encodeURIComponent(e)}`)).overview},async getAuditLogs(e,t){let r=new URLSearchParams;t?.limit&&r.set("limit",String(t.limit)),t?.offset&&r.set("offset",String(t.offset));let s=r.toString(),a=`/security/audit/${encodeURIComponent(e)}${s?`?${s}`:""}`;return n(a)},async listEnvVars(e,t){let r=new URLSearchParams;t&&r.set("envId",t);let s=r.toString(),a=`/projects/${encodeURIComponent(e)}/env-vars${s?`?${s}`:""}`;return (await n(a)).envVars},async createEnvVar(e,t){return (await n(`/projects/${encodeURIComponent(e)}/env-vars`,{method:"POST",body:JSON.stringify(t)})).envVar},async updateEnvVar(e,t,r){return (await n(`/projects/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(r)})).envVar},async deleteEnvVar(e,t){return n(`/projects/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(t)}`,{method:"DELETE"})},async getEnvVarValue(e,t){return n(`/projects/${encodeURIComponent(e)}/env-vars/${encodeURIComponent(t)}/value`)}}}function se(i){let n=p(i);return {async generatePlan(e){return n("/ai/plan",{method:"POST",body:JSON.stringify({projectId:e.projectId,prompt:e.prompt,context:e.context,taskType:e.taskType,mode:e.mode})})},async explainPlan(e){return n("/ai/explain",{method:"POST",body:JSON.stringify({plan:e.plan,projectId:e.projectId,taskType:e.taskType,mode:e.mode})})},async getOrgSettings(e){return n(`/ai/settings/org/${encodeURIComponent(e)}`)},async updateOrgSettings(e,t){return n(`/ai/settings/org/${encodeURIComponent(e)}`,{method:"POST",body:JSON.stringify(t)})},async getProjectOverrides(e){return n(`/ai/settings/project/${encodeURIComponent(e)}`)},async updateProjectOverrides(e,t){return n(`/ai/settings/project/${encodeURIComponent(e)}`,{method:"POST",body:JSON.stringify(t)})},async getUsage(e,t){let r=new URLSearchParams;t&&r.set("month",t);let s=r.toString(),a=`/ai/usage/org/${encodeURIComponent(e)}${s?`?${s}`:""}`;return n(a)},async getBudgetStatus(e){let[t,r]=await Promise.all([this.getOrgSettings(e),this.getUsage(e)]),s=t?.monthlyBudgetCents??1e4,a=r.costCents,l=Math.max(0,s-a),o=s>0?Math.round(a/s*100):0;return {spent:a,budget:s,remaining:l,hardStop:t?.hardStopEnabled??false,percentUsed:o}},async generateFunction(e){return n("/ai/generate-function",{method:"POST",body:JSON.stringify({projectId:e.projectId,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema,language:e.language??"typescript",mode:e.mode})})},async generateEndpoint(e){return n("/ai/generate-endpoint",{method:"POST",body:JSON.stringify({projectId:e.projectId,description:e.description,method:e.method??"GET",authRequired:e.authRequired??true,mode:e.mode})})},async exportCode(e){return n("/ai/export-code",{method:"POST",body:JSON.stringify({projectId:e.projectId,targetLanguage:e.targetLanguage,includeSchema:e.includeSchema??true,includeFunctions:e.includeFunctions??true,includeEndpoints:e.includeEndpoints??true})})},async createConversation(e,t){return n("/ai/conversations",{method:"POST",body:JSON.stringify({projectId:e,title:t?.title,context:t?.context})})},async sendMessage(e,t){return n(`/ai/conversations/${encodeURIComponent(e)}/messages`,{method:"POST",body:JSON.stringify({content:t.content,taskType:t.taskType})})},async getConversation(e){return n(`/ai/conversations/${encodeURIComponent(e)}`)},async listConversations(e){return (await n(`/ai/conversations/project/${encodeURIComponent(e)}`)).conversations},async deleteConversation(e){return n(`/ai/conversations/${encodeURIComponent(e)}`,{method:"DELETE"})}}}function oe(i){let n=p(i);return {async load(){return n("/bootstrap")}}}function ie(i){let n=p(i);return {async list(e){let t=new URLSearchParams;e?.visibility&&t.set("visibility",e.visibility),e?.category&&t.set("category",e.category),e?.orgId&&t.set("orgId",e.orgId);let r=t.toString(),s=`/templates${r?`?${r}`:""}`;return (await n(s)).templates},async get(e){return n(`/templates/${e}`)},async previewInstall(e){return n("/templates/install/preview",{method:"POST",body:JSON.stringify(e)})},async applyInstall(e){return n("/templates/install/apply",{method:"POST",body:JSON.stringify(e)})},async rollback(e){return n(`/templates/install/${e}/rollback`,{method:"POST"})},async createProject(e){return n("/templates/create-project",{method:"POST",body:JSON.stringify(e)})}}}function ae(i){let n=p(i);return {async list(e){return (await n(`/oauth/org/${e}`)).connections},async configure(e,t){return n(`/oauth/org/${e}/configure`,{method:"POST",body:JSON.stringify(t)})},async enable(e){return n(`/oauth/connections/${e}/enable`,{method:"POST"})},async disable(e){return n(`/oauth/connections/${e}/disable`,{method:"POST"})},async delete(e){return n(`/oauth/connections/${e}`,{method:"DELETE"})}}}function ce(i){let n=p(i);return {async listPages(e){let t=e?`?category=${encodeURIComponent(e)}`:"";return (await n(`/docs/pages${t}`)).pages},async getPage(e){return (await n(`/docs/pages/${encodeURIComponent(e)}`)).page},async createPage(e){return (await n("/docs/pages",{method:"POST",body:JSON.stringify(e)})).page},async updatePage(e,t){return (await n(`/docs/pages/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).page},async deletePage(e){return n(`/docs/pages/${encodeURIComponent(e)}`,{method:"DELETE"})},async listSdks(){return (await n("/docs/sdks")).sdks},async getSdk(e){return (await n(`/docs/sdks/${encodeURIComponent(e)}`)).sdk},async createSdk(e){return (await n("/docs/sdks",{method:"POST",body:JSON.stringify(e)})).sdk},async updateSdk(e,t){return (await n(`/docs/sdks/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).sdk},async deleteSdk(e){return n(`/docs/sdks/${encodeURIComponent(e)}`,{method:"DELETE"})},async listSdkExamples(e,t){let r=t?`?topic=${encodeURIComponent(t)}`:"";return (await n(`/docs/sdks/${encodeURIComponent(e)}/examples${r}`)).examples},async createSdkExample(e){return (await n("/docs/sdk-examples",{method:"POST",body:JSON.stringify(e)})).example},async deleteSdkExample(e){return n(`/docs/sdk-examples/${encodeURIComponent(e)}`,{method:"DELETE"})},async listEndpoints(e){let t=e?`?category=${encodeURIComponent(e)}`:"";return (await n(`/docs/api-endpoints${t}`)).endpoints},async getEndpoint(e){return (await n(`/docs/api-endpoints/${encodeURIComponent(e)}`)).endpoint},async createEndpoint(e){return (await n("/docs/api-endpoints",{method:"POST",body:JSON.stringify(e)})).endpoint},async updateEndpoint(e,t){return (await n(`/docs/api-endpoints/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).endpoint},async deleteEndpoint(e){return n(`/docs/api-endpoints/${encodeURIComponent(e)}`,{method:"DELETE"})},async listExamples(e){let t=e!==void 0?`?featured=${e}`:"";return (await n(`/docs/examples${t}`)).examples},async getExample(e){return (await n(`/docs/examples/${encodeURIComponent(e)}`)).example},async createExample(e){return (await n("/docs/examples",{method:"POST",body:JSON.stringify(e)})).example},async updateExample(e,t){return (await n(`/docs/examples/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).example},async deleteExample(e){return n(`/docs/examples/${encodeURIComponent(e)}`,{method:"DELETE"})},async listChangelog(){return (await n("/docs/changelog")).entries},async getChangelogEntry(e){return (await n(`/docs/changelog/${encodeURIComponent(e)}`)).entry},async createChangelogEntry(e){return (await n("/docs/changelog",{method:"POST",body:JSON.stringify(e)})).entry},async updateChangelogEntry(e,t){return (await n(`/docs/changelog/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})).entry},async deleteChangelogEntry(e){return n(`/docs/changelog/${encodeURIComponent(e)}`,{method:"DELETE"})},async search(e){return (await n(`/docs/search?q=${encodeURIComponent(e)}`)).results}}}function fe(i,n,e,t){let r=n.type||"public",s="unsubscribed",a=new Map,l=[],o={},c=null,g=null,m=new Set,h=new Set,S=new Set,I=u=>{if(u.event){let f=a.get(u.event);f&&f.forEach(T=>T(u.payload));}},R=u=>{o=u.state||{},m.forEach(f=>f(o));},b=u=>{let f=u.key||"",T=u.currentPresences||[],d=u.joinedPresences||[],y=u.leftPresences||[];d.length>0&&(o[f]=T,h.forEach(P=>P(f,T,d))),y.length>0&&(T.length===0?delete o[f]:o[f]=T,S.forEach(P=>P(f,T,y))),m.forEach(P=>P(o));},C=u=>{let f={type:"db_change",projectId:u.projectId||"",schema:u.schema||"",table:u.table||"",operation:u.op,new:u.record,old:u.old_record,timestamp:u.ts||new Date().toISOString(),partial:u.partial};l.forEach(({options:T,handler:d})=>{if(T.table===f.table){let y=T.event||"*";(y==="*"||(Array.isArray(y)?y.includes(f.operation):y===f.operation))&&d(f);}});},k={get name(){return i},get type(){return r},get status(){return s},_handleMessage:u=>{switch(u.type){case "broadcast":I(u);break;case "presence_state":R(u);break;case "presence":b(u);break;case "db_change":C(u);break;case "subscribed":s="subscribed";break;case "error":s="error";break}},onDbChange(u,f){return l.push({options:u,handler:f}),s==="subscribed"&&e({type:"subscribe",channel:i,options:{table:u.table,filter:u.filter,event:u.event,columns:u.columns}}),k},on(u,f){return a.has(u)||a.set(u,new Set),a.get(u).add(f),k},off(u,f){return f?a.get(u)?.delete(f):a.delete(u),k},async broadcast(u){if(s!=="subscribed")throw new Error("Channel must be subscribed before broadcasting");e({type:"broadcast",channel:i,event:u.event,payload:u.payload,includeSelf:u.includeSelf});},presence:{async track(u){if(r!=="presence")throw new Error("Presence tracking is only available on presence channels");c=u.key||t()||"anonymous",g=u.state,e({type:"presence_track",channel:i,key:c,state:g});},async update(u){if(!g)throw new Error("Must call track() before update()");g={...g,...u},e({type:"presence_update",channel:i,key:c,state:g});},async untrack(){c&&(e({type:"presence_untrack",channel:i,key:c}),c=null,g=null);},state(){return {...o}},onSync(u){return m.add(u),k},onJoin(u){return h.add(u),k},onLeave(u){return S.add(u),k}},async subscribe(){return s==="subscribed"||(s="subscribing",e({type:"subscribe",channel:i}),l.forEach(({options:u})=>{e({type:"subscribe",channel:i,options:{table:u.table,filter:u.filter,event:u.event,columns:u.columns}});}),n.presenceState&&r==="presence"&&await k.presence.track({state:n.presenceState})),k},async unsubscribe(){s!=="unsubscribed"&&(c&&await k.presence.untrack(),e({type:"unsubscribe",channel:i}),s="unsubscribed",o={},a.clear(),l.length=0);}};return k}function le(i,n){let{wsUrl:e=i.baseUrl.replace(/^http/,"ws")+"/realtime/ws",autoReconnect:t=true,reconnectDelay:r=1e3,maxReconnectAttempts:s=10}=n??{},a=null,l="disconnected",o=null,c=null,g=0,m=null,h=null,S=new Map,I=new Map,R=new Set,b={connect:new Set,disconnect:new Set,error:new Set,reconnect:new Set},C=d=>{b[d].forEach(y=>y());},D=d=>{let y=`table:${d.table}`;if(d.filter){let O=(Array.isArray(d.filter)?d.filter:[d.filter]).map(w=>`${w.field}${w.operator||"eq"}${w.value}`).join("&");y+=`?${O}`;}return y},k=d=>{a?.readyState===WebSocket.OPEN&&a.send(JSON.stringify(d));},u=d=>{if(d.channel){let y=S.get(d.channel);if(y){y._handleMessage(d);return}}switch(d.type){case "db_change":{let y={type:"db_change",projectId:d.projectId??"",schema:d.schema??"",table:d.table??"",operation:d.op,new:d.record,old:d.old_record,timestamp:d.ts??new Date().toISOString(),partial:d.partial},P=`table:${d.table}`;I.forEach((O,w)=>{(w===P||w.startsWith(P+"?"))&&O.forEach(B=>B(y));});break}case "presence":{let y={type:"presence",event:d.event,key:d.key||d.connectionId||"",connectionId:d.connectionId??"",projectId:d.projectId??"",currentPresences:d.currentPresences||[],leftPresences:d.leftPresences||[],joinedPresences:d.joinedPresences||[]};R.forEach(P=>P(y));break}case "welcome":o=d.connectionId||null;break;case "error":{console.error("[vaif/realtime] Server error:",d.message),C("error");break}}},f=()=>new Promise((d,y)=>{let P=new URLSearchParams;i.apiKey&&P.set(i.apiKeyHeader,i.apiKey),c&&P.set("token",c);let O=P.toString(),w=O?`${e}?${O}`:e;try{a=new WebSocket(w);}catch{y(new x("Failed to create WebSocket connection"));return}let B=()=>{l="connected",g=0,C("connect"),S.forEach(A=>{(A.status==="subscribed"||A.status==="subscribing")&&A.subscribe();}),I.forEach((A,N)=>{k({type:"subscribe",channel:N});}),h=setInterval(()=>{k({type:"ping"});},3e4),d();},ue=A=>{try{let N=JSON.parse(A.data);u(N);}catch{}},de=()=>{if(l="disconnected",o=null,a=null,h&&(clearInterval(h),h=null),C("disconnect"),t&&g<s){l="reconnecting";let A=r*Math.pow(2,g);m=setTimeout(()=>{g++,C("reconnect"),f().catch(()=>{});},Math.min(A,3e4));}},ge=()=>{C("error"),y(new x("WebSocket connection error"));};a.addEventListener("open",B),a.addEventListener("message",ue),a.addEventListener("close",de),a.addEventListener("error",ge);}),T=()=>{m&&(clearTimeout(m),m=null),h&&(clearInterval(h),h=null),g=s;};return {channel(d,y={}){let P=S.get(d);if(P)return P;let O=fe(d,y,k,()=>o);return S.set(d,O),O},async removeChannel(d){let y=S.get(d.name);y&&(await y.unsubscribe(),S.delete(d.name));},getChannels(){return Array.from(S.values())},subscribe(d,y){let P=D(d);return I.has(P)||I.set(P,new Set),I.get(P).add(y),a?.readyState===WebSocket.OPEN&&k({type:"subscribe",channel:P}),()=>{let O=I.get(P);O&&(O.delete(y),O.size===0&&(I.delete(P),a?.readyState===WebSocket.OPEN&&k({type:"unsubscribe",channel:P})));}},subscribeToPresence(d){return R.add(d),()=>{R.delete(d);}},async connect(){if(l!=="connected"){if(!i.apiKey)throw new M("API key is required for realtime connections");l="connecting",await f();}},disconnect(){T(),S.forEach(d=>{d.unsubscribe();}),S.clear(),a&&(a.close(),a=null),l="disconnected",o=null;},get isConnected(){return l==="connected"},get connectionState(){return l},get connectionId(){return o},on(d,y){b[d].add(y);},off(d,y){b[d].delete(y);},setAuth(d){c=d;}}}var $={apiKeyHeader:"x-vaif-key",timeout:3e4,retry:{maxRetries:3,retryDelay:1e3,retryOn:[429,500,502,503,504]}};function Pe(i){return {baseUrl:i.baseUrl.replace(/\/$/,""),apiKey:i.apiKey,apiKeyHeader:i.apiKeyHeader??$.apiKeyHeader,accessToken:i.accessToken,fetch:i.fetch??globalThis.fetch.bind(globalThis),timeout:i.timeout??$.timeout,retry:{maxRetries:i.retry?.maxRetries??$.retry.maxRetries,retryDelay:i.retry?.retryDelay??$.retry.retryDelay,retryOn:i.retry?.retryOn??[...$.retry.retryOn]}}}function he(i){let n=Pe(i),e=V(n),t=q(n),r=H(n),s=K(n),a=z(n),l=_(n),o=W(n),c=G(n),g=Q(n),m=X(n),h=Z(n),S=Y(n),I=ee(n),R=te(n),b=ne(n),C=re(n),D=se(n),k=oe(n),u=ie(n),f=ae(n),T=ce(n);return {from:e.from,auth:t,functions:r,storage:s,projects:a,orgs:l,schema:o,secrets:c,deployments:g,realtimeMonitoring:m,storageDashboard:h,integrations:S,billing:I,admin:R,flags:b,security:C,ai:D,bootstrap:k,templates:u,oauth:f,docs:T,realtime:d=>le(n,d)}}export{M as VaifAuthError,E as VaifError,x as VaifNetworkError,j as VaifNotFoundError,F as VaifRateLimitError,U as VaifValidationError,he as createVaifClient,pe as isVaifError};
|
package/package.json
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@vaiftech/client",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "TypeScript SDK for VAIF Studio BaaS",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"module": "dist/index.mjs",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.mjs",
|
|
12
|
+
"require": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist"
|
|
17
|
+
],
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "tsup",
|
|
20
|
+
"dev": "tsup --watch",
|
|
21
|
+
"lint": "tsc --noEmit",
|
|
22
|
+
"typecheck": "tsc --noEmit",
|
|
23
|
+
"test": "vitest run"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"tsup": "^8.0.0",
|
|
27
|
+
"typescript": "^5.5.4",
|
|
28
|
+
"vitest": "^1.0.0"
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"ws": "^8.0.0"
|
|
32
|
+
},
|
|
33
|
+
"peerDependenciesMeta": {
|
|
34
|
+
"ws": {
|
|
35
|
+
"optional": true
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"engines": {
|
|
39
|
+
"node": ">=18.0.0"
|
|
40
|
+
},
|
|
41
|
+
"keywords": [
|
|
42
|
+
"vaif",
|
|
43
|
+
"sdk",
|
|
44
|
+
"client",
|
|
45
|
+
"baas",
|
|
46
|
+
"backend-as-a-service",
|
|
47
|
+
"typescript",
|
|
48
|
+
"realtime",
|
|
49
|
+
"database",
|
|
50
|
+
"authentication",
|
|
51
|
+
"storage"
|
|
52
|
+
],
|
|
53
|
+
"author": "VAIF Technologies",
|
|
54
|
+
"license": "MIT",
|
|
55
|
+
"repository": {
|
|
56
|
+
"type": "git",
|
|
57
|
+
"url": "https://github.com/vaif-technologies/vaif-studio",
|
|
58
|
+
"directory": "packages/client"
|
|
59
|
+
},
|
|
60
|
+
"bugs": {
|
|
61
|
+
"url": "https://github.com/vaif-technologies/vaif-studio/issues"
|
|
62
|
+
},
|
|
63
|
+
"homepage": "https://vaif.studio"
|
|
64
|
+
}
|