@rushdb/javascript-sdk 1.18.0 → 1.19.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/api.d.ts +20 -0
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/sdk/record.d.ts +2 -0
- package/package.json +1 -1
package/dist/api/api.d.ts
CHANGED
|
@@ -220,6 +220,26 @@ export declare class RestAPI {
|
|
|
220
220
|
data: Partial<InferSchemaTypesWrite<S>> | Array<PropertyDraft>;
|
|
221
221
|
options?: Omit<DBRecordCreationOptions, "returnResult" | "capitalizeLabels" | "relationshipType">;
|
|
222
222
|
}, transaction?: Transaction | string) => Promise<DBRecordInstance<S, SearchQuery<S>>>;
|
|
223
|
+
/**
|
|
224
|
+
* Upserts a record: attempts to find an existing record matching mergeBy property values (and optional label)
|
|
225
|
+
* If found: mergeStrategy determines behavior.
|
|
226
|
+
* - 'rewrite': replaces all existing own properties with incoming (like set)
|
|
227
|
+
* - 'append': updates/adds provided properties, keeps others
|
|
228
|
+
* If not found: creates a new record.
|
|
229
|
+
* @param label - The label/type of the record
|
|
230
|
+
* @param data - Flat object or array of property drafts
|
|
231
|
+
* @param options.mergeBy - Property names to match on; If `[]`, all incoming keys are used for matching.
|
|
232
|
+
* @param options.mergeStrategy - 'rewrite' | 'append'
|
|
233
|
+
* @param transaction - Optional transaction for atomic operations
|
|
234
|
+
*/
|
|
235
|
+
upsert: <S extends Schema = any>({ label, data: rawData, options }: {
|
|
236
|
+
label?: string;
|
|
237
|
+
data: InferSchemaTypesWrite<S> | Array<PropertyDraft>;
|
|
238
|
+
options?: Omit<DBRecordCreationOptions, "returnResult" | "capitalizeLabels" | "relationshipType"> & {
|
|
239
|
+
mergeBy?: string[];
|
|
240
|
+
mergeStrategy?: "rewrite" | "append";
|
|
241
|
+
};
|
|
242
|
+
}, transaction?: Transaction | string) => Promise<DBRecordInstance<S>>;
|
|
223
243
|
};
|
|
224
244
|
/**
|
|
225
245
|
* API methods for managing relations between records
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Te=Object.create;var L=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var be=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var xe=(s,e)=>{for(var t in e)L(s,t,{get:e[t],enumerable:!0})},ae=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of we(e))!Ie.call(s,n)&&n!==t&&L(s,n,{get:()=>e[n],enumerable:!(r=De(e,n))||r.enumerable});return s};var oe=(s,e,t)=>(t=s!=null?Te(be(s)):{},ae(e||!s||!s.__esModule?L(t,"default",{value:s,enumerable:!0}):t,s)),Oe=s=>ae(L({},"__esModule",{value:!0}),s);var He={};xe(He,{DBRecordInstance:()=>S,DBRecordsArrayInstance:()=>b,EmptyTargetError:()=>I,HttpClient:()=>O,HttpClientResponse:()=>N,Model:()=>se,NonUniqueResultError:()=>M,RestAPI:()=>B,RushDB:()=>m,Transaction:()=>A,UniquenessError:()=>E,default:()=>Fe,extractMixedPropertiesFromToken:()=>re,idToDate:()=>te,idToTimestamp:()=>V,initSDK:()=>ne,mergeDefaultsWithPayload:()=>v,parseConfig:()=>Z,pickUniqFieldsFromRecord:()=>K,pickUniqFieldsFromRecords:()=>X,validateInteger:()=>ee});module.exports=Oe(He);var O=class s{makeRequest(e,{headers:t,method:r,protocol:n,requestData:a,timeout:o}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(s.TIMEOUT_ERROR_CODE);return e.code=s.TIMEOUT_ERROR_CODE,e}};O.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];O.TIMEOUT_ERROR_CODE="ETIMEDOUT";var $=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 Q=oe(require("http"),1),J=oe(require("https"),1);var Pe="string",Ee="datetime",Ae="boolean",_e="number",Be="null",Ce="vector",ie=[Pe,Ee,Ae,_e,Be,Ce];var de=Q.default||Q,pe=J.default||J,qe=new de.Agent({keepAlive:!0}),je=new pe.Agent({keepAlive:!0}),W=class extends O{constructor(e){super(),this._agent=e}makeRequest(e,{headers:t,method:r,protocol:n,requestData:a,timeout:o}){let i=new URL(e),d=n==="http"||i.protocol==="http:",c=this._agent;return c||(c=d?qe:je),new Promise((p,l)=>{let h=(d?de:pe).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(o!=null?o:8e4,()=>{h.destroy(O.makeTimeoutError())}),h.on("response",u=>{p(new Y(u))}),h.on("error",u=>{l(u)}),h.once("socket",u=>{let w=a?JSON.stringify(a):"";u.connecting?u.once(d?"connect":"secureConnect",()=>{h.write(w),h.end()}):(h.write(w),h.end())})})}},Y=class extends ${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",n=>{r+=n}),this._res.once("end",()=>{try{e(JSON.parse(r))}catch(n){t(n)}})})}};var R=s=>typeof s=="object"&&Array.isArray(s)&&s!==null,T=s=>s!==null&&Object.prototype.toString.call(s)==="[object Object]",q=s=>T(s)&&Object.keys(s).length===0,le=s=>typeof s=="number"||typeof s=="string"||typeof s=="boolean"||s===null;function ke(s,e){let t={...s};return e.forEach(r=>{delete t[r]}),t}var k=s=>T(s)?ke(s,["__label","__id","__proptypes"]):s,C=s=>R(s)?s.map(C):T(s)?Object.fromEntries(Object.entries(s).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,C(t)])):s,z=s=>R(s)?s.every(le):le(s),U=s=>T(s)&&Object.values(s).every(z),P=s=>typeof s=="string",D=s=>{if(typeof s=="string"){if(s.toLowerCase()==="true")return!0;if(s.toLowerCase()==="false")return!1}return R(s)&&s.length===0||T(s)&&Object.keys(s).length===0?!1:!!s};var G=["httpClient","timeout","host","port","protocol","url","logger","options"],he={initial:"in",extended:"ex",fullFeatured:"ff"};var E=class s extends Error{constructor(e,t){super(`Record with label "${e}" and properties ${JSON.stringify(t)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,s.prototype)}},I=class s extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,s.prototype)}},M=class s extends Error{constructor(e,t){super(`Expected a unique result but found ${e} matches for the provided SearchQuery: ${JSON.stringify(t)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,s.prototype)}};var v=async(s,e)=>{let t=Object.entries(s).map(async([a,o])=>o.default&&typeof o.default<"u"&&typeof e[a]>"u"?{key:a,value:typeof o.default=="function"?await o.default():o.default}:{key:a,value:void 0});return{...(await Promise.all(t)).reduce((a,{key:o,value:i})=>(i!==void 0&&(a[o]=i),a),{}),...e}},K=(s,e)=>Object.entries(e).filter(([t])=>{var r;return(r=s[t])==null?void 0:r.unique}).reduce((t,[r,n])=>(r in s&&(t[r]=n),t),{}),X=(s,e,t)=>{let r={},n=Object.entries(e).filter(([,a])=>a.unique).reduce((a,[o])=>(a[o]=!0,a),{});return s.forEach(a=>{Object.entries(a).forEach(([o,i])=>{if(o in n)if(r[o]){if(r[o].includes(i))throw new E(t,{[o]:i});r[o]=[...r[o],i]}else r[o]=[i]})}),r},Z=s=>{if(!s)return{};if(!T(s))throw new Error("Config must be an object");if(Object.keys(s).filter(t=>!G.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${G.join(", ")}`);return s};function ee(s,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${s} must be an integer`)}return e}function V(s){let e=s.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function te(s){return new Date(V(s))}function re(s){let e=/^([a-z]{2})_([01]{3}\d{0,})_(.+)$/,t=s.match(e);if(!t)return[null,s];let[,r,n,a]=t,i=Object.entries(he).find(([h,u])=>u===r)[0],[d,c,p]=n.split("");return[{...{customDB:d==="1",managedDB:c==="1",selfHosted:p==="1",planType:i}},a]}var S=class{constructor(e={}){this.data=e}exists(){return D(this.data.__id)&&D(this.data.__label)}id(){if(!D(this.data.__id))throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.");return this.data.__id}label(){if(!D(this.data.__label))throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.");return this.data.__label}proptypes(){if(!D(this.data.__proptypes))throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.");return this.data.__proptypes}date(){try{return te(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return V(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}async delete(e){if(!D(this.data))throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return await m.getInstance().records.deleteById(this.id(),e)}async update(e,t){if(!D(this.data))throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return m.getInstance().records.update({label:this.label(),target:this.id(),data:e},t)}async set(e,t){if(!D(this.data))throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return m.getInstance().records.set({label:this.label(),target:this.id(),data:e},t)}async attach(e,t,r){if(!D(this.data))throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return m.getInstance().records.attach({source:this.id(),target:e,options:t},r)}async detach(e,t,r){if(!D(this.data))throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return m.getInstance().records.detach({source:this.id(),target:e,options:t},r)}},b=class{constructor(e=[],t=0,r){this.data=e,this.total=t,this.searchQuery=r}};var Ue={"Content-Type":"application/json"},ge=({httpClient:s,token:e,url:t})=>async(r,{headers:n,...a})=>{let o=await s.makeRequest(`${t}${r}`,{credentials:"omit",headers:Object.assign({...Ue,...n},typeof e<"u"?{token:e}:{}),...a});if(o.getStatusCode()>=200&&o.getStatusCode()<300)return await o.toJSON();throw new Error(`${o.getStatusCode()}`)};var A=class{constructor(e){this.id=e}async rollback(){return await m.getInstance().tx.rollback(this.id)}async commit(){return await m.getInstance().tx.commit(this.id)}};var ye="api.rushdb.com";var ue="https",me="/api/v1";var f=s=>s?{"x-transaction-id":s}:void 0,ve=s=>P(s)||s instanceof A,y=s=>ve(s)?s instanceof A?s.id:s:void 0,fe=s=>/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(s),x=s=>{if(P(s)&&fe(s))return s;if(s instanceof S&&s.data)return s.data.__id;if(T(s)&&"__id"in s&&fe(s.__id))return s.__id},j=s=>!(!T(s)||T(s)&&"name"in s&&!P(s.name)||T(s)&&"type"in s&&(!P(s.type)||!ie.includes(s.type))||!("value"in s)||!z(s.value)||"metadata"in s&&!P(s.metadata)||"valueSeparator"in s&&!P(s.valueSeparator)),Se=s=>{let e=ue,t=ye,r=443,n=me;if("url"in s){let o=new URL(s.url);e=o.protocol.replace(":",""),t=o.hostname,r=parseInt(o.port||(e==="http"?"80":e==="https"?"443":""))}"host"in s&&"port"in s&&"protocol"in s&&(e=s.protocol.replace(":",""),t=s.host,r=s.port),n&&!n.startsWith("/")&&(n="/"+n);let a="";return e==="http"&&r===80||e==="https"&&r===443||(a=":"+r),`${e}://${t}${a}${n}`},g=(s=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let r=0;r<s;r++){let n=Math.floor(Math.random()*e.length);t+=e[n]}return t};var B=class{constructor(e,t){this.records={attach:async({source:e,target:t,options:r},n)=>{var l,h;let a=y(n),i=`/relationships/${x(e)}`,d={headers:Object.assign({},f(a)),method:"POST",requestData:{targetIds:this._extractTargetIds(t,"Attach"),...(r==null?void 0:r.type)&&{type:r.type},...(r==null?void 0:r.direction)&&{direction:r.direction}}},c=typeof this.logger=="function"?g():"";(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},n)=>{var l,h;let a=y(n),i=`/relationships/${x(e)}`,d={headers:Object.assign({},f(a)),method:"PUT",requestData:{targetIds:this._extractTargetIds(t,"Detach"),...(r==null?void 0:r.typeOrTypes)&&{typeOrTypes:r.typeOrTypes},...(r==null?void 0:r.direction)&&{direction:r.direction}}},c=typeof this.logger=="function"?g():"";(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},n)=>{var l,h;let a=y(n),o="/records",i={headers:Object.assign({},f(a)),method:"POST",requestData:{}},d=typeof this.logger=="function"?g():"",c=k(C(t));if(R(c)&&c.every(j))i.requestData={label:e,properties:c};else if(U(c))i.requestData={label:e,data:c,options:r};else throw T(c)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(l=this.logger)==null||l.call(this,{requestId:d,path:o,...i});let p=await this.fetcher(o,i);return(h=this.logger)==null||h.call(this,{requestId:d,path:o,...i,responseData:p.data}),p!=null&&p.success&&(p!=null&&p.data)?new S(p.data):new S},createMany:async(e,t)=>{var p,l,h;let r=R(e.data)?e.data:[e.data];if(!r.every(u=>U(u)))throw new Error("records.createMany supports only flat records (no nested objects/arrays). Use records.importJson for nested JSON.");let a=y(t),o="/records/import/json",i={headers:Object.assign({},f(a)),method:"POST",requestData:{...e,data:r}},d=typeof this.logger=="function"?g():"";(p=this.logger)==null||p.call(this,{requestId:d,path:o,...i});let c=await this.fetcher(o,i);if((l=this.logger)==null||l.call(this,{requestId:d,path:o,...i,responseData:c.data}),c!=null&&c.success&&(c!=null&&c.data)){let u=R(c.data)?(h=c.data)==null?void 0:h.map(w=>new S(w)):[];return new b(u,c.total)}return new b([])},importJson:async(e,t)=>{var h,u,w;let{data:r,options:n}=e,{label:a}=e,o=r;if(!a)if(T(r)&&!R(r)){let F=k(r),H=Object.keys(F);if(H.length===1)a=H[0],o=F[a];else throw new Error("records.importJson: Missing `label`. Provide `label` or pass an object with a single top-level key that determines the label, e.g. { ITEM: [...] }")}else throw new Error("records.importJson: Missing `label`. Provide `label` or pass an object with a single top-level key that determines the label, e.g. { ITEM: [...] }");let i=y(t),d="/records/import/json",c={headers:Object.assign({},f(i)),method:"POST",requestData:{label:a,data:o,options:n}},p=typeof this.logger=="function"?g():"";(h=this.logger)==null||h.call(this,{requestId:p,path:d,...c});let l=await this.fetcher(d,c);if((u=this.logger)==null||u.call(this,{requestId:p,path:d,...c,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)){let F=R(l.data)?(w=l.data)==null?void 0:w.map(H=>new S(H)):[];return new b(F,l.total)}return new b([])},importCsv:async(e,t)=>{var d,c;let r=y(t),n="/records/import/csv",a={headers:Object.assign({},f(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);if((c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i!=null&&i.success&&(i!=null&&i.data)){let p=R(i.data)?i.data.map(l=>new S(l)):[];return new b(p,i.total)}return new b([])},delete:async(e,t)=>{var d,c,p;if(q(e.where)&&!((d=this==null?void 0:this.options)!=null&&d.allowForceDelete))throw new I("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let r=y(t),n="/records/delete",a={headers:Object.assign({},f(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(p=this.logger)==null||p.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},deleteById:async(e,t)=>{var c,p;let r=y(t),n=R(e),a=n?"/records/delete":`/records/${e}`,o={headers:Object.assign({},f(r)),method:n?"POST":"DELETE",requestData:n?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:d.data}),d},export:async(e,t)=>{var d,c;let r=y(t),n="/records/export/csv",a={headers:Object.assign({},f(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},find:async(e,t)=>{var l,h;let{id:r,...n}=e,a=y(t),o=r?`/records/${r}/search`:"/records/search",i={headers:Object.assign({},f(a)),method:"POST",requestData:n!=null?n:{}},d=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,{requestId:d,path:o,...i});let c=await this.fetcher(o,i);(h=this.logger)==null||h.call(this,{requestId:d,path:o,...i,responseData:c.data});let p=c.data.map(u=>new S(u));return new b(p,c.total,e)},findById:async(e,t)=>{var d,c;let r=y(t),n=R(e)?"/records":`/records/${e}`,a={headers:Object.assign({},f(r)),method:R(e)?"POST":"GET",requestData:R(e)?{ids:e}:void 0},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);if((c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),R(e)){let p=i.data.map(l=>new S(l));return new b(p,i.total)}else return new S(i.data)},findOne:async(e,t)=>{var c,p;let r=y(t),n="/records/search",a={headers:Object.assign({},f(r)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);(p=this.logger)==null||p.call(this,{requestId:o,path:n,...a,responseData:i.data});let[d]=i.data;return new S(d)},findUniq:async(e,t)=>{var c,p;let r=y(t),n="/records/search",a={headers:Object.assign({},f(r)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);if((p=this.logger)==null||p.call(this,{requestId:o,path:n,...a,responseData:i.data}),typeof i.total<"u"&&i.total>1)throw new M(i.total,e);let[d]=i.data;return new S(d)},set:async({target:e,label:t,data:r,options:n},a)=>{var u,w;let o=y(a),d=`/records/${x(e)}`,c={headers:Object.assign({},f(o)),method:"PUT",requestData:{}},p=typeof this.logger=="function"?g():"",l=k(C(r));if(R(l)&&l.every(j))c.requestData={label:t,properties:l};else if(U(l))c.requestData={label:t,data:l,options:n};else throw T(l)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(u=this.logger)==null||u.call(this,{requestId:p,path:d,...c});let h=await this.fetcher(d,c);return(w=this.logger)==null||w.call(this,{requestId:p,path:d,...c,responseData:h.data}),h!=null&&h.success&&(h!=null&&h.data)?new S(h.data):new S},update:async({target:e,label:t,data:r,options:n},a)=>{var u,w;let o=y(a),d=`/records/${x(e)}`,c={headers:Object.assign({},f(o)),method:"PATCH",requestData:{}},p=typeof this.logger=="function"?g():"",l=k(C(r));if(R(l)&&l.every(j))c.requestData={label:t,properties:l};else if(U(l))c.requestData={label:t,data:l,options:n};else throw T(l)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(u=this.logger)==null||u.call(this,{requestId:p,path:d,...c});let h=await this.fetcher(d,c);return(w=this.logger)==null||w.call(this,{requestId:p,path:d,...c,responseData:h.data}),h!=null&&h.success&&(h!=null&&h.data)?new S(h.data):new S}};this.relationships={createMany:async(e,t)=>{var d,c;let r=y(t),n="/relationships/create-many",a={headers:Object.assign({},f(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},deleteMany:async(e,t)=>{var d,c;let r=y(t),n="/relationships/delete-many",a={headers:Object.assign({},f(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},find:async(e,t)=>{var p,l;let r=y(t),n=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&n.append("limit",e.limit.toString()),(e==null?void 0:e.skip)!==void 0&&n.append("skip",e.skip.toString());let o=`/relationships/search${n.toString()?"?"+n.toString():""}`,i={headers:Object.assign({},f(r)),method:"POST",requestData:e!=null?e:{}},d=typeof this.logger=="function"?g():"";(p=this.logger)==null||p.call(this,{requestId:d,path:o,...i});let c=await this.fetcher(o,i);return(l=this.logger)==null||l.call(this,{requestId:d,path:o,...i,responseData:c.data}),c}};this.properties={delete:async(e,t)=>{var d,c;let r=y(t),n=`/properties/${e}`,a={headers:Object.assign({},f(r)),method:"DELETE"},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},find:async(e,t)=>{var d,c;let r=y(t),n="/properties/search",a={headers:Object.assign({},f(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},findById:async(e,t)=>{var d,c;let r=y(t),n=`/properties/${e}`,a={headers:Object.assign({},f(r)),method:"GET"},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i},values:async(e,t,r)=>{var c,p;let n=y(r),a=`/properties/${e}/values`,o={headers:Object.assign({},f(n)),method:"POST",requestData:t!=null?t:{}},i=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:d.data}),d}};this.labels={find:async(e,t)=>{var d,c;let r=y(t),n="/labels/search",a={headers:Object.assign({},f(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:n,...a});let i=await this.fetcher(n,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:n,...a,responseData:i.data}),i}};this.tx={begin:async e=>{var o,i;let t="/tx",r={method:"POST",requestData:T(e)&&"ttl"in e?e:{}},n=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:n,path:t,...r});let a=await this.fetcher(t,r);return(i=this.logger)==null||i.call(this,{requestId:n,path:t,...r,responseData:a.data}),new A(a.data.id)},commit:async e=>{var i,d;let r=`/tx/${y(e)}/commit`,n={method:"POST",requestData:{}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,{requestId:a,path:r,...n});let o=await this.fetcher(r,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:r,...n,responseData:o.data}),o},get:async e=>{var i,d;let r=`/tx/${y(e)}`,n={method:"GET"},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,{requestId:a,path:r,...n});let o=await this.fetcher(r,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:r,...n,responseData:o.data}),new A(o.data.id)},rollback:async e=>{var i,d;let r=`/tx/${y(e)}/rollback`,n={method:"POST",requestData:{}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,{requestId:a,path:r,...n});let o=await this.fetcher(r,n);return(d=this.logger)==null||d.call(this,{requestId:a,path:r,...n,responseData:o.data}),o}};this.settings={get:async()=>{var a,o;let e="/sdk/settings",t={method:"GET"},r=typeof this.logger=="function"?g():"";(a=this.logger)==null||a.call(this,{requestId:r,path:e,...t});let n=await this.fetcher(e,t);return(o=this.logger)==null||o.call(this,{requestId:r,path:e,...t,responseData:n.data}),n}};this.query={raw:async({query:e,params:t},r)=>{var c,p;let n=y(r),a="/query/raw",o={headers:Object.assign({},f(n)),method:"POST",requestData:{query:e,params:t}},i=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:d.data}),d}};if(this.fetcher=null,t!=null&&t.httpClient){let r=Se(t);this.fetcher=ge({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 S){let n=x(e);if(!n)throw new I(`${t} error: Target id is empty`);return[n]}if(R(e)&&e.every(n=>n instanceof S)){let n=e.map(x).filter(D);if(!n.length)throw new I(`${t} error: Target ids are empty`);return n}if(e instanceof b){let n=(r=e.data)==null?void 0:r.map(x).filter(D);if(!(n!=null&&n.length))throw new I(`${t} error: Target ids are empty`);return n}if(T(e)&&"__id"in e)return[e.__id];if(R(e)&&e.every(n=>T(n)&&"__id"in n)){let n=e.map(x).filter(D);if(!n.length)throw new I(`${t} error: Target ids are empty`);return n}return R(e)?e:P(e)?[e]:[]}};var Re,_=class _ extends B{constructor(e,t){var a;let r=Z(t);super(e,{...r,httpClient:(a=r.httpClient)!=null?a:Re}),_.instance=this;let[n]=re(e!=null?e:"");this.initializeSync(n,e,r)}initializeSync(e,t,r){let n=e?{planType:e.planType,customDB:e.customDB,managedDB:e.managedDB,selfHosted:e.selfHosted}:null;_.state={initialized:!0,debug:!1,timeout:ee("timeout",r==null?void 0:r.timeout,8e4),token:t,...n&&{serverSettings:n}}}static getInstance(){if(_.instance)return _.instance;throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}static isInitialized(){return D(_.instance)}toDBRecordInstance(e){return new S(e)}};_.instance=null,_.state={initialized:!1,debug:!1,timeout:8e4};var m=_,ne=s=>{Re=s};var se=class{constructor(e,t){this.label=e,this.schema=t}getLabel(){return this.label}async toDBRecordInstance(e){try{return m.getInstance().toDBRecordInstance(e)}catch{throw new Error("No RushDB instance was provided during model initialization.")}}async find(e,t){let r=e!=null?e:{};return m.getInstance().records.find({...r,labels:[this.label]},t)}async findOne(e,t){let r=e!=null?e:{};return m.getInstance().records.findOne({...r,labels:[this.label]},t)}async findById(e,t){return this.findOne({where:{$id:e}},t)}async findUniq(e,t){let r=e!=null?e:{};return m.getInstance().records.findUniq({...r,labels:[this.label]},t)}async create(e,t){var i;let r=await v(this.schema,e),n=K(this.schema,r),a=D(n),o=m.getInstance();if(a){let d=t!=null?t:await o.tx.begin(),c=await this.find({where:n},d),p=typeof t<"u";if(!((i=c==null?void 0:c.data)!=null&&i.length)){let h=await o.records.create({label:this.label,data:r},d);return p||await d.commit(),h}else throw p||await d.commit(),new E(this.label,n)}return await o.records.create({label:this.label,data:r},t)}async attach({source:e,target:t,options:r},n){return await m.getInstance().records.attach({source:e,target:t,options:r},n)}async detach({source:e,target:t,options:r},n){return await m.getInstance().records.detach({source:e,target:t,options:r},n)}async handleSetOrUpdate(e,t,r,n){var d,c;if(R(t)&&t.every(j))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let a=m.getInstance(),o=await v(this.schema,t),i=K(this.schema,o);if(!q(i)){let p=n!=null?n:await a.tx.begin(),l=await this.find({where:i},p),h=typeof n<"u";if(!((d=l==null?void 0:l.data)!=null&&d.length)||l.data.length===1&&((c=l.data[0])==null?void 0:c.id())===x(e)){let w=await a.records[r]({target:e,label:this.label,data:o},p);return h||await p.commit(),w}else throw h||await p.commit(),new E(this.label,i)}return await a.records[r]({label:this.label,target:e,data:o},n)}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=m.getInstance(),n=typeof t<"u",a=t!=null?t:await r.tx.begin();try{let i=await Promise.all(e.map(async p=>await v(this.schema,p))),d=X(i,this.schema,this.label);if(!q(d)){let p=Object.entries(d).map(([h,u])=>({[h]:{$in:u}})),l=await this.find({where:{$or:p}},a);if((o=l==null?void 0:l.data)!=null&&o.length)throw new E(this.label,Object.keys(d))}let c=await r.records.createMany({label:this.label,data:i},a);return n||await a.commit(),c}catch(i){throw n||await a.rollback(),i}}async delete(e,t){if(q(e.where))throw new I(`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 m.getInstance().records.delete({...e,labels:[this.label]},t)}async deleteById(e,t){return await m.getInstance().records.deleteById(e,t)}};ne(new W);var Fe=m;0&&(module.exports={DBRecordInstance,DBRecordsArrayInstance,EmptyTargetError,HttpClient,HttpClientResponse,Model,NonUniqueResultError,RestAPI,RushDB,Transaction,UniquenessError,extractMixedPropertiesFromToken,idToDate,idToTimestamp,initSDK,mergeDefaultsWithPayload,parseConfig,pickUniqFieldsFromRecord,pickUniqFieldsFromRecords,validateInteger});
|
|
1
|
+
"use strict";var Te=Object.create;var L=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var be=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var xe=(n,e)=>{for(var t in e)L(n,t,{get:e[t],enumerable:!0})},ae=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of we(e))!Ie.call(n,s)&&s!==t&&L(n,s,{get:()=>e[s],enumerable:!(r=De(e,s))||r.enumerable});return n};var oe=(n,e,t)=>(t=n!=null?Te(be(n)):{},ae(e||!n||!n.__esModule?L(t,"default",{value:n,enumerable:!0}):t,n)),Oe=n=>ae(L({},"__esModule",{value:!0}),n);var He={};xe(He,{DBRecordInstance:()=>m,DBRecordsArrayInstance:()=>b,EmptyTargetError:()=>I,HttpClient:()=>O,HttpClientResponse:()=>N,Model:()=>ne,NonUniqueResultError:()=>v,RestAPI:()=>C,RushDB:()=>f,Transaction:()=>A,UniquenessError:()=>E,default:()=>Fe,extractMixedPropertiesFromToken:()=>re,idToDate:()=>te,idToTimestamp:()=>V,initSDK:()=>se,mergeDefaultsWithPayload:()=>M,parseConfig:()=>Z,pickUniqFieldsFromRecord:()=>K,pickUniqFieldsFromRecords:()=>X,validateInteger:()=>ee});module.exports=Oe(He);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 $=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 Y=oe(require("http"),1),Q=oe(require("https"),1);var Pe="string",Ee="datetime",Ae="boolean",Be="number",_e="null",qe="vector",ie=[Pe,Ee,Ae,Be,_e,qe];var de=Y.default||Y,pe=Q.default||Q,Ce=new de.Agent({keepAlive:!0}),je=new pe.Agent({keepAlive:!0}),W=class extends O{constructor(e){super(),this._agent=e}makeRequest(e,{headers:t,method:r,protocol:s,requestData:a,timeout:o}){let i=new URL(e),d=s==="http"||i.protocol==="http:",c=this._agent;return c||(c=d?Ce:je),new Promise((p,l)=>{let h=(d?de:pe).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(o!=null?o:8e4,()=>{h.destroy(O.makeTimeoutError())}),h.on("response",y=>{p(new J(y))}),h.on("error",y=>{l(y)}),h.once("socket",y=>{let w=a?JSON.stringify(a):"";y.connecting?y.once(d?"connect":"secureConnect",()=>{h.write(w),h.end()}):(h.write(w),h.end())})})}},J=class extends ${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 R=n=>typeof n=="object"&&Array.isArray(n)&&n!==null,T=n=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",j=n=>T(n)&&Object.keys(n).length===0,le=n=>typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null;function ke(n,e){let t={...n};return e.forEach(r=>{delete t[r]}),t}var k=n=>T(n)?ke(n,["__label","__id","__proptypes"]):n,_=n=>R(n)?n.map(_):T(n)?Object.fromEntries(Object.entries(n).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,_(t)])):n,z=n=>R(n)?n.every(le):le(n),U=n=>T(n)&&Object.values(n).every(z),P=n=>typeof n=="string",D=n=>{if(typeof n=="string"){if(n.toLowerCase()==="true")return!0;if(n.toLowerCase()==="false")return!1}return R(n)&&n.length===0||T(n)&&Object.keys(n).length===0?!1:!!n};var G=["httpClient","timeout","host","port","protocol","url","logger","options"],he={initial:"in",extended:"ex",fullFeatured:"ff"};var E=class n extends Error{constructor(e,t){super(`Record with label "${e}" and properties ${JSON.stringify(t)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,n.prototype)}},I=class n extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,n.prototype)}},v=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 M=async(n,e)=>{let t=Object.entries(n).map(async([a,o])=>o.default&&typeof o.default<"u"&&typeof e[a]>"u"?{key:a,value:typeof o.default=="function"?await o.default():o.default}:{key:a,value:void 0});return{...(await Promise.all(t)).reduce((a,{key:o,value:i})=>(i!==void 0&&(a[o]=i),a),{}),...e}},K=(n,e)=>Object.entries(e).filter(([t])=>{var r;return(r=n[t])==null?void 0:r.unique}).reduce((t,[r,s])=>(r in n&&(t[r]=s),t),{}),X=(n,e,t)=>{let r={},s=Object.entries(e).filter(([,a])=>a.unique).reduce((a,[o])=>(a[o]=!0,a),{});return n.forEach(a=>{Object.entries(a).forEach(([o,i])=>{if(o in s)if(r[o]){if(r[o].includes(i))throw new E(t,{[o]:i});r[o]=[...r[o],i]}else r[o]=[i]})}),r},Z=n=>{if(!n)return{};if(!T(n))throw new Error("Config must be an object");if(Object.keys(n).filter(t=>!G.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${G.join(", ")}`);return n};function ee(n,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${n} must be an integer`)}return e}function V(n){let e=n.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function te(n){return new Date(V(n))}function re(n){let e=/^([a-z]{2})_([01]{3}\d{0,})_(.+)$/,t=n.match(e);if(!t)return[null,n];let[,r,s,a]=t,i=Object.entries(he).find(([h,y])=>y===r)[0],[d,c,p]=s.split("");return[{...{customDB:d==="1",managedDB:c==="1",selfHosted:p==="1",planType:i}},a]}var m=class{constructor(e={}){this.data=e}exists(){return D(this.data.__id)&&D(this.data.__label)}id(){if(!D(this.data.__id))throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.");return this.data.__id}label(){if(!D(this.data.__label))throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.");return this.data.__label}proptypes(){if(!D(this.data.__proptypes))throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.");return this.data.__proptypes}date(){try{return te(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return V(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}async delete(e){if(!D(this.data))throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return await f.getInstance().records.deleteById(this.id(),e)}async update(e,t){if(!D(this.data))throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return f.getInstance().records.update({label:this.label(),target:this.id(),data:e},t)}async set(e,t){if(!D(this.data))throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return f.getInstance().records.set({label:this.label(),target:this.id(),data:e},t)}async attach(e,t,r){if(!D(this.data))throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return f.getInstance().records.attach({source:this.id(),target:e,options:t},r)}async detach(e,t,r){if(!D(this.data))throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return f.getInstance().records.detach({source:this.id(),target:e,options:t},r)}},b=class{constructor(e=[],t=0,r){this.data=e,this.total=t,this.searchQuery=r}};var Ue={"Content-Type":"application/json"},ge=({httpClient:n,token:e,url:t})=>async(r,{headers:s,...a})=>{let o=await n.makeRequest(`${t}${r}`,{credentials:"omit",headers:Object.assign({...Ue,...s},typeof e<"u"?{token:e}:{}),...a});if(o.getStatusCode()>=200&&o.getStatusCode()<300)return await o.toJSON();throw new Error(`${o.getStatusCode()}`)};var A=class{constructor(e){this.id=e}async rollback(){return await f.getInstance().tx.rollback(this.id)}async commit(){return await f.getInstance().tx.commit(this.id)}};var ye="api.rushdb.com";var ue="https",fe="/api/v1";var S=n=>n?{"x-transaction-id":n}:void 0,Me=n=>P(n)||n instanceof A,u=n=>Me(n)?n instanceof A?n.id:n:void 0,me=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(P(n)&&me(n))return n;if(n instanceof m&&n.data)return n.data.__id;if(T(n)&&"__id"in n&&me(n.__id))return n.__id},q=n=>!(!T(n)||T(n)&&"name"in n&&!P(n.name)||T(n)&&"type"in n&&(!P(n.type)||!ie.includes(n.type))||!("value"in n)||!z(n.value)||"metadata"in n&&!P(n.metadata)||"valueSeparator"in n&&!P(n.valueSeparator)),Se=n=>{let e=ue,t=ye,r=443,s=fe;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 C=class{constructor(e,t){this.records={attach:async({source:e,target:t,options:r},s)=>{var l,h;let a=u(s),i=`/relationships/${x(e)}`,d={headers:Object.assign({},S(a)),method:"POST",requestData:{targetIds:this._extractTargetIds(t,"Attach"),...(r==null?void 0:r.type)&&{type:r.type},...(r==null?void 0:r.direction)&&{direction:r.direction}}},c=typeof this.logger=="function"?g():"";(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 a=u(s),i=`/relationships/${x(e)}`,d={headers:Object.assign({},S(a)),method:"PUT",requestData:{targetIds:this._extractTargetIds(t,"Detach"),...(r==null?void 0:r.typeOrTypes)&&{typeOrTypes:r.typeOrTypes},...(r==null?void 0:r.direction)&&{direction:r.direction}}},c=typeof this.logger=="function"?g():"";(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 l,h;let a=u(s),o="/records",i={headers:Object.assign({},S(a)),method:"POST",requestData:{}},d=typeof this.logger=="function"?g():"",c=k(_(t));if(R(c)&&c.every(q))i.requestData={label:e,properties:c,options:r};else if(U(c))i.requestData={label:e,data:c,options:r};else throw T(c)?new Error("Provided data is not a flat object. Consider using the `importJson` method for nested objects or arrays of nested objects, or use `createMany` for arrays of flat objects."):new Error("Provided data is not valid.");(l=this.logger)==null||l.call(this,{requestId:d,path:o,...i});let p=await this.fetcher(o,i);return(h=this.logger)==null||h.call(this,{requestId:d,path:o,...i,responseData:p.data}),p!=null&&p.success&&(p!=null&&p.data)?new m(p.data):new m},createMany:async(e,t)=>{var p,l,h;let r=R(e.data)?e.data:[e.data];if(!r.every(y=>U(y)))throw new Error("records.createMany supports only flat records (no nested objects/arrays). Use records.importJson for nested JSON.");let a=u(t),o="/records/import/json",i={headers:Object.assign({},S(a)),method:"POST",requestData:{...e,data:r}},d=typeof this.logger=="function"?g():"";(p=this.logger)==null||p.call(this,{requestId:d,path:o,...i});let c=await this.fetcher(o,i);if((l=this.logger)==null||l.call(this,{requestId:d,path:o,...i,responseData:c.data}),c!=null&&c.success&&(c!=null&&c.data)){let y=R(c.data)?(h=c.data)==null?void 0:h.map(w=>new m(w)):[];return new b(y,c.total)}return new b([])},importJson:async(e,t)=>{var h,y,w;let{data:r,options:s}=e,{label:a}=e,o=r;if(!a)if(T(r)&&!R(r)){let F=k(r),H=Object.keys(F);if(H.length===1)a=H[0],o=F[a];else throw new Error("records.importJson: Missing `label`. Provide `label` or pass an object with a single top-level key that determines the label, e.g. { ITEM: [...] }")}else throw new Error("records.importJson: Missing `label`. Provide `label` or pass an object with a single top-level key that determines the label, e.g. { ITEM: [...] }");let i=u(t),d="/records/import/json",c={headers:Object.assign({},S(i)),method:"POST",requestData:{label:a,data:o,options:s}},p=typeof this.logger=="function"?g():"";(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 F=R(l.data)?(w=l.data)==null?void 0:w.map(H=>new m(H)):[];return new b(F,l.total)}return new b([])},importCsv:async(e,t)=>{var d,c;let r=u(t),s="/records/import/csv",a={headers:Object.assign({},S(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);if((c=this.logger)==null||c.call(this,{requestId:o,path:s,...a,responseData:i.data}),i!=null&&i.success&&(i!=null&&i.data)){let p=R(i.data)?i.data.map(l=>new m(l)):[];return new b(p,i.total)}return new b([])},delete:async(e,t)=>{var d,c,p;if(j(e.where)&&!((d=this==null?void 0:this.options)!=null&&d.allowForceDelete))throw new I("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let r=u(t),s="/records/delete",a={headers:Object.assign({},S(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(p=this.logger)==null||p.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},deleteById:async(e,t)=>{var c,p;let r=u(t),s=R(e),a=s?"/records/delete":`/records/${e}`,o={headers:Object.assign({},S(r)),method:s?"POST":"DELETE",requestData:s?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:d.data}),d},export:async(e,t)=>{var d,c;let r=u(t),s="/records/export/csv",a={headers:Object.assign({},S(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},find:async(e,t)=>{var l,h;let{id:r,...s}=e,a=u(t),o=r?`/records/${r}/search`:"/records/search",i={headers:Object.assign({},S(a)),method:"POST",requestData:s!=null?s:{}},d=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,{requestId:d,path:o,...i});let c=await this.fetcher(o,i);(h=this.logger)==null||h.call(this,{requestId:d,path:o,...i,responseData:c.data});let p=c.data.map(y=>new m(y));return new b(p,c.total,e)},findById:async(e,t)=>{var d,c;let r=u(t),s=R(e)?"/records":`/records/${e}`,a={headers:Object.assign({},S(r)),method:R(e)?"POST":"GET",requestData:R(e)?{ids:e}:void 0},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);if((c=this.logger)==null||c.call(this,{requestId:o,path:s,...a,responseData:i.data}),R(e)){let p=i.data.map(l=>new m(l));return new b(p,i.total)}else return new m(i.data)},findOne:async(e,t)=>{var c,p;let r=u(t),s="/records/search",a={headers:Object.assign({},S(r)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);(p=this.logger)==null||p.call(this,{requestId:o,path:s,...a,responseData:i.data});let[d]=i.data;return new m(d)},findUniq:async(e,t)=>{var c,p;let r=u(t),s="/records/search",a={headers:Object.assign({},S(r)),method:"POST",requestData:{...e,limit:1,skip:0}},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);if((p=this.logger)==null||p.call(this,{requestId:o,path:s,...a,responseData:i.data}),typeof i.total<"u"&&i.total>1)throw new v(i.total,e);let[d]=i.data;return new m(d)},set:async({target:e,label:t,data:r,options:s},a)=>{var y,w;let o=u(a),d=`/records/${x(e)}`,c={headers:Object.assign({},S(o)),method:"PUT",requestData:{}},p=typeof this.logger=="function"?g():"",l=k(_(r));if(R(l)&&l.every(q))c.requestData={label:t,properties:l};else if(U(l))c.requestData={label:t,data:l,options:s};else throw T(l)?new Error("Provided data is not a flat object. Consider to use `importJson` method."):new Error("Provided data is not valid.");(y=this.logger)==null||y.call(this,{requestId:p,path:d,...c});let h=await this.fetcher(d,c);return(w=this.logger)==null||w.call(this,{requestId:p,path:d,...c,responseData:h.data}),h!=null&&h.success&&(h!=null&&h.data)?new m(h.data):new m},update:async({target:e,label:t,data:r,options:s},a)=>{var y,w;let o=u(a),d=`/records/${x(e)}`,c={headers:Object.assign({},S(o)),method:"PATCH",requestData:{}},p=typeof this.logger=="function"?g():"",l=k(_(r));if(R(l)&&l.every(q))c.requestData={label:t,properties:l};else if(U(l))c.requestData={label:t,data:l,options:s};else throw T(l)?new Error("Provided data is not a flat object. Consider to use `importJson` method."):new Error("Provided data is not valid.");(y=this.logger)==null||y.call(this,{requestId:p,path:d,...c});let h=await this.fetcher(d,c);return(w=this.logger)==null||w.call(this,{requestId:p,path:d,...c,responseData:h.data}),h!=null&&h.success&&(h!=null&&h.data)?new m(h.data):new m},upsert:async({label:e,data:t,options:r},s)=>{var h,y,w;let a=u(s),o="/records",i={headers:Object.assign({},S(a)),method:"POST",requestData:{}},d=typeof this.logger=="function"?g():"",c=k(_(t)),p={...r,mergeBy:(h=r==null?void 0:r.mergeBy)!=null?h:[]};if(R(c)&&c.every(q))i.requestData={label:e,properties:c,options:p};else if(U(c))i.requestData={label:e,data:c,options:p};else throw T(c)?new Error("Provided data is not a flat object. Upsert supports flat objects or property drafts array."):new Error("Provided data is not valid.");(y=this.logger)==null||y.call(this,{requestId:d,path:o,...i});let l=await this.fetcher(o,i);return(w=this.logger)==null||w.call(this,{requestId:d,path:o,...i,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)?new m(l.data):new m}};this.relationships={createMany:async(e,t)=>{var d,c;let r=u(t),s="/relationships/create-many",a={headers:Object.assign({},S(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},deleteMany:async(e,t)=>{var d,c;let r=u(t),s="/relationships/delete-many",a={headers:Object.assign({},S(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},find:async(e,t)=>{var p,l;let r=u(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({},S(r)),method:"POST",requestData:e!=null?e:{}},d=typeof this.logger=="function"?g():"";(p=this.logger)==null||p.call(this,{requestId:d,path:o,...i});let c=await this.fetcher(o,i);return(l=this.logger)==null||l.call(this,{requestId:d,path:o,...i,responseData:c.data}),c}};this.properties={delete:async(e,t)=>{var d,c;let r=u(t),s=`/properties/${e}`,a={headers:Object.assign({},S(r)),method:"DELETE"},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},find:async(e,t)=>{var d,c;let r=u(t),s="/properties/search",a={headers:Object.assign({},S(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},findById:async(e,t)=>{var d,c;let r=u(t),s=`/properties/${e}`,a={headers:Object.assign({},S(r)),method:"GET"},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a,responseData:i.data}),i},values:async(e,t,r)=>{var c,p;let s=u(r),a=`/properties/${e}/values`,o={headers:Object.assign({},S(s)),method:"POST",requestData:t!=null?t:{}},i=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:d.data}),d}};this.labels={find:async(e,t)=>{var d,c;let r=u(t),s="/labels/search",a={headers:Object.assign({},S(r)),method:"POST",requestData:e!=null?e:{}},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,{requestId:o,path:s,...a});let i=await this.fetcher(s,a);return(c=this.logger)==null||c.call(this,{requestId:o,path:s,...a,responseData:i.data}),i}};this.tx={begin:async e=>{var o,i;let t="/tx",r={method:"POST",requestData:T(e)&&"ttl"in e?e:{}},s=typeof this.logger=="function"?g():"";(o=this.logger)==null||o.call(this,{requestId:s,path:t,...r});let a=await this.fetcher(t,r);return(i=this.logger)==null||i.call(this,{requestId:s,path:t,...r,responseData:a.data}),new A(a.data.id)},commit:async e=>{var i,d;let r=`/tx/${u(e)}/commit`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,{requestId:a,path:r,...s});let o=await this.fetcher(r,s);return(d=this.logger)==null||d.call(this,{requestId:a,path:r,...s,responseData:o.data}),o},get:async e=>{var i,d;let r=`/tx/${u(e)}`,s={method:"GET"},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,{requestId:a,path:r,...s});let o=await this.fetcher(r,s);return(d=this.logger)==null||d.call(this,{requestId:a,path:r,...s,responseData:o.data}),new A(o.data.id)},rollback:async e=>{var i,d;let r=`/tx/${u(e)}/rollback`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,{requestId:a,path:r,...s});let o=await this.fetcher(r,s);return(d=this.logger)==null||d.call(this,{requestId:a,path:r,...s,responseData:o.data}),o}};this.settings={get:async()=>{var a,o;let e="/sdk/settings",t={method:"GET"},r=typeof this.logger=="function"?g():"";(a=this.logger)==null||a.call(this,{requestId:r,path:e,...t});let s=await this.fetcher(e,t);return(o=this.logger)==null||o.call(this,{requestId:r,path:e,...t,responseData:s.data}),s}};this.query={raw:async({query:e,params:t},r)=>{var c,p;let s=u(r),a="/query/raw",o={headers:Object.assign({},S(s)),method:"POST",requestData:{query:e,params:t}},i=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,{requestId:i,path:a,...o});let d=await this.fetcher(a,o);return(p=this.logger)==null||p.call(this,{requestId:i,path:a,...o,responseData:d.data}),d}};if(this.fetcher=null,t!=null&&t.httpClient){let r=Se(t);this.fetcher=ge({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 m){let s=x(e);if(!s)throw new I(`${t} error: Target id is empty`);return[s]}if(R(e)&&e.every(s=>s instanceof m)){let s=e.map(x).filter(D);if(!s.length)throw new I(`${t} error: Target ids are empty`);return s}if(e instanceof b){let s=(r=e.data)==null?void 0:r.map(x).filter(D);if(!(s!=null&&s.length))throw new I(`${t} error: Target ids are empty`);return s}if(T(e)&&"__id"in e)return[e.__id];if(R(e)&&e.every(s=>T(s)&&"__id"in s)){let s=e.map(x).filter(D);if(!s.length)throw new I(`${t} error: Target ids are empty`);return s}return R(e)?e:P(e)?[e]:[]}};var Re,B=class B extends C{constructor(e,t){var a;let r=Z(t);super(e,{...r,httpClient:(a=r.httpClient)!=null?a:Re}),B.instance=this;let[s]=re(e!=null?e:"");this.initializeSync(s,e,r)}initializeSync(e,t,r){let s=e?{planType:e.planType,customDB:e.customDB,managedDB:e.managedDB,selfHosted:e.selfHosted}:null;B.state={initialized:!0,debug:!1,timeout:ee("timeout",r==null?void 0:r.timeout,8e4),token:t,...s&&{serverSettings:s}}}static getInstance(){if(B.instance)return B.instance;throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}static isInitialized(){return D(B.instance)}toDBRecordInstance(e){return new m(e)}};B.instance=null,B.state={initialized:!1,debug:!1,timeout:8e4};var f=B,se=n=>{Re=n};var ne=class{constructor(e,t){this.label=e,this.schema=t}getLabel(){return this.label}async toDBRecordInstance(e){try{return f.getInstance().toDBRecordInstance(e)}catch{throw new Error("No RushDB instance was provided during model initialization.")}}async find(e,t){let r=e!=null?e:{};return f.getInstance().records.find({...r,labels:[this.label]},t)}async findOne(e,t){let r=e!=null?e:{};return f.getInstance().records.findOne({...r,labels:[this.label]},t)}async findById(e,t){return this.findOne({where:{$id:e}},t)}async findUniq(e,t){let r=e!=null?e:{};return f.getInstance().records.findUniq({...r,labels:[this.label]},t)}async create(e,t){var i;let r=await M(this.schema,e),s=K(this.schema,r),a=D(s),o=f.getInstance();if(a){let d=t!=null?t:await o.tx.begin(),c=await this.find({where:s},d),p=typeof t<"u";if(!((i=c==null?void 0:c.data)!=null&&i.length)){let h=await o.records.create({label:this.label,data:r},d);return p||await d.commit(),h}else throw p||await d.commit(),new E(this.label,s)}return await o.records.create({label:this.label,data:r},t)}async attach({source:e,target:t,options:r},s){return await f.getInstance().records.attach({source:e,target:t,options:r},s)}async detach({source:e,target:t,options:r},s){return await f.getInstance().records.detach({source:e,target:t,options:r},s)}async handleSetOrUpdate(e,t,r,s){var d,c;if(R(t)&&t.every(q))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let a=f.getInstance(),o=await M(this.schema,t),i=K(this.schema,o);if(!j(i)){let p=s!=null?s:await a.tx.begin(),l=await this.find({where:i},p),h=typeof s<"u";if(!((d=l==null?void 0:l.data)!=null&&d.length)||l.data.length===1&&((c=l.data[0])==null?void 0:c.id())===x(e)){let w=await a.records[r]({target:e,label:this.label,data:o},p);return h||await p.commit(),w}else throw h||await p.commit(),new E(this.label,i)}return await a.records[r]({label:this.label,target:e,data:o},s)}async set(e,t,r){return await this.handleSetOrUpdate(e,t,"set",r)}async update(e,t,r){return await this.handleSetOrUpdate(e,t,"update",r)}async createMany(e,t){var o;let r=f.getInstance(),s=typeof t<"u",a=t!=null?t:await r.tx.begin();try{let i=await Promise.all(e.map(async p=>await M(this.schema,p))),d=X(i,this.schema,this.label);if(!j(d)){let p=Object.entries(d).map(([h,y])=>({[h]:{$in:y}})),l=await this.find({where:{$or:p}},a);if((o=l==null?void 0:l.data)!=null&&o.length)throw new E(this.label,Object.keys(d))}let c=await r.records.createMany({label:this.label,data:i},a);return s||await a.commit(),c}catch(i){throw s||await a.rollback(),i}}async delete(e,t){if(j(e.where))throw new I(`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 f.getInstance().records.delete({...e,labels:[this.label]},t)}async deleteById(e,t){return await f.getInstance().records.deleteById(e,t)}};se(new W);var Fe=f;0&&(module.exports={DBRecordInstance,DBRecordsArrayInstance,EmptyTargetError,HttpClient,HttpClientResponse,Model,NonUniqueResultError,RestAPI,RushDB,Transaction,UniquenessError,extractMixedPropertiesFromToken,idToDate,idToTimestamp,initSDK,mergeDefaultsWithPayload,parseConfig,pickUniqFieldsFromRecord,pickUniqFieldsFromRecords,validateInteger});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var be=Object.defineProperty,De=Object.defineProperties;var we=Object.getOwnPropertyDescriptors;var L=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,re=Object.prototype.propertyIsEnumerable;var ee=(n,e,t)=>e in n?be(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,l=(n,e)=>{for(var t in e||(e={}))te.call(e,t)&&ee(n,t,e[t]);if(L)for(var t of L(e))re.call(e,t)&&ee(n,t,e[t]);return n},u=(n,e)=>De(n,we(e));var W=(n,e)=>{var t={};for(var r in n)te.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&L)for(var r of L(n))e.indexOf(r)<0&&re.call(n,r)&&(t[r]=n[r]);return t};var y=(n,e,t)=>new Promise((r,s)=>{var a=c=>{try{o(t.next(c))}catch(d){s(d)}},i=c=>{try{o(t.throw(c))}catch(d){s(d)}},o=c=>c.done?r(c.value):Promise.resolve(c.value).then(a,i);o((t=t.apply(n,e)).next())});var Ie="string",xe="datetime",Oe="boolean",Pe="number",Ee="null",Ae="vector",se=[Ie,xe,Oe,Pe,Ee,Ae];var B=class n{makeRequest(e,{headers:t,method:r,protocol:s,requestData:a,timeout:i}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(n.TIMEOUT_ERROR_CODE);return e.code=n.TIMEOUT_ERROR_CODE,e}};B.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];B.TIMEOUT_ERROR_CODE="ETIMEDOUT";var N=class{constructor(e,t){this._statusCode=e,this._headers=t}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}},Q=class{constructor(e){this._res=e}getStatusCode(){throw new Error("getStatusCode not implemented.")}getHeaders(){throw new Error("getHeaders not implemented.")}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}};var K=class n extends B{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,i=new Promise((c,d)=>{a=setTimeout(()=>{a=null,d(B.makeTimeoutError())},s)}),o=e(t,r);return Promise.race([o,i]).finally(()=>{a&&clearTimeout(a)})}}static makeFetchWithAbortTimeout(e){return(t,r,s)=>y(this,null,function*(){let a=new AbortController,i=setTimeout(()=>{i=null,a.abort(B.makeTimeoutError())},s);try{return yield e(t,u(l({},r),{signal:a.signal}))}catch(o){throw o.name==="AbortError"?B.makeTimeoutError():o}finally{i&&clearTimeout(i)}})}makeRequest(o,c){return y(this,arguments,function*(e,{headers:t,method:r,protocol:s,requestData:a,timeout:i}){let d=r=="POST"||r=="PUT"||r=="PATCH",p=JSON.stringify(a)||(d?"":void 0),h=yield this._fetchFn(e,{body:p,headers:t,method:r},i!=null?i:8e4);return new J(h)})}},J=class n extends N{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 w=n=>typeof n=="object"&&Array.isArray(n)&&n!==null,I=n=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",v=n=>I(n)&&Object.keys(n).length===0,ae=n=>typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null;function Be(n,e){let t=l({},n);return e.forEach(r=>{delete t[r]}),t}var M=n=>I(n)?Be(n,["__label","__id","__proptypes"]):n,U=n=>w(n)?n.map(U):I(n)?Object.fromEntries(Object.entries(n).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,U(t)])):n,z=n=>w(n)?n.every(ae):ae(n),$=n=>I(n)&&Object.values(n).every(z),q=n=>typeof n=="string",x=n=>{if(typeof n=="string"){if(n.toLowerCase()==="true")return!0;if(n.toLowerCase()==="false")return!1}return w(n)&&n.length===0||I(n)&&Object.keys(n).length===0?!1:!!n};var G=["httpClient","timeout","host","port","protocol","url","logger","options"],oe={initial:"in",extended:"ex",fullFeatured:"ff"};var j=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)}},C=class n extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,n.prototype)}},V=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 Y=(n,e)=>y(void 0,null,function*(){let t=Object.entries(n).map(o=>y(void 0,[o],function*([a,i]){return i.default&&typeof i.default!="undefined"&&typeof e[a]=="undefined"?{key:a,value:typeof i.default=="function"?yield i.default():i.default}:{key:a,value:void 0}})),s=(yield Promise.all(t)).reduce((a,{key:i,value:o})=>(o!==void 0&&(a[i]=o),a),{});return l(l({},s),e)}),Z=(n,e)=>Object.entries(e).filter(([t])=>{var r;return(r=n[t])==null?void 0:r.unique}).reduce((t,[r,s])=>(r in n&&(t[r]=s),t),{}),ie=(n,e,t)=>{let r={},s=Object.entries(e).filter(([,a])=>a.unique).reduce((a,[i])=>(a[i]=!0,a),{});return n.forEach(a=>{Object.entries(a).forEach(([i,o])=>{if(i in s)if(r[i]){if(r[i].includes(o))throw new j(t,{[i]:o});r[i]=[...r[i],o]}else r[i]=[o]})}),r},ce=n=>{if(!n)return{};if(!I(n))throw new Error("Config must be an object");if(Object.keys(n).filter(t=>!G.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${G.join(", ")}`);return n};function de(n,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${n} must be an integer`)}return e}function X(n){let e=n.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function le(n){return new Date(X(n))}function pe(n){let e=/^([a-z]{2})_([01]{3}\d{0,})_(.+)$/,t=n.match(e);if(!t)return[null,n];let[,r,s,a]=t,o=Object.entries(oe).find(([g,m])=>m===r)[0],[c,d,p]=s.split("");return[l({},{customDB:c==="1",managedDB:d==="1",selfHosted:p==="1",planType:o}),a]}var D=class{constructor(e={}){this.data=e}exists(){return x(this.data.__id)&&x(this.data.__label)}id(){if(!x(this.data.__id))throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.");return this.data.__id}label(){if(!x(this.data.__label))throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.");return this.data.__label}proptypes(){if(!x(this.data.__proptypes))throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.");return this.data.__proptypes}date(){try{return le(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return X(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}delete(e){return y(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return yield T.getInstance().records.deleteById(this.id(),e)})}update(e,t){return y(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return T.getInstance().records.update({label:this.label(),target:this.id(),data:e},t)})}set(e,t){return y(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return T.getInstance().records.set({label:this.label(),target:this.id(),data:e},t)})}attach(e,t,r){return y(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return T.getInstance().records.attach({source:this.id(),target:e,options:t},r)})}detach(e,t,r){return y(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return T.getInstance().records.detach({source:this.id(),target:e,options:t},r)})}},O=class{constructor(e=[],t=0,r){this.data=e,this.total=t,this.searchQuery=r}};var Ce={"Content-Type":"application/json"},he=({httpClient:n,token:e,url:t})=>(r,i)=>y(void 0,null,function*(){var o=i,{headers:s}=o,a=W(o,["headers"]);let c=yield n.makeRequest(`${t}${r}`,l({credentials:"omit",headers:Object.assign(l(l({},Ce),s),typeof e!="undefined"?{token:e}:{})},a));if(c.getStatusCode()>=200&&c.getStatusCode()<300)return yield c.toJSON();throw new Error(`${c.getStatusCode()}`)});var k=class{constructor(e){this.id=e}rollback(){return y(this,null,function*(){return yield T.getInstance().tx.rollback(this.id)})}commit(){return y(this,null,function*(){return yield T.getInstance().tx.commit(this.id)})}};var ye="api.rushdb.com";var ue="https",ge="/api/v1";var b=n=>n?{"x-transaction-id":n}:void 0,_e=n=>q(n)||n instanceof k,R=n=>_e(n)?n instanceof k?n.id:n:void 0,me=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),P=n=>{if(q(n)&&me(n))return n;if(n instanceof D&&n.data)return n.data.__id;if(I(n)&&"__id"in n&&me(n.__id))return n.__id},F=n=>!(!I(n)||I(n)&&"name"in n&&!q(n.name)||I(n)&&"type"in n&&(!q(n.type)||!se.includes(n.type))||!("value"in n)||!z(n.value)||"metadata"in n&&!q(n.metadata)||"valueSeparator"in n&&!q(n.valueSeparator)),fe=n=>{let e=ue,t=ye,r=443,s=ge;if("url"in n){let i=new URL(n.url);e=i.protocol.replace(":",""),t=i.hostname,r=parseInt(i.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}`},S=(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 H=class{constructor(e,t){this.records={attach:(a,i)=>y(this,[a,i],function*({source:e,target:t,options:r},s){var m,f;let o=R(s),d=`/relationships/${P(e)}`,p={headers:Object.assign({},b(o)),method:"POST",requestData:l(l({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"?S():"";(m=this.logger)==null||m.call(this,l({requestId:h,path:d},p));let g=yield this.fetcher(d,p);return(f=this.logger)==null||f.call(this,u(l({requestId:h,path:d},p),{responseData:g.data})),g}),detach:(a,i)=>y(this,[a,i],function*({source:e,target:t,options:r},s){var m,f;let o=R(s),d=`/relationships/${P(e)}`,p={headers:Object.assign({},b(o)),method:"PUT",requestData:l(l({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"?S():"";(m=this.logger)==null||m.call(this,l({requestId:h,path:d},p));let g=yield this.fetcher(d,p);return(f=this.logger)==null||f.call(this,u(l({requestId:h,path:d},p),{responseData:g.data})),g}),create:(a,i)=>y(this,[a,i],function*({label:e,data:t,options:r},s){var m,f;let o=R(s),c="/records",d={headers:Object.assign({},b(o)),method:"POST",requestData:{}},p=typeof this.logger=="function"?S():"",h=M(U(t));if(w(h)&&h.every(F))d.requestData={label:e,properties:h};else if($(h))d.requestData={label:e,data:h,options:r};else throw I(h)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(m=this.logger)==null||m.call(this,l({requestId:p,path:c},d));let g=yield this.fetcher(c,d);return(f=this.logger)==null||f.call(this,u(l({requestId:p,path:c},d),{responseData:g.data})),g!=null&&g.success&&(g!=null&&g.data)?new D(g.data):new D}),createMany:(e,t)=>y(this,null,function*(){var p,h,g;let r=w(e.data)?e.data:[e.data];if(!r.every(m=>$(m)))throw new Error("records.createMany supports only flat records (no nested objects/arrays). Use records.importJson for nested JSON.");let a=R(t),i="/records/import/json",o={headers:Object.assign({},b(a)),method:"POST",requestData:u(l({},e),{data:r})},c=typeof this.logger=="function"?S():"";(p=this.logger)==null||p.call(this,l({requestId:c,path:i},o));let d=yield this.fetcher(i,o);if((h=this.logger)==null||h.call(this,u(l({requestId:c,path:i},o),{responseData:d.data})),d!=null&&d.success&&(d!=null&&d.data)){let m=w(d.data)?(g=d.data)==null?void 0:g.map(f=>new D(f)):[];return new O(m,d.total)}return new O([])}),importJson:(e,t)=>y(this,null,function*(){var g,m,f;let{data:r,options:s}=e,{label:a}=e,i=r;if(!a)if(I(r)&&!w(r)){let E=M(r),A=Object.keys(E);if(A.length===1)a=A[0],i=E[a];else throw new Error("records.importJson: Missing `label`. Provide `label` or pass an object with a single top-level key that determines the label, e.g. { ITEM: [...] }")}else throw new Error("records.importJson: Missing `label`. Provide `label` or pass an object with a single top-level key that determines the label, e.g. { ITEM: [...] }");let o=R(t),c="/records/import/json",d={headers:Object.assign({},b(o)),method:"POST",requestData:{label:a,data:i,options:s}},p=typeof this.logger=="function"?S():"";(g=this.logger)==null||g.call(this,l({requestId:p,path:c},d));let h=yield this.fetcher(c,d);if((m=this.logger)==null||m.call(this,u(l({requestId:p,path:c},d),{responseData:h.data})),h!=null&&h.success&&(h!=null&&h.data)){let E=w(h.data)?(f=h.data)==null?void 0:f.map(A=>new D(A)):[];return new O(E,h.total)}return new O([])}),importCsv:(e,t)=>y(this,null,function*(){var c,d;let r=R(t),s="/records/import/csv",a={headers:Object.assign({},b(r)),method:"POST",requestData:e},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,l({requestId:i,path:s},a));let o=yield this.fetcher(s,a);if((d=this.logger)==null||d.call(this,u(l({requestId:i,path:s},a),{responseData:o.data})),o!=null&&o.success&&(o!=null&&o.data)){let p=w(o.data)?o.data.map(h=>new D(h)):[];return new O(p,o.total)}return new O([])}),delete:(e,t)=>y(this,null,function*(){var c,d,p;if(v(e.where)&&!((c=this==null?void 0:this.options)!=null&&c.allowForceDelete))throw new C("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let r=R(t),s="/records/delete",a={headers:Object.assign({},b(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,l({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(p=this.logger)==null||p.call(this,u(l({requestId:i,path:s},a),{responseData:o.data})),o}),deleteById:(e,t)=>y(this,null,function*(){var d,p;let r=R(t),s=w(e),a=s?"/records/delete":`/records/${e}`,i={headers:Object.assign({},b(r)),method:s?"POST":"DELETE",requestData:s?{limit:1e3,where:{$id:{$in:e}}}:void 0},o=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,l({requestId:o,path:a},i));let c=yield this.fetcher(a,i);return(p=this.logger)==null||p.call(this,u(l({requestId:o,path:a},i),{responseData:c.data})),c}),export:(e,t)=>y(this,null,function*(){var c,d;let r=R(t),s="/records/export/csv",a={headers:Object.assign({},b(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,l({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,u(l({requestId:i,path:s},a),{responseData:o.data})),o}),find:(e,t)=>y(this,null,function*(){var g,m;let h=e,{id:r}=h,s=W(h,["id"]),a=R(t),i=r?`/records/${r}/search`:"/records/search",o={headers:Object.assign({},b(a)),method:"POST",requestData:s!=null?s:{}},c=typeof this.logger=="function"?S():"";(g=this.logger)==null||g.call(this,l({requestId:c,path:i},o));let d=yield this.fetcher(i,o);(m=this.logger)==null||m.call(this,u(l({requestId:c,path:i},o),{responseData:d.data}));let p=d.data.map(f=>new D(f));return new O(p,d.total,e)}),findById:(e,t)=>y(this,null,function*(){var c,d;let r=R(t),s=w(e)?"/records":`/records/${e}`,a={headers:Object.assign({},b(r)),method:w(e)?"POST":"GET",requestData:w(e)?{ids:e}:void 0},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,l({requestId:i,path:s},a));let o=yield this.fetcher(s,a);if((d=this.logger)==null||d.call(this,u(l({requestId:i,path:s},a),{responseData:o.data})),w(e)){let p=o.data.map(h=>new D(h));return new O(p,o.total)}else return new D(o.data)}),findOne:(e,t)=>y(this,null,function*(){var d,p;let r=R(t),s="/records/search",a={headers:Object.assign({},b(r)),method:"POST",requestData:u(l({},e),{limit:1,skip:0})},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,l({requestId:i,path:s},a));let o=yield this.fetcher(s,a);(p=this.logger)==null||p.call(this,u(l({requestId:i,path:s},a),{responseData:o.data}));let[c]=o.data;return new D(c)}),findUniq:(e,t)=>y(this,null,function*(){var d,p;let r=R(t),s="/records/search",a={headers:Object.assign({},b(r)),method:"POST",requestData:u(l({},e),{limit:1,skip:0})},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,l({requestId:i,path:s},a));let o=yield this.fetcher(s,a);if((p=this.logger)==null||p.call(this,u(l({requestId:i,path:s},a),{responseData:o.data})),typeof o.total!="undefined"&&o.total>1)throw new V(o.total,e);let[c]=o.data;return new D(c)}),set:(i,o)=>y(this,[i,o],function*({target:e,label:t,data:r,options:s},a){var E,A;let c=R(a),p=`/records/${P(e)}`,h={headers:Object.assign({},b(c)),method:"PUT",requestData:{}},g=typeof this.logger=="function"?S():"",m=M(U(r));if(w(m)&&m.every(F))h.requestData={label:t,properties:m};else if($(m))h.requestData={label:t,data:m,options:s};else throw I(m)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(E=this.logger)==null||E.call(this,l({requestId:g,path:p},h));let f=yield this.fetcher(p,h);return(A=this.logger)==null||A.call(this,u(l({requestId:g,path:p},h),{responseData:f.data})),f!=null&&f.success&&(f!=null&&f.data)?new D(f.data):new D}),update:(i,o)=>y(this,[i,o],function*({target:e,label:t,data:r,options:s},a){var E,A;let c=R(a),p=`/records/${P(e)}`,h={headers:Object.assign({},b(c)),method:"PATCH",requestData:{}},g=typeof this.logger=="function"?S():"",m=M(U(r));if(w(m)&&m.every(F))h.requestData={label:t,properties:m};else if($(m))h.requestData={label:t,data:m,options:s};else throw I(m)?new Error("Provided data is not a flat object. Consider to use `createMany` method."):new Error("Provided data is not valid.");(E=this.logger)==null||E.call(this,l({requestId:g,path:p},h));let f=yield this.fetcher(p,h);return(A=this.logger)==null||A.call(this,u(l({requestId:g,path:p},h),{responseData:f.data})),f!=null&&f.success&&(f!=null&&f.data)?new D(f.data):new D})};this.relationships={createMany:(e,t)=>y(this,null,function*(){var c,d;let r=R(t),s="/relationships/create-many",a={headers:Object.assign({},b(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,l({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,u(l({requestId:i,path:s},a),{responseData:o.data})),o}),deleteMany:(e,t)=>y(this,null,function*(){var c,d;let r=R(t),s="/relationships/delete-many",a={headers:Object.assign({},b(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,l({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,u(l({requestId:i,path:s},a),{responseData:o.data})),o}),find:(e,t)=>y(this,null,function*(){var p,h;let r=R(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 i=`/relationships/search${s.toString()?"?"+s.toString():""}`,o={headers:Object.assign({},b(r)),method:"POST",requestData:e!=null?e:{}},c=typeof this.logger=="function"?S():"";(p=this.logger)==null||p.call(this,l({requestId:c,path:i},o));let d=yield this.fetcher(i,o);return(h=this.logger)==null||h.call(this,u(l({requestId:c,path:i},o),{responseData:d.data})),d})};this.properties={delete:(e,t)=>y(this,null,function*(){var c,d;let r=R(t),s=`/properties/${e}`,a={headers:Object.assign({},b(r)),method:"DELETE"},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,l({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,u(l({requestId:i,path:s},a),{responseData:o.data})),o}),find:(e,t)=>y(this,null,function*(){var c,d;let r=R(t),s="/properties/search",a={headers:Object.assign({},b(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,l({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,u(l({requestId:i,path:s},a),{responseData:o.data})),o}),findById:(e,t)=>y(this,null,function*(){var c,d;let r=R(t),s=`/properties/${e}`,a={headers:Object.assign({},b(r)),method:"GET"},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,l({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,u(l({requestId:i,path:s},a),{responseData:o.data})),o}),values:(e,t,r)=>y(this,null,function*(){var d,p;let s=R(r),a=`/properties/${e}/values`,i={headers:Object.assign({},b(s)),method:"POST",requestData:t!=null?t:{}},o=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,l({requestId:o,path:a},i));let c=yield this.fetcher(a,i);return(p=this.logger)==null||p.call(this,u(l({requestId:o,path:a},i),{responseData:c.data})),c})};this.labels={find:(e,t)=>y(this,null,function*(){var c,d;let r=R(t),s="/labels/search",a={headers:Object.assign({},b(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,l({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,u(l({requestId:i,path:s},a),{responseData:o.data})),o})};this.tx={begin:e=>y(this,null,function*(){var i,o;let t="/tx",r={method:"POST",requestData:I(e)&&"ttl"in e?e:{}},s=typeof this.logger=="function"?S():"";(i=this.logger)==null||i.call(this,l({requestId:s,path:t},r));let a=yield this.fetcher(t,r);return(o=this.logger)==null||o.call(this,u(l({requestId:s,path:t},r),{responseData:a.data})),new k(a.data.id)}),commit:e=>y(this,null,function*(){var o,c;let r=`/tx/${R(e)}/commit`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,l({requestId:a,path:r},s));let i=yield this.fetcher(r,s);return(c=this.logger)==null||c.call(this,u(l({requestId:a,path:r},s),{responseData:i.data})),i}),get:e=>y(this,null,function*(){var o,c;let r=`/tx/${R(e)}`,s={method:"GET"},a=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,l({requestId:a,path:r},s));let i=yield this.fetcher(r,s);return(c=this.logger)==null||c.call(this,u(l({requestId:a,path:r},s),{responseData:i.data})),new k(i.data.id)}),rollback:e=>y(this,null,function*(){var o,c;let r=`/tx/${R(e)}/rollback`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,l({requestId:a,path:r},s));let i=yield this.fetcher(r,s);return(c=this.logger)==null||c.call(this,u(l({requestId:a,path:r},s),{responseData:i.data})),i})};this.settings={get:()=>y(this,null,function*(){var a,i;let e="/sdk/settings",t={method:"GET"},r=typeof this.logger=="function"?S():"";(a=this.logger)==null||a.call(this,l({requestId:r,path:e},t));let s=yield this.fetcher(e,t);return(i=this.logger)==null||i.call(this,u(l({requestId:r,path:e},t),{responseData:s.data})),s})};this.query={raw:(s,a)=>y(this,[s,a],function*({query:e,params:t},r){var h,g;let i=R(r),o="/query/raw",c={headers:Object.assign({},b(i)),method:"POST",requestData:{query:e,params:t}},d=typeof this.logger=="function"?S():"";(h=this.logger)==null||h.call(this,l({requestId:d,path:o},c));let p=yield this.fetcher(o,c);return(g=this.logger)==null||g.call(this,u(l({requestId:d,path:o},c),{responseData:p.data})),p})};if(this.fetcher=null,t!=null&&t.httpClient){let r=fe(t);this.fetcher=he({httpClient:t.httpClient,token:e,url:r})}t!=null&&t.options&&(this.options=t==null?void 0:t.options),t!=null&&t.logger&&(this.logger=t==null?void 0:t.logger)}_extractTargetIds(e,t){var r;if(e instanceof D){let s=P(e);if(!s)throw new C(`${t} error: Target id is empty`);return[s]}if(w(e)&&e.every(s=>s instanceof D)){let s=e.map(P).filter(x);if(!s.length)throw new C(`${t} error: Target ids are empty`);return s}if(e instanceof O){let s=(r=e.data)==null?void 0:r.map(P).filter(x);if(!(s!=null&&s.length))throw new C(`${t} error: Target ids are empty`);return s}if(I(e)&&"__id"in e)return[e.__id];if(w(e)&&e.every(s=>I(s)&&"__id"in s)){let s=e.map(P).filter(x);if(!s.length)throw new C(`${t} error: Target ids are empty`);return s}return w(e)?e:q(e)?[e]:[]}};var Se,_=class _ extends H{constructor(e,t){var a;let r=ce(t);super(e,u(l({},r),{httpClient:(a=r.httpClient)!=null?a:Se})),_.instance=this;let[s]=pe(e!=null?e:"");this.initializeSync(s,e,r)}initializeSync(e,t,r){let s=e?{planType:e.planType,customDB:e.customDB,managedDB:e.managedDB,selfHosted:e.selfHosted}:null;_.state=l({initialized:!0,debug:!1,timeout:de("timeout",r==null?void 0:r.timeout,8e4),token:t},s&&{serverSettings:s})}static getInstance(){if(_.instance)return _.instance;throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}static isInitialized(){return x(_.instance)}toDBRecordInstance(e){return new D(e)}};_.instance=null,_.state={initialized:!1,debug:!1,timeout:8e4};var T=_,Re=n=>{Se=n};var Te=class{constructor(e,t){this.label=e,this.schema=t}getLabel(){return this.label}toDBRecordInstance(e){return y(this,null,function*(){try{return T.getInstance().toDBRecordInstance(e)}catch(t){throw new Error("No RushDB instance was provided during model initialization.")}})}find(e,t){return y(this,null,function*(){let r=e!=null?e:{};return T.getInstance().records.find(u(l({},r),{labels:[this.label]}),t)})}findOne(e,t){return y(this,null,function*(){let r=e!=null?e:{};return T.getInstance().records.findOne(u(l({},r),{labels:[this.label]}),t)})}findById(e,t){return y(this,null,function*(){return this.findOne({where:{$id:e}},t)})}findUniq(e,t){return y(this,null,function*(){let r=e!=null?e:{};return T.getInstance().records.findUniq(u(l({},r),{labels:[this.label]}),t)})}create(e,t){return y(this,null,function*(){var o;let r=yield Y(this.schema,e),s=Z(this.schema,r),a=x(s),i=T.getInstance();if(a){let c=t!=null?t:yield i.tx.begin(),d=yield this.find({where:s},c),p=typeof t!="undefined";if(!((o=d==null?void 0:d.data)!=null&&o.length)){let g=yield i.records.create({label:this.label,data:r},c);return p||(yield c.commit()),g}else throw p||(yield c.commit()),new j(this.label,s)}return yield i.records.create({label:this.label,data:r},t)})}attach(a,i){return y(this,arguments,function*({source:e,target:t,options:r},s){return yield T.getInstance().records.attach({source:e,target:t,options:r},s)})}detach(a,i){return y(this,arguments,function*({source:e,target:t,options:r},s){return yield T.getInstance().records.detach({source:e,target:t,options:r},s)})}handleSetOrUpdate(e,t,r,s){return y(this,null,function*(){var c,d;if(w(t)&&t.every(F))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let a=T.getInstance(),i=yield Y(this.schema,t),o=Z(this.schema,i);if(!v(o)){let p=s!=null?s:yield a.tx.begin(),h=yield this.find({where:o},p),g=typeof s!="undefined";if(!((c=h==null?void 0:h.data)!=null&&c.length)||h.data.length===1&&((d=h.data[0])==null?void 0:d.id())===P(e)){let f=yield a.records[r]({target:e,label:this.label,data:i},p);return g||(yield p.commit()),f}else throw g||(yield p.commit()),new j(this.label,o)}return yield a.records[r]({label:this.label,target:e,data:i},s)})}set(e,t,r){return y(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"set",r)})}update(e,t,r){return y(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"update",r)})}createMany(e,t){return y(this,null,function*(){var i;let r=T.getInstance(),s=typeof t!="undefined",a=t!=null?t:yield r.tx.begin();try{let o=yield Promise.all(e.map(p=>y(this,null,function*(){return yield Y(this.schema,p)}))),c=ie(o,this.schema,this.label);if(!v(c)){let p=Object.entries(c).map(([g,m])=>({[g]:{$in:m}})),h=yield this.find({where:{$or:p}},a);if((i=h==null?void 0:h.data)!=null&&i.length)throw new j(this.label,Object.keys(c))}let d=yield r.records.createMany({label:this.label,data:o},a);return s||(yield a.commit()),d}catch(o){throw s||(yield a.rollback()),o}})}delete(e,t){return y(this,null,function*(){if(v(e.where))throw new C(`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 T.getInstance().records.delete(u(l({},e),{labels:[this.label]}),t)})}deleteById(e,t){return y(this,null,function*(){return yield T.getInstance().records.deleteById(e,t)})}};Re(new K);var Ht=T;export{D as DBRecordInstance,O as DBRecordsArrayInstance,C as EmptyTargetError,B as HttpClient,Q as HttpClientResponse,Te as Model,V as NonUniqueResultError,H as RestAPI,T as RushDB,k as Transaction,j as UniquenessError,Ht as default,pe as extractMixedPropertiesFromToken,le as idToDate,X as idToTimestamp,Re as initSDK,Y as mergeDefaultsWithPayload,ce as parseConfig,Z as pickUniqFieldsFromRecord,ie as pickUniqFieldsFromRecords,de as validateInteger};
|
|
1
|
+
var be=Object.defineProperty,De=Object.defineProperties;var we=Object.getOwnPropertyDescriptors;var W=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,re=Object.prototype.propertyIsEnumerable;var ee=(n,e,t)=>e in n?be(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,p=(n,e)=>{for(var t in e||(e={}))te.call(e,t)&&ee(n,t,e[t]);if(W)for(var t of W(e))re.call(e,t)&&ee(n,t,e[t]);return n},g=(n,e)=>De(n,we(e));var $=(n,e)=>{var t={};for(var r in n)te.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&W)for(var r of W(n))e.indexOf(r)<0&&re.call(n,r)&&(t[r]=n[r]);return t};var y=(n,e,t)=>new Promise((r,s)=>{var a=d=>{try{o(t.next(d))}catch(c){s(c)}},i=d=>{try{o(t.throw(d))}catch(c){s(c)}},o=d=>d.done?r(d.value):Promise.resolve(d.value).then(a,i);o((t=t.apply(n,e)).next())});var Ie="string",xe="datetime",Oe="boolean",Pe="number",Ee="null",Ae="vector",se=[Ie,xe,Oe,Pe,Ee,Ae];var B=class n{makeRequest(e,{headers:t,method:r,protocol:s,requestData:a,timeout:i}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(n.TIMEOUT_ERROR_CODE);return e.code=n.TIMEOUT_ERROR_CODE,e}};B.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];B.TIMEOUT_ERROR_CODE="ETIMEDOUT";var N=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.")}},Y=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 K=class n extends B{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,i=new Promise((d,c)=>{a=setTimeout(()=>{a=null,c(B.makeTimeoutError())},s)}),o=e(t,r);return Promise.race([o,i]).finally(()=>{a&&clearTimeout(a)})}}static makeFetchWithAbortTimeout(e){return(t,r,s)=>y(this,null,function*(){let a=new AbortController,i=setTimeout(()=>{i=null,a.abort(B.makeTimeoutError())},s);try{return yield e(t,g(p({},r),{signal:a.signal}))}catch(o){throw o.name==="AbortError"?B.makeTimeoutError():o}finally{i&&clearTimeout(i)}})}makeRequest(o,d){return y(this,arguments,function*(e,{headers:t,method:r,protocol:s,requestData:a,timeout:i}){let c=r=="POST"||r=="PUT"||r=="PATCH",h=JSON.stringify(a)||(c?"":void 0),l=yield this._fetchFn(e,{body:h,headers:t,method:r},i!=null?i:8e4);return new Q(l)})}},Q=class n extends N{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 w=n=>typeof n=="object"&&Array.isArray(n)&&n!==null,I=n=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",F=n=>I(n)&&Object.keys(n).length===0,ae=n=>typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null;function Be(n,e){let t=p({},n);return e.forEach(r=>{delete t[r]}),t}var H=n=>I(n)?Be(n,["__label","__id","__proptypes"]):n,v=n=>w(n)?n.map(v):I(n)?Object.fromEntries(Object.entries(n).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,v(t)])):n,z=n=>w(n)?n.every(ae):ae(n),M=n=>I(n)&&Object.values(n).every(z),C=n=>typeof n=="string",x=n=>{if(typeof n=="string"){if(n.toLowerCase()==="true")return!0;if(n.toLowerCase()==="false")return!1}return w(n)&&n.length===0||I(n)&&Object.keys(n).length===0?!1:!!n};var G=["httpClient","timeout","host","port","protocol","url","logger","options"],oe={initial:"in",extended:"ex",fullFeatured:"ff"};var j=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)}},q=class n extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,n.prototype)}},V=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 J=(n,e)=>y(void 0,null,function*(){let t=Object.entries(n).map(o=>y(void 0,[o],function*([a,i]){return i.default&&typeof i.default!="undefined"&&typeof e[a]=="undefined"?{key:a,value:typeof i.default=="function"?yield i.default():i.default}:{key:a,value:void 0}})),s=(yield Promise.all(t)).reduce((a,{key:i,value:o})=>(o!==void 0&&(a[i]=o),a),{});return p(p({},s),e)}),Z=(n,e)=>Object.entries(e).filter(([t])=>{var r;return(r=n[t])==null?void 0:r.unique}).reduce((t,[r,s])=>(r in n&&(t[r]=s),t),{}),ie=(n,e,t)=>{let r={},s=Object.entries(e).filter(([,a])=>a.unique).reduce((a,[i])=>(a[i]=!0,a),{});return n.forEach(a=>{Object.entries(a).forEach(([i,o])=>{if(i in s)if(r[i]){if(r[i].includes(o))throw new j(t,{[i]:o});r[i]=[...r[i],o]}else r[i]=[o]})}),r},ce=n=>{if(!n)return{};if(!I(n))throw new Error("Config must be an object");if(Object.keys(n).filter(t=>!G.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${G.join(", ")}`);return n};function de(n,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${n} must be an integer`)}return e}function X(n){let e=n.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function pe(n){return new Date(X(n))}function le(n){let e=/^([a-z]{2})_([01]{3}\d{0,})_(.+)$/,t=n.match(e);if(!t)return[null,n];let[,r,s,a]=t,o=Object.entries(oe).find(([m,u])=>u===r)[0],[d,c,h]=s.split("");return[p({},{customDB:d==="1",managedDB:c==="1",selfHosted:h==="1",planType:o}),a]}var D=class{constructor(e={}){this.data=e}exists(){return x(this.data.__id)&&x(this.data.__label)}id(){if(!x(this.data.__id))throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.");return this.data.__id}label(){if(!x(this.data.__label))throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.");return this.data.__label}proptypes(){if(!x(this.data.__proptypes))throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.");return this.data.__proptypes}date(){try{return pe(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return X(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}delete(e){return y(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return yield b.getInstance().records.deleteById(this.id(),e)})}update(e,t){return y(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return b.getInstance().records.update({label:this.label(),target:this.id(),data:e},t)})}set(e,t){return y(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return b.getInstance().records.set({label:this.label(),target:this.id(),data:e},t)})}attach(e,t,r){return y(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return b.getInstance().records.attach({source:this.id(),target:e,options:t},r)})}detach(e,t,r){return y(this,null,function*(){if(!x(this.data))throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return b.getInstance().records.detach({source:this.id(),target:e,options:t},r)})}},E=class{constructor(e=[],t=0,r){this.data=e,this.total=t,this.searchQuery=r}};var qe={"Content-Type":"application/json"},he=({httpClient:n,token:e,url:t})=>(r,i)=>y(void 0,null,function*(){var o=i,{headers:s}=o,a=$(o,["headers"]);let d=yield n.makeRequest(`${t}${r}`,p({credentials:"omit",headers:Object.assign(p(p({},qe),s),typeof e!="undefined"?{token:e}:{})},a));if(d.getStatusCode()>=200&&d.getStatusCode()<300)return yield d.toJSON();throw new Error(`${d.getStatusCode()}`)});var k=class{constructor(e){this.id=e}rollback(){return y(this,null,function*(){return yield b.getInstance().tx.rollback(this.id)})}commit(){return y(this,null,function*(){return yield b.getInstance().tx.commit(this.id)})}};var ye="api.rushdb.com";var ue="https",ge="/api/v1";var T=n=>n?{"x-transaction-id":n}:void 0,_e=n=>C(n)||n instanceof k,R=n=>_e(n)?n instanceof k?n.id:n:void 0,me=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),A=n=>{if(C(n)&&me(n))return n;if(n instanceof D&&n.data)return n.data.__id;if(I(n)&&"__id"in n&&me(n.__id))return n.__id},U=n=>!(!I(n)||I(n)&&"name"in n&&!C(n.name)||I(n)&&"type"in n&&(!C(n.type)||!se.includes(n.type))||!("value"in n)||!z(n.value)||"metadata"in n&&!C(n.metadata)||"valueSeparator"in n&&!C(n.valueSeparator)),fe=n=>{let e=ue,t=ye,r=443,s=ge;if("url"in n){let i=new URL(n.url);e=i.protocol.replace(":",""),t=i.hostname,r=parseInt(i.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}`},S=(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 L=class{constructor(e,t){this.records={attach:(a,i)=>y(this,[a,i],function*({source:e,target:t,options:r},s){var u,f;let o=R(s),c=`/relationships/${A(e)}`,h={headers:Object.assign({},T(o)),method:"POST",requestData:p(p({targetIds:this._extractTargetIds(t,"Attach")},(r==null?void 0:r.type)&&{type:r.type}),(r==null?void 0:r.direction)&&{direction:r.direction})},l=typeof this.logger=="function"?S():"";(u=this.logger)==null||u.call(this,p({requestId:l,path:c},h));let m=yield this.fetcher(c,h);return(f=this.logger)==null||f.call(this,g(p({requestId:l,path:c},h),{responseData:m.data})),m}),detach:(a,i)=>y(this,[a,i],function*({source:e,target:t,options:r},s){var u,f;let o=R(s),c=`/relationships/${A(e)}`,h={headers:Object.assign({},T(o)),method:"PUT",requestData:p(p({targetIds:this._extractTargetIds(t,"Detach")},(r==null?void 0:r.typeOrTypes)&&{typeOrTypes:r.typeOrTypes}),(r==null?void 0:r.direction)&&{direction:r.direction})},l=typeof this.logger=="function"?S():"";(u=this.logger)==null||u.call(this,p({requestId:l,path:c},h));let m=yield this.fetcher(c,h);return(f=this.logger)==null||f.call(this,g(p({requestId:l,path:c},h),{responseData:m.data})),m}),create:(a,i)=>y(this,[a,i],function*({label:e,data:t,options:r},s){var u,f;let o=R(s),d="/records",c={headers:Object.assign({},T(o)),method:"POST",requestData:{}},h=typeof this.logger=="function"?S():"",l=H(v(t));if(w(l)&&l.every(U))c.requestData={label:e,properties:l,options:r};else if(M(l))c.requestData={label:e,data:l,options:r};else throw I(l)?new Error("Provided data is not a flat object. Consider using the `importJson` method for nested objects or arrays of nested objects, or use `createMany` for arrays of flat objects."):new Error("Provided data is not valid.");(u=this.logger)==null||u.call(this,p({requestId:h,path:d},c));let m=yield this.fetcher(d,c);return(f=this.logger)==null||f.call(this,g(p({requestId:h,path:d},c),{responseData:m.data})),m!=null&&m.success&&(m!=null&&m.data)?new D(m.data):new D}),createMany:(e,t)=>y(this,null,function*(){var h,l,m;let r=w(e.data)?e.data:[e.data];if(!r.every(u=>M(u)))throw new Error("records.createMany supports only flat records (no nested objects/arrays). Use records.importJson for nested JSON.");let a=R(t),i="/records/import/json",o={headers:Object.assign({},T(a)),method:"POST",requestData:g(p({},e),{data:r})},d=typeof this.logger=="function"?S():"";(h=this.logger)==null||h.call(this,p({requestId:d,path:i},o));let c=yield this.fetcher(i,o);if((l=this.logger)==null||l.call(this,g(p({requestId:d,path:i},o),{responseData:c.data})),c!=null&&c.success&&(c!=null&&c.data)){let u=w(c.data)?(m=c.data)==null?void 0:m.map(f=>new D(f)):[];return new E(u,c.total)}return new E([])}),importJson:(e,t)=>y(this,null,function*(){var m,u,f;let{data:r,options:s}=e,{label:a}=e,i=r;if(!a)if(I(r)&&!w(r)){let O=H(r),P=Object.keys(O);if(P.length===1)a=P[0],i=O[a];else throw new Error("records.importJson: Missing `label`. Provide `label` or pass an object with a single top-level key that determines the label, e.g. { ITEM: [...] }")}else throw new Error("records.importJson: Missing `label`. Provide `label` or pass an object with a single top-level key that determines the label, e.g. { ITEM: [...] }");let o=R(t),d="/records/import/json",c={headers:Object.assign({},T(o)),method:"POST",requestData:{label:a,data:i,options:s}},h=typeof this.logger=="function"?S():"";(m=this.logger)==null||m.call(this,p({requestId:h,path:d},c));let l=yield this.fetcher(d,c);if((u=this.logger)==null||u.call(this,g(p({requestId:h,path:d},c),{responseData:l.data})),l!=null&&l.success&&(l!=null&&l.data)){let O=w(l.data)?(f=l.data)==null?void 0:f.map(P=>new D(P)):[];return new E(O,l.total)}return new E([])}),importCsv:(e,t)=>y(this,null,function*(){var d,c;let r=R(t),s="/records/import/csv",a={headers:Object.assign({},T(r)),method:"POST",requestData:e},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);if((c=this.logger)==null||c.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),o!=null&&o.success&&(o!=null&&o.data)){let h=w(o.data)?o.data.map(l=>new D(l)):[];return new E(h,o.total)}return new E([])}),delete:(e,t)=>y(this,null,function*(){var d,c,h;if(F(e.where)&&!((d=this==null?void 0:this.options)!=null&&d.allowForceDelete))throw new q("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let r=R(t),s="/records/delete",a={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(h=this.logger)==null||h.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),o}),deleteById:(e,t)=>y(this,null,function*(){var c,h;let r=R(t),s=w(e),a=s?"/records/delete":`/records/${e}`,i={headers:Object.assign({},T(r)),method:s?"POST":"DELETE",requestData:s?{limit:1e3,where:{$id:{$in:e}}}:void 0},o=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:a},i));let d=yield this.fetcher(a,i);return(h=this.logger)==null||h.call(this,g(p({requestId:o,path:a},i),{responseData:d.data})),d}),export:(e,t)=>y(this,null,function*(){var d,c;let r=R(t),s="/records/export/csv",a={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(c=this.logger)==null||c.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),o}),find:(e,t)=>y(this,null,function*(){var m,u;let l=e,{id:r}=l,s=$(l,["id"]),a=R(t),i=r?`/records/${r}/search`:"/records/search",o={headers:Object.assign({},T(a)),method:"POST",requestData:s!=null?s:{}},d=typeof this.logger=="function"?S():"";(m=this.logger)==null||m.call(this,p({requestId:d,path:i},o));let c=yield this.fetcher(i,o);(u=this.logger)==null||u.call(this,g(p({requestId:d,path:i},o),{responseData:c.data}));let h=c.data.map(f=>new D(f));return new E(h,c.total,e)}),findById:(e,t)=>y(this,null,function*(){var d,c;let r=R(t),s=w(e)?"/records":`/records/${e}`,a={headers:Object.assign({},T(r)),method:w(e)?"POST":"GET",requestData:w(e)?{ids:e}:void 0},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);if((c=this.logger)==null||c.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),w(e)){let h=o.data.map(l=>new D(l));return new E(h,o.total)}else return new D(o.data)}),findOne:(e,t)=>y(this,null,function*(){var c,h;let r=R(t),s="/records/search",a={headers:Object.assign({},T(r)),method:"POST",requestData:g(p({},e),{limit:1,skip:0})},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);(h=this.logger)==null||h.call(this,g(p({requestId:i,path:s},a),{responseData:o.data}));let[d]=o.data;return new D(d)}),findUniq:(e,t)=>y(this,null,function*(){var c,h;let r=R(t),s="/records/search",a={headers:Object.assign({},T(r)),method:"POST",requestData:g(p({},e),{limit:1,skip:0})},i=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);if((h=this.logger)==null||h.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),typeof o.total!="undefined"&&o.total>1)throw new V(o.total,e);let[d]=o.data;return new D(d)}),set:(i,o)=>y(this,[i,o],function*({target:e,label:t,data:r,options:s},a){var O,P;let d=R(a),h=`/records/${A(e)}`,l={headers:Object.assign({},T(d)),method:"PUT",requestData:{}},m=typeof this.logger=="function"?S():"",u=H(v(r));if(w(u)&&u.every(U))l.requestData={label:t,properties:u};else if(M(u))l.requestData={label:t,data:u,options:s};else throw I(u)?new Error("Provided data is not a flat object. Consider to use `importJson` method."):new Error("Provided data is not valid.");(O=this.logger)==null||O.call(this,p({requestId:m,path:h},l));let f=yield this.fetcher(h,l);return(P=this.logger)==null||P.call(this,g(p({requestId:m,path:h},l),{responseData:f.data})),f!=null&&f.success&&(f!=null&&f.data)?new D(f.data):new D}),update:(i,o)=>y(this,[i,o],function*({target:e,label:t,data:r,options:s},a){var O,P;let d=R(a),h=`/records/${A(e)}`,l={headers:Object.assign({},T(d)),method:"PATCH",requestData:{}},m=typeof this.logger=="function"?S():"",u=H(v(r));if(w(u)&&u.every(U))l.requestData={label:t,properties:u};else if(M(u))l.requestData={label:t,data:u,options:s};else throw I(u)?new Error("Provided data is not a flat object. Consider to use `importJson` method."):new Error("Provided data is not valid.");(O=this.logger)==null||O.call(this,p({requestId:m,path:h},l));let f=yield this.fetcher(h,l);return(P=this.logger)==null||P.call(this,g(p({requestId:m,path:h},l),{responseData:f.data})),f!=null&&f.success&&(f!=null&&f.data)?new D(f.data):new D}),upsert:(a,i)=>y(this,[a,i],function*({label:e,data:t,options:r},s){var f,O,P;let o=R(s),d="/records",c={headers:Object.assign({},T(o)),method:"POST",requestData:{}},h=typeof this.logger=="function"?S():"",l=H(v(t)),m=g(p({},r),{mergeBy:(f=r==null?void 0:r.mergeBy)!=null?f:[]});if(w(l)&&l.every(U))c.requestData={label:e,properties:l,options:m};else if(M(l))c.requestData={label:e,data:l,options:m};else throw I(l)?new Error("Provided data is not a flat object. Upsert supports flat objects or property drafts array."):new Error("Provided data is not valid.");(O=this.logger)==null||O.call(this,p({requestId:h,path:d},c));let u=yield this.fetcher(d,c);return(P=this.logger)==null||P.call(this,g(p({requestId:h,path:d},c),{responseData:u.data})),u!=null&&u.success&&(u!=null&&u.data)?new D(u.data):new D})};this.relationships={createMany:(e,t)=>y(this,null,function*(){var d,c;let r=R(t),s="/relationships/create-many",a={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(c=this.logger)==null||c.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),o}),deleteMany:(e,t)=>y(this,null,function*(){var d,c;let r=R(t),s="/relationships/delete-many",a={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(c=this.logger)==null||c.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),o}),find:(e,t)=>y(this,null,function*(){var h,l;let r=R(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 i=`/relationships/search${s.toString()?"?"+s.toString():""}`,o={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},d=typeof this.logger=="function"?S():"";(h=this.logger)==null||h.call(this,p({requestId:d,path:i},o));let c=yield this.fetcher(i,o);return(l=this.logger)==null||l.call(this,g(p({requestId:d,path:i},o),{responseData:c.data})),c})};this.properties={delete:(e,t)=>y(this,null,function*(){var d,c;let r=R(t),s=`/properties/${e}`,a={headers:Object.assign({},T(r)),method:"DELETE"},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(c=this.logger)==null||c.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),o}),find:(e,t)=>y(this,null,function*(){var d,c;let r=R(t),s="/properties/search",a={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(c=this.logger)==null||c.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),o}),findById:(e,t)=>y(this,null,function*(){var d,c;let r=R(t),s=`/properties/${e}`,a={headers:Object.assign({},T(r)),method:"GET"},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(c=this.logger)==null||c.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),o}),values:(e,t,r)=>y(this,null,function*(){var c,h;let s=R(r),a=`/properties/${e}/values`,i={headers:Object.assign({},T(s)),method:"POST",requestData:t!=null?t:{}},o=typeof this.logger=="function"?S():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:a},i));let d=yield this.fetcher(a,i);return(h=this.logger)==null||h.call(this,g(p({requestId:o,path:a},i),{responseData:d.data})),d})};this.labels={find:(e,t)=>y(this,null,function*(){var d,c;let r=R(t),s="/labels/search",a={headers:Object.assign({},T(r)),method:"POST",requestData:e!=null?e:{}},i=typeof this.logger=="function"?S():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:s},a));let o=yield this.fetcher(s,a);return(c=this.logger)==null||c.call(this,g(p({requestId:i,path:s},a),{responseData:o.data})),o})};this.tx={begin:e=>y(this,null,function*(){var i,o;let t="/tx",r={method:"POST",requestData:I(e)&&"ttl"in e?e:{}},s=typeof this.logger=="function"?S():"";(i=this.logger)==null||i.call(this,p({requestId:s,path:t},r));let a=yield this.fetcher(t,r);return(o=this.logger)==null||o.call(this,g(p({requestId:s,path:t},r),{responseData:a.data})),new k(a.data.id)}),commit:e=>y(this,null,function*(){var o,d;let r=`/tx/${R(e)}/commit`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,p({requestId:a,path:r},s));let i=yield this.fetcher(r,s);return(d=this.logger)==null||d.call(this,g(p({requestId:a,path:r},s),{responseData:i.data})),i}),get:e=>y(this,null,function*(){var o,d;let r=`/tx/${R(e)}`,s={method:"GET"},a=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,p({requestId:a,path:r},s));let i=yield this.fetcher(r,s);return(d=this.logger)==null||d.call(this,g(p({requestId:a,path:r},s),{responseData:i.data})),new k(i.data.id)}),rollback:e=>y(this,null,function*(){var o,d;let r=`/tx/${R(e)}/rollback`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?S():"";(o=this.logger)==null||o.call(this,p({requestId:a,path:r},s));let i=yield this.fetcher(r,s);return(d=this.logger)==null||d.call(this,g(p({requestId:a,path:r},s),{responseData:i.data})),i})};this.settings={get:()=>y(this,null,function*(){var a,i;let e="/sdk/settings",t={method:"GET"},r=typeof this.logger=="function"?S():"";(a=this.logger)==null||a.call(this,p({requestId:r,path:e},t));let s=yield this.fetcher(e,t);return(i=this.logger)==null||i.call(this,g(p({requestId:r,path:e},t),{responseData:s.data})),s})};this.query={raw:(s,a)=>y(this,[s,a],function*({query:e,params:t},r){var l,m;let i=R(r),o="/query/raw",d={headers:Object.assign({},T(i)),method:"POST",requestData:{query:e,params:t}},c=typeof this.logger=="function"?S():"";(l=this.logger)==null||l.call(this,p({requestId:c,path:o},d));let h=yield this.fetcher(o,d);return(m=this.logger)==null||m.call(this,g(p({requestId:c,path:o},d),{responseData:h.data})),h})};if(this.fetcher=null,t!=null&&t.httpClient){let r=fe(t);this.fetcher=he({httpClient:t.httpClient,token:e,url:r})}t!=null&&t.options&&(this.options=t==null?void 0:t.options),t!=null&&t.logger&&(this.logger=t==null?void 0:t.logger)}_extractTargetIds(e,t){var r;if(e instanceof D){let s=A(e);if(!s)throw new q(`${t} error: Target id is empty`);return[s]}if(w(e)&&e.every(s=>s instanceof D)){let s=e.map(A).filter(x);if(!s.length)throw new q(`${t} error: Target ids are empty`);return s}if(e instanceof E){let s=(r=e.data)==null?void 0:r.map(A).filter(x);if(!(s!=null&&s.length))throw new q(`${t} error: Target ids are empty`);return s}if(I(e)&&"__id"in e)return[e.__id];if(w(e)&&e.every(s=>I(s)&&"__id"in s)){let s=e.map(A).filter(x);if(!s.length)throw new q(`${t} error: Target ids are empty`);return s}return w(e)?e:C(e)?[e]:[]}};var Se,_=class _ extends L{constructor(e,t){var a;let r=ce(t);super(e,g(p({},r),{httpClient:(a=r.httpClient)!=null?a:Se})),_.instance=this;let[s]=le(e!=null?e:"");this.initializeSync(s,e,r)}initializeSync(e,t,r){let s=e?{planType:e.planType,customDB:e.customDB,managedDB:e.managedDB,selfHosted:e.selfHosted}:null;_.state=p({initialized:!0,debug:!1,timeout:de("timeout",r==null?void 0:r.timeout,8e4),token:t},s&&{serverSettings:s})}static getInstance(){if(_.instance)return _.instance;throw new Error('RushDB not initialized. Please create a RushDB instance first: new RushDB("RUSHDB_API_KEY")')}static isInitialized(){return x(_.instance)}toDBRecordInstance(e){return new D(e)}};_.instance=null,_.state={initialized:!1,debug:!1,timeout:8e4};var b=_,Re=n=>{Se=n};var Te=class{constructor(e,t){this.label=e,this.schema=t}getLabel(){return this.label}toDBRecordInstance(e){return y(this,null,function*(){try{return b.getInstance().toDBRecordInstance(e)}catch(t){throw new Error("No RushDB instance was provided during model initialization.")}})}find(e,t){return y(this,null,function*(){let r=e!=null?e:{};return b.getInstance().records.find(g(p({},r),{labels:[this.label]}),t)})}findOne(e,t){return y(this,null,function*(){let r=e!=null?e:{};return b.getInstance().records.findOne(g(p({},r),{labels:[this.label]}),t)})}findById(e,t){return y(this,null,function*(){return this.findOne({where:{$id:e}},t)})}findUniq(e,t){return y(this,null,function*(){let r=e!=null?e:{};return b.getInstance().records.findUniq(g(p({},r),{labels:[this.label]}),t)})}create(e,t){return y(this,null,function*(){var o;let r=yield J(this.schema,e),s=Z(this.schema,r),a=x(s),i=b.getInstance();if(a){let d=t!=null?t:yield i.tx.begin(),c=yield this.find({where:s},d),h=typeof t!="undefined";if(!((o=c==null?void 0:c.data)!=null&&o.length)){let m=yield i.records.create({label:this.label,data:r},d);return h||(yield d.commit()),m}else throw h||(yield d.commit()),new j(this.label,s)}return yield i.records.create({label:this.label,data:r},t)})}attach(a,i){return y(this,arguments,function*({source:e,target:t,options:r},s){return yield b.getInstance().records.attach({source:e,target:t,options:r},s)})}detach(a,i){return y(this,arguments,function*({source:e,target:t,options:r},s){return yield b.getInstance().records.detach({source:e,target:t,options:r},s)})}handleSetOrUpdate(e,t,r,s){return y(this,null,function*(){var d,c;if(w(t)&&t.every(U))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let a=b.getInstance(),i=yield J(this.schema,t),o=Z(this.schema,i);if(!F(o)){let h=s!=null?s:yield a.tx.begin(),l=yield this.find({where:o},h),m=typeof s!="undefined";if(!((d=l==null?void 0:l.data)!=null&&d.length)||l.data.length===1&&((c=l.data[0])==null?void 0:c.id())===A(e)){let f=yield a.records[r]({target:e,label:this.label,data:i},h);return m||(yield h.commit()),f}else throw m||(yield h.commit()),new j(this.label,o)}return yield a.records[r]({label:this.label,target:e,data:i},s)})}set(e,t,r){return y(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"set",r)})}update(e,t,r){return y(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"update",r)})}createMany(e,t){return y(this,null,function*(){var i;let r=b.getInstance(),s=typeof t!="undefined",a=t!=null?t:yield r.tx.begin();try{let o=yield Promise.all(e.map(h=>y(this,null,function*(){return yield J(this.schema,h)}))),d=ie(o,this.schema,this.label);if(!F(d)){let h=Object.entries(d).map(([m,u])=>({[m]:{$in:u}})),l=yield this.find({where:{$or:h}},a);if((i=l==null?void 0:l.data)!=null&&i.length)throw new j(this.label,Object.keys(d))}let c=yield r.records.createMany({label:this.label,data:o},a);return s||(yield a.commit()),c}catch(o){throw s||(yield a.rollback()),o}})}delete(e,t){return y(this,null,function*(){if(F(e.where))throw new q(`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 b.getInstance().records.delete(g(p({},e),{labels:[this.label]}),t)})}deleteById(e,t){return y(this,null,function*(){return yield b.getInstance().records.deleteById(e,t)})}};Re(new K);var Ht=b;export{D as DBRecordInstance,E as DBRecordsArrayInstance,q as EmptyTargetError,B as HttpClient,Y as HttpClientResponse,Te as Model,V as NonUniqueResultError,L as RestAPI,b as RushDB,k as Transaction,j as UniquenessError,Ht as default,le as extractMixedPropertiesFromToken,pe as idToDate,X as idToTimestamp,Re as initSDK,J as mergeDefaultsWithPayload,ce as parseConfig,Z as pickUniqFieldsFromRecord,ie as pickUniqFieldsFromRecords,de as validateInteger};
|
package/dist/sdk/record.d.ts
CHANGED
|
@@ -79,6 +79,8 @@ export type DBRecordCreationOptions = {
|
|
|
79
79
|
convertNumericValuesToNumbers?: boolean;
|
|
80
80
|
capitalizeLabels?: boolean;
|
|
81
81
|
relationshipType?: string;
|
|
82
|
+
mergeStrategy?: 'append' | 'rewrite';
|
|
83
|
+
mergeBy?: string[];
|
|
82
84
|
};
|
|
83
85
|
export declare class DBRecordInstance<S extends Schema = Schema, Q extends SearchQuery<S> = SearchQuery<S>> {
|
|
84
86
|
data: DBRecordInferred<S, Q>;
|