@rushdb/javascript-sdk 0.17.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var Pe=Object.create;var L=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var Ee=Object.getOwnPropertyNames;var Ae=Object.getPrototypeOf,_e=Object.prototype.hasOwnProperty;var Oe=(a,e)=>{for(var r in e)L(a,r,{get:e[r],enumerable:!0})},ne=(a,e,r,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ee(e))!_e.call(a,s)&&s!==r&&L(a,s,{get:()=>e[s],enumerable:!(t=Ie(e,s))||t.enumerable});return a};var ae=(a,e,r)=>(r=a!=null?Pe(Ae(a)):{},ne(e||!a||!a.__esModule?L(r,"default",{value:a,enumerable:!0}):r,a)),Be=a=>ne(L({},"__esModule",{value:!0}),a);var Ve={};Oe(Ve,{DBRecordDraft:()=>w,DBRecordInstance:()=>h,DBRecordsArrayInstance:()=>x,DBRecordsBatchDraft:()=>A,EmptyTargetError:()=>T,HttpClient:()=>I,HttpClientResponse:()=>H,Model:()=>Y,NonUniqueResultError:()=>M,RestAPI:()=>C,RushDB:()=>be,Transaction:()=>b,UniquenessError:()=>D,default:()=>$e,idToDate:()=>N,idToTimestamp:()=>k});module.exports=Be(Ve);var I=class a{makeRequest(e,{headers:r,method:t,protocol:s,requestData:i,timeout:n}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(a.TIMEOUT_ERROR_CODE);return e.code=a.TIMEOUT_ERROR_CODE,e}};I.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];I.TIMEOUT_ERROR_CODE="ETIMEDOUT";var F=class{constructor(e,r){this._statusCode=e,this._headers=r}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=ae(require("http"),1),g=ae(require("https"),1);var ie=/^(?:\d{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:\d{2}(?:[02468][048]|[13579][26])-02-29))Schema(0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9])?(?:\.([0-9]{1,9}))?([zZ]?|([\+-])(((([0][0-9])|([1][0-3])):?(([03][0])|([14][5])))|14:00)?)$/;var _="string",oe="datetime",J="boolean",G="number",z="null";var ce=Z.default||Z,de=g.default||g,qe=new ce.Agent({keepAlive:!0}),Ce=new de.Agent({keepAlive:!0}),$=class extends I{constructor(e){super(),this._agent=e}makeRequest(e,{headers:r,method:t,protocol:s,requestData:i,timeout:n}){let c=new URL(e),d=s==="http"||c.protocol==="http:",o=this._agent;return o||(o=d?qe:Ce),new Promise((p,y)=>{let S=(d?ce:de).request({agent:o,ciphers:"DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5",headers:r,host:c.hostname,method:t,path:c.pathname+c.search,port:c.port});S.setTimeout(n!=null?n:8e4,()=>{S.destroy(I.makeTimeoutError())}),S.on("response",P=>{p(new X(P))}),S.on("error",P=>{y(P)}),S.once("socket",P=>{let j=i?JSON.stringify(i):"";P.connecting?P.once(d?"connect":"secureConnect",()=>{S.write(j),S.end()}):(S.write(j),S.end())})})}},X=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,r)=>{let t="";this._res.setEncoding("utf8"),this._res.on("data",s=>{t+=s}),this._res.once("end",()=>{try{e(JSON.parse(t))}catch(s){r(s)}})})}};var l=a=>typeof a=="object"&&Array.isArray(a)&&a!==null,R=a=>a!==null&&Object.prototype.toString.call(a)==="[object Object]",O=a=>R(a)&&Object.keys(a).length===0,V=a=>R(a)&&Object.keys(a).every(e=>{let r=a[e];return l(r)?r.every(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t===null):!(r&&typeof r=="object")}),B=a=>typeof a=="string",pe=a=>{if(typeof a=="string"){if(a.toLowerCase()==="true")return!0;if(a.toLowerCase()==="false")return!1}return l(a)&&a.length===0||R(a)&&Object.keys(a).length===0?!1:!!a};var je={"Content-Type":"application/json"},ye=({httpClient:a,token:e,url:r})=>async(t,{headers:s,...i})=>{let n=await a.makeRequest(`${r}${t}`,{credentials:"omit",headers:Object.assign({...je,...s},typeof e<"u"?{token:e}:{}),...i});if(n.getStatusCode()>=200&&n.getStatusCode()<300)return await n.toJSON();throw new Error(`${n.getStatusCode()}`)};var D=class a extends Error{constructor(e,r){super(`Record with label "${e}" and properties ${JSON.stringify(r)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,a.prototype)}},T=class a extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,a.prototype)}},M=class a extends Error{constructor(e,r){super(`Expected a unique result but found ${e} matches for the provided search parameters: ${JSON.stringify(r)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,a.prototype)}};var E=class{constructor(){this.apiProxy={};return new Proxy(this,{get:(e,r,t)=>{if(r in e)return Reflect.get(e,r,t);if(this.apiProxy&&r in this.apiProxy)return Reflect.get(this.apiProxy,r,t)}})}init(e,r){this.apiProxy=e}};var ee=["httpClient","timeout","host","port","protocol","url","logger","options"];var W=async(a,e)=>{let r=Object.entries(a).map(async([i,n])=>n.default&&typeof n.default<"u"&&typeof e[i]>"u"?{key:i,value:typeof n.default=="function"?await n.default():n.default}:{key:i,value:void 0});return{...(await Promise.all(r)).reduce((i,{key:n,value:c})=>(c!==void 0&&(i[n]=c),i),{}),...e}},te=(a,e)=>Object.entries(e).filter(([r])=>{var t;return(t=a[r])==null?void 0:t.uniq}).reduce((r,[t,s])=>(t in a&&(r[t]=s),r),{}),ue=(a,e,r)=>{let t={},s=Object.entries(e).filter(([i,n])=>n.uniq).reduce((i,[n])=>(i[n]=!0,i),{});return a.forEach(i=>{Object.entries(i).forEach(([n,c])=>{if(n in s)if(t[n]){if(t[n].includes(c))throw new D(r,{[n]:c});t[n]=[...t[n],c]}else t[n]=[c]})}),t},he=a=>{if(!a)return{};if(!R(a))throw new Error("Config must be an object");if(Object.keys(a).filter(r=>!ee.includes(r)).length>0)throw new Error(`Config object may only contain the following: ${ee.join(", ")}`);return a};function fe(a,e,r){if(!Number.isInteger(e)){if(r!==void 0)return r;throw new Error(`${a} must be an integer`)}return e}function k(a){let e=a.split("-"),r=e[0]+e[1].slice(0,4);return parseInt(r,16)}function N(a){return new Date(k(a))}var A=class{constructor({label:e,options:r={returnResult:!0,suggestTypes:!0},payload:t}){this.label=e,this.options=r,this.payload=t}toJson(){return{label:this.label,options:this.options,payload:this.payload}}},w=class{constructor({label:e,properties:r=[]}){this.label=e,this.properties=r}toJson(){return{label:this.label,properties:this.properties}}},h=class extends E{constructor(e){super(),this.data=e}get id(){try{return this.data.__id}catch{throw new Error("DBRecordInstance: Unable to access 'id'. The Record data is undefined.")}}get label(){try{return this.data.__label}catch{throw new Error("DBRecordInstance: Unable to access 'label'. The Record data is undefined.")}}get proptypes(){try{return this.data.__proptypes}catch{throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record data' is undefined.")}}get date(){try{return N(this.data.__id)}catch{throw new Error("DBRecordInstance: Unable to access 'date'. The Record data is undefined.")}}get timestamp(){try{return k(this.data.__id)}catch{throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record data is undefined.")}}async delete(e){if(!this.data)throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return await this.apiProxy.records.deleteById(this.data.__id,e)}async update(e,r){if(!this.data)throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return this.apiProxy.records.update(this.data.__id,e,r)}async set(e,r){if(!this.data)throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return this.apiProxy.records.set(this.data.__id,e,r)}async attach(e,r,t){if(!this.data)throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return this.apiProxy.records.attach(this.data.__id,e,r,t)}async detach(e,r,t){if(!this.data)throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return this.apiProxy.records.detach(this.data.__id,e,r,t)}},x=class extends E{constructor(e,r,t){super(),this.data=e,this.total=r,this.searchParams=t}};var b=class extends E{constructor(e){super(),this.id=e}async rollback(){return await this.apiProxy.tx.rollback(this.id)}async commit(){return await this.apiProxy.tx.commit(this.id)}};var me="api.rushdb.com";var Se="https",le="/api/v1";var f=a=>a?{"x-transaction-id":a}:void 0,Q=a=>B(a)||a instanceof b,v=a=>Q(a)?a:void 0,m=a=>Q(a)?a instanceof b?a.id:a:void 0,q=a=>{if(B(a))return a;if(a instanceof h&&a.data)return a.data.__id;if("__id"in a)return a.__id},U=(a,e)=>{var n,c,d;let r=B(a),t=ke(a),i=Q(e)||!R(e);if(r){let o=t?{id:a}:{searchParams:{labels:[a]}};return i?{...o,searchParams:{...o.searchParams}}:{...o,searchParams:{...e,labels:[...(c=(n=o.searchParams)==null?void 0:n.labels)!=null?c:[],...(d=e.labels)!=null?d:[]]}}}else return{searchParams:a!=null?a:{}}},ke=a=>/^[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(a),Ue=a=>a.every(e=>typeof e==typeof a[0]),Le=a=>Array.isArray(a)?{isEmptyArray:a.length===0,isEmptyStringsArray:a.every(e=>e===""),isInconsistentArray:!Ue(a)}:{isEmptyString:a===""},Re=a=>typeof a===_?ie.test(a)?oe:_:typeof a===G?G:typeof a===J?J:a===null?z:_,Fe=(a,e)=>{let{isEmptyArray:r,isInconsistentArray:t}=Le(a);return r?{type:_,value:[]}:t||!e?{type:_,value:a.map(String)}:{type:Re(a[0]),value:a}},He=(a,e)=>{if(!e)return{type:_,value:String(a)};let r=Re(a);return{type:r,value:r===z?null:a}},K=(a,e={suggestTypes:!0})=>Object.entries(a).map(([r,t])=>{let{type:s,value:i}=l(t)?Fe(t,e.suggestTypes):He(t,e.suggestTypes);return{name:r,type:s,value:i}}),Te=({label:a,options:e={suggestTypes:!0},payload:r})=>({label:a,properties:K(r,e)}),we=a=>{let e=Se,r=me,t=443,s=le;if("url"in a){let n=new URL(a.url);e=n.protocol.replace(":",""),r=n.hostname,t=parseInt(n.port||(e==="http"?"80":e==="https"?"443":""))}"host"in a&&"port"in a&&"protocol"in a&&(e=a.protocol.replace(":",""),r=a.host,t=a.port),s&&!s.startsWith("/")&&(s="/"+s);let i="";return e==="http"&&t===80||e==="https"&&t===443||(i=":"+t),`${e}://${r}${i}${s}`},u=(a=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r="";for(let t=0;t<a;t++){let s=Math.floor(Math.random()*e.length);r+=e[s]}return r};var xe=(a,e)=>({labels:{async find(r,t){let s=m(t),i="/labels",n={headers:Object.assign({},f(s)),method:"POST",requestData:r},c=typeof e=="function"?u():"";e==null||e({requestId:c,path:i,...n});let d=await a(i,n);return e==null||e({requestId:c,path:i,...n,responseData:d.data}),d}},properties:{delete:async(r,t)=>{let s=m(t),i=`/properties/${r}`,n={headers:Object.assign({},f(s)),method:"DELETE"},c=typeof e=="function"?u():"";e==null||e({requestId:c,path:i,...n});let d=await a(i,n);return e==null||e({requestId:c,path:i,...n,responseData:d.data}),d},find:async(r,t)=>{let s=m(t),i="/properties",n={headers:Object.assign({},f(s)),method:"POST",requestData:r},c=typeof e=="function"?u():"";e==null||e({requestId:c,path:i,...n});let d=await a(i,n);return e==null||e({requestId:c,path:i,...n,responseData:d.data}),d},findById:async(r,t)=>{let s=m(t),i=`/properties/${r}`,n={headers:Object.assign({},f(s)),method:"GET"},c=typeof e=="function"?u():"";e==null||e({requestId:c,path:i,...n});let d=await a(i,n);return e==null||e({requestId:c,path:i,...n,responseData:d.data}),d},values:async(r,t,s)=>{let i=m(s),n=`/properties/${r}/values`,{sort:c,skip:d,limit:o,query:p}=t!=null?t:{},y=new URLSearchParams;c!==void 0&&y.append("sort",c),d!==void 0&&y.append("skip",d.toString()),o!==void 0&&y.append("limit",o.toString()),p!==void 0&&y.append("query",p);let S=y.toString(),P=S?`${n}?${S}`:n,j={headers:Object.assign({},f(i)),method:"GET"},se=typeof e=="function"?u():"";e==null||e({requestId:se,path:n,...j});let re=await a(P,j);return e==null||e({requestId:se,path:P,...j,responseData:re.data}),re}},records:{async attach(r,t,s,i){let n=m(i),d=`/records/${q(r)}/relations`,o={headers:Object.assign({},f(n)),method:"POST",requestData:{targetIds:t,...(s==null?void 0:s.type)&&{type:s.type},...(s==null?void 0:s.direction)&&{direction:s.direction}}},p=typeof e=="function"?u():"";e==null||e({requestId:p,path:d,...o});let y=await a(d,o);return e==null||e({requestId:p,path:d,...o,responseData:y.data}),y},async create(r,t){let s=m(t),i="/records",n={headers:Object.assign({},f(s)),method:"POST",requestData:r instanceof w?r.toJson():r},c=typeof e=="function"?u():"";e==null||e({requestId:c,path:i,...n});let d=await a(i,n);return e==null||e({requestId:c,path:i,...n,responseData:d.data}),d},async createMany(r,t){let s=m(t),i="/records/import/json",n={headers:Object.assign({},f(s)),method:"POST",requestData:r instanceof A?r.toJson():r},c=typeof e=="function"?u():"";e==null||e({requestId:c,path:i,...n});let d=await a(i,n);return e==null||e({requestId:c,path:i,...n,responseData:d.data}),d},async delete(r,t){let s=m(t),i="/records/delete",n={headers:Object.assign({},f(s)),method:"PUT",requestData:r},c=typeof e=="function"?u():"";e==null||e({requestId:c,path:i,...n});let d=await a(i,n);return e==null||e({requestId:c,path:i,...n,responseData:d.data}),d},async deleteById(r,t){let s=m(t),i=l(r),n=i?"/records/delete":`/records/${r}`,c={headers:Object.assign({},f(s)),method:i?"PUT":"DELETE",requestData:i?{limit:1e3,where:{$id:{$in:r}}}:void 0},d=typeof e=="function"?u():"";e==null||e({requestId:d,path:n,...c});let o=await a(n,c);return e==null||e({requestId:d,path:n,...c,responseData:o.data}),o},async detach(r,t,s,i){let n=m(i),d=`/records/${q(r)}/relations`,o={headers:Object.assign({},f(n)),method:"PUT",requestData:{targetIds:t,...(s==null?void 0:s.typeOrTypes)&&{typeOrTypes:s.typeOrTypes},...(s==null?void 0:s.direction)&&{direction:s.direction}}},p=typeof e=="function"?u():"";e==null||e({requestId:p,path:d,...o});let y=await a(d,o);return e==null||e({requestId:p,path:d,...o,responseData:y.data}),y},async export(r,t){let s=m(t),i="/records/export/csv",n={headers:Object.assign({},f(s)),method:"POST",requestData:r},c=typeof e=="function"?u():"";e==null||e({requestId:c,path:i,...n});let d=await a(i,n);return e==null||e({requestId:c,path:i,...n,responseData:d.data}),d},async find(r,t){let s=m(t),i=r!=null&&r.id?`/records/${r.id}/search`:"/records/search",n={headers:Object.assign({},f(s)),method:"POST",requestData:r==null?void 0:r.searchParams},c=typeof e=="function"?u():"";e==null||e({requestId:c,path:i,...n});let d=await a(i,n);return e==null||e({requestId:c,path:i,...n,responseData:d.data}),d},async findById(r,t){let s=m(t),i=l(r)?"/records":`/records/${r}`,n={headers:Object.assign({},f(s)),method:l(r)?"POST":"GET",requestData:l(r)?{ids:r}:void 0},c=typeof e=="function"?u():"";e==null||e({requestId:c,path:i,...n});let d=await a(i,n);return e==null||e({requestId:c,path:i,...n,responseData:d.data}),d},async findOne(r,t){let s=m(t),i="/records/search",n={headers:Object.assign({},f(s)),method:"POST",requestData:{...r,limit:1,skip:0}},c=typeof e=="function"?u():"";e==null||e({requestId:c,path:i,...n});let d=await a(i,n);e==null||e({requestId:c,path:i,...n,responseData:d.data});let[o]=d.data;return{...d,data:o}},async findUniq(r,t){let s=m(t),i="/records/search",n={headers:Object.assign({},f(s)),method:"POST",requestData:{...r,limit:1,skip:0}},c=typeof e=="function"?u():"";e==null||e({requestId:c,path:i,...n});let d=await a(i,n);if(e==null||e({requestId:c,path:i,...n,responseData:d.data}),typeof d.total<"u"&&d.total>1)throw new M(d.total,r);let[o]=d.data;return{...d,data:o}},async properties(r,t){let s=m(t),n=`/records/${q(r)}/properties`,c={headers:Object.assign({},f(s)),method:"GET"},d=typeof e=="function"?u():"";e==null||e({requestId:d,path:n,...c});let o=await a(n,c);return e==null||e({requestId:d,path:n,...c,responseData:o.data}),o},async relations(r,t){let s=m(t),n=`/records/${q(r)}/relations`,c={headers:Object.assign({},f(s)),method:"GET"},d=typeof e=="function"?u():"";e==null||e({requestId:d,path:n,...c});let o=await a(n,c);return e==null||e({requestId:d,path:n,...c,responseData:o.data}),o},async set(r,t,s){let i=m(s),c=`/records/${q(r)}`,d={headers:Object.assign({},f(i)),method:"PUT",requestData:t instanceof w?t.toJson():t},o=typeof e=="function"?u():"";e==null||e({requestId:o,path:c,...d});let p=await a(c,d);return e==null||e({requestId:o,path:c,...d,responseData:p.data}),p},async update(r,t,s){let i=m(s),c=`/records/${q(r)}`,d={headers:Object.assign({},f(i)),method:"PATCH",requestData:t instanceof w?t.toJson():t},o=typeof e=="function"?u():"";e==null||e({requestId:o,path:c,...d});let p=await a(c,d);return e==null||e({requestId:o,path:c,...d,responseData:p.data}),p}},relations:{async find(r,t,s){let i=m(s),n=new URLSearchParams;(t==null?void 0:t.limit)!==void 0&&n.append("limit",t.limit.toString()),(t==null?void 0:t.skip)!==void 0&&n.append("skip",t.skip.toString());let d=`/records/relations/search${n.toString()?"?"+n.toString():""}`,o={headers:Object.assign({},f(i)),method:"POST",requestData:r},p=typeof e=="function"?u():"";e==null||e({requestId:p,path:d,...o});let y=await a(d,o);return e==null||e({requestId:p,path:d,...o,responseData:y.data}),y}},tx:{async begin(r={}){let t="/tx",s={method:"POST",requestData:r},i=typeof e=="function"?u():"";e==null||e({requestId:i,path:t,...s});let n=await a(t,s);return e==null||e({requestId:i,path:t,...s,responseData:n.data}),n},async commit(r){let t=`/tx/${r}/commit`,s={method:"POST",requestData:{}},i=typeof e=="function"?u():"";e==null||e({requestId:i,path:t,...s});let n=await a(t,s);return e==null||e({requestId:i,path:t,...s,responseData:n.data}),n},async get(r){let t=`/tx/${r}`,s={method:"GET"},i=typeof e=="function"?u():"";e==null||e({requestId:i,path:t,...s});let n=await a(t,s);return e==null||e({requestId:i,path:t,...s,responseData:n.data}),n},async rollback(r){let t=`/tx/${r}/rollback`,s={method:"POST",requestData:{}},i=typeof e=="function"?u():"";e==null||e({requestId:i,path:t,...s});let n=await a(t,s);e==null||e({requestId:i,path:t,...s,responseData:n.data})}}});var C=class{constructor(e,r){this.relations={find:async({pagination:e,search:r,transaction:t})=>{let{searchParams:s}=U(r),i=v(t);return await this.api.relations.find(s,e,i)}};this.properties={delete:async(e,r)=>{var t;return(t=this.api)==null?void 0:t.properties.delete(e,r)},find:async(e,r)=>{var t;return(t=this.api)==null?void 0:t.properties.find(e,r)},findById:async(e,r)=>{var t;return(t=this.api)==null?void 0:t.properties.findById(e,r)},values:async(e,r,t)=>{var s;return(s=this.api)==null?void 0:s.properties.values(e,r,t)}};this.labels={find:async(e,r)=>this.api.labels.find(e,r)};this.tx={begin:async e=>{var s;let r=await((s=this.api)==null?void 0:s.tx.begin(e)),t=new b(r.data.id);return t.init(this),t},commit:async e=>{var r;return(r=this.api)==null?void 0:r.tx.commit(e)},get:async e=>{var s;let r=await((s=this.api)==null?void 0:s.tx.get(e)),t=new b(r.data.id);return t.init(this),t},rollback:async e=>{var r;return(r=this.api)==null?void 0:r.tx.commit(e)}};if(this.fetcher=null,r!=null&&r.httpClient){let t=we(r);this.fetcher=ye({httpClient:r.httpClient,token:e,url:t})}this.api=xe(this.fetcher,r==null?void 0:r.logger),this.records={attach:async(t,s,i,n)=>{var c,d;if(s instanceof h){let o=(c=s.data)==null?void 0:c.__id;if(o)return await this.api.records.attach(t,o,i,n);throw new T("Attach error: Target id is empty")}else if(l(s)&&s.every(o=>o instanceof h)){let o=s.map(p=>{var y;return(y=p.data)==null?void 0:y.__id}).filter(pe);if(o.length)return await this.api.records.attach(t,o,i,n);throw new T("Attach error: Target ids are empty")}else if(s instanceof x){let o=(d=s.data)==null?void 0:d.map(p=>p.__id).filter(Boolean);if(o!=null&&o.length)return await this.api.records.attach(t,o,i,n);throw new T("Attach error: Target ids are empty")}else{if(R(s)&&"__id"in s)return await this.api.records.attach(t,s.__id,i,n);if(l(s)&&s.every(o=>R(o)&&"__id"in o)){let o=s==null?void 0:s.map(p=>p.__id).filter(Boolean);if(o!=null&&o.length)return await this.api.records.attach(t,o,i,n);throw new T("Attach error: Target ids are empty")}else return await this.api.records.attach(t,s,i,n)}},create:async(t,s,i)=>{var c,d;let n;if(t instanceof w&&(n=await((c=this.api)==null?void 0:c.records.create(t,v(s)))),!n&&B(t)){if(V(s)){let o=Te({label:t,payload:s});n=await((d=this.api)==null?void 0:d.records.create(new w(o),i))}else if(R(s))throw Error("Provided data is not a flat object. Consider to use `createMany` method.")}if(n!=null&&n.success&&(n!=null&&n.data)){let o=new h(n.data);return o.init(this),o}return new h},createMany:async(t,s,i)=>{var c,d;let n;if(t instanceof A&&(n=await((c=this.api)==null?void 0:c.records.createMany(t,v(s)))),!n&&B(t)&&(l(s)||R(s))){let o=new A({label:t,payload:s});n=await((d=this.api)==null?void 0:d.records.createMany(o,i))}if(n!=null&&n.success&&(n!=null&&n.data)){let o=new x(n.data,n.total);return o.init(this),o}return new x([])},delete:async(t,s)=>{var i,n;if(O(t.where)&&!((i=r==null?void 0:r.options)!=null&&i.allowForceDelete))throw new T("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");return(n=this.api)==null?void 0:n.records.delete(t,s)},deleteById:async(t,s)=>{var i;return(i=this.api)==null?void 0:i.records.deleteById(t,s)},detach:async(t,s,i,n)=>{var c,d;if(s instanceof h){let o=(c=s.data)==null?void 0:c.__id;if(o)return await this.api.records.detach(t,o,i,n);throw new T("Detach error: Target id is empty")}else if(l(s)&&s.every(o=>o instanceof h)){let o=s.map(p=>{var y;return(y=p.data)==null?void 0:y.__id}).filter(Boolean);if(o.length)return await this.api.records.detach(t,o,i,n);throw new T("Detach error: Target ids are empty")}else if(s instanceof x){let o=(d=s.data)==null?void 0:d.map(p=>p.__id).filter(Boolean);if(o!=null&&o.length)return await this.api.records.detach(t,o,i,n);throw new T("Detach error: Target ids are empty")}else{if(R(s)&&"__id"in s)return await this.api.records.detach(t,s.__id,i,n);if(l(s)&&s.every(o=>R(o)&&"__id"in o)){let o=s==null?void 0:s.map(p=>p.__id).filter(Boolean);if(o!=null&&o.length)return await this.api.records.detach(t,o,i,n);throw new T("Detach error: Target ids are empty")}else return await this.api.records.detach(t,s,i,n)}},export:async(t,s)=>{var i;return(i=this.api)==null?void 0:i.records.export(t,s)},find:async(t,s,i)=>{var S;let n=Q(s),{id:c,searchParams:d}=U(t,s),o=n?s:i,p=await((S=this.api)==null?void 0:S.records.find({id:c,searchParams:d},o)),y=new x(p.data,p.total,s);return y.init(this),y},findById:async(t,s)=>{var i,n;if(l(t)){let c=await((i=this.api)==null?void 0:i.records.findById(t,s)),d=new x(c.data,c.total);return d.init(this),d}else{let c=await((n=this.api)==null?void 0:n.records.findById(t,s)),d=new h(c.data);return d.init(this),d}},findOne:async(t,s,i)=>{var y;let n=Q(s),{searchParams:c}=U(t,s),d=n?s:i,o=await((y=this.api)==null?void 0:y.records.findOne(c,d)),p=new h(o.data);return p.init(this),p},findUniq:async(t,s,i)=>{var y;let n=Q(s),{searchParams:c}=U(t,s),d=n?s:i,o=await((y=this.api)==null?void 0:y.records.findUniq(c,d)),p=new h(o.data);return p.init(this),p},properties:async(t,s)=>{var i;return(i=this.api)==null?void 0:i.records.properties(t,s)},relations:async(t,s)=>await this.api.records.relations(t,s),set:async(t,s,i)=>{var c,d;let n;if(s instanceof w)n=await((c=this.api)==null?void 0:c.records.set(t,s,i));else if(V(s)){let o=K(s);n=await((d=this.api)==null?void 0:d.records.set(t,new w({properties:o}),i))}else if(R(s))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");if(n!=null&&n.success&&(n!=null&&n.data)){let o=new h(n.data);return o.init(this),o}return new h},update:async(t,s,i)=>{var c,d;let n;if(s instanceof w)n=await((c=this.api)==null?void 0:c.records.update(t,s,i));else if(V(s)){let o=K(s),p=new w({properties:o});n=await((d=this.api)==null?void 0:d.records.update(t,p,i))}else if(R(s))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");if(n!=null&&n.success&&(n!=null&&n.data)){let o=new h(n.data);return o.init(this),o}return new h}}}};var De=a=>{class e extends C{constructor(t,s){var n;let i=he(s);super(t,{...i,httpClient:(n=i.httpClient)!=null?n:a}),this.state={debug:!1,timeout:fe("timeout",i.timeout,8e4),token:t},this.models=new Map,e.instance=this}static getInstance(){return e.instance}registerModel(t){let s=t.getLabel();return t.init(this),this.models.set(s,t),t}getModels(){return this.models}getModel(t){return this.models.get(t)}toInstance(t){let s=new h(t);return s.init(this),s}}return e};var Y=class extends E{constructor(e,r,t){super(),this.label=e,this.schema=r,t==null||t.registerModel(this)}getLabel(){return this.label}async find(e,r){var s;let t=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.find(this.label,t,r)}async findOne(e,r){var s;let t=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.findOne(this.label,t,r)}async findById(e,r){return this.findOne({where:{$id:e}},r)}async findUniq(e,r){var s;let t=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.findUniq(this.label,t,r)}async create(e,r){var i;let t=await W(this.schema,e),s=te(this.schema,t);if(!O(s)){let n=r!=null?r:await this.apiProxy.tx.begin(),c=await this.find({where:s},n),d=typeof r<"u";if(!((i=c==null?void 0:c.data)!=null&&i.length)){let p=await this.apiProxy.records.create(this.label,t,n);return d||await n.commit(),p}else throw d||await n.commit(),new D(this.label,s)}return await this.apiProxy.records.create(this.label,t,r)}attach(e,r,t,s){return this.apiProxy.records.attach(e,r,t,s)}detach(e,r,t,s){return this.apiProxy.records.detach(e,r,t,s)}async handleSetOrUpdate(e,r,t,s){var c;let i=await W(this.schema,r),n=te(this.schema,i);if(!O(n)){let d=s!=null?s:await this.apiProxy.tx.begin(),o=await this.find({where:n},d),p=typeof s<"u";if(!((c=o==null?void 0:o.data)!=null&&c.length)||o.data.length===1&&o.data[0].__id===e){let S=await this.apiProxy.records[t](e,i,d);return p||await d.commit(),S}else throw p||await d.commit(),new D(this.label,n)}return await this.apiProxy.records[t](e,i,s)}async set(e,r,t){return await this.handleSetOrUpdate(e,r,"set",t)}async update(e,r,t){return await this.handleSetOrUpdate(e,r,"update",t)}async createMany(e,r){var i;let t=typeof r<"u",s=r!=null?r:await this.apiProxy.tx.begin();try{let n=await Promise.all(e.map(async o=>await W(this.schema,o))),c=ue(n,this.schema,this.label);if(!O(c)){let o=Object.entries(c).map(([y,S])=>({[y]:{$in:S}})),p=await this.find({where:{$or:o}},s);if((i=p==null?void 0:p.data)!=null&&i.length)throw new D(this.label,Object.keys(c))}let d=await this.apiProxy.records.createMany(this.label,n,s);return t||await s.commit(),d}catch(n){throw t||await s.rollback(),n}}async delete(e,r){if(O(e.where))throw new T(`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 this.apiProxy.records.delete({...e,labels:[this.label]},r)}async deleteById(e,r){return await this.apiProxy.records.deleteById(e,r)}};var be=De(new $);var $e=be;0&&(module.exports={DBRecordDraft,DBRecordInstance,DBRecordsArrayInstance,DBRecordsBatchDraft,EmptyTargetError,HttpClient,HttpClientResponse,Model,NonUniqueResultError,RestAPI,RushDB,Transaction,UniquenessError,idToDate,idToTimestamp});
1
+ "use strict";var me=Object.create;var M=Object.defineProperty;var ge=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var Se=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var Te=(n,e)=>{for(var t in e)M(n,t,{get:e[t],enumerable:!0})},re=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of fe(e))!Re.call(n,s)&&s!==t&&M(n,s,{get:()=>e[s],enumerable:!(r=ge(e,s))||r.enumerable});return n};var se=(n,e,t)=>(t=n!=null?me(Se(n)):{},re(e||!n||!n.__esModule?M(t,"default",{value:n,enumerable:!0}):t,n)),De=n=>re(M({},"__esModule",{value:!0}),n);var Me={};Te(Me,{DBRecordInstance:()=>g,DBRecordsArrayInstance:()=>O,EmptyTargetError:()=>D,HttpClient:()=>w,HttpClientResponse:()=>U,Model:()=>Z,NonUniqueResultError:()=>q,RestAPI:()=>_,RushDB:()=>ue,Transaction:()=>A,UniquenessError:()=>I,default:()=>je,idToDate:()=>z,idToTimestamp:()=>$,initSDK:()=>X,mergeDefaultsWithPayload:()=>j,parseConfig:()=>J,pickUniqFieldsFromRecord:()=>Q,pickUniqFieldsFromRecords:()=>Y,validateInteger:()=>G});module.exports=De(Me);var w=class n{makeRequest(e,{headers:t,method:r,protocol:s,requestData:o,timeout:a}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(n.TIMEOUT_ERROR_CODE);return e.code=n.TIMEOUT_ERROR_CODE,e}};w.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];w.TIMEOUT_ERROR_CODE="ETIMEDOUT";var k=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.")}},U=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=se(require("http"),1),W=se(require("https"),1);var xe="string",we="datetime",be="boolean",Ie="number",Pe="null",Oe="vector",ne=[xe,we,be,Ie,Pe,Oe];var ae=N.default||N,oe=W.default||W,Ee=new ae.Agent({keepAlive:!0}),_e=new oe.Agent({keepAlive:!0}),L=class extends w{constructor(e){super(),this._agent=e}makeRequest(e,{headers:t,method:r,protocol:s,requestData:o,timeout:a}){let i=new URL(e),d=s==="http"||i.protocol==="http:",c=this._agent;return c||(c=d?Ee:_e),new Promise((p,l)=>{let h=(d?ae:oe).request({agent:c,ciphers:"DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5",headers:t,host:i.hostname,method:r,path:i.pathname+i.search,port:i.port});h.setTimeout(a!=null?a:8e4,()=>{h.destroy(w.makeTimeoutError())}),h.on("response",y=>{p(new v(y))}),h.on("error",y=>{l(y)}),h.once("socket",y=>{let T=o?JSON.stringify(o):"";y.connecting?y.once(d?"connect":"secureConnect",()=>{h.write(T),h.end()}):(h.write(T),h.end())})})}},v=class extends k{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 S=n=>typeof n=="object"&&Array.isArray(n)&&n!==null,R=n=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",E=n=>R(n)&&Object.keys(n).length===0,ie=n=>typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null,K=n=>S(n)?n.every(ie):ie(n),F=n=>R(n)&&Object.values(n).every(K),b=n=>typeof n=="string",H=n=>{if(typeof n=="string"){if(n.toLowerCase()==="true")return!0;if(n.toLowerCase()==="false")return!1}return S(n)&&n.length===0||R(n)&&Object.keys(n).length===0?!1:!!n};var Ce={"Content-Type":"application/json"},ce=({httpClient:n,token:e,url:t})=>async(r,{headers:s,...o})=>{let a=await n.makeRequest(`${t}${r}`,{credentials:"omit",headers:Object.assign({...Ce,...s},typeof e<"u"?{token:e}:{}),...o});if(a.getStatusCode()>=200&&a.getStatusCode()<300)return await a.toJSON();throw new Error(`${a.getStatusCode()}`)};var I=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)}},D=class n extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,n.prototype)}},q=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 P=class{constructor(){this.apiProxy={};return new Proxy(this,{get:(e,t,r)=>{if(t in e)return Reflect.get(e,t,r);if(this.apiProxy&&t in this.apiProxy)return Reflect.get(this.apiProxy,t,r)}})}init(e){this.apiProxy=e}};var V=["httpClient","timeout","host","port","protocol","url","logger","options"];var j=async(n,e)=>{let t=Object.entries(n).map(async([o,a])=>a.default&&typeof a.default<"u"&&typeof e[o]>"u"?{key:o,value:typeof a.default=="function"?await a.default():a.default}:{key:o,value:void 0});return{...(await Promise.all(t)).reduce((o,{key:a,value:i})=>(i!==void 0&&(o[a]=i),o),{}),...e}},Q=(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),{}),Y=(n,e,t)=>{let r={},s=Object.entries(e).filter(([,o])=>o.uniq).reduce((o,[a])=>(o[a]=!0,o),{});return n.forEach(o=>{Object.entries(o).forEach(([a,i])=>{if(a in s)if(r[a]){if(r[a].includes(i))throw new I(t,{[a]:i});r[a]=[...r[a],i]}else r[a]=[i]})}),r},J=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 G(n,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${n} must be an integer`)}return e}function $(n){let e=n.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function z(n){return new Date($(n))}var g=class extends P{constructor(e){super(),this.data=e}id(){try{return this.data.__id}catch{throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.")}}label(){try{return this.data.__label}catch{throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.")}}proptypes(){try{return this.data.__proptypes}catch{throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.")}}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 $(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}async delete(e){if(!this.data)throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return await this.apiProxy.records.deleteById(this.id(),e)}async update(e,t){if(!this.data)throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return this.apiProxy.records.update({label:this.label(),target:this.id(),data:e},t)}async set(e,t){if(!this.data)throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return this.apiProxy.records.set({label:this.label(),target:this.id(),data:e},t)}async attach(e,t,r){if(!this.data)throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return this.apiProxy.records.attach({source:this.id(),target:e,options:t},r)}async detach(e,t,r){if(!this.data)throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return this.apiProxy.records.detach({source:this.id(),target:e,options:t},r)}},O=class extends P{constructor(e,t,r){super(),this.data=e,this.total=t,this.searchQuery=r}};var A=class extends P{constructor(e){super(),this.id=e}async rollback(){return await this.apiProxy.tx.rollback(this.id)}async commit(){return await this.apiProxy.tx.commit(this.id)}};var de="api.rushdb.com";var pe="https",le="/api/v1";var f=n=>n?{"x-transaction-id":n}:void 0,qe=n=>b(n)||n instanceof A,m=n=>qe(n)?n instanceof A?n.id:n:void 0,he=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),x=n=>{if(b(n)&&he(n))return n;if(n instanceof g&&n.data)return n.data.__id;if(R(n)&&"__id"in n&&he(n.__id))return n.__id},C=n=>!(!R(n)||R(n)&&"name"in n&&!b(n.name)||R(n)&&"type"in n&&(!b(n.type)||!ne.includes(n.type))||!("value"in n)||!K(n.value)||"metadata"in n&&!b(n.metadata)||"valueSeparator"in n&&!b(n.valueSeparator)),ye=n=>{let e=pe,t=de,r=443,s=le;if("url"in n){let a=new URL(n.url);e=a.protocol.replace(":",""),t=a.hostname,r=parseInt(a.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 o="";return e==="http"&&r===80||e==="https"&&r===443||(o=":"+r),`${e}://${t}${o}${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 l,h;let o=m(s),i=`/relationships/${x(e)}`,d={headers:Object.assign({},f(o)),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}}},c=typeof this.logger=="function"?u():"";(l=this.logger)==null||l.call(this,{requestId:c,path:i,...d});let p=await this.fetcher(i,d);return(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d,responseData:p.data}),p},detach:async({source:e,target:t,options:r},s)=>{var l,h;let o=m(s),i=`/relationships/${x(e)}`,d={headers:Object.assign({},f(o)),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}}},c=typeof this.logger=="function"?u():"";(l=this.logger)==null||l.call(this,{requestId:c,path:i,...d});let p=await this.fetcher(i,d);return(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d,responseData:p.data}),p},create:async({label:e,data:t,options:r},s)=>{var p,l;let o=m(s),a="/records",i={headers:Object.assign({},f(o)),method:"POST",requestData:{}},d=typeof this.logger=="function"?u():"";if(S(t)&&t.every(C))i.requestData={label:e,properties:t};else if(F(t))i.requestData={label:e,payload:t,options:r};else if(R(t))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(p=this.logger)==null||p.call(this,{requestId:d,path:a,...i});let c=await this.fetcher(a,i);if((l=this.logger)==null||l.call(this,{requestId:d,path:a,...i,responseData:c.data}),c!=null&&c.success&&(c!=null&&c.data)){let h=new g(c.data);return h.init(this),h}return new g},createMany:async(e,t)=>{var d,c;let r=m(t),s="/records/import/json",o={headers:Object.assign({},f(r)),method:"POST",requestData:e},a=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);if((c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i!=null&&i.success&&(i!=null&&i.data)){let p=i.data.map(h=>{let y=new g(h);return y.init(this),y}),l=new O(p,i.total);return l.init(this),l}return new O([])},delete:async(e,t)=>{var d,c,p;if(E(e.where)&&!((d=this==null?void 0:this.options)!=null&&d.allowForceDelete))throw new D("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let r=m(t),s="/records/delete",o={headers:Object.assign({},f(r)),method:"PUT",requestData:e},a=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(p=this.logger)==null||p.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},deleteById:async(e,t)=>{var c,p;let r=m(t),s=S(e),o=s?"/records/delete":`/records/${e}`,a={headers:Object.assign({},f(r)),method:s?"PUT":"DELETE",requestData:s?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:i,path:o,...a});let d=await this.fetcher(o,a);return(p=this.logger)==null||p.call(this,{requestId:i,path:o,...a,responseData:d.data}),d},export:async(e,t)=>{var d,c;let r=m(t),s="/records/export/csv",o={headers:Object.assign({},f(r)),method:"POST",requestData:e},a=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},find:async(e,t)=>{var h,y;let{id:r,...s}=e,o=m(t),a=r?`/records/${r}/search`:"/records/search",i={headers:Object.assign({},f(o)),method:"POST",requestData:s},d=typeof this.logger=="function"?u():"";(h=this.logger)==null||h.call(this,{requestId:d,path:a,...i});let c=await this.fetcher(a,i);(y=this.logger)==null||y.call(this,{requestId:d,path:a,...i,responseData:c.data});let p=c.data.map(T=>{let B=new g(T);return B.init(this),B}),l=new O(p,c.total,e);return l.init(this),l},findById:async(e,t)=>{var d,c;let r=m(t),s=S(e)?"/records":`/records/${e}`,o={headers:Object.assign({},f(r)),method:S(e)?"POST":"GET",requestData:S(e)?{ids:e}:void 0},a=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);if((c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),S(e)){let p=i.data.map(h=>{let y=new g(h);return y.init(this),y}),l=new O(p,i.total);return l.init(this),l}else{let p=new g(i.data);return p.init(this),p}},findOne:async(e,t)=>{var p,l;let r=m(t),s="/records/search",o={headers:Object.assign({},f(r)),method:"POST",requestData:{...e,limit:1,skip:0}},a=typeof this.logger=="function"?u():"";(p=this.logger)==null||p.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);(l=this.logger)==null||l.call(this,{requestId:a,path:s,...o,responseData:i.data});let[d]=i.data,c=new g(d);return c.init(this),c},findUniq:async(e,t)=>{var p,l;let r=m(t),s="/records/search",o={headers:Object.assign({},f(r)),method:"POST",requestData:{...e,limit:1,skip:0}},a=typeof this.logger=="function"?u():"";(p=this.logger)==null||p.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);if((l=this.logger)==null||l.call(this,{requestId:a,path:s,...o,responseData:i.data}),typeof i.total<"u"&&i.total>1)throw new q(i.total,e);let[d]=i.data,c=new g(d);return c.init(this),c},set:async({target:e,label:t,data:r,options:s},o)=>{var h,y;let a=m(o),d=`/records/${x(e)}`,c={headers:Object.assign({},f(a)),method:"PUT",requestData:{}},p=typeof this.logger=="function"?u():"";if(S(r)&&r.every(C))c.requestData={label:t,properties:r};else if(F(r))c.requestData={label:t,data:r,options:s};else if(R(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(h=this.logger)==null||h.call(this,{requestId:p,path:d,...c});let l=await this.fetcher(d,c);if((y=this.logger)==null||y.call(this,{requestId:p,path:d,...c,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)){let T=new g(l.data);return T.init(this),T}return new g},update:async({target:e,label:t,data:r,options:s},o)=>{var h,y;let a=m(o),d=`/records/${x(e)}`,c={headers:Object.assign({},f(a)),method:"PATCH",requestData:{}},p=typeof this.logger=="function"?u():"";if(S(r)&&r.every(C))c.requestData={label:t,properties:r};else if(F(r))c.requestData={label:t,data:r,options:s};else if(R(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(h=this.logger)==null||h.call(this,{requestId:p,path:d,...c});let l=await this.fetcher(d,c);if((y=this.logger)==null||y.call(this,{requestId:p,path:d,...c,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)){let T=new g(l.data);return T.init(this),T}return new g}};this.relationships={find:async(e,t)=>{var p,l;let r=m(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 a=`/relationships/search${s.toString()?"?"+s.toString():""}`,i={headers:Object.assign({},f(r)),method:"POST",requestData:e},d=typeof this.logger=="function"?u():"";(p=this.logger)==null||p.call(this,{requestId:d,path:a,...i});let c=await this.fetcher(a,i);return(l=this.logger)==null||l.call(this,{requestId:d,path:a,...i,responseData:c.data}),c}};this.properties={delete:async(e,t)=>{var d,c;let r=m(t),s=`/properties/${e}`,o={headers:Object.assign({},f(r)),method:"DELETE"},a=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},find:async(e,t)=>{var d,c;let r=m(t),s="/properties/search",o={headers:Object.assign({},f(r)),method:"POST",requestData:e},a=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},findById:async(e,t)=>{var d,c;let r=m(t),s=`/properties/${e}`,o={headers:Object.assign({},f(r)),method:"GET"},a=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},values:async(e,t,r)=>{var ee,te;let s=m(r),o=`/properties/${e}/values`,{sort:a,skip:i,limit:d,query:c}=t!=null?t:{},p=new URLSearchParams;a!==void 0&&p.append("sort",a),i!==void 0&&p.append("skip",i.toString()),d!==void 0&&p.append("limit",d.toString()),c!==void 0&&p.append("query",c);let l=p.toString(),h=l?`${o}?${l}`:o,y={headers:Object.assign({},f(s)),method:"GET"},T=typeof this.logger=="function"?u():"";(ee=this.logger)==null||ee.call(this,{requestId:T,path:o,...y});let B=await this.fetcher(h,y);return(te=this.logger)==null||te.call(this,{requestId:T,path:h,...y,responseData:B.data}),B}};this.labels={find:async(e,t)=>{var d,c;let r=m(t),s="/labels/search",o={headers:Object.assign({},f(r)),method:"POST",requestData:e},a=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i}};this.tx={begin:async e=>{var i,d;let t="/tx",r={method:"POST",requestData:e},s=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:s,path:t,...r});let o=await this.fetcher(t,r);(d=this.logger)==null||d.call(this,{requestId:s,path:t,...r,responseData:o.data});let a=new A(o.data.id);return a.init(this),a},commit:async e=>{var i,d;let r=`/tx/${m(e)}/commit`,s={method:"POST",requestData:{}},o=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:o,path:r,...s});let a=await this.fetcher(r,s);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...s,responseData:a.data}),a},get:async e=>{var d,c;let r=`/tx/${m(e)}`,s={method:"GET"},o=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:o,path:r,...s});let a=await this.fetcher(r,s);(c=this.logger)==null||c.call(this,{requestId:o,path:r,...s,responseData:a.data});let i=new A(a.data.id);return i.init(this),i},rollback:async e=>{var i,d;let r=`/tx/${m(e)}/rollback`,s={method:"POST",requestData:{}},o=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:o,path:r,...s});let a=await this.fetcher(r,s);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...s,responseData:a.data}),a}};if(this.fetcher=null,t!=null&&t.httpClient){let r=ye(t);this.fetcher=ce({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=x(e);if(!s)throw new D(`${t} error: Target id is empty`);return[s]}if(S(e)&&e.every(s=>s instanceof g)){let s=e.map(x).filter(H);if(!s.length)throw new D(`${t} error: Target ids are empty`);return s}if(e instanceof O){let s=(r=e.data)==null?void 0:r.map(x).filter(H);if(!(s!=null&&s.length))throw new D(`${t} error: Target ids are empty`);return s}if(R(e)&&"__id"in e)return[e.__id];if(S(e)&&e.every(s=>R(s)&&"__id"in s)){let s=e.map(x).filter(H);if(!s.length)throw new D(`${t} error: Target ids are empty`);return s}return S(e)?e:b(e)?[e]:[]}};var X=n=>{class e extends _{constructor(r,s){var a;let o=J(s);super(r,{...o,httpClient:(a=o.httpClient)!=null?a:n}),this.state={debug:!1,timeout:G("timeout",o.timeout,8e4),token:r},this.models=new Map,e.instance=this}static getInstance(){return e.instance}registerModel(r){let s=r.getLabel();return r.init(this),this.models.set(s,r),r}getModels(){return this.models}getModel(r){return this.models.get(r)}toInstance(r){let s=new g(r);return s.init(this),s}}return e};var Z=class extends P{constructor(e,t,r){super(),this.label=e,this.schema=t,this.rushDBInstance=r,r==null||r.registerModel(this)}getLabel(){return this.label}toInstance(e){if(this.rushDBInstance)return this.rushDBInstance.toInstance(e);throw new Error("No RushDB instance was provided during model initialization.")}async find(e,t){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.find({...r,labels:[this.label]},t)}async findOne(e,t){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.findOne({...r,labels:[this.label]},t)}async findById(e,t){return this.findOne({where:{$id:e}},t)}async findUniq(e,t){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.findUniq({...r,labels:[this.label]},t)}async create(e,t){var o;let r=await j(this.schema,e),s=Q(this.schema,r);if(!E(s)){let a=t!=null?t:await this.apiProxy.tx.begin(),i=await this.find({where:s},a),d=typeof t<"u";if(!((o=i==null?void 0:i.data)!=null&&o.length)){let p=await this.apiProxy.records.create({label:this.label,data:r},a);return d||await a.commit(),p}else throw d||await a.commit(),new I(this.label,s)}return await this.apiProxy.records.create({label:this.label,data:r},t)}attach({source:e,target:t,options:r},s){return this.apiProxy.records.attach({source:e,target:t,options:r},s)}detach({source:e,target:t,options:r},s){return this.apiProxy.records.detach({source:e,target:t,options:r},s)}async handleSetOrUpdate(e,t,r,s){var i,d;if(S(t)&&t.every(C))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let o=await j(this.schema,t),a=Q(this.schema,o);if(!E(a)){let c=s!=null?s:await this.apiProxy.tx.begin(),p=await this.find({where:a},c),l=typeof s<"u";if(!((i=p==null?void 0:p.data)!=null&&i.length)||p.data.length===1&&((d=p.data[0])==null?void 0:d.id())===x(e)){let y=await this.apiProxy.records[r]({target:e,label:this.label,data:o},c);return l||await c.commit(),y}else throw l||await c.commit(),new I(this.label,a)}return await this.apiProxy.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=typeof t<"u",s=t!=null?t:await this.apiProxy.tx.begin();try{let a=await Promise.all(e.map(async c=>await j(this.schema,c))),i=Y(a,this.schema,this.label);if(!E(i)){let c=Object.entries(i).map(([l,h])=>({[l]:{$in:h}})),p=await this.find({where:{$or:c}},s);if((o=p==null?void 0:p.data)!=null&&o.length)throw new I(this.label,Object.keys(i))}let d=await this.apiProxy.records.createMany({label:this.label,data:a},s);return r||await s.commit(),d}catch(a){throw r||await s.rollback(),a}}async delete(e,t){if(E(e.where))throw new D(`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 this.apiProxy.records.delete({...e,labels:[this.label]},t)}async deleteById(e,t){return await this.apiProxy.records.deleteById(e,t)}};var ue=X(new L);var je=ue;0&&(module.exports={DBRecordInstance,DBRecordsArrayInstance,EmptyTargetError,HttpClient,HttpClientResponse,Model,NonUniqueResultError,RestAPI,RushDB,Transaction,UniquenessError,idToDate,idToTimestamp,initSDK,mergeDefaultsWithPayload,parseConfig,pickUniqFieldsFromRecord,pickUniqFieldsFromRecords,validateInteger});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- var Oe=Object.defineProperty,Be=Object.defineProperties;var _e=Object.getOwnPropertyDescriptors;var W=Object.getOwnPropertySymbols;var pe=Object.prototype.hasOwnProperty,ye=Object.prototype.propertyIsEnumerable;var de=(r,e,a)=>e in r?Oe(r,e,{enumerable:!0,configurable:!0,writable:!0,value:a}):r[e]=a,m=(r,e)=>{for(var a in e||(e={}))pe.call(e,a)&&de(r,a,e[a]);if(W)for(var a of W(e))ye.call(e,a)&&de(r,a,e[a]);return r},f=(r,e)=>Be(r,_e(e));var ue=(r,e)=>{var a={};for(var s in r)pe.call(r,s)&&e.indexOf(s)<0&&(a[s]=r[s]);if(r!=null&&W)for(var s of W(r))e.indexOf(s)<0&&ye.call(r,s)&&(a[s]=r[s]);return a};var y=(r,e,a)=>new Promise((s,i)=>{var p=c=>{try{o(a.next(c))}catch(n){i(n)}},t=c=>{try{o(a.throw(c))}catch(n){i(n)}},o=c=>c.done?s(c.value):Promise.resolve(c.value).then(p,t);o((a=a.apply(r,e)).next())});var he=/^(?:\d{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:\d{2}(?:[02468][048]|[13579][26])-02-29))Schema(0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9])?(?:\.([0-9]{1,9}))?([zZ]?|([\+-])(((([0][0-9])|([1][0-3])):?(([03][0])|([14][5])))|14:00)?)$/;var j="string",me="datetime",z="boolean",Z="number",X="null";var A=class r{makeRequest(e,{headers:a,method:s,protocol:i,requestData:p,timeout:t}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(r.TIMEOUT_ERROR_CODE);return e.code=r.TIMEOUT_ERROR_CODE,e}};A.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];A.TIMEOUT_ERROR_CODE="ETIMEDOUT";var $=class{constructor(e,a){this._statusCode=e,this._headers=a}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.")}},g=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=class r extends A{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=r.makeFetchWithAbortTimeout(e):this._fetchFn=r.makeFetchWithRaceTimeout(e)}static makeFetchWithRaceTimeout(e){return(a,s,i)=>{let p,t=new Promise((c,n)=>{p=setTimeout(()=>{p=null,n(A.makeTimeoutError())},i)}),o=e(a,s);return Promise.race([o,t]).finally(()=>{p&&clearTimeout(p)})}}static makeFetchWithAbortTimeout(e){return(a,s,i)=>y(this,null,function*(){let p=new AbortController,t=setTimeout(()=>{t=null,p.abort(A.makeTimeoutError())},i);try{return yield e(a,f(m({},s),{signal:p.signal}))}catch(o){throw o.name==="AbortError"?A.makeTimeoutError():o}finally{t&&clearTimeout(t)}})}makeRequest(o,c){return y(this,arguments,function*(e,{headers:a,method:s,protocol:i,requestData:p,timeout:t}){let n=s=="POST"||s=="PUT"||s=="PATCH",d=JSON.stringify(p)||(n?"":void 0),u=yield this._fetchFn(e,{body:d,headers:a,method:s},t!=null?t:8e4);return new ee(u)})}},ee=class r extends ${constructor(e){super(e.status,r._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 a={};for(let s of e){if(!Array.isArray(s)||s.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.");a[s[0]]=s[1]}return a}};var b=r=>typeof r=="object"&&Array.isArray(r)&&r!==null,D=r=>r!==null&&Object.prototype.toString.call(r)==="[object Object]",q=r=>D(r)&&Object.keys(r).length===0,v=r=>D(r)&&Object.keys(r).every(e=>{let a=r[e];return b(a)?a.every(s=>typeof s=="string"||typeof s=="number"||typeof s=="boolean"||s===null):!(a&&typeof a=="object")}),k=r=>typeof r=="string",fe=r=>{if(typeof r=="string"){if(r.toLowerCase()==="true")return!0;if(r.toLowerCase()==="false")return!1}return b(r)&&r.length===0||D(r)&&Object.keys(r).length===0?!1:!!r};var Qe={"Content-Type":"application/json"},Se=({httpClient:r,token:e,url:a})=>(s,t)=>y(void 0,null,function*(){var o=t,{headers:i}=o,p=ue(o,["headers"]);let c=yield r.makeRequest(`${a}${s}`,m({credentials:"omit",headers:Object.assign(m(m({},Qe),i),typeof e!="undefined"?{token:e}:{})},p));if(c.getStatusCode()>=200&&c.getStatusCode()<300)return yield c.toJSON();throw new Error(`${c.getStatusCode()}`)});var B=class r extends Error{constructor(e,a){super(`Record with label "${e}" and properties ${JSON.stringify(a)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,r.prototype)}},P=class r extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,r.prototype)}},H=class r extends Error{constructor(e,a){super(`Expected a unique result but found ${e} matches for the provided search parameters: ${JSON.stringify(a)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,r.prototype)}};var _=class{constructor(){this.apiProxy={};return new Proxy(this,{get:(e,a,s)=>{if(a in e)return Reflect.get(e,a,s);if(this.apiProxy&&a in this.apiProxy)return Reflect.get(this.apiProxy,a,s)}})}init(e,a){this.apiProxy=e}};var te=["httpClient","timeout","host","port","protocol","url","logger","options"];var N=(r,e)=>y(void 0,null,function*(){let a=Object.entries(r).map(o=>y(void 0,[o],function*([p,t]){return t.default&&typeof t.default!="undefined"&&typeof e[p]=="undefined"?{key:p,value:typeof t.default=="function"?yield t.default():t.default}:{key:p,value:void 0}})),i=(yield Promise.all(a)).reduce((p,{key:t,value:o})=>(o!==void 0&&(p[t]=o),p),{});return m(m({},i),e)}),re=(r,e)=>Object.entries(e).filter(([a])=>{var s;return(s=r[a])==null?void 0:s.uniq}).reduce((a,[s,i])=>(s in r&&(a[s]=i),a),{}),le=(r,e,a)=>{let s={},i=Object.entries(e).filter(([p,t])=>t.uniq).reduce((p,[t])=>(p[t]=!0,p),{});return r.forEach(p=>{Object.entries(p).forEach(([t,o])=>{if(t in i)if(s[t]){if(s[t].includes(o))throw new B(a,{[t]:o});s[t]=[...s[t],o]}else s[t]=[o]})}),s},Re=r=>{if(!r)return{};if(!D(r))throw new Error("Config must be an object");if(Object.keys(r).filter(a=>!te.includes(a)).length>0)throw new Error(`Config object may only contain the following: ${te.join(", ")}`);return r};function Te(r,e,a){if(!Number.isInteger(e)){if(a!==void 0)return a;throw new Error(`${r} must be an integer`)}return e}function K(r){let e=r.split("-"),a=e[0]+e[1].slice(0,4);return parseInt(a,16)}function se(r){return new Date(K(r))}var Q=class{constructor({label:e,options:a={returnResult:!0,suggestTypes:!0},payload:s}){this.label=e,this.options=a,this.payload=s}toJson(){return{label:this.label,options:this.options,payload:this.payload}}},E=class{constructor({label:e,properties:a=[]}){this.label=e,this.properties=a}toJson(){return{label:this.label,properties:this.properties}}},w=class extends _{constructor(e){super(),this.data=e}get id(){try{return this.data.__id}catch(e){throw new Error("DBRecordInstance: Unable to access 'id'. The Record data is undefined.")}}get label(){try{return this.data.__label}catch(e){throw new Error("DBRecordInstance: Unable to access 'label'. The Record data is undefined.")}}get proptypes(){try{return this.data.__proptypes}catch(e){throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record data' is undefined.")}}get date(){try{return se(this.data.__id)}catch(e){throw new Error("DBRecordInstance: Unable to access 'date'. The Record data is undefined.")}}get timestamp(){try{return K(this.data.__id)}catch(e){throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record data is undefined.")}}delete(e){return y(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return yield this.apiProxy.records.deleteById(this.data.__id,e)})}update(e,a){return y(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return this.apiProxy.records.update(this.data.__id,e,a)})}set(e,a){return y(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return this.apiProxy.records.set(this.data.__id,e,a)})}attach(e,a,s){return y(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return this.apiProxy.records.attach(this.data.__id,e,a,s)})}detach(e,a,s){return y(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return this.apiProxy.records.detach(this.data.__id,e,a,s)})}},O=class extends _{constructor(e,a,s){super(),this.data=e,this.total=a,this.searchParams=s}};var C=class extends _{constructor(e){super(),this.id=e}rollback(){return y(this,null,function*(){return yield this.apiProxy.tx.rollback(this.id)})}commit(){return y(this,null,function*(){return yield this.apiProxy.tx.commit(this.id)})}};var we="api.rushdb.com";var xe="https",be="/api/v1";var R=r=>r?{"x-transaction-id":r}:void 0,M=r=>k(r)||r instanceof C,Y=r=>M(r)?r:void 0,T=r=>M(r)?r instanceof C?r.id:r:void 0,U=r=>{if(k(r))return r;if(r instanceof w&&r.data)return r.data.__id;if("__id"in r)return r.__id},L=(r,e)=>{var t,o,c;let a=k(r),s=qe(r),p=M(e)||!D(e);if(a){let n=s?{id:r}:{searchParams:{labels:[r]}};return p?f(m({},n),{searchParams:m({},n.searchParams)}):f(m({},n),{searchParams:f(m({},e),{labels:[...(o=(t=n.searchParams)==null?void 0:t.labels)!=null?o:[],...(c=e.labels)!=null?c:[]]})})}else return{searchParams:r!=null?r:{}}},qe=r=>/^[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(r),ke=r=>r.every(e=>typeof e==typeof r[0]),Me=r=>Array.isArray(r)?{isEmptyArray:r.length===0,isEmptyStringsArray:r.every(e=>e===""),isInconsistentArray:!ke(r)}:{isEmptyString:r===""},De=r=>typeof r===j?he.test(r)?me:j:typeof r===Z?Z:typeof r===z?z:r===null?X:j,Ue=(r,e)=>{let{isEmptyArray:a,isInconsistentArray:s}=Me(r);return a?{type:j,value:[]}:s||!e?{type:j,value:r.map(String)}:{type:De(r[0]),value:r}},Fe=(r,e)=>{if(!e)return{type:j,value:String(r)};let a=De(r);return{type:a,value:a===X?null:r}},J=(r,e={suggestTypes:!0})=>Object.entries(r).map(([a,s])=>{let{type:i,value:p}=b(s)?Ue(s,e.suggestTypes):Fe(s,e.suggestTypes);return{name:a,type:i,value:p}}),Pe=({label:r,options:e={suggestTypes:!0},payload:a})=>({label:r,properties:J(a,e)}),Ie=r=>{let e=xe,a=we,s=443,i=be;if("url"in r){let t=new URL(r.url);e=t.protocol.replace(":",""),a=t.hostname,s=parseInt(t.port||(e==="http"?"80":e==="https"?"443":""))}"host"in r&&"port"in r&&"protocol"in r&&(e=r.protocol.replace(":",""),a=r.host,s=r.port),i&&!i.startsWith("/")&&(i="/"+i);let p="";return e==="http"&&s===80||e==="https"&&s===443||(p=":"+s),`${e}://${a}${p}${i}`},l=(r=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",a="";for(let s=0;s<r;s++){let i=Math.floor(Math.random()*e.length);a+=e[i]}return a};var Ee=(r,e)=>({labels:{find(t,o){return y(this,null,function*(){let c=T(o),n="/labels",d={headers:Object.assign({},R(c)),method:"POST",requestData:t},u=typeof e=="function"?l():"";e==null||e(m({requestId:u,path:n},d));let h=yield r(n,d);return e==null||e(f(m({requestId:u,path:n},d),{responseData:h.data})),h})}},properties:{delete:(t,o)=>y(void 0,null,function*(){let c=T(o),n=`/properties/${t}`,d={headers:Object.assign({},R(c)),method:"DELETE"},u=typeof e=="function"?l():"";e==null||e(m({requestId:u,path:n},d));let h=yield r(n,d);return e==null||e(f(m({requestId:u,path:n},d),{responseData:h.data})),h}),find:(t,o)=>y(void 0,null,function*(){let c=T(o),n="/properties",d={headers:Object.assign({},R(c)),method:"POST",requestData:t},u=typeof e=="function"?l():"";e==null||e(m({requestId:u,path:n},d));let h=yield r(n,d);return e==null||e(f(m({requestId:u,path:n},d),{responseData:h.data})),h}),findById:(t,o)=>y(void 0,null,function*(){let c=T(o),n=`/properties/${t}`,d={headers:Object.assign({},R(c)),method:"GET"},u=typeof e=="function"?l():"";e==null||e(m({requestId:u,path:n},d));let h=yield r(n,d);return e==null||e(f(m({requestId:u,path:n},d),{responseData:h.data})),h}),values:(t,o,c)=>y(void 0,null,function*(){let n=T(c),d=`/properties/${t}/values`,{sort:u,skip:h,limit:S,query:x}=o!=null?o:{},I=new URLSearchParams;u!==void 0&&I.append("sort",u),h!==void 0&&I.append("skip",h.toString()),S!==void 0&&I.append("limit",S.toString()),x!==void 0&&I.append("query",x);let ae=I.toString(),ie=ae?`${d}?${ae}`:d,G={headers:Object.assign({},R(n)),method:"GET"},oe=typeof e=="function"?l():"";e==null||e(m({requestId:oe,path:d},G));let ce=yield r(ie,G);return e==null||e(f(m({requestId:oe,path:ie},G),{responseData:ce.data})),ce})},records:{attach(t,o,c,n){return y(this,null,function*(){let d=T(n),h=`/records/${U(t)}/relations`,S={headers:Object.assign({},R(d)),method:"POST",requestData:m(m({targetIds:o},(c==null?void 0:c.type)&&{type:c.type}),(c==null?void 0:c.direction)&&{direction:c.direction})},x=typeof e=="function"?l():"";e==null||e(m({requestId:x,path:h},S));let I=yield r(h,S);return e==null||e(f(m({requestId:x,path:h},S),{responseData:I.data})),I})},create(t,o){return y(this,null,function*(){let c=T(o),n="/records",d={headers:Object.assign({},R(c)),method:"POST",requestData:t instanceof E?t.toJson():t},u=typeof e=="function"?l():"";e==null||e(m({requestId:u,path:n},d));let h=yield r(n,d);return e==null||e(f(m({requestId:u,path:n},d),{responseData:h.data})),h})},createMany(t,o){return y(this,null,function*(){let c=T(o),n="/records/import/json",d={headers:Object.assign({},R(c)),method:"POST",requestData:t instanceof Q?t.toJson():t},u=typeof e=="function"?l():"";e==null||e(m({requestId:u,path:n},d));let h=yield r(n,d);return e==null||e(f(m({requestId:u,path:n},d),{responseData:h.data})),h})},delete(t,o){return y(this,null,function*(){let c=T(o),n="/records/delete",d={headers:Object.assign({},R(c)),method:"PUT",requestData:t},u=typeof e=="function"?l():"";e==null||e(m({requestId:u,path:n},d));let h=yield r(n,d);return e==null||e(f(m({requestId:u,path:n},d),{responseData:h.data})),h})},deleteById(t,o){return y(this,null,function*(){let c=T(o),n=b(t),d=n?"/records/delete":`/records/${t}`,u={headers:Object.assign({},R(c)),method:n?"PUT":"DELETE",requestData:n?{limit:1e3,where:{$id:{$in:t}}}:void 0},h=typeof e=="function"?l():"";e==null||e(m({requestId:h,path:d},u));let S=yield r(d,u);return e==null||e(f(m({requestId:h,path:d},u),{responseData:S.data})),S})},detach(t,o,c,n){return y(this,null,function*(){let d=T(n),h=`/records/${U(t)}/relations`,S={headers:Object.assign({},R(d)),method:"PUT",requestData:m(m({targetIds:o},(c==null?void 0:c.typeOrTypes)&&{typeOrTypes:c.typeOrTypes}),(c==null?void 0:c.direction)&&{direction:c.direction})},x=typeof e=="function"?l():"";e==null||e(m({requestId:x,path:h},S));let I=yield r(h,S);return e==null||e(f(m({requestId:x,path:h},S),{responseData:I.data})),I})},export(t,o){return y(this,null,function*(){let c=T(o),n="/records/export/csv",d={headers:Object.assign({},R(c)),method:"POST",requestData:t},u=typeof e=="function"?l():"";e==null||e(m({requestId:u,path:n},d));let h=yield r(n,d);return e==null||e(f(m({requestId:u,path:n},d),{responseData:h.data})),h})},find(t,o){return y(this,null,function*(){let c=T(o),n=t!=null&&t.id?`/records/${t.id}/search`:"/records/search",d={headers:Object.assign({},R(c)),method:"POST",requestData:t==null?void 0:t.searchParams},u=typeof e=="function"?l():"";e==null||e(m({requestId:u,path:n},d));let h=yield r(n,d);return e==null||e(f(m({requestId:u,path:n},d),{responseData:h.data})),h})},findById(t,o){return y(this,null,function*(){let c=T(o),n=b(t)?"/records":`/records/${t}`,d={headers:Object.assign({},R(c)),method:b(t)?"POST":"GET",requestData:b(t)?{ids:t}:void 0},u=typeof e=="function"?l():"";e==null||e(m({requestId:u,path:n},d));let h=yield r(n,d);return e==null||e(f(m({requestId:u,path:n},d),{responseData:h.data})),h})},findOne(t,o){return y(this,null,function*(){let c=T(o),n="/records/search",d={headers:Object.assign({},R(c)),method:"POST",requestData:f(m({},t),{limit:1,skip:0})},u=typeof e=="function"?l():"";e==null||e(m({requestId:u,path:n},d));let h=yield r(n,d);e==null||e(f(m({requestId:u,path:n},d),{responseData:h.data}));let[S]=h.data;return f(m({},h),{data:S})})},findUniq(t,o){return y(this,null,function*(){let c=T(o),n="/records/search",d={headers:Object.assign({},R(c)),method:"POST",requestData:f(m({},t),{limit:1,skip:0})},u=typeof e=="function"?l():"";e==null||e(m({requestId:u,path:n},d));let h=yield r(n,d);if(e==null||e(f(m({requestId:u,path:n},d),{responseData:h.data})),typeof h.total!="undefined"&&h.total>1)throw new H(h.total,t);let[S]=h.data;return f(m({},h),{data:S})})},properties(t,o){return y(this,null,function*(){let c=T(o),d=`/records/${U(t)}/properties`,u={headers:Object.assign({},R(c)),method:"GET"},h=typeof e=="function"?l():"";e==null||e(m({requestId:h,path:d},u));let S=yield r(d,u);return e==null||e(f(m({requestId:h,path:d},u),{responseData:S.data})),S})},relations(t,o){return y(this,null,function*(){let c=T(o),d=`/records/${U(t)}/relations`,u={headers:Object.assign({},R(c)),method:"GET"},h=typeof e=="function"?l():"";e==null||e(m({requestId:h,path:d},u));let S=yield r(d,u);return e==null||e(f(m({requestId:h,path:d},u),{responseData:S.data})),S})},set(t,o,c){return y(this,null,function*(){let n=T(c),u=`/records/${U(t)}`,h={headers:Object.assign({},R(n)),method:"PUT",requestData:o instanceof E?o.toJson():o},S=typeof e=="function"?l():"";e==null||e(m({requestId:S,path:u},h));let x=yield r(u,h);return e==null||e(f(m({requestId:S,path:u},h),{responseData:x.data})),x})},update(t,o,c){return y(this,null,function*(){let n=T(c),u=`/records/${U(t)}`,h={headers:Object.assign({},R(n)),method:"PATCH",requestData:o instanceof E?o.toJson():o},S=typeof e=="function"?l():"";e==null||e(m({requestId:S,path:u},h));let x=yield r(u,h);return e==null||e(f(m({requestId:S,path:u},h),{responseData:x.data})),x})}},relations:{find(t,o,c){return y(this,null,function*(){let n=T(c),d=new URLSearchParams;(o==null?void 0:o.limit)!==void 0&&d.append("limit",o.limit.toString()),(o==null?void 0:o.skip)!==void 0&&d.append("skip",o.skip.toString());let h=`/records/relations/search${d.toString()?"?"+d.toString():""}`,S={headers:Object.assign({},R(n)),method:"POST",requestData:t},x=typeof e=="function"?l():"";e==null||e(m({requestId:x,path:h},S));let I=yield r(h,S);return e==null||e(f(m({requestId:x,path:h},S),{responseData:I.data})),I})}},tx:{begin(){return y(this,arguments,function*(t={}){let o="/tx",c={method:"POST",requestData:t},n=typeof e=="function"?l():"";e==null||e(m({requestId:n,path:o},c));let d=yield r(o,c);return e==null||e(f(m({requestId:n,path:o},c),{responseData:d.data})),d})},commit(t){return y(this,null,function*(){let o=`/tx/${t}/commit`,c={method:"POST",requestData:{}},n=typeof e=="function"?l():"";e==null||e(m({requestId:n,path:o},c));let d=yield r(o,c);return e==null||e(f(m({requestId:n,path:o},c),{responseData:d.data})),d})},get(t){return y(this,null,function*(){let o=`/tx/${t}`,c={method:"GET"},n=typeof e=="function"?l():"";e==null||e(m({requestId:n,path:o},c));let d=yield r(o,c);return e==null||e(f(m({requestId:n,path:o},c),{responseData:d.data})),d})},rollback(t){return y(this,null,function*(){let o=`/tx/${t}/rollback`,c={method:"POST",requestData:{}},n=typeof e=="function"?l():"";e==null||e(m({requestId:n,path:o},c));let d=yield r(o,c);e==null||e(f(m({requestId:n,path:o},c),{responseData:d.data}))})}}});var F=class{constructor(e,a){this.relations={find:i=>y(this,[i],function*({pagination:e,search:a,transaction:s}){let{searchParams:p}=L(a),t=Y(s);return yield this.api.relations.find(p,e,t)})};this.properties={delete:(e,a)=>y(this,null,function*(){var s;return(s=this.api)==null?void 0:s.properties.delete(e,a)}),find:(e,a)=>y(this,null,function*(){var s;return(s=this.api)==null?void 0:s.properties.find(e,a)}),findById:(e,a)=>y(this,null,function*(){var s;return(s=this.api)==null?void 0:s.properties.findById(e,a)}),values:(e,a,s)=>y(this,null,function*(){var i;return(i=this.api)==null?void 0:i.properties.values(e,a,s)})};this.labels={find:(e,a)=>y(this,null,function*(){return this.api.labels.find(e,a)})};this.tx={begin:e=>y(this,null,function*(){var i;let a=yield(i=this.api)==null?void 0:i.tx.begin(e),s=new C(a.data.id);return s.init(this),s}),commit:e=>y(this,null,function*(){var a;return(a=this.api)==null?void 0:a.tx.commit(e)}),get:e=>y(this,null,function*(){var i;let a=yield(i=this.api)==null?void 0:i.tx.get(e),s=new C(a.data.id);return s.init(this),s}),rollback:e=>y(this,null,function*(){var a;return(a=this.api)==null?void 0:a.tx.commit(e)})};if(this.fetcher=null,a!=null&&a.httpClient){let s=Ie(a);this.fetcher=Se({httpClient:a.httpClient,token:e,url:s})}this.api=Ee(this.fetcher,a==null?void 0:a.logger),this.records={attach:(s,i,p,t)=>y(this,null,function*(){var o,c;if(i instanceof w){let n=(o=i.data)==null?void 0:o.__id;if(n)return yield this.api.records.attach(s,n,p,t);throw new P("Attach error: Target id is empty")}else if(b(i)&&i.every(n=>n instanceof w)){let n=i.map(d=>{var u;return(u=d.data)==null?void 0:u.__id}).filter(fe);if(n.length)return yield this.api.records.attach(s,n,p,t);throw new P("Attach error: Target ids are empty")}else if(i instanceof O){let n=(c=i.data)==null?void 0:c.map(d=>d.__id).filter(Boolean);if(n!=null&&n.length)return yield this.api.records.attach(s,n,p,t);throw new P("Attach error: Target ids are empty")}else{if(D(i)&&"__id"in i)return yield this.api.records.attach(s,i.__id,p,t);if(b(i)&&i.every(n=>D(n)&&"__id"in n)){let n=i==null?void 0:i.map(d=>d.__id).filter(Boolean);if(n!=null&&n.length)return yield this.api.records.attach(s,n,p,t);throw new P("Attach error: Target ids are empty")}else return yield this.api.records.attach(s,i,p,t)}}),create:(s,i,p)=>y(this,null,function*(){var o,c;let t;if(s instanceof E&&(t=yield(o=this.api)==null?void 0:o.records.create(s,Y(i))),!t&&k(s)){if(v(i)){let n=Pe({label:s,payload:i});t=yield(c=this.api)==null?void 0:c.records.create(new E(n),p)}else if(D(i))throw Error("Provided data is not a flat object. Consider to use `createMany` method.")}if(t!=null&&t.success&&(t!=null&&t.data)){let n=new w(t.data);return n.init(this),n}return new w}),createMany:(s,i,p)=>y(this,null,function*(){var o,c;let t;if(s instanceof Q&&(t=yield(o=this.api)==null?void 0:o.records.createMany(s,Y(i))),!t&&k(s)&&(b(i)||D(i))){let n=new Q({label:s,payload:i});t=yield(c=this.api)==null?void 0:c.records.createMany(n,p)}if(t!=null&&t.success&&(t!=null&&t.data)){let n=new O(t.data,t.total);return n.init(this),n}return new O([])}),delete:(s,i)=>y(this,null,function*(){var p,t;if(q(s.where)&&!((p=a==null?void 0:a.options)!=null&&p.allowForceDelete))throw new P("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");return(t=this.api)==null?void 0:t.records.delete(s,i)}),deleteById:(s,i)=>y(this,null,function*(){var p;return(p=this.api)==null?void 0:p.records.deleteById(s,i)}),detach:(s,i,p,t)=>y(this,null,function*(){var o,c;if(i instanceof w){let n=(o=i.data)==null?void 0:o.__id;if(n)return yield this.api.records.detach(s,n,p,t);throw new P("Detach error: Target id is empty")}else if(b(i)&&i.every(n=>n instanceof w)){let n=i.map(d=>{var u;return(u=d.data)==null?void 0:u.__id}).filter(Boolean);if(n.length)return yield this.api.records.detach(s,n,p,t);throw new P("Detach error: Target ids are empty")}else if(i instanceof O){let n=(c=i.data)==null?void 0:c.map(d=>d.__id).filter(Boolean);if(n!=null&&n.length)return yield this.api.records.detach(s,n,p,t);throw new P("Detach error: Target ids are empty")}else{if(D(i)&&"__id"in i)return yield this.api.records.detach(s,i.__id,p,t);if(b(i)&&i.every(n=>D(n)&&"__id"in n)){let n=i==null?void 0:i.map(d=>d.__id).filter(Boolean);if(n!=null&&n.length)return yield this.api.records.detach(s,n,p,t);throw new P("Detach error: Target ids are empty")}else return yield this.api.records.detach(s,i,p,t)}}),export:(s,i)=>y(this,null,function*(){var p;return(p=this.api)==null?void 0:p.records.export(s,i)}),find:(s,i,p)=>y(this,null,function*(){var h;let t=M(i),{id:o,searchParams:c}=L(s,i),n=t?i:p,d=yield(h=this.api)==null?void 0:h.records.find({id:o,searchParams:c},n),u=new O(d.data,d.total,i);return u.init(this),u}),findById:(s,i)=>y(this,null,function*(){var p,t;if(b(s)){let o=yield(p=this.api)==null?void 0:p.records.findById(s,i),c=new O(o.data,o.total);return c.init(this),c}else{let o=yield(t=this.api)==null?void 0:t.records.findById(s,i),c=new w(o.data);return c.init(this),c}}),findOne:(s,i,p)=>y(this,null,function*(){var u;let t=M(i),{searchParams:o}=L(s,i),c=t?i:p,n=yield(u=this.api)==null?void 0:u.records.findOne(o,c),d=new w(n.data);return d.init(this),d}),findUniq:(s,i,p)=>y(this,null,function*(){var u;let t=M(i),{searchParams:o}=L(s,i),c=t?i:p,n=yield(u=this.api)==null?void 0:u.records.findUniq(o,c),d=new w(n.data);return d.init(this),d}),properties:(s,i)=>y(this,null,function*(){var p;return(p=this.api)==null?void 0:p.records.properties(s,i)}),relations:(s,i)=>y(this,null,function*(){return yield this.api.records.relations(s,i)}),set:(s,i,p)=>y(this,null,function*(){var o,c;let t;if(i instanceof E)t=yield(o=this.api)==null?void 0:o.records.set(s,i,p);else if(v(i)){let n=J(i);t=yield(c=this.api)==null?void 0:c.records.set(s,new E({properties:n}),p)}else if(D(i))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");if(t!=null&&t.success&&(t!=null&&t.data)){let n=new w(t.data);return n.init(this),n}return new w}),update:(s,i,p)=>y(this,null,function*(){var o,c;let t;if(i instanceof E)t=yield(o=this.api)==null?void 0:o.records.update(s,i,p);else if(v(i)){let n=J(i),d=new E({properties:n});t=yield(c=this.api)==null?void 0:c.records.update(s,d,p)}else if(D(i))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");if(t!=null&&t.success&&(t!=null&&t.data)){let n=new w(t.data);return n.init(this),n}return new w})}}};var Ae=r=>{class e extends F{constructor(s,i){var t;let p=Re(i);super(s,f(m({},p),{httpClient:(t=p.httpClient)!=null?t:r})),this.state={debug:!1,timeout:Te("timeout",p.timeout,8e4),token:s},this.models=new Map,e.instance=this}static getInstance(){return e.instance}registerModel(s){let i=s.getLabel();return s.init(this),this.models.set(i,s),s}getModels(){return this.models}getModel(s){return this.models.get(s)}toInstance(s){let i=new w(s);return i.init(this),i}}return e};var ne=class extends _{constructor(e,a,s){super(),this.label=e,this.schema=a,s==null||s.registerModel(this)}getLabel(){return this.label}find(e,a){return y(this,null,function*(){var i;let s=e!=null?e:{};return(i=this.apiProxy)==null?void 0:i.records.find(this.label,s,a)})}findOne(e,a){return y(this,null,function*(){var i;let s=e!=null?e:{};return(i=this.apiProxy)==null?void 0:i.records.findOne(this.label,s,a)})}findById(e,a){return y(this,null,function*(){return this.findOne({where:{$id:e}},a)})}findUniq(e,a){return y(this,null,function*(){var i;let s=e!=null?e:{};return(i=this.apiProxy)==null?void 0:i.records.findUniq(this.label,s,a)})}create(e,a){return y(this,null,function*(){var p;let s=yield N(this.schema,e),i=re(this.schema,s);if(!q(i)){let t=a!=null?a:yield this.apiProxy.tx.begin(),o=yield this.find({where:i},t),c=typeof a!="undefined";if(!((p=o==null?void 0:o.data)!=null&&p.length)){let d=yield this.apiProxy.records.create(this.label,s,t);return c||(yield t.commit()),d}else throw c||(yield t.commit()),new B(this.label,i)}return yield this.apiProxy.records.create(this.label,s,a)})}attach(e,a,s,i){return this.apiProxy.records.attach(e,a,s,i)}detach(e,a,s,i){return this.apiProxy.records.detach(e,a,s,i)}handleSetOrUpdate(e,a,s,i){return y(this,null,function*(){var o;let p=yield N(this.schema,a),t=re(this.schema,p);if(!q(t)){let c=i!=null?i:yield this.apiProxy.tx.begin(),n=yield this.find({where:t},c),d=typeof i!="undefined";if(!((o=n==null?void 0:n.data)!=null&&o.length)||n.data.length===1&&n.data[0].__id===e){let h=yield this.apiProxy.records[s](e,p,c);return d||(yield c.commit()),h}else throw d||(yield c.commit()),new B(this.label,t)}return yield this.apiProxy.records[s](e,p,i)})}set(e,a,s){return y(this,null,function*(){return yield this.handleSetOrUpdate(e,a,"set",s)})}update(e,a,s){return y(this,null,function*(){return yield this.handleSetOrUpdate(e,a,"update",s)})}createMany(e,a){return y(this,null,function*(){var p;let s=typeof a!="undefined",i=a!=null?a:yield this.apiProxy.tx.begin();try{let t=yield Promise.all(e.map(n=>y(this,null,function*(){return yield N(this.schema,n)}))),o=le(t,this.schema,this.label);if(!q(o)){let n=Object.entries(o).map(([u,h])=>({[u]:{$in:h}})),d=yield this.find({where:{$or:n}},i);if((p=d==null?void 0:d.data)!=null&&p.length)throw new B(this.label,Object.keys(o))}let c=yield this.apiProxy.records.createMany(this.label,t,i);return s||(yield i.commit()),c}catch(t){throw s||(yield i.rollback()),t}})}delete(e,a){return y(this,null,function*(){if(q(e.where))throw new P(`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 this.apiProxy.records.delete(f(m({},e),{labels:[this.label]}),a)})}deleteById(e,a){return y(this,null,function*(){return yield this.apiProxy.records.deleteById(e,a)})}};var He=Ae(new V);var zt=He;export{E as DBRecordDraft,w as DBRecordInstance,O as DBRecordsArrayInstance,Q as DBRecordsBatchDraft,P as EmptyTargetError,A as HttpClient,g as HttpClientResponse,ne as Model,H as NonUniqueResultError,F as RestAPI,He as RushDB,C as Transaction,B as UniquenessError,zt as default,se as idToDate,K as idToTimestamp};
1
+ var me=Object.defineProperty,fe=Object.defineProperties;var ge=Object.getOwnPropertyDescriptors;var U=Object.getOwnPropertySymbols;var X=Object.prototype.hasOwnProperty,ee=Object.prototype.propertyIsEnumerable;var Z=(n,e,t)=>e in n?me(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,p=(n,e)=>{for(var t in e||(e={}))X.call(e,t)&&Z(n,t,e[t]);if(U)for(var t of U(e))ee.call(e,t)&&Z(n,t,e[t]);return n},m=(n,e)=>fe(n,ge(e));var F=(n,e)=>{var t={};for(var r in n)X.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&U)for(var r of U(n))e.indexOf(r)<0&&ee.call(n,r)&&(t[r]=n[r]);return t};var u=(n,e,t)=>new Promise((r,s)=>{var a=c=>{try{i(t.next(c))}catch(d){s(d)}},o=c=>{try{i(t.throw(c))}catch(d){s(d)}},i=c=>c.done?r(c.value):Promise.resolve(c.value).then(a,o);i((t=t.apply(n,e)).next())});var Se="string",Re="datetime",Te="boolean",be="number",De="null",xe="vector",te=[Se,Re,Te,be,De,xe];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 H=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.")}},N=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 L=class n extends O{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=n.makeFetchWithAbortTimeout(e):this._fetchFn=n.makeFetchWithRaceTimeout(e)}static makeFetchWithRaceTimeout(e){return(t,r,s)=>{let a,o=new Promise((c,d)=>{a=setTimeout(()=>{a=null,d(O.makeTimeoutError())},s)}),i=e(t,r);return Promise.race([i,o]).finally(()=>{a&&clearTimeout(a)})}}static makeFetchWithAbortTimeout(e){return(t,r,s)=>u(this,null,function*(){let a=new AbortController,o=setTimeout(()=>{o=null,a.abort(O.makeTimeoutError())},s);try{return yield e(t,m(p({},r),{signal:a.signal}))}catch(i){throw i.name==="AbortError"?O.makeTimeoutError():i}finally{o&&clearTimeout(o)}})}makeRequest(i,c){return u(this,arguments,function*(e,{headers:t,method:r,protocol:s,requestData:a,timeout:o}){let d=r=="POST"||r=="PUT"||r=="PATCH",l=JSON.stringify(a)||(d?"":void 0),h=yield this._fetchFn(e,{body:l,headers:t,method:r},o!=null?o:8e4);return new K(h)})}},K=class n extends H{constructor(e){super(e.status,n._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 D=n=>typeof n=="object"&&Array.isArray(n)&&n!==null,x=n=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",j=n=>x(n)&&Object.keys(n).length===0,re=n=>typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null,V=n=>D(n)?n.every(re):re(n),v=n=>x(n)&&Object.values(n).every(V),A=n=>typeof n=="string",Q=n=>{if(typeof n=="string"){if(n.toLowerCase()==="true")return!0;if(n.toLowerCase()==="false")return!1}return D(n)&&n.length===0||x(n)&&Object.keys(n).length===0?!1:!!n};var Ie={"Content-Type":"application/json"},se=({httpClient:n,token:e,url:t})=>(r,o)=>u(void 0,null,function*(){var i=o,{headers:s}=i,a=F(i,["headers"]);let c=yield n.makeRequest(`${t}${r}`,p({credentials:"omit",headers:Object.assign(p(p({},Ie),s),typeof e!="undefined"?{token:e}:{})},a));if(c.getStatusCode()>=200&&c.getStatusCode()<300)return yield c.toJSON();throw new Error(`${c.getStatusCode()}`)});var B=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)}},E=class n extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,n.prototype)}},$=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 C=class{constructor(){this.apiProxy={};return new Proxy(this,{get:(e,t,r)=>{if(t in e)return Reflect.get(e,t,r);if(this.apiProxy&&t in this.apiProxy)return Reflect.get(this.apiProxy,t,r)}})}init(e){this.apiProxy=e}};var Y=["httpClient","timeout","host","port","protocol","url","logger","options"];var W=(n,e)=>u(void 0,null,function*(){let t=Object.entries(n).map(i=>u(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}})),s=(yield Promise.all(t)).reduce((a,{key:o,value:i})=>(i!==void 0&&(a[o]=i),a),{});return p(p({},s),e)}),J=(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),{}),ne=(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 B(t,{[o]:i});r[o]=[...r[o],i]}else r[o]=[i]})}),r},ae=n=>{if(!n)return{};if(!x(n))throw new Error("Config must be an object");if(Object.keys(n).filter(t=>!Y.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${Y.join(", ")}`);return n};function oe(n,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${n} must be an integer`)}return e}function G(n){let e=n.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function ie(n){return new Date(G(n))}var R=class extends C{constructor(e){super(),this.data=e}id(){try{return this.data.__id}catch(e){throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.")}}label(){try{return this.data.__label}catch(e){throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.")}}proptypes(){try{return this.data.__proptypes}catch(e){throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.")}}date(){try{return ie(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return G(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}delete(e){return u(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return yield this.apiProxy.records.deleteById(this.id(),e)})}update(e,t){return u(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return this.apiProxy.records.update({label:this.label(),target:this.id(),data:e},t)})}set(e,t){return u(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return this.apiProxy.records.set({label:this.label(),target:this.id(),data:e},t)})}attach(e,t,r){return u(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return this.apiProxy.records.attach({source:this.id(),target:e,options:t},r)})}detach(e,t,r){return u(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return this.apiProxy.records.detach({source:this.id(),target:e,options:t},r)})}},q=class extends C{constructor(e,t,r){super(),this.data=e,this.total=t,this.searchQuery=r}};var _=class extends C{constructor(e){super(),this.id=e}rollback(){return u(this,null,function*(){return yield this.apiProxy.tx.rollback(this.id)})}commit(){return u(this,null,function*(){return yield this.apiProxy.tx.commit(this.id)})}};var ce="api.rushdb.com";var de="https",pe="/api/v1";var b=n=>n?{"x-transaction-id":n}:void 0,Oe=n=>A(n)||n instanceof _,S=n=>Oe(n)?n instanceof _?n.id:n:void 0,le=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(A(n)&&le(n))return n;if(n instanceof R&&n.data)return n.data.__id;if(x(n)&&"__id"in n&&le(n.__id))return n.__id},k=n=>!(!x(n)||x(n)&&"name"in n&&!A(n.name)||x(n)&&"type"in n&&(!A(n.type)||!te.includes(n.type))||!("value"in n)||!V(n.value)||"metadata"in n&&!A(n.metadata)||"valueSeparator"in n&&!A(n.valueSeparator)),he=n=>{let e=de,t=ce,r=443,s=pe;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}`},g=(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 M=class{constructor(e,t){this.records={attach:(a,o)=>u(this,[a,o],function*({source:e,target:t,options:r},s){var y,T;let i=S(s),d=`/relationships/${I(e)}`,l={headers:Object.assign({},b(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})},h=typeof this.logger=="function"?g():"";(y=this.logger)==null||y.call(this,p({requestId:h,path:d},l));let f=yield this.fetcher(d,l);return(T=this.logger)==null||T.call(this,m(p({requestId:h,path:d},l),{responseData:f.data})),f}),detach:(a,o)=>u(this,[a,o],function*({source:e,target:t,options:r},s){var y,T;let i=S(s),d=`/relationships/${I(e)}`,l={headers:Object.assign({},b(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})},h=typeof this.logger=="function"?g():"";(y=this.logger)==null||y.call(this,p({requestId:h,path:d},l));let f=yield this.fetcher(d,l);return(T=this.logger)==null||T.call(this,m(p({requestId:h,path:d},l),{responseData:f.data})),f}),create:(a,o)=>u(this,[a,o],function*({label:e,data:t,options:r},s){var f,y;let i=S(s),c="/records",d={headers:Object.assign({},b(i)),method:"POST",requestData:{}},l=typeof this.logger=="function"?g():"";if(D(t)&&t.every(k))d.requestData={label:e,properties:t};else if(v(t))d.requestData={label:e,payload:t,options:r};else if(x(t))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(f=this.logger)==null||f.call(this,p({requestId:l,path:c},d));let h=yield this.fetcher(c,d);if((y=this.logger)==null||y.call(this,m(p({requestId:l,path:c},d),{responseData:h.data})),h!=null&&h.success&&(h!=null&&h.data)){let T=new R(h.data);return T.init(this),T}return new R}),createMany:(e,t)=>u(this,null,function*(){var c,d;let r=S(t),s="/records/import/json",a={headers:Object.assign({},b(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);if((d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i!=null&&i.success&&(i!=null&&i.data)){let l=i.data.map(f=>{let y=new R(f);return y.init(this),y}),h=new q(l,i.total);return h.init(this),h}return new q([])}),delete:(e,t)=>u(this,null,function*(){var c,d,l;if(j(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=S(t),s="/records/delete",a={headers:Object.assign({},b(r)),method:"PUT",requestData:e},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(l=this.logger)==null||l.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),deleteById:(e,t)=>u(this,null,function*(){var d,l;let r=S(t),s=D(e),a=s?"/records/delete":`/records/${e}`,o={headers:Object.assign({},b(r)),method:s?"PUT":"DELETE",requestData:s?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:a},o));let c=yield this.fetcher(a,o);return(l=this.logger)==null||l.call(this,m(p({requestId:i,path:a},o),{responseData:c.data})),c}),export:(e,t)=>u(this,null,function*(){var c,d;let r=S(t),s="/records/export/csv",a={headers:Object.assign({},b(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),find:(e,t)=>u(this,null,function*(){var y,T;let f=e,{id:r}=f,s=F(f,["id"]),a=S(t),o=r?`/records/${r}/search`:"/records/search",i={headers:Object.assign({},b(a)),method:"POST",requestData:s},c=typeof this.logger=="function"?g():"";(y=this.logger)==null||y.call(this,p({requestId:c,path:o},i));let d=yield this.fetcher(o,i);(T=this.logger)==null||T.call(this,m(p({requestId:c,path:o},i),{responseData:d.data}));let l=d.data.map(P=>{let w=new R(P);return w.init(this),w}),h=new q(l,d.total,e);return h.init(this),h}),findById:(e,t)=>u(this,null,function*(){var c,d;let r=S(t),s=D(e)?"/records":`/records/${e}`,a={headers:Object.assign({},b(r)),method:D(e)?"POST":"GET",requestData:D(e)?{ids:e}:void 0},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);if((d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),D(e)){let l=i.data.map(f=>{let y=new R(f);return y.init(this),y}),h=new q(l,i.total);return h.init(this),h}else{let l=new R(i.data);return l.init(this),l}}),findOne:(e,t)=>u(this,null,function*(){var l,h;let r=S(t),s="/records/search",a={headers:Object.assign({},b(r)),method:"POST",requestData:m(p({},e),{limit:1,skip:0})},o=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);(h=this.logger)==null||h.call(this,m(p({requestId:o,path:s},a),{responseData:i.data}));let[c]=i.data,d=new R(c);return d.init(this),d}),findUniq:(e,t)=>u(this,null,function*(){var l,h;let r=S(t),s="/records/search",a={headers:Object.assign({},b(r)),method:"POST",requestData:m(p({},e),{limit:1,skip:0})},o=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);if((h=this.logger)==null||h.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),typeof i.total!="undefined"&&i.total>1)throw new $(i.total,e);let[c]=i.data,d=new R(c);return d.init(this),d}),set:(o,i)=>u(this,[o,i],function*({target:e,label:t,data:r,options:s},a){var T,P;let c=S(a),l=`/records/${I(e)}`,h={headers:Object.assign({},b(c)),method:"PUT",requestData:{}},f=typeof this.logger=="function"?g():"";if(D(r)&&r.every(k))h.requestData={label:t,properties:r};else if(v(r))h.requestData={label:t,data:r,options:s};else if(x(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(T=this.logger)==null||T.call(this,p({requestId:f,path:l},h));let y=yield this.fetcher(l,h);if((P=this.logger)==null||P.call(this,m(p({requestId:f,path:l},h),{responseData:y.data})),y!=null&&y.success&&(y!=null&&y.data)){let w=new R(y.data);return w.init(this),w}return new R}),update:(o,i)=>u(this,[o,i],function*({target:e,label:t,data:r,options:s},a){var T,P;let c=S(a),l=`/records/${I(e)}`,h={headers:Object.assign({},b(c)),method:"PATCH",requestData:{}},f=typeof this.logger=="function"?g():"";if(D(r)&&r.every(k))h.requestData={label:t,properties:r};else if(v(r))h.requestData={label:t,data:r,options:s};else if(x(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(T=this.logger)==null||T.call(this,p({requestId:f,path:l},h));let y=yield this.fetcher(l,h);if((P=this.logger)==null||P.call(this,m(p({requestId:f,path:l},h),{responseData:y.data})),y!=null&&y.success&&(y!=null&&y.data)){let w=new R(y.data);return w.init(this),w}return new R})};this.relationships={find:(e,t)=>u(this,null,function*(){var l,h;let r=S(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({},b(r)),method:"POST",requestData:e},c=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,p({requestId:c,path:o},i));let d=yield this.fetcher(o,i);return(h=this.logger)==null||h.call(this,m(p({requestId:c,path:o},i),{responseData:d.data})),d})};this.properties={delete:(e,t)=>u(this,null,function*(){var c,d;let r=S(t),s=`/properties/${e}`,a={headers:Object.assign({},b(r)),method:"DELETE"},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),find:(e,t)=>u(this,null,function*(){var c,d;let r=S(t),s="/properties/search",a={headers:Object.assign({},b(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),findById:(e,t)=>u(this,null,function*(){var c,d;let r=S(t),s=`/properties/${e}`,a={headers:Object.assign({},b(r)),method:"GET"},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),values:(e,t,r)=>u(this,null,function*(){var w,z;let s=S(r),a=`/properties/${e}/values`,{sort:o,skip:i,limit:c,query:d}=t!=null?t:{},l=new URLSearchParams;o!==void 0&&l.append("sort",o),i!==void 0&&l.append("skip",i.toString()),c!==void 0&&l.append("limit",c.toString()),d!==void 0&&l.append("query",d);let h=l.toString(),f=h?`${a}?${h}`:a,y={headers:Object.assign({},b(s)),method:"GET"},T=typeof this.logger=="function"?g():"";(w=this.logger)==null||w.call(this,p({requestId:T,path:a},y));let P=yield this.fetcher(f,y);return(z=this.logger)==null||z.call(this,m(p({requestId:T,path:f},y),{responseData:P.data})),P})};this.labels={find:(e,t)=>u(this,null,function*(){var c,d;let r=S(t),s="/labels/search",a={headers:Object.assign({},b(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i})};this.tx={begin:e=>u(this,null,function*(){var i,c;let t="/tx",r={method:"POST",requestData:e},s=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,p({requestId:s,path:t},r));let a=yield this.fetcher(t,r);(c=this.logger)==null||c.call(this,m(p({requestId:s,path:t},r),{responseData:a.data}));let o=new _(a.data.id);return o.init(this),o}),commit:e=>u(this,null,function*(){var i,c;let r=`/tx/${S(e)}/commit`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,p({requestId:a,path:r},s));let o=yield this.fetcher(r,s);return(c=this.logger)==null||c.call(this,m(p({requestId:a,path:r},s),{responseData:o.data})),o}),get:e=>u(this,null,function*(){var c,d;let r=`/tx/${S(e)}`,s={method:"GET"},a=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:a,path:r},s));let o=yield this.fetcher(r,s);(d=this.logger)==null||d.call(this,m(p({requestId:a,path:r},s),{responseData:o.data}));let i=new _(o.data.id);return i.init(this),i}),rollback:e=>u(this,null,function*(){var i,c;let r=`/tx/${S(e)}/rollback`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,p({requestId:a,path:r},s));let o=yield this.fetcher(r,s);return(c=this.logger)==null||c.call(this,m(p({requestId:a,path:r},s),{responseData:o.data})),o})};if(this.fetcher=null,t!=null&&t.httpClient){let r=he(t);this.fetcher=se({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 R){let s=I(e);if(!s)throw new E(`${t} error: Target id is empty`);return[s]}if(D(e)&&e.every(s=>s instanceof R)){let s=e.map(I).filter(Q);if(!s.length)throw new E(`${t} error: Target ids are empty`);return s}if(e instanceof q){let s=(r=e.data)==null?void 0:r.map(I).filter(Q);if(!(s!=null&&s.length))throw new E(`${t} error: Target ids are empty`);return s}if(x(e)&&"__id"in e)return[e.__id];if(D(e)&&e.every(s=>x(s)&&"__id"in s)){let s=e.map(I).filter(Q);if(!s.length)throw new E(`${t} error: Target ids are empty`);return s}return D(e)?e:A(e)?[e]:[]}};var ue=n=>{class e extends M{constructor(r,s){var o;let a=ae(s);super(r,m(p({},a),{httpClient:(o=a.httpClient)!=null?o:n})),this.state={debug:!1,timeout:oe("timeout",a.timeout,8e4),token:r},this.models=new Map,e.instance=this}static getInstance(){return e.instance}registerModel(r){let s=r.getLabel();return r.init(this),this.models.set(s,r),r}getModels(){return this.models}getModel(r){return this.models.get(r)}toInstance(r){let s=new R(r);return s.init(this),s}}return e};var ye=class extends C{constructor(e,t,r){super(),this.label=e,this.schema=t,this.rushDBInstance=r,r==null||r.registerModel(this)}getLabel(){return this.label}toInstance(e){if(this.rushDBInstance)return this.rushDBInstance.toInstance(e);throw new Error("No RushDB instance was provided during model initialization.")}find(e,t){return u(this,null,function*(){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.find(m(p({},r),{labels:[this.label]}),t)})}findOne(e,t){return u(this,null,function*(){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.findOne(m(p({},r),{labels:[this.label]}),t)})}findById(e,t){return u(this,null,function*(){return this.findOne({where:{$id:e}},t)})}findUniq(e,t){return u(this,null,function*(){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.findUniq(m(p({},r),{labels:[this.label]}),t)})}create(e,t){return u(this,null,function*(){var a;let r=yield W(this.schema,e),s=J(this.schema,r);if(!j(s)){let o=t!=null?t:yield this.apiProxy.tx.begin(),i=yield this.find({where:s},o),c=typeof t!="undefined";if(!((a=i==null?void 0:i.data)!=null&&a.length)){let l=yield this.apiProxy.records.create({label:this.label,data:r},o);return c||(yield o.commit()),l}else throw c||(yield o.commit()),new B(this.label,s)}return yield this.apiProxy.records.create({label:this.label,data:r},t)})}attach({source:e,target:t,options:r},s){return this.apiProxy.records.attach({source:e,target:t,options:r},s)}detach({source:e,target:t,options:r},s){return this.apiProxy.records.detach({source:e,target:t,options:r},s)}handleSetOrUpdate(e,t,r,s){return u(this,null,function*(){var i,c;if(D(t)&&t.every(k))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let a=yield W(this.schema,t),o=J(this.schema,a);if(!j(o)){let d=s!=null?s:yield this.apiProxy.tx.begin(),l=yield this.find({where:o},d),h=typeof s!="undefined";if(!((i=l==null?void 0:l.data)!=null&&i.length)||l.data.length===1&&((c=l.data[0])==null?void 0:c.id())===I(e)){let y=yield this.apiProxy.records[r]({target:e,label:this.label,data:a},d);return h||(yield d.commit()),y}else throw h||(yield d.commit()),new B(this.label,o)}return yield this.apiProxy.records[r]({label:this.label,target:e,data:a},s)})}set(e,t,r){return u(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"set",r)})}update(e,t,r){return u(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"update",r)})}createMany(e,t){return u(this,null,function*(){var a;let r=typeof t!="undefined",s=t!=null?t:yield this.apiProxy.tx.begin();try{let o=yield Promise.all(e.map(d=>u(this,null,function*(){return yield W(this.schema,d)}))),i=ne(o,this.schema,this.label);if(!j(i)){let d=Object.entries(i).map(([h,f])=>({[h]:{$in:f}})),l=yield this.find({where:{$or:d}},s);if((a=l==null?void 0:l.data)!=null&&a.length)throw new B(this.label,Object.keys(i))}let c=yield this.apiProxy.records.createMany({label:this.label,data:o},s);return r||(yield s.commit()),c}catch(o){throw r||(yield s.rollback()),o}})}delete(e,t){return u(this,null,function*(){if(j(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 this.apiProxy.records.delete(m(p({},e),{labels:[this.label]}),t)})}deleteById(e,t){return u(this,null,function*(){return yield this.apiProxy.records.deleteById(e,t)})}};var Ee=ue(new L);var qt=Ee;export{R as DBRecordInstance,q as DBRecordsArrayInstance,E as EmptyTargetError,O as HttpClient,N as HttpClientResponse,ye as Model,$ as NonUniqueResultError,M as RestAPI,Ee as RushDB,_ as Transaction,B as UniquenessError,qt as default,ie as idToDate,G as idToTimestamp,ue as initSDK,W as mergeDefaultsWithPayload,ae as parseConfig,J as pickUniqFieldsFromRecord,ne as pickUniqFieldsFromRecords,oe as validateInteger};