@rushdb/javascript-sdk 1.8.1 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/api/api.d.ts CHANGED
@@ -284,10 +284,9 @@ export declare class RestAPI {
284
284
  settings: {
285
285
  get: () => Promise<ApiResponse<{
286
286
  selfHosted: boolean;
287
- dashboardUrl: string;
288
- googleOAuthEnabled: boolean;
289
- githubOAuthEnabled: boolean;
290
287
  customDB?: boolean;
288
+ managedDB?: boolean;
289
+ planType?: import("../sdk/types.js").PlanType;
291
290
  } | undefined>>;
292
291
  };
293
292
  }
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var me=Object.create;var v=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var Re=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty;var we=(n,e)=>{for(var t in e)v(n,t,{get:e[t],enumerable:!0})},re=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Se(e))!Te.call(n,s)&&s!==t&&v(n,s,{get:()=>e[s],enumerable:!(r=fe(e,s))||r.enumerable});return n};var se=(n,e,t)=>(t=n!=null?me(Re(n)):{},re(e||!n||!n.__esModule?v(t,"default",{value:n,enumerable:!0}):t,n)),De=n=>re(v({},"__esModule",{value:!0}),n);var ke={};we(ke,{DBRecordInstance:()=>g,DBRecordsArrayInstance:()=>A,EmptyTargetError:()=>b,HttpClient:()=>O,HttpClientResponse:()=>H,Model:()=>te,NonUniqueResultError:()=>U,RestAPI:()=>_,RushDB:()=>D,Transaction:()=>B,UniquenessError:()=>E,default:()=>Ue,idToDate:()=>Z,idToTimestamp:()=>K,initSDK:()=>ee,mergeDefaultsWithPayload:()=>k,parseConfig:()=>G,pickUniqFieldsFromRecord:()=>N,pickUniqFieldsFromRecords:()=>J,validateInteger:()=>X});module.exports=De(ke);var O=class n{makeRequest(e,{headers:t,method:r,protocol:s,requestData:a,timeout:o}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(n.TIMEOUT_ERROR_CODE);return e.code=n.TIMEOUT_ERROR_CODE,e}};O.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];O.TIMEOUT_ERROR_CODE="ETIMEDOUT";var F=class{constructor(e,t){this._statusCode=e,this._headers=t}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}},H=class{constructor(e){this._res=e}getStatusCode(){throw new Error("getStatusCode not implemented.")}getHeaders(){throw new Error("getHeaders not implemented.")}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}};var z=se(require("http"),1),Y=se(require("https"),1);var be="string",Ie="datetime",xe="boolean",Oe="number",Pe="null",Ee="vector",ne=[be,Ie,xe,Oe,Pe,Ee];var oe=z.default||z,ie=Y.default||Y,Ae=new oe.Agent({keepAlive:!0}),Be=new ie.Agent({keepAlive:!0}),M=class extends O{constructor(e){super(),this._agent=e}makeRequest(e,{headers:t,method:r,protocol:s,requestData:a,timeout:o}){let i=new URL(e),c=s==="http"||i.protocol==="http:",d=this._agent;return d||(d=c?Ae:Be),new Promise((p,h)=>{let l=(c?oe:ie).request({agent:d,ciphers:"DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5",headers:t,host:i.hostname,method:r,path:i.pathname+i.search,port:i.port});l.setTimeout(o!=null?o:8e4,()=>{l.destroy(O.makeTimeoutError())}),l.on("response",S=>{p(new W(S))}),l.on("error",S=>{h(S)}),l.once("socket",S=>{let x=a?JSON.stringify(a):"";S.connecting?S.once(c?"connect":"secureConnect",()=>{l.write(x),l.end()}):(l.write(x),l.end())})})}},W=class extends F{constructor(e){super(e.statusCode,e.headers||{}),this._res=e}getRawResponse(){return this._res}toStream(e){return this._res.once("end",()=>e()),this._res}toJSON(){return new Promise((e,t)=>{let r="";this._res.setEncoding("utf8"),this._res.on("data",s=>{r+=s}),this._res.once("end",()=>{try{e(JSON.parse(r))}catch(s){t(s)}})})}};var T=n=>typeof n=="object"&&Array.isArray(n)&&n!==null,R=n=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",q=n=>R(n)&&Object.keys(n).length===0,ce=n=>typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null;function _e(n,e){let t={...n};return e.forEach(r=>{delete t[r]}),t}var L=n=>R(n)?_e(n,["__label","__id","__proptypes"]):n,C=n=>T(n)?n.map(C):R(n)?Object.fromEntries(Object.entries(n).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,C(t)])):n,Q=n=>T(n)?n.every(ce):ce(n),$=n=>R(n)&&Object.values(n).every(Q),P=n=>typeof n=="string",w=n=>{if(typeof n=="string"){if(n.toLowerCase()==="true")return!0;if(n.toLowerCase()==="false")return!1}return T(n)&&n.length===0||R(n)&&Object.keys(n).length===0?!1:!!n};var V=["httpClient","timeout","host","port","protocol","url","logger","options"];var E=class n extends Error{constructor(e,t){super(`Record with label "${e}" and properties ${JSON.stringify(t)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,n.prototype)}},b=class n extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,n.prototype)}},U=class n extends Error{constructor(e,t){super(`Expected a unique result but found ${e} matches for the provided SearchQuery: ${JSON.stringify(t)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,n.prototype)}};var k=async(n,e)=>{let t=Object.entries(n).map(async([a,o])=>o.default&&typeof o.default<"u"&&typeof e[a]>"u"?{key:a,value:typeof o.default=="function"?await o.default():o.default}:{key:a,value:void 0});return{...(await Promise.all(t)).reduce((a,{key:o,value:i})=>(i!==void 0&&(a[o]=i),a),{}),...e}},N=(n,e)=>Object.entries(e).filter(([t])=>{var r;return(r=n[t])==null?void 0:r.uniq}).reduce((t,[r,s])=>(r in n&&(t[r]=s),t),{}),J=(n,e,t)=>{let r={},s=Object.entries(e).filter(([,a])=>a.uniq).reduce((a,[o])=>(a[o]=!0,a),{});return n.forEach(a=>{Object.entries(a).forEach(([o,i])=>{if(o in s)if(r[o]){if(r[o].includes(i))throw new E(t,{[o]:i});r[o]=[...r[o],i]}else r[o]=[i]})}),r},G=n=>{if(!n)return{};if(!R(n))throw new Error("Config must be an object");if(Object.keys(n).filter(t=>!V.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${V.join(", ")}`);return n};function X(n,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${n} must be an integer`)}return e}function K(n){let e=n.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function Z(n){return new Date(K(n))}var g=class{constructor(e={}){this.data=e}exists(){return w(this.data.__id)&&w(this.data.__label)}id(){if(!w(this.data.__id))throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.");return this.data.__id}label(){if(!w(this.data.__label))throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.");return this.data.__label}proptypes(){if(!w(this.data.__proptypes))throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.");return this.data.__proptypes}date(){try{return Z(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return K(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}async delete(e){if(!w(this.data))throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return await(await D.init()).records.deleteById(this.id(),e)}async update(e,t){if(!w(this.data))throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return(await D.init()).records.update({label:this.label(),target:this.id(),data:e},t)}async set(e,t){if(!w(this.data))throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return(await D.init()).records.set({label:this.label(),target:this.id(),data:e},t)}async attach(e,t,r){if(!w(this.data))throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return(await D.init()).records.attach({source:this.id(),target:e,options:t},r)}async detach(e,t,r){if(!w(this.data))throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return(await D.init()).records.detach({source:this.id(),target:e,options:t},r)}},A=class{constructor(e=[],t=0,r){this.data=e,this.total=t,this.searchQuery=r}};var Ce={"Content-Type":"application/json"},de=({httpClient:n,token:e,url:t})=>async(r,{headers:s,...a})=>{let o=await n.makeRequest(`${t}${r}`,{credentials:"omit",headers:Object.assign({...Ce,...s},typeof e<"u"?{token:e}:{}),...a});if(o.getStatusCode()>=200&&o.getStatusCode()<300)return await o.toJSON();throw new Error(`${o.getStatusCode()}`)};var B=class{constructor(e){this.id=e}async rollback(){return await(await D.init()).tx.rollback(this.id)}async commit(){return await(await D.init()).tx.commit(this.id)}};var pe="api.rushdb.com";var le="https",he="/api/v1";var f=n=>n?{"x-transaction-id":n}:void 0,je=n=>P(n)||n instanceof B,y=n=>je(n)?n instanceof B?n.id:n:void 0,ue=n=>/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(n),I=n=>{if(P(n)&&ue(n))return n;if(n instanceof g&&n.data)return n.data.__id;if(R(n)&&"__id"in n&&ue(n.__id))return n.__id},j=n=>!(!R(n)||R(n)&&"name"in n&&!P(n.name)||R(n)&&"type"in n&&(!P(n.type)||!ne.includes(n.type))||!("value"in n)||!Q(n.value)||"metadata"in n&&!P(n.metadata)||"valueSeparator"in n&&!P(n.valueSeparator)),ye=n=>{let e=le,t=pe,r=443,s=he;if("url"in n){let o=new URL(n.url);e=o.protocol.replace(":",""),t=o.hostname,r=parseInt(o.port||(e==="http"?"80":e==="https"?"443":""))}"host"in n&&"port"in n&&"protocol"in n&&(e=n.protocol.replace(":",""),t=n.host,r=n.port),s&&!s.startsWith("/")&&(s="/"+s);let a="";return e==="http"&&r===80||e==="https"&&r===443||(a=":"+r),`${e}://${t}${a}${s}`},u=(n=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let r=0;r<n;r++){let s=Math.floor(Math.random()*e.length);t+=e[s]}return t};var _=class{constructor(e,t){this.records={attach:async({source:e,target:t,options:r},s)=>{var h,l;let a=y(s),i=`/relationships/${I(e)}`,c={headers:Object.assign({},f(a)),method:"POST",requestData:{targetIds:this._extractTargetIds(t,"Attach"),...(r==null?void 0:r.type)&&{type:r.type},...(r==null?void 0:r.direction)&&{direction:r.direction}}},d=typeof this.logger=="function"?u():"";(h=this.logger)==null||h.call(this,{requestId:d,path:i,...c});let p=await this.fetcher(i,c);return(l=this.logger)==null||l.call(this,{requestId:d,path:i,...c,responseData:p.data}),p},detach:async({source:e,target:t,options:r},s)=>{var h,l;let a=y(s),i=`/relationships/${I(e)}`,c={headers:Object.assign({},f(a)),method:"PUT",requestData:{targetIds:this._extractTargetIds(t,"Detach"),...(r==null?void 0:r.typeOrTypes)&&{typeOrTypes:r.typeOrTypes},...(r==null?void 0:r.direction)&&{direction:r.direction}}},d=typeof this.logger=="function"?u():"";(h=this.logger)==null||h.call(this,{requestId:d,path:i,...c});let p=await this.fetcher(i,c);return(l=this.logger)==null||l.call(this,{requestId:d,path:i,...c,responseData:p.data}),p},create:async({label:e,data:t,options:r},s)=>{var h,l;let a=y(s),o="/records",i={headers:Object.assign({},f(a)),method:"POST",requestData:{}},c=typeof this.logger=="function"?u():"",d=L(C(t));if(T(d)&&d.every(j))i.requestData={label:e,properties:d};else if($(d))i.requestData={label:e,data:d,options:r};else throw R(d)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(h=this.logger)==null||h.call(this,{requestId:c,path:o,...i});let p=await this.fetcher(o,i);return(l=this.logger)==null||l.call(this,{requestId:c,path:o,...i,responseData:p.data}),p!=null&&p.success&&(p!=null&&p.data)?new g(p.data):new g},createMany:async(e,t)=>{var c,d,p,h;let r=y(t),s="/records/import/json",a={headers:Object.assign({},f(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);if((d=this.logger)==null||d.call(this,{requestId:o,path:s,...a,responseData:i.data}),i!=null&&i.success&&(i!=null&&i.data)){let l=(h=(p=i.data)==null?void 0:p.map(S=>new g(S)))!=null?h:[];return new A(l,i.total)}return new A([])},delete:async(e,t)=>{var c,d,p;if(q(e.where)&&!((c=this==null?void 0:this.options)!=null&&c.allowForceDelete))throw new b("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let r=y(t),s="/records/delete",a={headers:Object.assign({},f(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(p=this.logger)==null||p.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},deleteById:async(e,t)=>{var d,p;let r=y(t),s=T(e),a=s?"/records/delete":`/records/${e}`,o={headers:Object.assign({},f(r)),method:s?"POST":"DELETE",requestData:s?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:i,path:a,...o});let c=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:c.data}),c},export:async(e,t)=>{var c,d;let r=y(t),s="/records/export/csv",a={headers:Object.assign({},f(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},find:async(e,t)=>{var h,l;let{id:r,...s}=e,a=y(t),o=r?`/records/${r}/search`:"/records/search",i={headers:Object.assign({},f(a)),method:"POST",requestData:s!=null?s:{}},c=typeof this.logger=="function"?u():"";(h=this.logger)==null||h.call(this,{requestId:c,path:o,...i});let d=await this.fetcher(o,i);(l=this.logger)==null||l.call(this,{requestId:c,path:o,...i,responseData:d.data});let p=d.data.map(S=>new g(S));return new A(p,d.total,e)},findById:async(e,t)=>{var c,d;let r=y(t),s=T(e)?"/records":`/records/${e}`,a={headers:Object.assign({},f(r)),method:T(e)?"POST":"GET",requestData:T(e)?{ids:e}:void 0},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);if((d=this.logger)==null||d.call(this,{requestId:o,path:s,...a,responseData:i.data}),T(e)){let p=i.data.map(h=>new g(h));return new A(p,i.total)}else return new g(i.data)},findOne:async(e,t)=>{var d,p;let r=y(t),s="/records/search",a={headers:Object.assign({},f(r)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);(p=this.logger)==null||p.call(this,{requestId:o,path:s,...a,responseData:i.data});let[c]=i.data;return new g(c)},findUniq:async(e,t)=>{var d,p;let r=y(t),s="/records/search",a={headers:Object.assign({},f(r)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);if((p=this.logger)==null||p.call(this,{requestId:o,path:s,...a,responseData:i.data}),typeof i.total<"u"&&i.total>1)throw new U(i.total,e);let[c]=i.data;return new g(c)},set:async({target:e,label:t,data:r,options:s},a)=>{var S,x;let o=y(a),c=`/records/${I(e)}`,d={headers:Object.assign({},f(o)),method:"PUT",requestData:{}},p=typeof this.logger=="function"?u():"",h=L(C(r));if(T(h)&&h.every(j))d.requestData={label:t,properties:h};else if($(h))d.requestData={label:t,data:h,options:s};else throw R(h)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(S=this.logger)==null||S.call(this,{requestId:p,path:c,...d});let l=await this.fetcher(c,d);return(x=this.logger)==null||x.call(this,{requestId:p,path:c,...d,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)?new g(l.data):new g},update:async({target:e,label:t,data:r,options:s},a)=>{var S,x;let o=y(a),c=`/records/${I(e)}`,d={headers:Object.assign({},f(o)),method:"PATCH",requestData:{}},p=typeof this.logger=="function"?u():"",h=L(C(r));if(T(h)&&h.every(j))d.requestData={label:t,properties:h};else if($(h))d.requestData={label:t,data:h,options:s};else throw R(h)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(S=this.logger)==null||S.call(this,{requestId:p,path:c,...d});let l=await this.fetcher(c,d);return(x=this.logger)==null||x.call(this,{requestId:p,path:c,...d,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)?new g(l.data):new g}};this.relationships={find:async(e,t)=>{var p,h;let r=y(t),s=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&s.append("limit",e.limit.toString()),(e==null?void 0:e.skip)!==void 0&&s.append("skip",e.skip.toString());let o=`/relationships/search${s.toString()?"?"+s.toString():""}`,i={headers:Object.assign({},f(r)),method:"POST",requestData:e!=null?e:{}},c=typeof this.logger=="function"?u():"";(p=this.logger)==null||p.call(this,{requestId:c,path:o,...i});let d=await this.fetcher(o,i);return(h=this.logger)==null||h.call(this,{requestId:c,path:o,...i,responseData:d.data}),d}};this.properties={delete:async(e,t)=>{var c,d;let r=y(t),s=`/properties/${e}`,a={headers:Object.assign({},f(r)),method:"DELETE"},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},find:async(e,t)=>{var c,d;let r=y(t),s="/properties/search",a={headers:Object.assign({},f(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},findById:async(e,t)=>{var c,d;let r=y(t),s=`/properties/${e}`,a={headers:Object.assign({},f(r)),method:"GET"},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},values:async(e,t,r)=>{var d,p;let s=y(r),a=`/properties/${e}/values`,o={headers:Object.assign({},f(s)),method:"POST",requestData:t!=null?t:{}},i=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:i,path:a,...o});let c=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:c.data}),c}};this.labels={find:async(e,t)=>{var c,d;let r=y(t),s="/labels/search",a={headers:Object.assign({},f(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a,responseData:i.data}),i}};this.tx={begin:async e=>{var o,i;let t="/tx",r={method:"POST",requestData:R(e)&&"ttl"in e?e:{}},s=typeof this.logger=="function"?u():"";(o=this.logger)==null||o.call(this,{requestId:s,path:t,...r});let a=await this.fetcher(t,r);return(i=this.logger)==null||i.call(this,{requestId:s,path:t,...r,responseData:a.data}),new B(a.data.id)},commit:async e=>{var i,c;let r=`/tx/${y(e)}/commit`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:a,path:r,...s});let o=await this.fetcher(r,s);return(c=this.logger)==null||c.call(this,{requestId:a,path:r,...s,responseData:o.data}),o},get:async e=>{var i,c;let r=`/tx/${y(e)}`,s={method:"GET"},a=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:a,path:r,...s});let o=await this.fetcher(r,s);return(c=this.logger)==null||c.call(this,{requestId:a,path:r,...s,responseData:o.data}),new B(o.data.id)},rollback:async e=>{var i,c;let r=`/tx/${y(e)}/rollback`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:a,path:r,...s});let o=await this.fetcher(r,s);return(c=this.logger)==null||c.call(this,{requestId:a,path:r,...s,responseData:o.data}),o}};this.settings={get:async()=>{var a,o;let e="/sdk/settings",t={method:"GET"},r=typeof this.logger=="function"?u():"";(a=this.logger)==null||a.call(this,{requestId:r,path:e,...t});let s=await this.fetcher(e,t);return(o=this.logger)==null||o.call(this,{requestId:r,path:e,...t,responseData:s.data}),s}};if(this.fetcher=null,t!=null&&t.httpClient){let r=ye(t);this.fetcher=de({httpClient:t.httpClient,token:e,url:r})}t!=null&&t.options&&(this.options=t==null?void 0:t.options),t!=null&&t.logger&&(this.logger=t==null?void 0:t.logger)}_extractTargetIds(e,t){var r;if(e instanceof g){let s=I(e);if(!s)throw new b(`${t} error: Target id is empty`);return[s]}if(T(e)&&e.every(s=>s instanceof g)){let s=e.map(I).filter(w);if(!s.length)throw new b(`${t} error: Target ids are empty`);return s}if(e instanceof A){let s=(r=e.data)==null?void 0:r.map(I).filter(w);if(!(s!=null&&s.length))throw new b(`${t} error: Target ids are empty`);return s}if(R(e)&&"__id"in e)return[e.__id];if(T(e)&&e.every(s=>R(s)&&"__id"in s)){let s=e.map(I).filter(w);if(!s.length)throw new b(`${t} error: Target ids are empty`);return s}return T(e)?e:P(e)?[e]:[]}};var ge,m=class m extends _{constructor(e,t){var s;let r=G(t);super(e,{...r,httpClient:(s=r.httpClient)!=null?s:ge}),m.instance=this,m.initPromise=this.initializeAsync(e,r).catch(a=>{throw console.error("RushDB initialization failed:",a),a})}async waitForInitialization(){return m.initPromise?await m.initPromise:this}async initializeAsync(e,t){try{let{data:r}=await this.settings.get();return m.state={initialized:!0,debug:!1,timeout:X("timeout",t==null?void 0:t.timeout,8e4),token:e,serverSettings:r},this}catch(r){throw console.error("Failed to initialize RushDB:",r),new Error(`RushDB initialization failed: ${r}`)}finally{m.state.initialized=!0}}static async init(){if(m.state.initialized&&m.instance)return m.instance;if(m.initPromise)return await m.initPromise;if(m.instance)return await m.instance.waitForInitialization();throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}static getInstance(){return m.instance}static isInitialized(){return m.state.initialized&&m.instance!==null}toDBRecordInstance(e){return new g(e)}};m.instance=null,m.initPromise=null,m.state={initialized:!1,debug:!1,timeout:8e4};var D=m,ee=n=>{ge=n};var te=class{constructor(e,t){this.label=e,this.schema=t}getLabel(){return this.label}async getRushDBInstance(){if(D.getInstance())return await D.init();throw new Error('No RushDB instance found. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}async toDBRecordInstance(e){try{return(await this.getRushDBInstance()).toDBRecordInstance(e)}catch{throw new Error("No RushDB instance was provided during model initialization.")}}async find(e,t){let r=e!=null?e:{};return(await this.getRushDBInstance()).records.find({...r,labels:[this.label]},t)}async findOne(e,t){let r=e!=null?e:{};return(await this.getRushDBInstance()).records.findOne({...r,labels:[this.label]},t)}async findById(e,t){return this.findOne({where:{$id:e}},t)}async findUniq(e,t){let r=e!=null?e:{};return(await this.getRushDBInstance()).records.findUniq({...r,labels:[this.label]},t)}async create(e,t){var i;let r=await k(this.schema,e),s=N(this.schema,r),a=w(s),o=await this.getRushDBInstance();if(a){let c=t!=null?t:await o.tx.begin(),d=await this.find({where:s},c),p=typeof t<"u";if(!((i=d==null?void 0:d.data)!=null&&i.length)){let l=await o.records.create({label:this.label,data:r},c);return p||await c.commit(),l}else throw p||await c.commit(),new E(this.label,s)}return await o.records.create({label:this.label,data:r},t)}async attach({source:e,target:t,options:r},s){return await(await this.getRushDBInstance()).records.attach({source:e,target:t,options:r},s)}async detach({source:e,target:t,options:r},s){return await(await this.getRushDBInstance()).records.detach({source:e,target:t,options:r},s)}async handleSetOrUpdate(e,t,r,s){var c,d;if(T(t)&&t.every(j))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let a=await this.getRushDBInstance(),o=await k(this.schema,t),i=N(this.schema,o);if(!q(i)){let p=s!=null?s:await a.tx.begin(),h=await this.find({where:i},p),l=typeof s<"u";if(!((c=h==null?void 0:h.data)!=null&&c.length)||h.data.length===1&&((d=h.data[0])==null?void 0:d.id())===I(e)){let x=await a.records[r]({target:e,label:this.label,data:o},p);return l||await p.commit(),x}else throw l||await p.commit(),new E(this.label,i)}return await a.records[r]({label:this.label,target:e,data:o},s)}async set(e,t,r){return await this.handleSetOrUpdate(e,t,"set",r)}async update(e,t,r){return await this.handleSetOrUpdate(e,t,"update",r)}async createMany(e,t){var o;let r=await this.getRushDBInstance(),s=typeof t<"u",a=t!=null?t:await r.tx.begin();try{let i=await Promise.all(e.map(async p=>await k(this.schema,p))),c=J(i,this.schema,this.label);if(!q(c)){let p=Object.entries(c).map(([l,S])=>({[l]:{$in:S}})),h=await this.find({where:{$or:p}},a);if((o=h==null?void 0:h.data)!=null&&o.length)throw new E(this.label,Object.keys(c))}let d=await r.records.createMany({label:this.label,data:i},a);return s||await a.commit(),d}catch(i){throw s||await a.rollback(),i}}async delete(e,t){if(q(e.where))throw new b(`You must specify criteria to delete records of type '${this.label}'. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.`);return await(await this.getRushDBInstance()).records.delete({...e,labels:[this.label]},t)}async deleteById(e,t){return await(await this.getRushDBInstance()).records.deleteById(e,t)}};ee(new M);var Ue=D;0&&(module.exports={DBRecordInstance,DBRecordsArrayInstance,EmptyTargetError,HttpClient,HttpClientResponse,Model,NonUniqueResultError,RestAPI,RushDB,Transaction,UniquenessError,idToDate,idToTimestamp,initSDK,mergeDefaultsWithPayload,parseConfig,pickUniqFieldsFromRecord,pickUniqFieldsFromRecords,validateInteger});
1
+ "use strict";var Se=Object.create;var H=Object.defineProperty;var Re=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var De=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty;var be=(s,e)=>{for(var t in e)H(s,t,{get:e[t],enumerable:!0})},ne=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Te(e))!we.call(s,r)&&r!==t&&H(s,r,{get:()=>e[r],enumerable:!(n=Re(e,r))||n.enumerable});return s};var se=(s,e,t)=>(t=s!=null?Se(De(s)):{},ne(e||!s||!s.__esModule?H(t,"default",{value:s,enumerable:!0}):t,s)),Ie=s=>ne(H({},"__esModule",{value:!0}),s);var Me={};be(Me,{DBRecordInstance:()=>g,DBRecordsArrayInstance:()=>A,EmptyTargetError:()=>w,HttpClient:()=>O,HttpClientResponse:()=>v,Model:()=>re,NonUniqueResultError:()=>k,RestAPI:()=>_,RushDB:()=>D,Transaction:()=>B,UniquenessError:()=>E,default:()=>He,extractMixedPropertiesFromToken:()=>ee,idToDate:()=>Z,idToTimestamp:()=>K,initSDK:()=>te,mergeDefaultsWithPayload:()=>U,parseConfig:()=>G,pickUniqFieldsFromRecord:()=>N,pickUniqFieldsFromRecords:()=>J,validateInteger:()=>X});module.exports=Ie(Me);var O=class s{makeRequest(e,{headers:t,method:n,protocol:r,requestData:a,timeout:o}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(s.TIMEOUT_ERROR_CODE);return e.code=s.TIMEOUT_ERROR_CODE,e}};O.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];O.TIMEOUT_ERROR_CODE="ETIMEDOUT";var M=class{constructor(e,t){this._statusCode=e,this._headers=t}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}},v=class{constructor(e){this._res=e}getStatusCode(){throw new Error("getStatusCode not implemented.")}getHeaders(){throw new Error("getHeaders not implemented.")}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}};var V=se(require("http"),1),Y=se(require("https"),1);var xe="string",Oe="datetime",Pe="boolean",Ee="number",Ae="null",Be="vector",ae=[xe,Oe,Pe,Ee,Ae,Be];var ie=V.default||V,ce=Y.default||Y,_e=new ie.Agent({keepAlive:!0}),Ce=new ce.Agent({keepAlive:!0}),F=class extends O{constructor(e){super(),this._agent=e}makeRequest(e,{headers:t,method:n,protocol:r,requestData:a,timeout:o}){let i=new URL(e),c=r==="http"||i.protocol==="http:",d=this._agent;return d||(d=c?_e:Ce),new Promise((p,h)=>{let l=(c?ie:ce).request({agent:d,ciphers:"DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5",headers:t,host:i.hostname,method:n,path:i.pathname+i.search,port:i.port});l.setTimeout(o!=null?o:8e4,()=>{l.destroy(O.makeTimeoutError())}),l.on("response",f=>{p(new W(f))}),l.on("error",f=>{h(f)}),l.once("socket",f=>{let I=a?JSON.stringify(a):"";f.connecting?f.once(c?"connect":"secureConnect",()=>{l.write(I),l.end()}):(l.write(I),l.end())})})}},W=class extends M{constructor(e){super(e.statusCode,e.headers||{}),this._res=e}getRawResponse(){return this._res}toStream(e){return this._res.once("end",()=>e()),this._res}toJSON(){return new Promise((e,t)=>{let n="";this._res.setEncoding("utf8"),this._res.on("data",r=>{n+=r}),this._res.once("end",()=>{try{e(JSON.parse(n))}catch(r){t(r)}})})}};var R=s=>typeof s=="object"&&Array.isArray(s)&&s!==null,S=s=>s!==null&&Object.prototype.toString.call(s)==="[object Object]",q=s=>S(s)&&Object.keys(s).length===0,de=s=>typeof s=="number"||typeof s=="string"||typeof s=="boolean"||s===null;function qe(s,e){let t={...s};return e.forEach(n=>{delete t[n]}),t}var L=s=>S(s)?qe(s,["__label","__id","__proptypes"]):s,C=s=>R(s)?s.map(C):S(s)?Object.fromEntries(Object.entries(s).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,C(t)])):s,Q=s=>R(s)?s.every(de):de(s),$=s=>S(s)&&Object.values(s).every(Q),P=s=>typeof s=="string",T=s=>{if(typeof s=="string"){if(s.toLowerCase()==="true")return!0;if(s.toLowerCase()==="false")return!1}return R(s)&&s.length===0||S(s)&&Object.keys(s).length===0?!1:!!s};var z=["httpClient","timeout","host","port","protocol","url","logger","options"],pe={initial:"in",extended:"ex",fullFeatured:"ff"};var E=class s extends Error{constructor(e,t){super(`Record with label "${e}" and properties ${JSON.stringify(t)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,s.prototype)}},w=class s extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,s.prototype)}},k=class s extends Error{constructor(e,t){super(`Expected a unique result but found ${e} matches for the provided SearchQuery: ${JSON.stringify(t)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,s.prototype)}};var U=async(s,e)=>{let t=Object.entries(s).map(async([a,o])=>o.default&&typeof o.default<"u"&&typeof e[a]>"u"?{key:a,value:typeof o.default=="function"?await o.default():o.default}:{key:a,value:void 0});return{...(await Promise.all(t)).reduce((a,{key:o,value:i})=>(i!==void 0&&(a[o]=i),a),{}),...e}},N=(s,e)=>Object.entries(e).filter(([t])=>{var n;return(n=s[t])==null?void 0:n.uniq}).reduce((t,[n,r])=>(n in s&&(t[n]=r),t),{}),J=(s,e,t)=>{let n={},r=Object.entries(e).filter(([,a])=>a.uniq).reduce((a,[o])=>(a[o]=!0,a),{});return s.forEach(a=>{Object.entries(a).forEach(([o,i])=>{if(o in r)if(n[o]){if(n[o].includes(i))throw new E(t,{[o]:i});n[o]=[...n[o],i]}else n[o]=[i]})}),n},G=s=>{if(!s)return{};if(!S(s))throw new Error("Config must be an object");if(Object.keys(s).filter(t=>!z.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${z.join(", ")}`);return s};function X(s,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${s} must be an integer`)}return e}function K(s){let e=s.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function Z(s){return new Date(K(s))}function ee(s){let e=/^([a-z]{2})_([01]{3}\d{0,})_(.+)$/,t=s.match(e);if(!t)return[null,s];let[,n,r,a]=t,i=Object.entries(pe).find(([l,f])=>f===n)[0],[c,d,p]=r.split("");return[{...{customDB:c==="1",managedDB:d==="1",selfHosted:p==="1",planType:i}},a]}var g=class{constructor(e={}){this.data=e}exists(){return T(this.data.__id)&&T(this.data.__label)}id(){if(!T(this.data.__id))throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.");return this.data.__id}label(){if(!T(this.data.__label))throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.");return this.data.__label}proptypes(){if(!T(this.data.__proptypes))throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.");return this.data.__proptypes}date(){try{return Z(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return K(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}async delete(e){if(!T(this.data))throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return await D.init().records.deleteById(this.id(),e)}async update(e,t){if(!T(this.data))throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return D.init().records.update({label:this.label(),target:this.id(),data:e},t)}async set(e,t){if(!T(this.data))throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return D.init().records.set({label:this.label(),target:this.id(),data:e},t)}async attach(e,t,n){if(!T(this.data))throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return D.init().records.attach({source:this.id(),target:e,options:t},n)}async detach(e,t,n){if(!T(this.data))throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return D.init().records.detach({source:this.id(),target:e,options:t},n)}},A=class{constructor(e=[],t=0,n){this.data=e,this.total=t,this.searchQuery=n}};var je={"Content-Type":"application/json"},le=({httpClient:s,token:e,url:t})=>async(n,{headers:r,...a})=>{let o=await s.makeRequest(`${t}${n}`,{credentials:"omit",headers:Object.assign({...je,...r},typeof e<"u"?{token:e}:{}),...a});if(o.getStatusCode()>=200&&o.getStatusCode()<300)return await o.toJSON();throw new Error(`${o.getStatusCode()}`)};var B=class{constructor(e){this.id=e}async rollback(){return await D.init().tx.rollback(this.id)}async commit(){return await D.init().tx.commit(this.id)}};var he="api.rushdb.com";var ue="https",ye="/api/v1";var m=s=>s?{"x-transaction-id":s}:void 0,Ue=s=>P(s)||s instanceof B,y=s=>Ue(s)?s instanceof B?s.id:s:void 0,ge=s=>/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(s),b=s=>{if(P(s)&&ge(s))return s;if(s instanceof g&&s.data)return s.data.__id;if(S(s)&&"__id"in s&&ge(s.__id))return s.__id},j=s=>!(!S(s)||S(s)&&"name"in s&&!P(s.name)||S(s)&&"type"in s&&(!P(s.type)||!ae.includes(s.type))||!("value"in s)||!Q(s.value)||"metadata"in s&&!P(s.metadata)||"valueSeparator"in s&&!P(s.valueSeparator)),fe=s=>{let e=ue,t=he,n=443,r=ye;if("url"in s){let o=new URL(s.url);e=o.protocol.replace(":",""),t=o.hostname,n=parseInt(o.port||(e==="http"?"80":e==="https"?"443":""))}"host"in s&&"port"in s&&"protocol"in s&&(e=s.protocol.replace(":",""),t=s.host,n=s.port),r&&!r.startsWith("/")&&(r="/"+r);let a="";return e==="http"&&n===80||e==="https"&&n===443||(a=":"+n),`${e}://${t}${a}${r}`},u=(s=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let n=0;n<s;n++){let r=Math.floor(Math.random()*e.length);t+=e[r]}return t};var _=class{constructor(e,t){this.records={attach:async({source:e,target:t,options:n},r)=>{var h,l;let a=y(r),i=`/relationships/${b(e)}`,c={headers:Object.assign({},m(a)),method:"POST",requestData:{targetIds:this._extractTargetIds(t,"Attach"),...(n==null?void 0:n.type)&&{type:n.type},...(n==null?void 0:n.direction)&&{direction:n.direction}}},d=typeof this.logger=="function"?u():"";(h=this.logger)==null||h.call(this,{requestId:d,path:i,...c});let p=await this.fetcher(i,c);return(l=this.logger)==null||l.call(this,{requestId:d,path:i,...c,responseData:p.data}),p},detach:async({source:e,target:t,options:n},r)=>{var h,l;let a=y(r),i=`/relationships/${b(e)}`,c={headers:Object.assign({},m(a)),method:"PUT",requestData:{targetIds:this._extractTargetIds(t,"Detach"),...(n==null?void 0:n.typeOrTypes)&&{typeOrTypes:n.typeOrTypes},...(n==null?void 0:n.direction)&&{direction:n.direction}}},d=typeof this.logger=="function"?u():"";(h=this.logger)==null||h.call(this,{requestId:d,path:i,...c});let p=await this.fetcher(i,c);return(l=this.logger)==null||l.call(this,{requestId:d,path:i,...c,responseData:p.data}),p},create:async({label:e,data:t,options:n},r)=>{var h,l;let a=y(r),o="/records",i={headers:Object.assign({},m(a)),method:"POST",requestData:{}},c=typeof this.logger=="function"?u():"",d=L(C(t));if(R(d)&&d.every(j))i.requestData={label:e,properties:d};else if($(d))i.requestData={label:e,data:d,options:n};else throw S(d)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(h=this.logger)==null||h.call(this,{requestId:c,path:o,...i});let p=await this.fetcher(o,i);return(l=this.logger)==null||l.call(this,{requestId:c,path:o,...i,responseData:p.data}),p!=null&&p.success&&(p!=null&&p.data)?new g(p.data):new g},createMany:async(e,t)=>{var c,d,p,h;let n=y(t),r="/records/import/json",a={headers:Object.assign({},m(n)),method:"POST",requestData:e},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);if((d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i!=null&&i.success&&(i!=null&&i.data)){let l=(h=(p=i.data)==null?void 0:p.map(f=>new g(f)))!=null?h:[];return new A(l,i.total)}return new A([])},delete:async(e,t)=>{var c,d,p;if(q(e.where)&&!((c=this==null?void 0:this.options)!=null&&c.allowForceDelete))throw new w("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let n=y(t),r="/records/delete",a={headers:Object.assign({},m(n)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(p=this.logger)==null||p.call(this,{requestId:o,path:r,...a,responseData:i.data}),i},deleteById:async(e,t)=>{var d,p;let n=y(t),r=R(e),a=r?"/records/delete":`/records/${e}`,o={headers:Object.assign({},m(n)),method:r?"POST":"DELETE",requestData:r?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:i,path:a,...o});let c=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:c.data}),c},export:async(e,t)=>{var c,d;let n=y(t),r="/records/export/csv",a={headers:Object.assign({},m(n)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i},find:async(e,t)=>{var h,l;let{id:n,...r}=e,a=y(t),o=n?`/records/${n}/search`:"/records/search",i={headers:Object.assign({},m(a)),method:"POST",requestData:r!=null?r:{}},c=typeof this.logger=="function"?u():"";(h=this.logger)==null||h.call(this,{requestId:c,path:o,...i});let d=await this.fetcher(o,i);(l=this.logger)==null||l.call(this,{requestId:c,path:o,...i,responseData:d.data});let p=d.data.map(f=>new g(f));return new A(p,d.total,e)},findById:async(e,t)=>{var c,d;let n=y(t),r=R(e)?"/records":`/records/${e}`,a={headers:Object.assign({},m(n)),method:R(e)?"POST":"GET",requestData:R(e)?{ids:e}:void 0},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);if((d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),R(e)){let p=i.data.map(h=>new g(h));return new A(p,i.total)}else return new g(i.data)},findOne:async(e,t)=>{var d,p;let n=y(t),r="/records/search",a={headers:Object.assign({},m(n)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);(p=this.logger)==null||p.call(this,{requestId:o,path:r,...a,responseData:i.data});let[c]=i.data;return new g(c)},findUniq:async(e,t)=>{var d,p;let n=y(t),r="/records/search",a={headers:Object.assign({},m(n)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);if((p=this.logger)==null||p.call(this,{requestId:o,path:r,...a,responseData:i.data}),typeof i.total<"u"&&i.total>1)throw new k(i.total,e);let[c]=i.data;return new g(c)},set:async({target:e,label:t,data:n,options:r},a)=>{var f,I;let o=y(a),c=`/records/${b(e)}`,d={headers:Object.assign({},m(o)),method:"PUT",requestData:{}},p=typeof this.logger=="function"?u():"",h=L(C(n));if(R(h)&&h.every(j))d.requestData={label:t,properties:h};else if($(h))d.requestData={label:t,data:h,options:r};else throw S(h)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(f=this.logger)==null||f.call(this,{requestId:p,path:c,...d});let l=await this.fetcher(c,d);return(I=this.logger)==null||I.call(this,{requestId:p,path:c,...d,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)?new g(l.data):new g},update:async({target:e,label:t,data:n,options:r},a)=>{var f,I;let o=y(a),c=`/records/${b(e)}`,d={headers:Object.assign({},m(o)),method:"PATCH",requestData:{}},p=typeof this.logger=="function"?u():"",h=L(C(n));if(R(h)&&h.every(j))d.requestData={label:t,properties:h};else if($(h))d.requestData={label:t,data:h,options:r};else throw S(h)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(f=this.logger)==null||f.call(this,{requestId:p,path:c,...d});let l=await this.fetcher(c,d);return(I=this.logger)==null||I.call(this,{requestId:p,path:c,...d,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)?new g(l.data):new g}};this.relationships={find:async(e,t)=>{var p,h;let n=y(t),r=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&r.append("limit",e.limit.toString()),(e==null?void 0:e.skip)!==void 0&&r.append("skip",e.skip.toString());let o=`/relationships/search${r.toString()?"?"+r.toString():""}`,i={headers:Object.assign({},m(n)),method:"POST",requestData:e!=null?e:{}},c=typeof this.logger=="function"?u():"";(p=this.logger)==null||p.call(this,{requestId:c,path:o,...i});let d=await this.fetcher(o,i);return(h=this.logger)==null||h.call(this,{requestId:c,path:o,...i,responseData:d.data}),d}};this.properties={delete:async(e,t)=>{var c,d;let n=y(t),r=`/properties/${e}`,a={headers:Object.assign({},m(n)),method:"DELETE"},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i},find:async(e,t)=>{var c,d;let n=y(t),r="/properties/search",a={headers:Object.assign({},m(n)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i},findById:async(e,t)=>{var c,d;let n=y(t),r=`/properties/${e}`,a={headers:Object.assign({},m(n)),method:"GET"},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i},values:async(e,t,n)=>{var d,p;let r=y(n),a=`/properties/${e}/values`,o={headers:Object.assign({},m(r)),method:"POST",requestData:t!=null?t:{}},i=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:i,path:a,...o});let c=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:c.data}),c}};this.labels={find:async(e,t)=>{var c,d;let n=y(t),r="/labels/search",a={headers:Object.assign({},m(n)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:o,path:r,...a});let i=await this.fetcher(r,a);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...a,responseData:i.data}),i}};this.tx={begin:async e=>{var o,i;let t="/tx",n={method:"POST",requestData:S(e)&&"ttl"in e?e:{}},r=typeof this.logger=="function"?u():"";(o=this.logger)==null||o.call(this,{requestId:r,path:t,...n});let a=await this.fetcher(t,n);return(i=this.logger)==null||i.call(this,{requestId:r,path:t,...n,responseData:a.data}),new B(a.data.id)},commit:async e=>{var i,c;let n=`/tx/${y(e)}/commit`,r={method:"POST",requestData:{}},a=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:a,path:n,...r});let o=await this.fetcher(n,r);return(c=this.logger)==null||c.call(this,{requestId:a,path:n,...r,responseData:o.data}),o},get:async e=>{var i,c;let n=`/tx/${y(e)}`,r={method:"GET"},a=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:a,path:n,...r});let o=await this.fetcher(n,r);return(c=this.logger)==null||c.call(this,{requestId:a,path:n,...r,responseData:o.data}),new B(o.data.id)},rollback:async e=>{var i,c;let n=`/tx/${y(e)}/rollback`,r={method:"POST",requestData:{}},a=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:a,path:n,...r});let o=await this.fetcher(n,r);return(c=this.logger)==null||c.call(this,{requestId:a,path:n,...r,responseData:o.data}),o}};this.settings={get:async()=>{var a,o;let e="/sdk/settings",t={method:"GET"},n=typeof this.logger=="function"?u():"";(a=this.logger)==null||a.call(this,{requestId:n,path:e,...t});let r=await this.fetcher(e,t);return(o=this.logger)==null||o.call(this,{requestId:n,path:e,...t,responseData:r.data}),r}};if(this.fetcher=null,t!=null&&t.httpClient){let n=fe(t);this.fetcher=le({httpClient:t.httpClient,token:e,url:n})}t!=null&&t.options&&(this.options=t==null?void 0:t.options),t!=null&&t.logger&&(this.logger=t==null?void 0:t.logger)}_extractTargetIds(e,t){var n;if(e instanceof g){let r=b(e);if(!r)throw new w(`${t} error: Target id is empty`);return[r]}if(R(e)&&e.every(r=>r instanceof g)){let r=e.map(b).filter(T);if(!r.length)throw new w(`${t} error: Target ids are empty`);return r}if(e instanceof A){let r=(n=e.data)==null?void 0:n.map(b).filter(T);if(!(r!=null&&r.length))throw new w(`${t} error: Target ids are empty`);return r}if(S(e)&&"__id"in e)return[e.__id];if(R(e)&&e.every(r=>S(r)&&"__id"in r)){let r=e.map(b).filter(T);if(!r.length)throw new w(`${t} error: Target ids are empty`);return r}return R(e)?e:P(e)?[e]:[]}};var me,x=class x extends _{constructor(e,t){var a;let n=G(t);super(e,{...n,httpClient:(a=n.httpClient)!=null?a:me}),x.instance=this;let[r]=ee(e!=null?e:"");this.initializeSync(r,e,n)}initializeSync(e,t,n){let r=e?{planType:e.planType,customDB:e.customDB,managedDB:e.managedDB,selfHosted:e.selfHosted}:null;x.state={initialized:!0,debug:!1,timeout:X("timeout",n==null?void 0:n.timeout,8e4),token:t,...r&&{serverSettings:r}}}static init(){if(x.instance)return x.instance;throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}static getInstance(){return x.instance}static isInitialized(){return x.instance!==null}toDBRecordInstance(e){return new g(e)}};x.instance=null,x.state={initialized:!1,debug:!1,timeout:8e4};var D=x,te=s=>{me=s};var re=class{constructor(e,t){this.label=e,this.schema=t}getLabel(){return this.label}async getRushDBInstance(){if(D.getInstance())return D.init();throw new Error('No RushDB instance found. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}async toDBRecordInstance(e){try{return(await this.getRushDBInstance()).toDBRecordInstance(e)}catch{throw new Error("No RushDB instance was provided during model initialization.")}}async find(e,t){let n=e!=null?e:{};return(await this.getRushDBInstance()).records.find({...n,labels:[this.label]},t)}async findOne(e,t){let n=e!=null?e:{};return(await this.getRushDBInstance()).records.findOne({...n,labels:[this.label]},t)}async findById(e,t){return this.findOne({where:{$id:e}},t)}async findUniq(e,t){let n=e!=null?e:{};return(await this.getRushDBInstance()).records.findUniq({...n,labels:[this.label]},t)}async create(e,t){var i;let n=await U(this.schema,e),r=N(this.schema,n),a=T(r),o=await this.getRushDBInstance();if(a){let c=t!=null?t:await o.tx.begin(),d=await this.find({where:r},c),p=typeof t<"u";if(!((i=d==null?void 0:d.data)!=null&&i.length)){let l=await o.records.create({label:this.label,data:n},c);return p||await c.commit(),l}else throw p||await c.commit(),new E(this.label,r)}return await o.records.create({label:this.label,data:n},t)}async attach({source:e,target:t,options:n},r){return await(await this.getRushDBInstance()).records.attach({source:e,target:t,options:n},r)}async detach({source:e,target:t,options:n},r){return await(await this.getRushDBInstance()).records.detach({source:e,target:t,options:n},r)}async handleSetOrUpdate(e,t,n,r){var c,d;if(R(t)&&t.every(j))throw new Error(`Model.${n} with Array<PropertyDraft> as payload is not implemented yet.`);let a=await this.getRushDBInstance(),o=await U(this.schema,t),i=N(this.schema,o);if(!q(i)){let p=r!=null?r:await a.tx.begin(),h=await this.find({where:i},p),l=typeof r<"u";if(!((c=h==null?void 0:h.data)!=null&&c.length)||h.data.length===1&&((d=h.data[0])==null?void 0:d.id())===b(e)){let I=await a.records[n]({target:e,label:this.label,data:o},p);return l||await p.commit(),I}else throw l||await p.commit(),new E(this.label,i)}return await a.records[n]({label:this.label,target:e,data:o},r)}async set(e,t,n){return await this.handleSetOrUpdate(e,t,"set",n)}async update(e,t,n){return await this.handleSetOrUpdate(e,t,"update",n)}async createMany(e,t){var o;let n=await this.getRushDBInstance(),r=typeof t<"u",a=t!=null?t:await n.tx.begin();try{let i=await Promise.all(e.map(async p=>await U(this.schema,p))),c=J(i,this.schema,this.label);if(!q(c)){let p=Object.entries(c).map(([l,f])=>({[l]:{$in:f}})),h=await this.find({where:{$or:p}},a);if((o=h==null?void 0:h.data)!=null&&o.length)throw new E(this.label,Object.keys(c))}let d=await n.records.createMany({label:this.label,data:i},a);return r||await a.commit(),d}catch(i){throw r||await a.rollback(),i}}async delete(e,t){if(q(e.where))throw new w(`You must specify criteria to delete records of type '${this.label}'. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.`);return await(await this.getRushDBInstance()).records.delete({...e,labels:[this.label]},t)}async deleteById(e,t){return await(await this.getRushDBInstance()).records.deleteById(e,t)}};te(new F);var He=D;0&&(module.exports={DBRecordInstance,DBRecordsArrayInstance,EmptyTargetError,HttpClient,HttpClientResponse,Model,NonUniqueResultError,RestAPI,RushDB,Transaction,UniquenessError,extractMixedPropertiesFromToken,idToDate,idToTimestamp,initSDK,mergeDefaultsWithPayload,parseConfig,pickUniqFieldsFromRecord,pickUniqFieldsFromRecords,validateInteger});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- var Re=Object.defineProperty,Te=Object.defineProperties;var we=Object.getOwnPropertyDescriptors;var M=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,re=Object.prototype.propertyIsEnumerable;var ee=(s,e,t)=>e in s?Re(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,p=(s,e)=>{for(var t in e||(e={}))te.call(e,t)&&ee(s,t,e[t]);if(M)for(var t of M(e))re.call(e,t)&&ee(s,t,e[t]);return s},y=(s,e)=>Te(s,we(e));var $=(s,e)=>{var t={};for(var r in s)te.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&M)for(var r of M(s))e.indexOf(r)<0&&re.call(s,r)&&(t[r]=s[r]);return t};var l=(s,e,t)=>new Promise((r,n)=>{var a=c=>{try{i(t.next(c))}catch(d){n(d)}},o=c=>{try{i(t.throw(c))}catch(d){n(d)}},i=c=>c.done?r(c.value):Promise.resolve(c.value).then(a,o);i((t=t.apply(s,e)).next())});var De="string",be="datetime",Ie="boolean",xe="number",Oe="null",Pe="vector",se=[De,be,Ie,xe,Oe,Pe];var E=class s{makeRequest(e,{headers:t,method:r,protocol:n,requestData:a,timeout:o}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(s.TIMEOUT_ERROR_CODE);return e.code=s.TIMEOUT_ERROR_CODE,e}};E.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];E.TIMEOUT_ERROR_CODE="ETIMEDOUT";var L=class{constructor(e,t){this._statusCode=e,this._headers=t}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}},Q=class{constructor(e){this._res=e}getStatusCode(){throw new Error("getStatusCode not implemented.")}getHeaders(){throw new Error("getHeaders not implemented.")}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}};var N=class s extends E{constructor(e){if(super(),!e){if(!globalThis.fetch)throw new Error("fetch() function not provided and is not defined in the global scope. You must provide a fetch implementation.");e=globalThis.fetch}globalThis.AbortController?this._fetchFn=s.makeFetchWithAbortTimeout(e):this._fetchFn=s.makeFetchWithRaceTimeout(e)}static makeFetchWithRaceTimeout(e){return(t,r,n)=>{let a,o=new Promise((c,d)=>{a=setTimeout(()=>{a=null,d(E.makeTimeoutError())},n)}),i=e(t,r);return Promise.race([i,o]).finally(()=>{a&&clearTimeout(a)})}}static makeFetchWithAbortTimeout(e){return(t,r,n)=>l(this,null,function*(){let a=new AbortController,o=setTimeout(()=>{o=null,a.abort(E.makeTimeoutError())},n);try{return yield e(t,y(p({},r),{signal:a.signal}))}catch(i){throw i.name==="AbortError"?E.makeTimeoutError():i}finally{o&&clearTimeout(o)}})}makeRequest(i,c){return l(this,arguments,function*(e,{headers:t,method:r,protocol:n,requestData:a,timeout:o}){let d=r=="POST"||r=="PUT"||r=="PATCH",h=JSON.stringify(a)||(d?"":void 0),u=yield this._fetchFn(e,{body:h,headers:t,method:r},o!=null?o:8e4);return new V(u)})}},V=class s extends L{constructor(e){super(e.status,s._transformHeadersToObject(e.headers)),this._res=e}getRawResponse(){return this._res}toStream(e){return e(),this._res.body}toJSON(){return this._res.json()}static _transformHeadersToObject(e){let t={};for(let r of e){if(!Array.isArray(r)||r.length!=2)throw new Error("Response objects produced by the fetch function given to FetchHttpClient do not have an iterable headers map. Response#headers should be an iterable object.");t[r[0]]=r[1]}return t}};var I=s=>typeof s=="object"&&Array.isArray(s)&&s!==null,b=s=>s!==null&&Object.prototype.toString.call(s)==="[object Object]",k=s=>b(s)&&Object.keys(s).length===0,ae=s=>typeof s=="number"||typeof s=="string"||typeof s=="boolean"||s===null;function Ee(s,e){let t=p({},s);return e.forEach(r=>{delete t[r]}),t}var W=s=>b(s)?Ee(s,["__label","__id","__proptypes"]):s,j=s=>I(s)?s.map(j):b(s)?Object.fromEntries(Object.entries(s).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,j(t)])):s,J=s=>I(s)?s.every(ae):ae(s),K=s=>b(s)&&Object.values(s).every(J),B=s=>typeof s=="string",x=s=>{if(typeof s=="string"){if(s.toLowerCase()==="true")return!0;if(s.toLowerCase()==="false")return!1}return I(s)&&s.length===0||b(s)&&Object.keys(s).length===0?!1:!!s};var G=["httpClient","timeout","host","port","protocol","url","logger","options"];var C=class s extends Error{constructor(e,t){super(`Record with label "${e}" and properties ${JSON.stringify(t)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,s.prototype)}},A=class s extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,s.prototype)}},Y=class s extends Error{constructor(e,t){super(`Expected a unique result but found ${e} matches for the provided SearchQuery: ${JSON.stringify(t)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,s.prototype)}};var z=(s,e)=>l(void 0,null,function*(){let t=Object.entries(s).map(i=>l(void 0,[i],function*([a,o]){return o.default&&typeof o.default!="undefined"&&typeof e[a]=="undefined"?{key:a,value:typeof o.default=="function"?yield o.default():o.default}:{key:a,value:void 0}})),n=(yield Promise.all(t)).reduce((a,{key:o,value:i})=>(i!==void 0&&(a[o]=i),a),{});return p(p({},n),e)}),Z=(s,e)=>Object.entries(e).filter(([t])=>{var r;return(r=s[t])==null?void 0:r.uniq}).reduce((t,[r,n])=>(r in s&&(t[r]=n),t),{}),oe=(s,e,t)=>{let r={},n=Object.entries(e).filter(([,a])=>a.uniq).reduce((a,[o])=>(a[o]=!0,a),{});return s.forEach(a=>{Object.entries(a).forEach(([o,i])=>{if(o in n)if(r[o]){if(r[o].includes(i))throw new C(t,{[o]:i});r[o]=[...r[o],i]}else r[o]=[i]})}),r},ie=s=>{if(!s)return{};if(!b(s))throw new Error("Config must be an object");if(Object.keys(s).filter(t=>!G.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${G.join(", ")}`);return s};function ce(s,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${s} must be an integer`)}return e}function X(s){let e=s.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function de(s){return new Date(X(s))}var T=class{constructor(e={}){this.data=e}exists(){return x(this.data.__id)&&x(this.data.__label)}id(){if(!x(this.data.__id))throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.");return this.data.__id}label(){if(!x(this.data.__label))throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.");return this.data.__label}proptypes(){if(!x(this.data.__proptypes))throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.");return this.data.__proptypes}date(){try{return de(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return X(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}delete(e){return l(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return yield(yield O.init()).records.deleteById(this.id(),e)})}update(e,t){return l(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return(yield O.init()).records.update({label:this.label(),target:this.id(),data:e},t)})}set(e,t){return l(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return(yield O.init()).records.set({label:this.label(),target:this.id(),data:e},t)})}attach(e,t,r){return l(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return(yield O.init()).records.attach({source:this.id(),target:e,options:t},r)})}detach(e,t,r){return l(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return(yield O.init()).records.detach({source:this.id(),target:e,options:t},r)})}},q=class{constructor(e=[],t=0,r){this.data=e,this.total=t,this.searchQuery=r}};var Ae={"Content-Type":"application/json"},pe=({httpClient:s,token:e,url:t})=>(r,o)=>l(void 0,null,function*(){var i=o,{headers:n}=i,a=$(i,["headers"]);let c=yield s.makeRequest(`${t}${r}`,p({credentials:"omit",headers:Object.assign(p(p({},Ae),n),typeof e!="undefined"?{token:e}:{})},a));if(c.getStatusCode()>=200&&c.getStatusCode()<300)return yield c.toJSON();throw new Error(`${c.getStatusCode()}`)});var _=class{constructor(e){this.id=e}rollback(){return l(this,null,function*(){return yield(yield O.init()).tx.rollback(this.id)})}commit(){return l(this,null,function*(){return yield(yield O.init()).tx.commit(this.id)})}};var le="api.rushdb.com";var he="https",ue="/api/v1";var D=s=>s?{"x-transaction-id":s}:void 0,Ce=s=>B(s)||s instanceof _,R=s=>Ce(s)?s instanceof _?s.id:s:void 0,ye=s=>/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(s),P=s=>{if(B(s)&&ye(s))return s;if(s instanceof T&&s.data)return s.data.__id;if(b(s)&&"__id"in s&&ye(s.__id))return s.__id},U=s=>!(!b(s)||b(s)&&"name"in s&&!B(s.name)||b(s)&&"type"in s&&(!B(s.type)||!se.includes(s.type))||!("value"in s)||!J(s.value)||"metadata"in s&&!B(s.metadata)||"valueSeparator"in s&&!B(s.valueSeparator)),me=s=>{let e=he,t=le,r=443,n=ue;if("url"in s){let o=new URL(s.url);e=o.protocol.replace(":",""),t=o.hostname,r=parseInt(o.port||(e==="http"?"80":e==="https"?"443":""))}"host"in s&&"port"in s&&"protocol"in s&&(e=s.protocol.replace(":",""),t=s.host,r=s.port),n&&!n.startsWith("/")&&(n="/"+n);let a="";return e==="http"&&r===80||e==="https"&&r===443||(a=":"+r),`${e}://${t}${a}${n}`},S=(s=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t};var F=class{constructor(e,t){this.records={attach:(a,o)=>l(this,[a,o],function*({source:e,target:t,options:r},n){var f,g;let i=R(n),d=`/relationships/${P(e)}`,h={headers:Object.assign({},D(i)),method:"POST",requestData:p(p({targetIds:this._extractTargetIds(t,"Attach")},(r==null?void 0:r.type)&&{type:r.type}),(r==null?void 0:r.direction)&&{direction:r.direction})},u=typeof this.logger=="function"?S():"";(f=this.logger)==null||f.call(this,p({requestId:u,path:d},h));let m=yield this.fetcher(d,h);return(g=this.logger)==null||g.call(this,y(p({requestId:u,path:d},h),{responseData:m.data})),m}),detach:(a,o)=>l(this,[a,o],function*({source:e,target:t,options:r},n){var f,g;let i=R(n),d=`/relationships/${P(e)}`,h={headers:Object.assign({},D(i)),method:"PUT",requestData:p(p({targetIds:this._extractTargetIds(t,"Detach")},(r==null?void 0:r.typeOrTypes)&&{typeOrTypes:r.typeOrTypes}),(r==null?void 0:r.direction)&&{direction:r.direction})},u=typeof this.logger=="function"?S():"";(f=this.logger)==null||f.call(this,p({requestId:u,path:d},h));let m=yield this.fetcher(d,h);return(g=this.logger)==null||g.call(this,y(p({requestId:u,path:d},h),{responseData:m.data})),m}),create:(a,o)=>l(this,[a,o],function*({label:e,data:t,options:r},n){var f,g;let i=R(n),c="/records",d={headers:Object.assign({},D(i)),method:"POST",requestData:{}},h=typeof this.logger=="function"?S():"",u=W(j(t));if(I(u)&&u.every(U))d.requestData={label:e,properties:u};else if(K(u))d.requestData={label:e,data:u,options:r};else throw b(u)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(f=this.logger)==null||f.call(this,p({requestId:h,path:c},d));let m=yield this.fetcher(c,d);return(g=this.logger)==null||g.call(this,y(p({requestId:h,path:c},d),{responseData:m.data})),m!=null&&m.success&&(m!=null&&m.data)?new T(m.data):new T}),createMany:(e,t)=>l(this,null,function*(){var c,d,h,u;let r=R(t),n="/records/import/json",a={headers:Object.assign({},D(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:n},a));let i=yield this.fetcher(n,a);if((d=this.logger)==null||d.call(this,y(p({requestId:o,path:n},a),{responseData:i.data})),i!=null&&i.success&&(i!=null&&i.data)){let m=(u=(h=i.data)==null?void 0:h.map(f=>new T(f)))!=null?u:[];return new q(m,i.total)}return new q([])}),delete:(e,t)=>l(this,null,function*(){var c,d,h;if(k(e.where)&&!((c=this==null?void 0:this.options)!=null&&c.allowForceDelete))throw new A("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let r=R(t),n="/records/delete",a={headers:Object.assign({},D(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:o,path:n},a));let i=yield this.fetcher(n,a);return(h=this.logger)==null||h.call(this,y(p({requestId:o,path:n},a),{responseData:i.data})),i}),deleteById:(e,t)=>l(this,null,function*(){var d,h;let r=R(t),n=I(e),a=n?"/records/delete":`/records/${e}`,o={headers:Object.assign({},D(r)),method:n?"POST":"DELETE",requestData:n?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:a},o));let c=yield this.fetcher(a,o);return(h=this.logger)==null||h.call(this,y(p({requestId:i,path:a},o),{responseData:c.data})),c}),export:(e,t)=>l(this,null,function*(){var c,d;let r=R(t),n="/records/export/csv",a={headers:Object.assign({},D(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:n},a));let i=yield this.fetcher(n,a);return(d=this.logger)==null||d.call(this,y(p({requestId:o,path:n},a),{responseData:i.data})),i}),find:(e,t)=>l(this,null,function*(){var m,f;let u=e,{id:r}=u,n=$(u,["id"]),a=R(t),o=r?`/records/${r}/search`:"/records/search",i={headers:Object.assign({},D(a)),method:"POST",requestData:n!=null?n:{}},c=typeof this.logger=="function"?S():"";(m=this.logger)==null||m.call(this,p({requestId:c,path:o},i));let d=yield this.fetcher(o,i);(f=this.logger)==null||f.call(this,y(p({requestId:c,path:o},i),{responseData:d.data}));let h=d.data.map(g=>new T(g));return new q(h,d.total,e)}),findById:(e,t)=>l(this,null,function*(){var c,d;let r=R(t),n=I(e)?"/records":`/records/${e}`,a={headers:Object.assign({},D(r)),method:I(e)?"POST":"GET",requestData:I(e)?{ids:e}:void 0},o=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:n},a));let i=yield this.fetcher(n,a);if((d=this.logger)==null||d.call(this,y(p({requestId:o,path:n},a),{responseData:i.data})),I(e)){let h=i.data.map(u=>new T(u));return new q(h,i.total)}else return new T(i.data)}),findOne:(e,t)=>l(this,null,function*(){var d,h;let r=R(t),n="/records/search",a={headers:Object.assign({},D(r)),method:"POST",requestData:y(p({},e),{limit:1,skip:0})},o=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:o,path:n},a));let i=yield this.fetcher(n,a);(h=this.logger)==null||h.call(this,y(p({requestId:o,path:n},a),{responseData:i.data}));let[c]=i.data;return new T(c)}),findUniq:(e,t)=>l(this,null,function*(){var d,h;let r=R(t),n="/records/search",a={headers:Object.assign({},D(r)),method:"POST",requestData:y(p({},e),{limit:1,skip:0})},o=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:o,path:n},a));let i=yield this.fetcher(n,a);if((h=this.logger)==null||h.call(this,y(p({requestId:o,path:n},a),{responseData:i.data})),typeof i.total!="undefined"&&i.total>1)throw new Y(i.total,e);let[c]=i.data;return new T(c)}),set:(o,i)=>l(this,[o,i],function*({target:e,label:t,data:r,options:n},a){var H,v;let c=R(a),h=`/records/${P(e)}`,u={headers:Object.assign({},D(c)),method:"PUT",requestData:{}},m=typeof this.logger=="function"?S():"",f=W(j(r));if(I(f)&&f.every(U))u.requestData={label:t,properties:f};else if(K(f))u.requestData={label:t,data:f,options:n};else throw b(f)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(H=this.logger)==null||H.call(this,p({requestId:m,path:h},u));let g=yield this.fetcher(h,u);return(v=this.logger)==null||v.call(this,y(p({requestId:m,path:h},u),{responseData:g.data})),g!=null&&g.success&&(g!=null&&g.data)?new T(g.data):new T}),update:(o,i)=>l(this,[o,i],function*({target:e,label:t,data:r,options:n},a){var H,v;let c=R(a),h=`/records/${P(e)}`,u={headers:Object.assign({},D(c)),method:"PATCH",requestData:{}},m=typeof this.logger=="function"?S():"",f=W(j(r));if(I(f)&&f.every(U))u.requestData={label:t,properties:f};else if(K(f))u.requestData={label:t,data:f,options:n};else throw b(f)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(H=this.logger)==null||H.call(this,p({requestId:m,path:h},u));let g=yield this.fetcher(h,u);return(v=this.logger)==null||v.call(this,y(p({requestId:m,path:h},u),{responseData:g.data})),g!=null&&g.success&&(g!=null&&g.data)?new T(g.data):new T})};this.relationships={find:(e,t)=>l(this,null,function*(){var h,u;let r=R(t),n=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&n.append("limit",e.limit.toString()),(e==null?void 0:e.skip)!==void 0&&n.append("skip",e.skip.toString());let o=`/relationships/search${n.toString()?"?"+n.toString():""}`,i={headers:Object.assign({},D(r)),method:"POST",requestData:e!=null?e:{}},c=typeof this.logger=="function"?S():"";(h=this.logger)==null||h.call(this,p({requestId:c,path:o},i));let d=yield this.fetcher(o,i);return(u=this.logger)==null||u.call(this,y(p({requestId:c,path:o},i),{responseData:d.data})),d})};this.properties={delete:(e,t)=>l(this,null,function*(){var c,d;let r=R(t),n=`/properties/${e}`,a={headers:Object.assign({},D(r)),method:"DELETE"},o=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:n},a));let i=yield this.fetcher(n,a);return(d=this.logger)==null||d.call(this,y(p({requestId:o,path:n},a),{responseData:i.data})),i}),find:(e,t)=>l(this,null,function*(){var c,d;let r=R(t),n="/properties/search",a={headers:Object.assign({},D(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:n},a));let i=yield this.fetcher(n,a);return(d=this.logger)==null||d.call(this,y(p({requestId:o,path:n},a),{responseData:i.data})),i}),findById:(e,t)=>l(this,null,function*(){var c,d;let r=R(t),n=`/properties/${e}`,a={headers:Object.assign({},D(r)),method:"GET"},o=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:n},a));let i=yield this.fetcher(n,a);return(d=this.logger)==null||d.call(this,y(p({requestId:o,path:n},a),{responseData:i.data})),i}),values:(e,t,r)=>l(this,null,function*(){var d,h;let n=R(r),a=`/properties/${e}/values`,o={headers:Object.assign({},D(n)),method:"POST",requestData:t!=null?t:{}},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:a},o));let c=yield this.fetcher(a,o);return(h=this.logger)==null||h.call(this,y(p({requestId:i,path:a},o),{responseData:c.data})),c})};this.labels={find:(e,t)=>l(this,null,function*(){var c,d;let r=R(t),n="/labels/search",a={headers:Object.assign({},D(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:n},a));let i=yield this.fetcher(n,a);return(d=this.logger)==null||d.call(this,y(p({requestId:o,path:n},a),{responseData:i.data})),i})};this.tx={begin:e=>l(this,null,function*(){var o,i;let t="/tx",r={method:"POST",requestData:b(e)&&"ttl"in e?e:{}},n=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,p({requestId:n,path:t},r));let a=yield this.fetcher(t,r);return(i=this.logger)==null||i.call(this,y(p({requestId:n,path:t},r),{responseData:a.data})),new _(a.data.id)}),commit:e=>l(this,null,function*(){var i,c;let r=`/tx/${R(e)}/commit`,n={method:"POST",requestData:{}},a=typeof this.logger=="function"?S():"";(i=this.logger)==null||i.call(this,p({requestId:a,path:r},n));let o=yield this.fetcher(r,n);return(c=this.logger)==null||c.call(this,y(p({requestId:a,path:r},n),{responseData:o.data})),o}),get:e=>l(this,null,function*(){var i,c;let r=`/tx/${R(e)}`,n={method:"GET"},a=typeof this.logger=="function"?S():"";(i=this.logger)==null||i.call(this,p({requestId:a,path:r},n));let o=yield this.fetcher(r,n);return(c=this.logger)==null||c.call(this,y(p({requestId:a,path:r},n),{responseData:o.data})),new _(o.data.id)}),rollback:e=>l(this,null,function*(){var i,c;let r=`/tx/${R(e)}/rollback`,n={method:"POST",requestData:{}},a=typeof this.logger=="function"?S():"";(i=this.logger)==null||i.call(this,p({requestId:a,path:r},n));let o=yield this.fetcher(r,n);return(c=this.logger)==null||c.call(this,y(p({requestId:a,path:r},n),{responseData:o.data})),o})};this.settings={get:()=>l(this,null,function*(){var a,o;let e="/sdk/settings",t={method:"GET"},r=typeof this.logger=="function"?S():"";(a=this.logger)==null||a.call(this,p({requestId:r,path:e},t));let n=yield this.fetcher(e,t);return(o=this.logger)==null||o.call(this,y(p({requestId:r,path:e},t),{responseData:n.data})),n})};if(this.fetcher=null,t!=null&&t.httpClient){let r=me(t);this.fetcher=pe({httpClient:t.httpClient,token:e,url:r})}t!=null&&t.options&&(this.options=t==null?void 0:t.options),t!=null&&t.logger&&(this.logger=t==null?void 0:t.logger)}_extractTargetIds(e,t){var r;if(e instanceof T){let n=P(e);if(!n)throw new A(`${t} error: Target id is empty`);return[n]}if(I(e)&&e.every(n=>n instanceof T)){let n=e.map(P).filter(x);if(!n.length)throw new A(`${t} error: Target ids are empty`);return n}if(e instanceof q){let n=(r=e.data)==null?void 0:r.map(P).filter(x);if(!(n!=null&&n.length))throw new A(`${t} error: Target ids are empty`);return n}if(b(e)&&"__id"in e)return[e.__id];if(I(e)&&e.every(n=>b(n)&&"__id"in n)){let n=e.map(P).filter(x);if(!n.length)throw new A(`${t} error: Target ids are empty`);return n}return I(e)?e:B(e)?[e]:[]}};var fe,w=class w extends F{constructor(e,t){var n;let r=ie(t);super(e,y(p({},r),{httpClient:(n=r.httpClient)!=null?n:fe})),w.instance=this,w.initPromise=this.initializeAsync(e,r).catch(a=>{throw console.error("RushDB initialization failed:",a),a})}waitForInitialization(){return l(this,null,function*(){return w.initPromise?yield w.initPromise:this})}initializeAsync(e,t){return l(this,null,function*(){try{let{data:r}=yield this.settings.get();return w.state={initialized:!0,debug:!1,timeout:ce("timeout",t==null?void 0:t.timeout,8e4),token:e,serverSettings:r},this}catch(r){throw console.error("Failed to initialize RushDB:",r),new Error(`RushDB initialization failed: ${r}`)}finally{w.state.initialized=!0}})}static init(){return l(this,null,function*(){if(w.state.initialized&&w.instance)return w.instance;if(w.initPromise)return yield w.initPromise;if(w.instance)return yield w.instance.waitForInitialization();throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')})}static getInstance(){return w.instance}static isInitialized(){return w.state.initialized&&w.instance!==null}toDBRecordInstance(e){return new T(e)}};w.instance=null,w.initPromise=null,w.state={initialized:!1,debug:!1,timeout:8e4};var O=w,ge=s=>{fe=s};var Se=class{constructor(e,t){this.label=e,this.schema=t}getLabel(){return this.label}getRushDBInstance(){return l(this,null,function*(){if(O.getInstance())return yield O.init();throw new Error('No RushDB instance found. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')})}toDBRecordInstance(e){return l(this,null,function*(){try{return(yield this.getRushDBInstance()).toDBRecordInstance(e)}catch(t){throw new Error("No RushDB instance was provided during model initialization.")}})}find(e,t){return l(this,null,function*(){let r=e!=null?e:{};return(yield this.getRushDBInstance()).records.find(y(p({},r),{labels:[this.label]}),t)})}findOne(e,t){return l(this,null,function*(){let r=e!=null?e:{};return(yield this.getRushDBInstance()).records.findOne(y(p({},r),{labels:[this.label]}),t)})}findById(e,t){return l(this,null,function*(){return this.findOne({where:{$id:e}},t)})}findUniq(e,t){return l(this,null,function*(){let r=e!=null?e:{};return(yield this.getRushDBInstance()).records.findUniq(y(p({},r),{labels:[this.label]}),t)})}create(e,t){return l(this,null,function*(){var i;let r=yield z(this.schema,e),n=Z(this.schema,r),a=x(n),o=yield this.getRushDBInstance();if(a){let c=t!=null?t:yield o.tx.begin(),d=yield this.find({where:n},c),h=typeof t!="undefined";if(!((i=d==null?void 0:d.data)!=null&&i.length)){let m=yield o.records.create({label:this.label,data:r},c);return h||(yield c.commit()),m}else throw h||(yield c.commit()),new C(this.label,n)}return yield o.records.create({label:this.label,data:r},t)})}attach(a,o){return l(this,arguments,function*({source:e,target:t,options:r},n){return yield(yield this.getRushDBInstance()).records.attach({source:e,target:t,options:r},n)})}detach(a,o){return l(this,arguments,function*({source:e,target:t,options:r},n){return yield(yield this.getRushDBInstance()).records.detach({source:e,target:t,options:r},n)})}handleSetOrUpdate(e,t,r,n){return l(this,null,function*(){var c,d;if(I(t)&&t.every(U))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let a=yield this.getRushDBInstance(),o=yield z(this.schema,t),i=Z(this.schema,o);if(!k(i)){let h=n!=null?n:yield a.tx.begin(),u=yield this.find({where:i},h),m=typeof n!="undefined";if(!((c=u==null?void 0:u.data)!=null&&c.length)||u.data.length===1&&((d=u.data[0])==null?void 0:d.id())===P(e)){let g=yield a.records[r]({target:e,label:this.label,data:o},h);return m||(yield h.commit()),g}else throw m||(yield h.commit()),new C(this.label,i)}return yield a.records[r]({label:this.label,target:e,data:o},n)})}set(e,t,r){return l(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"set",r)})}update(e,t,r){return l(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"update",r)})}createMany(e,t){return l(this,null,function*(){var o;let r=yield this.getRushDBInstance(),n=typeof t!="undefined",a=t!=null?t:yield r.tx.begin();try{let i=yield Promise.all(e.map(h=>l(this,null,function*(){return yield z(this.schema,h)}))),c=oe(i,this.schema,this.label);if(!k(c)){let h=Object.entries(c).map(([m,f])=>({[m]:{$in:f}})),u=yield this.find({where:{$or:h}},a);if((o=u==null?void 0:u.data)!=null&&o.length)throw new C(this.label,Object.keys(c))}let d=yield r.records.createMany({label:this.label,data:i},a);return n||(yield a.commit()),d}catch(i){throw n||(yield a.rollback()),i}})}delete(e,t){return l(this,null,function*(){if(k(e.where))throw new A(`You must specify criteria to delete records of type '${this.label}'. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.`);return yield(yield this.getRushDBInstance()).records.delete(y(p({},e),{labels:[this.label]}),t)})}deleteById(e,t){return l(this,null,function*(){return yield(yield this.getRushDBInstance()).records.deleteById(e,t)})}};ge(new N);var Ut=O;export{T as DBRecordInstance,q as DBRecordsArrayInstance,A as EmptyTargetError,E as HttpClient,Q as HttpClientResponse,Se as Model,Y as NonUniqueResultError,F as RestAPI,O as RushDB,_ as Transaction,C as UniquenessError,Ut as default,de as idToDate,X as idToTimestamp,ge as initSDK,z as mergeDefaultsWithPayload,ie as parseConfig,Z as pickUniqFieldsFromRecord,oe as pickUniqFieldsFromRecords,ce as validateInteger};
1
+ var De=Object.defineProperty,be=Object.defineProperties;var we=Object.getOwnPropertyDescriptors;var M=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,re=Object.prototype.propertyIsEnumerable;var ee=(s,e,t)=>e in s?De(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,p=(s,e)=>{for(var t in e||(e={}))te.call(e,t)&&ee(s,t,e[t]);if(M)for(var t of M(e))re.call(e,t)&&ee(s,t,e[t]);return s},y=(s,e)=>be(s,we(e));var $=(s,e)=>{var t={};for(var r in s)te.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&M)for(var r of M(s))e.indexOf(r)<0&&re.call(s,r)&&(t[r]=s[r]);return t};var h=(s,e,t)=>new Promise((r,n)=>{var a=c=>{try{o(t.next(c))}catch(d){n(d)}},i=c=>{try{o(t.throw(c))}catch(d){n(d)}},o=c=>c.done?r(c.value):Promise.resolve(c.value).then(a,i);o((t=t.apply(s,e)).next())});var Ie="string",xe="datetime",Oe="boolean",Pe="number",Ee="null",Ae="vector",se=[Ie,xe,Oe,Pe,Ee,Ae];var P=class s{makeRequest(e,{headers:t,method:r,protocol:n,requestData:a,timeout:i}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(s.TIMEOUT_ERROR_CODE);return e.code=s.TIMEOUT_ERROR_CODE,e}};P.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];P.TIMEOUT_ERROR_CODE="ETIMEDOUT";var L=class{constructor(e,t){this._statusCode=e,this._headers=t}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}},Q=class{constructor(e){this._res=e}getStatusCode(){throw new Error("getStatusCode not implemented.")}getHeaders(){throw new Error("getHeaders not implemented.")}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}};var N=class s extends P{constructor(e){if(super(),!e){if(!globalThis.fetch)throw new Error("fetch() function not provided and is not defined in the global scope. You must provide a fetch implementation.");e=globalThis.fetch}globalThis.AbortController?this._fetchFn=s.makeFetchWithAbortTimeout(e):this._fetchFn=s.makeFetchWithRaceTimeout(e)}static makeFetchWithRaceTimeout(e){return(t,r,n)=>{let a,i=new Promise((c,d)=>{a=setTimeout(()=>{a=null,d(P.makeTimeoutError())},n)}),o=e(t,r);return Promise.race([o,i]).finally(()=>{a&&clearTimeout(a)})}}static makeFetchWithAbortTimeout(e){return(t,r,n)=>h(this,null,function*(){let a=new AbortController,i=setTimeout(()=>{i=null,a.abort(P.makeTimeoutError())},n);try{return yield e(t,y(p({},r),{signal:a.signal}))}catch(o){throw o.name==="AbortError"?P.makeTimeoutError():o}finally{i&&clearTimeout(i)}})}makeRequest(o,c){return h(this,arguments,function*(e,{headers:t,method:r,protocol:n,requestData:a,timeout:i}){let d=r=="POST"||r=="PUT"||r=="PATCH",l=JSON.stringify(a)||(d?"":void 0),u=yield this._fetchFn(e,{body:l,headers:t,method:r},i!=null?i:8e4);return new z(u)})}},z=class s extends L{constructor(e){super(e.status,s._transformHeadersToObject(e.headers)),this._res=e}getRawResponse(){return this._res}toStream(e){return e(),this._res.body}toJSON(){return this._res.json()}static _transformHeadersToObject(e){let t={};for(let r of e){if(!Array.isArray(r)||r.length!=2)throw new Error("Response objects produced by the fetch function given to FetchHttpClient do not have an iterable headers map. Response#headers should be an iterable object.");t[r[0]]=r[1]}return t}};var w=s=>typeof s=="object"&&Array.isArray(s)&&s!==null,b=s=>s!==null&&Object.prototype.toString.call(s)==="[object Object]",k=s=>b(s)&&Object.keys(s).length===0,ae=s=>typeof s=="number"||typeof s=="string"||typeof s=="boolean"||s===null;function Be(s,e){let t=p({},s);return e.forEach(r=>{delete t[r]}),t}var W=s=>b(s)?Be(s,["__label","__id","__proptypes"]):s,j=s=>w(s)?s.map(j):b(s)?Object.fromEntries(Object.entries(s).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,j(t)])):s,J=s=>w(s)?s.every(ae):ae(s),K=s=>b(s)&&Object.values(s).every(J),B=s=>typeof s=="string",I=s=>{if(typeof s=="string"){if(s.toLowerCase()==="true")return!0;if(s.toLowerCase()==="false")return!1}return w(s)&&s.length===0||b(s)&&Object.keys(s).length===0?!1:!!s};var G=["httpClient","timeout","host","port","protocol","url","logger","options"],oe={initial:"in",extended:"ex",fullFeatured:"ff"};var _=class s extends Error{constructor(e,t){super(`Record with label "${e}" and properties ${JSON.stringify(t)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,s.prototype)}},E=class s extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,s.prototype)}},V=class s extends Error{constructor(e,t){super(`Expected a unique result but found ${e} matches for the provided SearchQuery: ${JSON.stringify(t)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,s.prototype)}};var Y=(s,e)=>h(void 0,null,function*(){let t=Object.entries(s).map(o=>h(void 0,[o],function*([a,i]){return i.default&&typeof i.default!="undefined"&&typeof e[a]=="undefined"?{key:a,value:typeof i.default=="function"?yield i.default():i.default}:{key:a,value:void 0}})),n=(yield Promise.all(t)).reduce((a,{key:i,value:o})=>(o!==void 0&&(a[i]=o),a),{});return p(p({},n),e)}),Z=(s,e)=>Object.entries(e).filter(([t])=>{var r;return(r=s[t])==null?void 0:r.uniq}).reduce((t,[r,n])=>(r in s&&(t[r]=n),t),{}),ie=(s,e,t)=>{let r={},n=Object.entries(e).filter(([,a])=>a.uniq).reduce((a,[i])=>(a[i]=!0,a),{});return s.forEach(a=>{Object.entries(a).forEach(([i,o])=>{if(i in n)if(r[i]){if(r[i].includes(o))throw new _(t,{[i]:o});r[i]=[...r[i],o]}else r[i]=[o]})}),r},ce=s=>{if(!s)return{};if(!b(s))throw new Error("Config must be an object");if(Object.keys(s).filter(t=>!G.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${G.join(", ")}`);return s};function de(s,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${s} must be an integer`)}return e}function X(s){let e=s.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function pe(s){return new Date(X(s))}function le(s){let e=/^([a-z]{2})_([01]{3}\d{0,})_(.+)$/,t=s.match(e);if(!t)return[null,s];let[,r,n,a]=t,o=Object.entries(oe).find(([m,f])=>f===r)[0],[c,d,l]=n.split("");return[p({},{customDB:c==="1",managedDB:d==="1",selfHosted:l==="1",planType:o}),a]}var T=class{constructor(e={}){this.data=e}exists(){return I(this.data.__id)&&I(this.data.__label)}id(){if(!I(this.data.__id))throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.");return this.data.__id}label(){if(!I(this.data.__label))throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.");return this.data.__label}proptypes(){if(!I(this.data.__proptypes))throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.");return this.data.__proptypes}date(){try{return pe(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return X(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}delete(e){return h(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return yield x.init().records.deleteById(this.id(),e)})}update(e,t){return h(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return x.init().records.update({label:this.label(),target:this.id(),data:e},t)})}set(e,t){return h(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return x.init().records.set({label:this.label(),target:this.id(),data:e},t)})}attach(e,t,r){return h(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return x.init().records.attach({source:this.id(),target:e,options:t},r)})}detach(e,t,r){return h(this,null,function*(){if(!I(this.data))throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return x.init().records.detach({source:this.id(),target:e,options:t},r)})}},C=class{constructor(e=[],t=0,r){this.data=e,this.total=t,this.searchQuery=r}};var _e={"Content-Type":"application/json"},he=({httpClient:s,token:e,url:t})=>(r,i)=>h(void 0,null,function*(){var o=i,{headers:n}=o,a=$(o,["headers"]);let c=yield s.makeRequest(`${t}${r}`,p({credentials:"omit",headers:Object.assign(p(p({},_e),n),typeof e!="undefined"?{token:e}:{})},a));if(c.getStatusCode()>=200&&c.getStatusCode()<300)return yield c.toJSON();throw new Error(`${c.getStatusCode()}`)});var q=class{constructor(e){this.id=e}rollback(){return h(this,null,function*(){return yield x.init().tx.rollback(this.id)})}commit(){return h(this,null,function*(){return yield x.init().tx.commit(this.id)})}};var ue="api.rushdb.com";var ye="https",me="/api/v1";var D=s=>s?{"x-transaction-id":s}:void 0,qe=s=>B(s)||s instanceof q,R=s=>qe(s)?s instanceof q?s.id:s:void 0,fe=s=>/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(s),O=s=>{if(B(s)&&fe(s))return s;if(s instanceof T&&s.data)return s.data.__id;if(b(s)&&"__id"in s&&fe(s.__id))return s.__id},U=s=>!(!b(s)||b(s)&&"name"in s&&!B(s.name)||b(s)&&"type"in s&&(!B(s.type)||!se.includes(s.type))||!("value"in s)||!J(s.value)||"metadata"in s&&!B(s.metadata)||"valueSeparator"in s&&!B(s.valueSeparator)),ge=s=>{let e=ye,t=ue,r=443,n=me;if("url"in s){let i=new URL(s.url);e=i.protocol.replace(":",""),t=i.hostname,r=parseInt(i.port||(e==="http"?"80":e==="https"?"443":""))}"host"in s&&"port"in s&&"protocol"in s&&(e=s.protocol.replace(":",""),t=s.host,r=s.port),n&&!n.startsWith("/")&&(n="/"+n);let a="";return e==="http"&&r===80||e==="https"&&r===443||(a=":"+r),`${e}://${t}${a}${n}`},S=(s=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t};var H=class{constructor(e,t){this.records={attach:(a,i)=>h(this,[a,i],function*({source:e,target:t,options:r},n){var f,g;let o=R(n),d=`/relationships/${O(e)}`,l={headers:Object.assign({},D(o)),method:"POST",requestData:p(p({targetIds:this._extractTargetIds(t,"Attach")},(r==null?void 0:r.type)&&{type:r.type}),(r==null?void 0:r.direction)&&{direction:r.direction})},u=typeof this.logger=="function"?S():"";(f=this.logger)==null||f.call(this,p({requestId:u,path:d},l));let m=yield this.fetcher(d,l);return(g=this.logger)==null||g.call(this,y(p({requestId:u,path:d},l),{responseData:m.data})),m}),detach:(a,i)=>h(this,[a,i],function*({source:e,target:t,options:r},n){var f,g;let o=R(n),d=`/relationships/${O(e)}`,l={headers:Object.assign({},D(o)),method:"PUT",requestData:p(p({targetIds:this._extractTargetIds(t,"Detach")},(r==null?void 0:r.typeOrTypes)&&{typeOrTypes:r.typeOrTypes}),(r==null?void 0:r.direction)&&{direction:r.direction})},u=typeof this.logger=="function"?S():"";(f=this.logger)==null||f.call(this,p({requestId:u,path:d},l));let m=yield this.fetcher(d,l);return(g=this.logger)==null||g.call(this,y(p({requestId:u,path:d},l),{responseData:m.data})),m}),create:(a,i)=>h(this,[a,i],function*({label:e,data:t,options:r},n){var f,g;let o=R(n),c="/records",d={headers:Object.assign({},D(o)),method:"POST",requestData:{}},l=typeof this.logger=="function"?S():"",u=W(j(t));if(w(u)&&u.every(U))d.requestData={label:e,properties:u};else if(K(u))d.requestData={label:e,data:u,options:r};else throw b(u)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(f=this.logger)==null||f.call(this,p({requestId:l,path:c},d));let m=yield this.fetcher(c,d);return(g=this.logger)==null||g.call(this,y(p({requestId:l,path:c},d),{responseData:m.data})),m!=null&&m.success&&(m!=null&&m.data)?new T(m.data):new T}),createMany:(e,t)=>h(this,null,function*(){var c,d,l,u;let r=R(t),n="/records/import/json",a={headers:Object.assign({},D(r)),method:"POST",requestData:e},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);if((d=this.logger)==null||d.call(this,y(p({requestId:i,path:n},a),{responseData:o.data})),o!=null&&o.success&&(o!=null&&o.data)){let m=(u=(l=o.data)==null?void 0:l.map(f=>new T(f)))!=null?u:[];return new C(m,o.total)}return new C([])}),delete:(e,t)=>h(this,null,function*(){var c,d,l;if(k(e.where)&&!((c=this==null?void 0:this.options)!=null&&c.allowForceDelete))throw new E("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let r=R(t),n="/records/delete",a={headers:Object.assign({},D(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);return(l=this.logger)==null||l.call(this,y(p({requestId:i,path:n},a),{responseData:o.data})),o}),deleteById:(e,t)=>h(this,null,function*(){var d,l;let r=R(t),n=w(e),a=n?"/records/delete":`/records/${e}`,i={headers:Object.assign({},D(r)),method:n?"POST":"DELETE",requestData:n?{limit:1e3,where:{$id:{$in:e}}}:void 0},o=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:o,path:a},i));let c=yield this.fetcher(a,i);return(l=this.logger)==null||l.call(this,y(p({requestId:o,path:a},i),{responseData:c.data})),c}),export:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),n="/records/export/csv",a={headers:Object.assign({},D(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:n},a),{responseData:o.data})),o}),find:(e,t)=>h(this,null,function*(){var m,f;let u=e,{id:r}=u,n=$(u,["id"]),a=R(t),i=r?`/records/${r}/search`:"/records/search",o={headers:Object.assign({},D(a)),method:"POST",requestData:n!=null?n:{}},c=typeof this.logger=="function"?S():"";(m=this.logger)==null||m.call(this,p({requestId:c,path:i},o));let d=yield this.fetcher(i,o);(f=this.logger)==null||f.call(this,y(p({requestId:c,path:i},o),{responseData:d.data}));let l=d.data.map(g=>new T(g));return new C(l,d.total,e)}),findById:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),n=w(e)?"/records":`/records/${e}`,a={headers:Object.assign({},D(r)),method:w(e)?"POST":"GET",requestData:w(e)?{ids:e}:void 0},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);if((d=this.logger)==null||d.call(this,y(p({requestId:i,path:n},a),{responseData:o.data})),w(e)){let l=o.data.map(u=>new T(u));return new C(l,o.total)}else return new T(o.data)}),findOne:(e,t)=>h(this,null,function*(){var d,l;let r=R(t),n="/records/search",a={headers:Object.assign({},D(r)),method:"POST",requestData:y(p({},e),{limit:1,skip:0})},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);(l=this.logger)==null||l.call(this,y(p({requestId:i,path:n},a),{responseData:o.data}));let[c]=o.data;return new T(c)}),findUniq:(e,t)=>h(this,null,function*(){var d,l;let r=R(t),n="/records/search",a={headers:Object.assign({},D(r)),method:"POST",requestData:y(p({},e),{limit:1,skip:0})},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);if((l=this.logger)==null||l.call(this,y(p({requestId:i,path:n},a),{responseData:o.data})),typeof o.total!="undefined"&&o.total>1)throw new V(o.total,e);let[c]=o.data;return new T(c)}),set:(i,o)=>h(this,[i,o],function*({target:e,label:t,data:r,options:n},a){var F,v;let c=R(a),l=`/records/${O(e)}`,u={headers:Object.assign({},D(c)),method:"PUT",requestData:{}},m=typeof this.logger=="function"?S():"",f=W(j(r));if(w(f)&&f.every(U))u.requestData={label:t,properties:f};else if(K(f))u.requestData={label:t,data:f,options:n};else throw b(f)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(F=this.logger)==null||F.call(this,p({requestId:m,path:l},u));let g=yield this.fetcher(l,u);return(v=this.logger)==null||v.call(this,y(p({requestId:m,path:l},u),{responseData:g.data})),g!=null&&g.success&&(g!=null&&g.data)?new T(g.data):new T}),update:(i,o)=>h(this,[i,o],function*({target:e,label:t,data:r,options:n},a){var F,v;let c=R(a),l=`/records/${O(e)}`,u={headers:Object.assign({},D(c)),method:"PATCH",requestData:{}},m=typeof this.logger=="function"?S():"",f=W(j(r));if(w(f)&&f.every(U))u.requestData={label:t,properties:f};else if(K(f))u.requestData={label:t,data:f,options:n};else throw b(f)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(F=this.logger)==null||F.call(this,p({requestId:m,path:l},u));let g=yield this.fetcher(l,u);return(v=this.logger)==null||v.call(this,y(p({requestId:m,path:l},u),{responseData:g.data})),g!=null&&g.success&&(g!=null&&g.data)?new T(g.data):new T})};this.relationships={find:(e,t)=>h(this,null,function*(){var l,u;let r=R(t),n=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&n.append("limit",e.limit.toString()),(e==null?void 0:e.skip)!==void 0&&n.append("skip",e.skip.toString());let i=`/relationships/search${n.toString()?"?"+n.toString():""}`,o={headers:Object.assign({},D(r)),method:"POST",requestData:e!=null?e:{}},c=typeof this.logger=="function"?S():"";(l=this.logger)==null||l.call(this,p({requestId:c,path:i},o));let d=yield this.fetcher(i,o);return(u=this.logger)==null||u.call(this,y(p({requestId:c,path:i},o),{responseData:d.data})),d})};this.properties={delete:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),n=`/properties/${e}`,a={headers:Object.assign({},D(r)),method:"DELETE"},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:n},a),{responseData:o.data})),o}),find:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),n="/properties/search",a={headers:Object.assign({},D(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:n},a),{responseData:o.data})),o}),findById:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),n=`/properties/${e}`,a={headers:Object.assign({},D(r)),method:"GET"},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:n},a),{responseData:o.data})),o}),values:(e,t,r)=>h(this,null,function*(){var d,l;let n=R(r),a=`/properties/${e}/values`,i={headers:Object.assign({},D(n)),method:"POST",requestData:t!=null?t:{}},o=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:o,path:a},i));let c=yield this.fetcher(a,i);return(l=this.logger)==null||l.call(this,y(p({requestId:o,path:a},i),{responseData:c.data})),c})};this.labels={find:(e,t)=>h(this,null,function*(){var c,d;let r=R(t),n="/labels/search",a={headers:Object.assign({},D(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:n},a));let o=yield this.fetcher(n,a);return(d=this.logger)==null||d.call(this,y(p({requestId:i,path:n},a),{responseData:o.data})),o})};this.tx={begin:e=>h(this,null,function*(){var i,o;let t="/tx",r={method:"POST",requestData:b(e)&&"ttl"in e?e:{}},n=typeof this.logger=="function"?S():"";(i=this.logger)==null||i.call(this,p({requestId:n,path:t},r));let a=yield this.fetcher(t,r);return(o=this.logger)==null||o.call(this,y(p({requestId:n,path:t},r),{responseData:a.data})),new q(a.data.id)}),commit:e=>h(this,null,function*(){var o,c;let r=`/tx/${R(e)}/commit`,n={method:"POST",requestData:{}},a=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,p({requestId:a,path:r},n));let i=yield this.fetcher(r,n);return(c=this.logger)==null||c.call(this,y(p({requestId:a,path:r},n),{responseData:i.data})),i}),get:e=>h(this,null,function*(){var o,c;let r=`/tx/${R(e)}`,n={method:"GET"},a=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,p({requestId:a,path:r},n));let i=yield this.fetcher(r,n);return(c=this.logger)==null||c.call(this,y(p({requestId:a,path:r},n),{responseData:i.data})),new q(i.data.id)}),rollback:e=>h(this,null,function*(){var o,c;let r=`/tx/${R(e)}/rollback`,n={method:"POST",requestData:{}},a=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,p({requestId:a,path:r},n));let i=yield this.fetcher(r,n);return(c=this.logger)==null||c.call(this,y(p({requestId:a,path:r},n),{responseData:i.data})),i})};this.settings={get:()=>h(this,null,function*(){var a,i;let e="/sdk/settings",t={method:"GET"},r=typeof this.logger=="function"?S():"";(a=this.logger)==null||a.call(this,p({requestId:r,path:e},t));let n=yield this.fetcher(e,t);return(i=this.logger)==null||i.call(this,y(p({requestId:r,path:e},t),{responseData:n.data})),n})};if(this.fetcher=null,t!=null&&t.httpClient){let r=ge(t);this.fetcher=he({httpClient:t.httpClient,token:e,url:r})}t!=null&&t.options&&(this.options=t==null?void 0:t.options),t!=null&&t.logger&&(this.logger=t==null?void 0:t.logger)}_extractTargetIds(e,t){var r;if(e instanceof T){let n=O(e);if(!n)throw new E(`${t} error: Target id is empty`);return[n]}if(w(e)&&e.every(n=>n instanceof T)){let n=e.map(O).filter(I);if(!n.length)throw new E(`${t} error: Target ids are empty`);return n}if(e instanceof C){let n=(r=e.data)==null?void 0:r.map(O).filter(I);if(!(n!=null&&n.length))throw new E(`${t} error: Target ids are empty`);return n}if(b(e)&&"__id"in e)return[e.__id];if(w(e)&&e.every(n=>b(n)&&"__id"in n)){let n=e.map(O).filter(I);if(!n.length)throw new E(`${t} error: Target ids are empty`);return n}return w(e)?e:B(e)?[e]:[]}};var Se,A=class A extends H{constructor(e,t){var a;let r=ce(t);super(e,y(p({},r),{httpClient:(a=r.httpClient)!=null?a:Se})),A.instance=this;let[n]=le(e!=null?e:"");this.initializeSync(n,e,r)}initializeSync(e,t,r){let n=e?{planType:e.planType,customDB:e.customDB,managedDB:e.managedDB,selfHosted:e.selfHosted}:null;A.state=p({initialized:!0,debug:!1,timeout:de("timeout",r==null?void 0:r.timeout,8e4),token:t},n&&{serverSettings:n})}static init(){if(A.instance)return A.instance;throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}static getInstance(){return A.instance}static isInitialized(){return A.instance!==null}toDBRecordInstance(e){return new T(e)}};A.instance=null,A.state={initialized:!1,debug:!1,timeout:8e4};var x=A,Re=s=>{Se=s};var Te=class{constructor(e,t){this.label=e,this.schema=t}getLabel(){return this.label}getRushDBInstance(){return h(this,null,function*(){if(x.getInstance())return x.init();throw new Error('No RushDB instance found. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')})}toDBRecordInstance(e){return h(this,null,function*(){try{return(yield this.getRushDBInstance()).toDBRecordInstance(e)}catch(t){throw new Error("No RushDB instance was provided during model initialization.")}})}find(e,t){return h(this,null,function*(){let r=e!=null?e:{};return(yield this.getRushDBInstance()).records.find(y(p({},r),{labels:[this.label]}),t)})}findOne(e,t){return h(this,null,function*(){let r=e!=null?e:{};return(yield this.getRushDBInstance()).records.findOne(y(p({},r),{labels:[this.label]}),t)})}findById(e,t){return h(this,null,function*(){return this.findOne({where:{$id:e}},t)})}findUniq(e,t){return h(this,null,function*(){let r=e!=null?e:{};return(yield this.getRushDBInstance()).records.findUniq(y(p({},r),{labels:[this.label]}),t)})}create(e,t){return h(this,null,function*(){var o;let r=yield Y(this.schema,e),n=Z(this.schema,r),a=I(n),i=yield this.getRushDBInstance();if(a){let c=t!=null?t:yield i.tx.begin(),d=yield this.find({where:n},c),l=typeof t!="undefined";if(!((o=d==null?void 0:d.data)!=null&&o.length)){let m=yield i.records.create({label:this.label,data:r},c);return l||(yield c.commit()),m}else throw l||(yield c.commit()),new _(this.label,n)}return yield i.records.create({label:this.label,data:r},t)})}attach(a,i){return h(this,arguments,function*({source:e,target:t,options:r},n){return yield(yield this.getRushDBInstance()).records.attach({source:e,target:t,options:r},n)})}detach(a,i){return h(this,arguments,function*({source:e,target:t,options:r},n){return yield(yield this.getRushDBInstance()).records.detach({source:e,target:t,options:r},n)})}handleSetOrUpdate(e,t,r,n){return h(this,null,function*(){var c,d;if(w(t)&&t.every(U))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let a=yield this.getRushDBInstance(),i=yield Y(this.schema,t),o=Z(this.schema,i);if(!k(o)){let l=n!=null?n:yield a.tx.begin(),u=yield this.find({where:o},l),m=typeof n!="undefined";if(!((c=u==null?void 0:u.data)!=null&&c.length)||u.data.length===1&&((d=u.data[0])==null?void 0:d.id())===O(e)){let g=yield a.records[r]({target:e,label:this.label,data:i},l);return m||(yield l.commit()),g}else throw m||(yield l.commit()),new _(this.label,o)}return yield a.records[r]({label:this.label,target:e,data:i},n)})}set(e,t,r){return h(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"set",r)})}update(e,t,r){return h(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"update",r)})}createMany(e,t){return h(this,null,function*(){var i;let r=yield this.getRushDBInstance(),n=typeof t!="undefined",a=t!=null?t:yield r.tx.begin();try{let o=yield Promise.all(e.map(l=>h(this,null,function*(){return yield Y(this.schema,l)}))),c=ie(o,this.schema,this.label);if(!k(c)){let l=Object.entries(c).map(([m,f])=>({[m]:{$in:f}})),u=yield this.find({where:{$or:l}},a);if((i=u==null?void 0:u.data)!=null&&i.length)throw new _(this.label,Object.keys(c))}let d=yield r.records.createMany({label:this.label,data:o},a);return n||(yield a.commit()),d}catch(o){throw n||(yield a.rollback()),o}})}delete(e,t){return h(this,null,function*(){if(k(e.where))throw new E(`You must specify criteria to delete records of type '${this.label}'. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.`);return yield(yield this.getRushDBInstance()).records.delete(y(p({},e),{labels:[this.label]}),t)})}deleteById(e,t){return h(this,null,function*(){return yield(yield this.getRushDBInstance()).records.deleteById(e,t)})}};Re(new N);var Ft=x;export{T as DBRecordInstance,C as DBRecordsArrayInstance,E as EmptyTargetError,P as HttpClient,Q as HttpClientResponse,Te as Model,V as NonUniqueResultError,H as RestAPI,x as RushDB,q as Transaction,_ as UniquenessError,Ft as default,le as extractMixedPropertiesFromToken,pe as idToDate,X as idToTimestamp,Re as initSDK,Y as mergeDefaultsWithPayload,ce as parseConfig,Z as pickUniqFieldsFromRecord,ie as pickUniqFieldsFromRecords,de as validateInteger};
@@ -1 +1,6 @@
1
1
  export declare const ALLOWED_CONFIG_PROPERTIES: string[];
2
+ export declare const PlanPrefix: {
3
+ readonly initial: "in";
4
+ readonly extended: "ex";
5
+ readonly fullFeatured: "ff";
6
+ };
package/dist/sdk/sdk.d.ts CHANGED
@@ -2,24 +2,18 @@ import type { HttpClient } from '../network/HttpClient.js';
2
2
  import type { Schema } from '../types/index.js';
3
3
  import type { DBRecord } from './record.js';
4
4
  import { DBRecordInstance } from './record.js';
5
- import type { SDKConfig, State } from './types.js';
5
+ import { SDKConfig, State } from './types.js';
6
6
  import { RestAPI } from '../api/api.js';
7
7
  export declare class RushDB extends RestAPI {
8
8
  static instance: RushDB | null;
9
- static initPromise: Promise<RushDB> | null;
10
9
  static state: State;
11
10
  constructor(token?: string, config?: SDKConfig);
11
+ private initializeSync;
12
12
  /**
13
- * Returns a promise that resolves when the SDK is fully initialized
14
- * Use this to ensure the SDK is ready before using it
15
- */
16
- waitForInitialization(): Promise<RushDB>;
17
- private initializeAsync;
18
- /**
19
- * Static method to get or wait for initialization
13
+ * Static method to get instance
20
14
  * This is the preferred way to get an initialized RushDB instance
21
15
  */
22
- static init(): Promise<RushDB>;
16
+ static init(): RushDB;
23
17
  /**
24
18
  * Synchronous getInstance that returns instance or null
25
19
  */
@@ -1,4 +1,5 @@
1
1
  import type { HttpClientInterface } from '../network/HttpClient.js';
2
+ import { PlanPrefix } from './constants';
2
3
  type ApiConnectionConfig = {
3
4
  host?: string;
4
5
  port?: number;
@@ -13,10 +14,9 @@ export type State = {
13
14
  initialized: boolean;
14
15
  serverSettings?: {
15
16
  selfHosted: boolean;
16
- dashboardUrl: string;
17
- googleOAuthEnabled: boolean;
18
- githubOAuthEnabled: boolean;
19
17
  customDB?: boolean;
18
+ managedDB?: boolean;
19
+ planType?: PlanType;
20
20
  };
21
21
  } & Partial<ApiConnectionConfig>;
22
22
  export type Logger = (payload: any) => void;
@@ -34,4 +34,7 @@ export type SDKConfig = {
34
34
  allowForceDelete?: boolean;
35
35
  };
36
36
  } & ApiConnectionConfig;
37
+ export type PlanType = keyof typeof PlanPrefix;
38
+ type RawServerSettings = NonNullable<State['serverSettings']>;
39
+ export type TokenPublicVariables = Pick<RawServerSettings, 'selfHosted' | 'customDB' | 'managedDB' | 'planType'>;
37
40
  export {};
@@ -1,5 +1,5 @@
1
1
  import type { PropertyValue, Schema, InferSchemaTypesWrite } from '../types/index.js';
2
- import type { SDKConfig } from './types.js';
2
+ import { SDKConfig, TokenPublicVariables } from './types.js';
3
3
  export declare const mergeDefaultsWithPayload: <S extends Schema = Schema>(schema: S, data: Partial<InferSchemaTypesWrite<S>>) => Promise<InferSchemaTypesWrite<S>>;
4
4
  export declare const pickUniqFieldsFromRecord: <S extends Schema = Schema>(schema: S, data: Partial<InferSchemaTypesWrite<S>>) => Record<string, PropertyValue>;
5
5
  export declare const pickUniqFieldsFromRecords: <S extends Schema = Schema>(data: Array<Partial<InferSchemaTypesWrite<S>>>, schema: S, label: string) => Record<string, PropertyValue[]>;
@@ -7,3 +7,4 @@ export declare const parseConfig: (config?: Record<string, unknown>) => SDKConfi
7
7
  export declare function validateInteger(name: string, n: unknown, defaultVal?: number): number;
8
8
  export declare function idToTimestamp(id: string): number;
9
9
  export declare function idToDate(id: string): Date;
10
+ export declare function extractMixedPropertiesFromToken(prefixedToken: string): [TokenPublicVariables | null, string];
package/package.json CHANGED
@@ -33,7 +33,7 @@
33
33
  "rushdb"
34
34
  ],
35
35
  "license": "Apache-2.0",
36
- "version": "1.8.1",
36
+ "version": "1.9.0",
37
37
  "type": "module",
38
38
  "files": [
39
39
  "dist"