@rushdb/javascript-sdk 1.0.3 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/api/api.d.ts +7 -7
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.node.d.ts +12 -3
- package/dist/index.worker.d.ts +12 -3
- package/dist/sdk/sdk.d.ts +12 -3
- package/dist/types/value.d.ts +0 -7
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -55,7 +55,7 @@ import RushDB from '@rushdb/javascript-sdk';
|
|
|
55
55
|
|
|
56
56
|
// Setup SDK
|
|
57
57
|
const db = new RushDB("API_TOKEN");
|
|
58
|
-
// Default URL is "https://api.rushdb.com". See SDK Configuration for more options.
|
|
58
|
+
// Default URL is "https://api.rushdb.com/api/v1". See SDK Configuration for more options.
|
|
59
59
|
|
|
60
60
|
// Push any data, and RushDB will automatically flatten it into Records
|
|
61
61
|
// and establish relationships between them accordingly.
|
|
@@ -122,7 +122,7 @@ import RushDB from '@rushdb/javascript-sdk';
|
|
|
122
122
|
|
|
123
123
|
// Example: Initialize with a custom URL and timeout
|
|
124
124
|
const db = new RushDB('API_TOKEN', {
|
|
125
|
-
url: 'http://your-custom-rushdb-server.com', // Default is 'https://api.rushdb.com'
|
|
125
|
+
url: 'http://your-custom-rushdb-server.com/api/v1', // Default is 'https://api.rushdb.com/api/v1'
|
|
126
126
|
timeout: 30000 // 30 seconds
|
|
127
127
|
});
|
|
128
128
|
```
|
package/dist/api/api.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { HttpClient } from '../network/HttpClient.js';
|
|
2
2
|
import type { DBRecordTarget, RelationDetachOptions, RelationOptions, RelationTarget, Relation, DBRecordCreationOptions } from '../sdk/record.js';
|
|
3
3
|
import type { SDKConfig } from '../sdk/types.js';
|
|
4
|
-
import type { SearchQuery, Schema, InferSchemaTypesWrite, MaybeArray,
|
|
4
|
+
import type { SearchQuery, Schema, InferSchemaTypesWrite, MaybeArray, PropertyDraft, Property, PropertyValuesData, AnyObject, OrderDirection } from '../types/index.js';
|
|
5
5
|
import type { ApiResponse } from './types.js';
|
|
6
6
|
import { createFetcher } from '../network/index.js';
|
|
7
7
|
import { DBRecordInstance, DBRecordsArrayInstance } from '../sdk/record.js';
|
|
@@ -213,15 +213,15 @@ export declare class RestAPI {
|
|
|
213
213
|
/**
|
|
214
214
|
* Retrieves values for a specific property
|
|
215
215
|
* @param id - The unique identifier of the property
|
|
216
|
-
* @param
|
|
217
|
-
* @param
|
|
218
|
-
* @param options.skip - Number of values to skip
|
|
219
|
-
* @param options.limit - Maximum number of values to return
|
|
220
|
-
* @param options.query - Filter query for values
|
|
216
|
+
* @param searchQuery - Query parameters to filter properties
|
|
217
|
+
* @param searchQuery.query - Filter query for values
|
|
221
218
|
* @param transaction - Optional transaction for atomic operations
|
|
222
219
|
* @returns Promise with the API response containing the property and its values
|
|
223
220
|
*/
|
|
224
|
-
values: (id: string,
|
|
221
|
+
values: (id: string, searchQuery?: SearchQuery & {
|
|
222
|
+
query?: string;
|
|
223
|
+
orderBy?: OrderDirection;
|
|
224
|
+
}, transaction?: Transaction | string) => Promise<ApiResponse<{
|
|
225
225
|
metadata?: string;
|
|
226
226
|
name: string;
|
|
227
227
|
type: import("../types/value.js").PropertyType;
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var me=Object.create;var M=Object.defineProperty;var ge=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var Se=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var Te=(n,e)=>{for(var t in e)M(n,t,{get:e[t],enumerable:!0})},re=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of fe(e))!Re.call(n,s)&&s!==t&&M(n,s,{get:()=>e[s],enumerable:!(r=ge(e,s))||r.enumerable});return n};var se=(n,e,t)=>(t=n!=null?me(Se(n)):{},re(e||!n||!n.__esModule?M(t,"default",{value:n,enumerable:!0}):t,n)),De=n=>re(M({},"__esModule",{value:!0}),n);var Me={};Te(Me,{DBRecordInstance:()=>g,DBRecordsArrayInstance:()=>O,EmptyTargetError:()=>D,HttpClient:()=>w,HttpClientResponse:()=>U,Model:()=>Z,NonUniqueResultError:()=>q,RestAPI:()=>_,RushDB:()=>ue,Transaction:()=>A,UniquenessError:()=>I,default:()=>je,idToDate:()=>z,idToTimestamp:()=>$,initSDK:()=>X,mergeDefaultsWithPayload:()=>j,parseConfig:()=>J,pickUniqFieldsFromRecord:()=>Q,pickUniqFieldsFromRecords:()=>Y,validateInteger:()=>G});module.exports=De(Me);var w=class n{makeRequest(e,{headers:t,method:r,protocol:s,requestData:o,timeout:a}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(n.TIMEOUT_ERROR_CODE);return e.code=n.TIMEOUT_ERROR_CODE,e}};w.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];w.TIMEOUT_ERROR_CODE="ETIMEDOUT";var k=class{constructor(e,t){this._statusCode=e,this._headers=t}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}},U=class{constructor(e){this._res=e}getStatusCode(){throw new Error("getStatusCode not implemented.")}getHeaders(){throw new Error("getHeaders not implemented.")}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}};var N=se(require("http"),1),W=se(require("https"),1);var xe="string",we="datetime",be="boolean",Ie="number",Pe="null",Oe="vector",ne=[xe,we,be,Ie,Pe,Oe];var ae=N.default||N,oe=W.default||W,Ee=new ae.Agent({keepAlive:!0}),_e=new oe.Agent({keepAlive:!0}),L=class extends w{constructor(e){super(),this._agent=e}makeRequest(e,{headers:t,method:r,protocol:s,requestData:o,timeout:a}){let i=new URL(e),d=s==="http"||i.protocol==="http:",c=this._agent;return c||(c=d?Ee:_e),new Promise((p,l)=>{let h=(d?ae:oe).request({agent:c,ciphers:"DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5",headers:t,host:i.hostname,method:r,path:i.pathname+i.search,port:i.port});h.setTimeout(a!=null?a:8e4,()=>{h.destroy(w.makeTimeoutError())}),h.on("response",y=>{p(new v(y))}),h.on("error",y=>{l(y)}),h.once("socket",y=>{let T=o?JSON.stringify(o):"";y.connecting?y.once(d?"connect":"secureConnect",()=>{h.write(T),h.end()}):(h.write(T),h.end())})})}},v=class extends k{constructor(e){super(e.statusCode,e.headers||{}),this._res=e}getRawResponse(){return this._res}toStream(e){return this._res.once("end",()=>e()),this._res}toJSON(){return new Promise((e,t)=>{let r="";this._res.setEncoding("utf8"),this._res.on("data",s=>{r+=s}),this._res.once("end",()=>{try{e(JSON.parse(r))}catch(s){t(s)}})})}};var S=n=>typeof n=="object"&&Array.isArray(n)&&n!==null,R=n=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",E=n=>R(n)&&Object.keys(n).length===0,ie=n=>typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null,K=n=>S(n)?n.every(ie):ie(n),F=n=>R(n)&&Object.values(n).every(K),b=n=>typeof n=="string",H=n=>{if(typeof n=="string"){if(n.toLowerCase()==="true")return!0;if(n.toLowerCase()==="false")return!1}return S(n)&&n.length===0||R(n)&&Object.keys(n).length===0?!1:!!n};var Ce={"Content-Type":"application/json"},ce=({httpClient:n,token:e,url:t})=>async(r,{headers:s,...o})=>{let a=await n.makeRequest(`${t}${r}`,{credentials:"omit",headers:Object.assign({...Ce,...s},typeof e<"u"?{token:e}:{}),...o});if(a.getStatusCode()>=200&&a.getStatusCode()<300)return await a.toJSON();throw new Error(`${a.getStatusCode()}`)};var I=class n extends Error{constructor(e,t){super(`Record with label "${e}" and properties ${JSON.stringify(t)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,n.prototype)}},D=class n extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,n.prototype)}},q=class n extends Error{constructor(e,t){super(`Expected a unique result but found ${e} matches for the provided SearchQuery: ${JSON.stringify(t)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,n.prototype)}};var P=class{constructor(){this.apiProxy={};return new Proxy(this,{get:(e,t,r)=>{if(t in e)return Reflect.get(e,t,r);if(this.apiProxy&&t in this.apiProxy)return Reflect.get(this.apiProxy,t,r)}})}init(e){this.apiProxy=e}};var V=["httpClient","timeout","host","port","protocol","url","logger","options"];var j=async(n,e)=>{let t=Object.entries(n).map(async([o,a])=>a.default&&typeof a.default<"u"&&typeof e[o]>"u"?{key:o,value:typeof a.default=="function"?await a.default():a.default}:{key:o,value:void 0});return{...(await Promise.all(t)).reduce((o,{key:a,value:i})=>(i!==void 0&&(o[a]=i),o),{}),...e}},Q=(n,e)=>Object.entries(e).filter(([t])=>{var r;return(r=n[t])==null?void 0:r.uniq}).reduce((t,[r,s])=>(r in n&&(t[r]=s),t),{}),Y=(n,e,t)=>{let r={},s=Object.entries(e).filter(([,o])=>o.uniq).reduce((o,[a])=>(o[a]=!0,o),{});return n.forEach(o=>{Object.entries(o).forEach(([a,i])=>{if(a in s)if(r[a]){if(r[a].includes(i))throw new I(t,{[a]:i});r[a]=[...r[a],i]}else r[a]=[i]})}),r},J=n=>{if(!n)return{};if(!R(n))throw new Error("Config must be an object");if(Object.keys(n).filter(t=>!V.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${V.join(", ")}`);return n};function G(n,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${n} must be an integer`)}return e}function $(n){let e=n.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function z(n){return new Date($(n))}var g=class extends P{constructor(e){super(),this.data=e}id(){try{return this.data.__id}catch{throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.")}}label(){try{return this.data.__label}catch{throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.")}}proptypes(){try{return this.data.__proptypes}catch{throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.")}}date(){try{return z(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return $(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}async delete(e){if(!this.data)throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return await this.apiProxy.records.deleteById(this.id(),e)}async update(e,t){if(!this.data)throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return this.apiProxy.records.update({label:this.label(),target:this.id(),data:e},t)}async set(e,t){if(!this.data)throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return this.apiProxy.records.set({label:this.label(),target:this.id(),data:e},t)}async attach(e,t,r){if(!this.data)throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return this.apiProxy.records.attach({source:this.id(),target:e,options:t},r)}async detach(e,t,r){if(!this.data)throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return this.apiProxy.records.detach({source:this.id(),target:e,options:t},r)}},O=class extends P{constructor(e,t,r){super(),this.data=e,this.total=t,this.searchQuery=r}};var A=class extends P{constructor(e){super(),this.id=e}async rollback(){return await this.apiProxy.tx.rollback(this.id)}async commit(){return await this.apiProxy.tx.commit(this.id)}};var de="api.rushdb.com";var pe="https",le="/api/v1";var f=n=>n?{"x-transaction-id":n}:void 0,qe=n=>b(n)||n instanceof A,m=n=>qe(n)?n instanceof A?n.id:n:void 0,he=n=>/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(n),x=n=>{if(b(n)&&he(n))return n;if(n instanceof g&&n.data)return n.data.__id;if(R(n)&&"__id"in n&&he(n.__id))return n.__id},C=n=>!(!R(n)||R(n)&&"name"in n&&!b(n.name)||R(n)&&"type"in n&&(!b(n.type)||!ne.includes(n.type))||!("value"in n)||!K(n.value)||"metadata"in n&&!b(n.metadata)||"valueSeparator"in n&&!b(n.valueSeparator)),ye=n=>{let e=pe,t=de,r=443,s=le;if("url"in n){let a=new URL(n.url);e=a.protocol.replace(":",""),t=a.hostname,r=parseInt(a.port||(e==="http"?"80":e==="https"?"443":""))}"host"in n&&"port"in n&&"protocol"in n&&(e=n.protocol.replace(":",""),t=n.host,r=n.port),s&&!s.startsWith("/")&&(s="/"+s);let o="";return e==="http"&&r===80||e==="https"&&r===443||(o=":"+r),`${e}://${t}${o}${s}`},u=(n=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let r=0;r<n;r++){let s=Math.floor(Math.random()*e.length);t+=e[s]}return t};var _=class{constructor(e,t){this.records={attach:async({source:e,target:t,options:r},s)=>{var l,h;let o=m(s),i=`/relationships/${x(e)}`,d={headers:Object.assign({},f(o)),method:"POST",requestData:{targetIds:this._extractTargetIds(t,"Attach"),...(r==null?void 0:r.type)&&{type:r.type},...(r==null?void 0:r.direction)&&{direction:r.direction}}},c=typeof this.logger=="function"?u():"";(l=this.logger)==null||l.call(this,{requestId:c,path:i,...d});let p=await this.fetcher(i,d);return(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d,responseData:p.data}),p},detach:async({source:e,target:t,options:r},s)=>{var l,h;let o=m(s),i=`/relationships/${x(e)}`,d={headers:Object.assign({},f(o)),method:"PUT",requestData:{targetIds:this._extractTargetIds(t,"Detach"),...(r==null?void 0:r.typeOrTypes)&&{typeOrTypes:r.typeOrTypes},...(r==null?void 0:r.direction)&&{direction:r.direction}}},c=typeof this.logger=="function"?u():"";(l=this.logger)==null||l.call(this,{requestId:c,path:i,...d});let p=await this.fetcher(i,d);return(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d,responseData:p.data}),p},create:async({label:e,data:t,options:r},s)=>{var p,l;let o=m(s),a="/records",i={headers:Object.assign({},f(o)),method:"POST",requestData:{}},d=typeof this.logger=="function"?u():"";if(S(t)&&t.every(C))i.requestData={label:e,properties:t};else if(F(t))i.requestData={label:e,data:t,options:r};else if(R(t))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(p=this.logger)==null||p.call(this,{requestId:d,path:a,...i});let c=await this.fetcher(a,i);if((l=this.logger)==null||l.call(this,{requestId:d,path:a,...i,responseData:c.data}),c!=null&&c.success&&(c!=null&&c.data)){let h=new g(c.data);return h.init(this),h}return new g},createMany:async(e,t)=>{var d,c;let r=m(t),s="/records/import/json",o={headers:Object.assign({},f(r)),method:"POST",requestData:e},a=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);if((c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i!=null&&i.success&&(i!=null&&i.data)){let p=i.data.map(h=>{let y=new g(h);return y.init(this),y}),l=new O(p,i.total);return l.init(this),l}return new O([])},delete:async(e,t)=>{var d,c,p;if(E(e.where)&&!((d=this==null?void 0:this.options)!=null&&d.allowForceDelete))throw new D("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let r=m(t),s="/records/delete",o={headers:Object.assign({},f(r)),method:"PUT",requestData:e},a=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(p=this.logger)==null||p.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},deleteById:async(e,t)=>{var c,p;let r=m(t),s=S(e),o=s?"/records/delete":`/records/${e}`,a={headers:Object.assign({},f(r)),method:s?"PUT":"DELETE",requestData:s?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?u():"";(c=this.logger)==null||c.call(this,{requestId:i,path:o,...a});let d=await this.fetcher(o,a);return(p=this.logger)==null||p.call(this,{requestId:i,path:o,...a,responseData:d.data}),d},export:async(e,t)=>{var d,c;let r=m(t),s="/records/export/csv",o={headers:Object.assign({},f(r)),method:"POST",requestData:e},a=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},find:async(e,t)=>{var h,y;let{id:r,...s}=e,o=m(t),a=r?`/records/${r}/search`:"/records/search",i={headers:Object.assign({},f(o)),method:"POST",requestData:s},d=typeof this.logger=="function"?u():"";(h=this.logger)==null||h.call(this,{requestId:d,path:a,...i});let c=await this.fetcher(a,i);(y=this.logger)==null||y.call(this,{requestId:d,path:a,...i,responseData:c.data});let p=c.data.map(T=>{let B=new g(T);return B.init(this),B}),l=new O(p,c.total,e);return l.init(this),l},findById:async(e,t)=>{var d,c;let r=m(t),s=S(e)?"/records":`/records/${e}`,o={headers:Object.assign({},f(r)),method:S(e)?"POST":"GET",requestData:S(e)?{ids:e}:void 0},a=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);if((c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),S(e)){let p=i.data.map(h=>{let y=new g(h);return y.init(this),y}),l=new O(p,i.total);return l.init(this),l}else{let p=new g(i.data);return p.init(this),p}},findOne:async(e,t)=>{var p,l;let r=m(t),s="/records/search",o={headers:Object.assign({},f(r)),method:"POST",requestData:{...e,limit:1,skip:0}},a=typeof this.logger=="function"?u():"";(p=this.logger)==null||p.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);(l=this.logger)==null||l.call(this,{requestId:a,path:s,...o,responseData:i.data});let[d]=i.data,c=new g(d);return c.init(this),c},findUniq:async(e,t)=>{var p,l;let r=m(t),s="/records/search",o={headers:Object.assign({},f(r)),method:"POST",requestData:{...e,limit:1,skip:0}},a=typeof this.logger=="function"?u():"";(p=this.logger)==null||p.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);if((l=this.logger)==null||l.call(this,{requestId:a,path:s,...o,responseData:i.data}),typeof i.total<"u"&&i.total>1)throw new q(i.total,e);let[d]=i.data,c=new g(d);return c.init(this),c},set:async({target:e,label:t,data:r,options:s},o)=>{var h,y;let a=m(o),d=`/records/${x(e)}`,c={headers:Object.assign({},f(a)),method:"PUT",requestData:{}},p=typeof this.logger=="function"?u():"";if(S(r)&&r.every(C))c.requestData={label:t,properties:r};else if(F(r))c.requestData={label:t,data:r,options:s};else if(R(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(h=this.logger)==null||h.call(this,{requestId:p,path:d,...c});let l=await this.fetcher(d,c);if((y=this.logger)==null||y.call(this,{requestId:p,path:d,...c,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)){let T=new g(l.data);return T.init(this),T}return new g},update:async({target:e,label:t,data:r,options:s},o)=>{var h,y;let a=m(o),d=`/records/${x(e)}`,c={headers:Object.assign({},f(a)),method:"PATCH",requestData:{}},p=typeof this.logger=="function"?u():"";if(S(r)&&r.every(C))c.requestData={label:t,properties:r};else if(F(r))c.requestData={label:t,data:r,options:s};else if(R(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(h=this.logger)==null||h.call(this,{requestId:p,path:d,...c});let l=await this.fetcher(d,c);if((y=this.logger)==null||y.call(this,{requestId:p,path:d,...c,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)){let T=new g(l.data);return T.init(this),T}return new g}};this.relationships={find:async(e,t)=>{var p,l;let r=m(t),s=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&s.append("limit",e.limit.toString()),(e==null?void 0:e.skip)!==void 0&&s.append("skip",e.skip.toString());let a=`/relationships/search${s.toString()?"?"+s.toString():""}`,i={headers:Object.assign({},f(r)),method:"POST",requestData:e},d=typeof this.logger=="function"?u():"";(p=this.logger)==null||p.call(this,{requestId:d,path:a,...i});let c=await this.fetcher(a,i);return(l=this.logger)==null||l.call(this,{requestId:d,path:a,...i,responseData:c.data}),c}};this.properties={delete:async(e,t)=>{var d,c;let r=m(t),s=`/properties/${e}`,o={headers:Object.assign({},f(r)),method:"DELETE"},a=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},find:async(e,t)=>{var d,c;let r=m(t),s="/properties/search",o={headers:Object.assign({},f(r)),method:"POST",requestData:e},a=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},findById:async(e,t)=>{var d,c;let r=m(t),s=`/properties/${e}`,o={headers:Object.assign({},f(r)),method:"GET"},a=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},values:async(e,t,r)=>{var ee,te;let s=m(r),o=`/properties/${e}/values`,{sort:a,skip:i,limit:d,query:c}=t!=null?t:{},p=new URLSearchParams;a!==void 0&&p.append("sort",a),i!==void 0&&p.append("skip",i.toString()),d!==void 0&&p.append("limit",d.toString()),c!==void 0&&p.append("query",c);let l=p.toString(),h=l?`${o}?${l}`:o,y={headers:Object.assign({},f(s)),method:"GET"},T=typeof this.logger=="function"?u():"";(ee=this.logger)==null||ee.call(this,{requestId:T,path:o,...y});let B=await this.fetcher(h,y);return(te=this.logger)==null||te.call(this,{requestId:T,path:h,...y,responseData:B.data}),B}};this.labels={find:async(e,t)=>{var d,c;let r=m(t),s="/labels/search",o={headers:Object.assign({},f(r)),method:"POST",requestData:e},a=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i}};this.tx={begin:async e=>{var i,d;let t="/tx",r={method:"POST",requestData:e},s=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:s,path:t,...r});let o=await this.fetcher(t,r);(d=this.logger)==null||d.call(this,{requestId:s,path:t,...r,responseData:o.data});let a=new A(o.data.id);return a.init(this),a},commit:async e=>{var i,d;let r=`/tx/${m(e)}/commit`,s={method:"POST",requestData:{}},o=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:o,path:r,...s});let a=await this.fetcher(r,s);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...s,responseData:a.data}),a},get:async e=>{var d,c;let r=`/tx/${m(e)}`,s={method:"GET"},o=typeof this.logger=="function"?u():"";(d=this.logger)==null||d.call(this,{requestId:o,path:r,...s});let a=await this.fetcher(r,s);(c=this.logger)==null||c.call(this,{requestId:o,path:r,...s,responseData:a.data});let i=new A(a.data.id);return i.init(this),i},rollback:async e=>{var i,d;let r=`/tx/${m(e)}/rollback`,s={method:"POST",requestData:{}},o=typeof this.logger=="function"?u():"";(i=this.logger)==null||i.call(this,{requestId:o,path:r,...s});let a=await this.fetcher(r,s);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...s,responseData:a.data}),a}};if(this.fetcher=null,t!=null&&t.httpClient){let r=ye(t);this.fetcher=ce({httpClient:t.httpClient,token:e,url:r})}t!=null&&t.options&&(this.options=t==null?void 0:t.options),t!=null&&t.logger&&(this.logger=t==null?void 0:t.logger)}_extractTargetIds(e,t){var r;if(e instanceof g){let s=x(e);if(!s)throw new D(`${t} error: Target id is empty`);return[s]}if(S(e)&&e.every(s=>s instanceof g)){let s=e.map(x).filter(H);if(!s.length)throw new D(`${t} error: Target ids are empty`);return s}if(e instanceof O){let s=(r=e.data)==null?void 0:r.map(x).filter(H);if(!(s!=null&&s.length))throw new D(`${t} error: Target ids are empty`);return s}if(R(e)&&"__id"in e)return[e.__id];if(S(e)&&e.every(s=>R(s)&&"__id"in s)){let s=e.map(x).filter(H);if(!s.length)throw new D(`${t} error: Target ids are empty`);return s}return S(e)?e:b(e)?[e]:[]}};var X=n=>{class e extends _{constructor(r,s){var a;let o=J(s);super(r,{...o,httpClient:(a=o.httpClient)!=null?a:n}),this.state={debug:!1,timeout:G("timeout",o.timeout,8e4),token:r},this.models=new Map,e.instance=this}static getInstance(){return e.instance}registerModel(r){let s=r.getLabel();return r.init(this),this.models.set(s,r),r}getModels(){return this.models}getModel(r){return this.models.get(r)}toInstance(r){let s=new g(r);return s.init(this),s}}return e};var Z=class extends P{constructor(e,t,r){super(),this.label=e,this.schema=t,this.rushDBInstance=r,r==null||r.registerModel(this)}getLabel(){return this.label}toInstance(e){if(this.rushDBInstance)return this.rushDBInstance.toInstance(e);throw new Error("No RushDB instance was provided during model initialization.")}async find(e,t){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.find({...r,labels:[this.label]},t)}async findOne(e,t){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.findOne({...r,labels:[this.label]},t)}async findById(e,t){return this.findOne({where:{$id:e}},t)}async findUniq(e,t){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.findUniq({...r,labels:[this.label]},t)}async create(e,t){var o;let r=await j(this.schema,e),s=Q(this.schema,r);if(!E(s)){let a=t!=null?t:await this.apiProxy.tx.begin(),i=await this.find({where:s},a),d=typeof t<"u";if(!((o=i==null?void 0:i.data)!=null&&o.length)){let p=await this.apiProxy.records.create({label:this.label,data:r},a);return d||await a.commit(),p}else throw d||await a.commit(),new I(this.label,s)}return await this.apiProxy.records.create({label:this.label,data:r},t)}attach({source:e,target:t,options:r},s){return this.apiProxy.records.attach({source:e,target:t,options:r},s)}detach({source:e,target:t,options:r},s){return this.apiProxy.records.detach({source:e,target:t,options:r},s)}async handleSetOrUpdate(e,t,r,s){var i,d;if(S(t)&&t.every(C))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let o=await j(this.schema,t),a=Q(this.schema,o);if(!E(a)){let c=s!=null?s:await this.apiProxy.tx.begin(),p=await this.find({where:a},c),l=typeof s<"u";if(!((i=p==null?void 0:p.data)!=null&&i.length)||p.data.length===1&&((d=p.data[0])==null?void 0:d.id())===x(e)){let y=await this.apiProxy.records[r]({target:e,label:this.label,data:o},c);return l||await c.commit(),y}else throw l||await c.commit(),new I(this.label,a)}return await this.apiProxy.records[r]({label:this.label,target:e,data:o},s)}async set(e,t,r){return await this.handleSetOrUpdate(e,t,"set",r)}async update(e,t,r){return await this.handleSetOrUpdate(e,t,"update",r)}async createMany(e,t){var o;let r=typeof t<"u",s=t!=null?t:await this.apiProxy.tx.begin();try{let a=await Promise.all(e.map(async c=>await j(this.schema,c))),i=Y(a,this.schema,this.label);if(!E(i)){let c=Object.entries(i).map(([l,h])=>({[l]:{$in:h}})),p=await this.find({where:{$or:c}},s);if((o=p==null?void 0:p.data)!=null&&o.length)throw new I(this.label,Object.keys(i))}let d=await this.apiProxy.records.createMany({label:this.label,data:a},s);return r||await s.commit(),d}catch(a){throw r||await s.rollback(),a}}async delete(e,t){if(E(e.where))throw new D(`You must specify criteria to delete records of type '${this.label}'. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.`);return await this.apiProxy.records.delete({...e,labels:[this.label]},t)}async deleteById(e,t){return await this.apiProxy.records.deleteById(e,t)}};var ue=X(new L);var je=ue;0&&(module.exports={DBRecordInstance,DBRecordsArrayInstance,EmptyTargetError,HttpClient,HttpClientResponse,Model,NonUniqueResultError,RestAPI,RushDB,Transaction,UniquenessError,idToDate,idToTimestamp,initSDK,mergeDefaultsWithPayload,parseConfig,pickUniqFieldsFromRecord,pickUniqFieldsFromRecords,validateInteger});
|
|
1
|
+
"use strict";var ye=Object.create;var j=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var ge=Object.getOwnPropertyNames;var me=Object.getPrototypeOf,fe=Object.prototype.hasOwnProperty;var Se=(n,e)=>{for(var t in e)j(n,t,{get:e[t],enumerable:!0})},ee=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ge(e))!fe.call(n,s)&&s!==t&&j(n,s,{get:()=>e[s],enumerable:!(r=ue(e,s))||r.enumerable});return n};var te=(n,e,t)=>(t=n!=null?ye(me(n)):{},ee(e||!n||!n.__esModule?j(t,"default",{value:n,enumerable:!0}):t,n)),Re=n=>ee(j({},"__esModule",{value:!0}),n);var qe={};Se(qe,{DBRecordInstance:()=>m,DBRecordsArrayInstance:()=>O,EmptyTargetError:()=>T,HttpClient:()=>w,HttpClientResponse:()=>k,Model:()=>X,NonUniqueResultError:()=>B,RestAPI:()=>_,RushDB:()=>he,Transaction:()=>A,UniquenessError:()=>I,default:()=>Be,idToDate:()=>z,idToTimestamp:()=>Q,initSDK:()=>G,mergeDefaultsWithPayload:()=>q,parseConfig:()=>V,pickUniqFieldsFromRecord:()=>H,pickUniqFieldsFromRecords:()=>Y,validateInteger:()=>J});module.exports=Re(qe);var w=class n{makeRequest(e,{headers:t,method:r,protocol:s,requestData:o,timeout:a}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(n.TIMEOUT_ERROR_CODE);return e.code=n.TIMEOUT_ERROR_CODE,e}};w.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];w.TIMEOUT_ERROR_CODE="ETIMEDOUT";var M=class{constructor(e,t){this._statusCode=e,this._headers=t}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}},k=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 $=te(require("http"),1),N=te(require("https"),1);var Te="string",De="datetime",xe="boolean",we="number",be="null",Ie="vector",re=[Te,De,xe,we,be,Ie];var se=$.default||$,ne=N.default||N,Oe=new se.Agent({keepAlive:!0}),Ae=new ne.Agent({keepAlive:!0}),U=class extends w{constructor(e){super(),this._agent=e}makeRequest(e,{headers:t,method:r,protocol:s,requestData:o,timeout:a}){let i=new URL(e),d=s==="http"||i.protocol==="http:",c=this._agent;return c||(c=d?Oe:Ae),new Promise((p,l)=>{let h=(d?se:ne).request({agent:c,ciphers:"DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5",headers:t,host:i.hostname,method:r,path:i.pathname+i.search,port:i.port});h.setTimeout(a!=null?a:8e4,()=>{h.destroy(w.makeTimeoutError())}),h.on("response",u=>{p(new v(u))}),h.on("error",u=>{l(u)}),h.once("socket",u=>{let x=o?JSON.stringify(o):"";u.connecting?u.once(d?"connect":"secureConnect",()=>{h.write(x),h.end()}):(h.write(x),h.end())})})}},v=class extends M{constructor(e){super(e.statusCode,e.headers||{}),this._res=e}getRawResponse(){return this._res}toStream(e){return this._res.once("end",()=>e()),this._res}toJSON(){return new Promise((e,t)=>{let r="";this._res.setEncoding("utf8"),this._res.on("data",s=>{r+=s}),this._res.once("end",()=>{try{e(JSON.parse(r))}catch(s){t(s)}})})}};var S=n=>typeof n=="object"&&Array.isArray(n)&&n!==null,R=n=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",E=n=>R(n)&&Object.keys(n).length===0,ae=n=>typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null,W=n=>S(n)?n.every(ae):ae(n),L=n=>R(n)&&Object.values(n).every(W),b=n=>typeof n=="string",F=n=>{if(typeof n=="string"){if(n.toLowerCase()==="true")return!0;if(n.toLowerCase()==="false")return!1}return S(n)&&n.length===0||R(n)&&Object.keys(n).length===0?!1:!!n};var Ee={"Content-Type":"application/json"},oe=({httpClient:n,token:e,url:t})=>async(r,{headers:s,...o})=>{let a=await n.makeRequest(`${t}${r}`,{credentials:"omit",headers:Object.assign({...Ee,...s},typeof e<"u"?{token:e}:{}),...o});if(a.getStatusCode()>=200&&a.getStatusCode()<300)return await a.toJSON();throw new Error(`${a.getStatusCode()}`)};var I=class n extends Error{constructor(e,t){super(`Record with label "${e}" and properties ${JSON.stringify(t)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,n.prototype)}},T=class n extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,n.prototype)}},B=class n extends Error{constructor(e,t){super(`Expected a unique result but found ${e} matches for the provided SearchQuery: ${JSON.stringify(t)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,n.prototype)}};var P=class{constructor(){this.apiProxy={};return new Proxy(this,{get:(e,t,r)=>{if(t in e)return Reflect.get(e,t,r);if(this.apiProxy&&t in this.apiProxy)return Reflect.get(this.apiProxy,t,r)}})}init(e){this.apiProxy=e}};var K=["httpClient","timeout","host","port","protocol","url","logger","options"];var q=async(n,e)=>{let t=Object.entries(n).map(async([o,a])=>a.default&&typeof a.default<"u"&&typeof e[o]>"u"?{key:o,value:typeof a.default=="function"?await a.default():a.default}:{key:o,value:void 0});return{...(await Promise.all(t)).reduce((o,{key:a,value:i})=>(i!==void 0&&(o[a]=i),o),{}),...e}},H=(n,e)=>Object.entries(e).filter(([t])=>{var r;return(r=n[t])==null?void 0:r.uniq}).reduce((t,[r,s])=>(r in n&&(t[r]=s),t),{}),Y=(n,e,t)=>{let r={},s=Object.entries(e).filter(([,o])=>o.uniq).reduce((o,[a])=>(o[a]=!0,o),{});return n.forEach(o=>{Object.entries(o).forEach(([a,i])=>{if(a in s)if(r[a]){if(r[a].includes(i))throw new I(t,{[a]:i});r[a]=[...r[a],i]}else r[a]=[i]})}),r},V=n=>{if(!n)return{};if(!R(n))throw new Error("Config must be an object");if(Object.keys(n).filter(t=>!K.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${K.join(", ")}`);return n};function J(n,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${n} must be an integer`)}return e}function Q(n){let e=n.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function z(n){return new Date(Q(n))}var m=class extends P{constructor(e){super(),this.data=e}id(){try{return this.data.__id}catch{throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.")}}label(){try{return this.data.__label}catch{throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.")}}proptypes(){try{return this.data.__proptypes}catch{throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.")}}date(){try{return z(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return Q(this.id())}catch{throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}async delete(e){if(!this.data)throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return await this.apiProxy.records.deleteById(this.id(),e)}async update(e,t){if(!this.data)throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return this.apiProxy.records.update({label:this.label(),target:this.id(),data:e},t)}async set(e,t){if(!this.data)throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return this.apiProxy.records.set({label:this.label(),target:this.id(),data:e},t)}async attach(e,t,r){if(!this.data)throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return this.apiProxy.records.attach({source:this.id(),target:e,options:t},r)}async detach(e,t,r){if(!this.data)throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return this.apiProxy.records.detach({source:this.id(),target:e,options:t},r)}},O=class extends P{constructor(e,t,r){super(),this.data=e,this.total=t,this.searchQuery=r}};var A=class extends P{constructor(e){super(),this.id=e}async rollback(){return await this.apiProxy.tx.rollback(this.id)}async commit(){return await this.apiProxy.tx.commit(this.id)}};var ie="api.rushdb.com";var ce="https",de="/api/v1";var f=n=>n?{"x-transaction-id":n}:void 0,Ce=n=>b(n)||n instanceof A,g=n=>Ce(n)?n instanceof A?n.id:n:void 0,pe=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),D=n=>{if(b(n)&&pe(n))return n;if(n instanceof m&&n.data)return n.data.__id;if(R(n)&&"__id"in n&&pe(n.__id))return n.__id},C=n=>!(!R(n)||R(n)&&"name"in n&&!b(n.name)||R(n)&&"type"in n&&(!b(n.type)||!re.includes(n.type))||!("value"in n)||!W(n.value)||"metadata"in n&&!b(n.metadata)||"valueSeparator"in n&&!b(n.valueSeparator)),le=n=>{let e=ce,t=ie,r=443,s=de;if("url"in n){let a=new URL(n.url);e=a.protocol.replace(":",""),t=a.hostname,r=parseInt(a.port||(e==="http"?"80":e==="https"?"443":""))}"host"in n&&"port"in n&&"protocol"in n&&(e=n.protocol.replace(":",""),t=n.host,r=n.port),s&&!s.startsWith("/")&&(s="/"+s);let o="";return e==="http"&&r===80||e==="https"&&r===443||(o=":"+r),`${e}://${t}${o}${s}`},y=(n=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let r=0;r<n;r++){let s=Math.floor(Math.random()*e.length);t+=e[s]}return t};var _=class{constructor(e,t){this.records={attach:async({source:e,target:t,options:r},s)=>{var l,h;let o=g(s),i=`/relationships/${D(e)}`,d={headers:Object.assign({},f(o)),method:"POST",requestData:{targetIds:this._extractTargetIds(t,"Attach"),...(r==null?void 0:r.type)&&{type:r.type},...(r==null?void 0:r.direction)&&{direction:r.direction}}},c=typeof this.logger=="function"?y():"";(l=this.logger)==null||l.call(this,{requestId:c,path:i,...d});let p=await this.fetcher(i,d);return(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d,responseData:p.data}),p},detach:async({source:e,target:t,options:r},s)=>{var l,h;let o=g(s),i=`/relationships/${D(e)}`,d={headers:Object.assign({},f(o)),method:"PUT",requestData:{targetIds:this._extractTargetIds(t,"Detach"),...(r==null?void 0:r.typeOrTypes)&&{typeOrTypes:r.typeOrTypes},...(r==null?void 0:r.direction)&&{direction:r.direction}}},c=typeof this.logger=="function"?y():"";(l=this.logger)==null||l.call(this,{requestId:c,path:i,...d});let p=await this.fetcher(i,d);return(h=this.logger)==null||h.call(this,{requestId:c,path:i,...d,responseData:p.data}),p},create:async({label:e,data:t,options:r},s)=>{var p,l;let o=g(s),a="/records",i={headers:Object.assign({},f(o)),method:"POST",requestData:{}},d=typeof this.logger=="function"?y():"";if(S(t)&&t.every(C))i.requestData={label:e,properties:t};else if(L(t))i.requestData={label:e,data:t,options:r};else if(R(t))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(p=this.logger)==null||p.call(this,{requestId:d,path:a,...i});let c=await this.fetcher(a,i);if((l=this.logger)==null||l.call(this,{requestId:d,path:a,...i,responseData:c.data}),c!=null&&c.success&&(c!=null&&c.data)){let h=new m(c.data);return h.init(this),h}return new m},createMany:async(e,t)=>{var d,c;let r=g(t),s="/records/import/json",o={headers:Object.assign({},f(r)),method:"POST",requestData:e},a=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);if((c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i!=null&&i.success&&(i!=null&&i.data)){let p=i.data.map(h=>{let u=new m(h);return u.init(this),u}),l=new O(p,i.total);return l.init(this),l}return new O([])},delete:async(e,t)=>{var d,c,p;if(E(e.where)&&!((d=this==null?void 0:this.options)!=null&&d.allowForceDelete))throw new T("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let r=g(t),s="/records/delete",o={headers:Object.assign({},f(r)),method:"POST",requestData:e},a=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(p=this.logger)==null||p.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},deleteById:async(e,t)=>{var c,p;let r=g(t),s=S(e),o=s?"/records/delete":`/records/${e}`,a={headers:Object.assign({},f(r)),method:s?"PUT":"DELETE",requestData:s?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:i,path:o,...a});let d=await this.fetcher(o,a);return(p=this.logger)==null||p.call(this,{requestId:i,path:o,...a,responseData:d.data}),d},export:async(e,t)=>{var d,c;let r=g(t),s="/records/export/csv",o={headers:Object.assign({},f(r)),method:"POST",requestData:e},a=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},find:async(e,t)=>{var h,u;let{id:r,...s}=e,o=g(t),a=r?`/records/${r}/search`:"/records/search",i={headers:Object.assign({},f(o)),method:"POST",requestData:s},d=typeof this.logger=="function"?y():"";(h=this.logger)==null||h.call(this,{requestId:d,path:a,...i});let c=await this.fetcher(a,i);(u=this.logger)==null||u.call(this,{requestId:d,path:a,...i,responseData:c.data});let p=c.data.map(x=>{let Z=new m(x);return Z.init(this),Z}),l=new O(p,c.total,e);return l.init(this),l},findById:async(e,t)=>{var d,c;let r=g(t),s=S(e)?"/records":`/records/${e}`,o={headers:Object.assign({},f(r)),method:S(e)?"POST":"GET",requestData:S(e)?{ids:e}:void 0},a=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);if((c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),S(e)){let p=i.data.map(h=>{let u=new m(h);return u.init(this),u}),l=new O(p,i.total);return l.init(this),l}else{let p=new m(i.data);return p.init(this),p}},findOne:async(e,t)=>{var p,l;let r=g(t),s="/records/search",o={headers:Object.assign({},f(r)),method:"POST",requestData:{...e,limit:1,skip:0}},a=typeof this.logger=="function"?y():"";(p=this.logger)==null||p.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);(l=this.logger)==null||l.call(this,{requestId:a,path:s,...o,responseData:i.data});let[d]=i.data,c=new m(d);return c.init(this),c},findUniq:async(e,t)=>{var p,l;let r=g(t),s="/records/search",o={headers:Object.assign({},f(r)),method:"POST",requestData:{...e,limit:1,skip:0}},a=typeof this.logger=="function"?y():"";(p=this.logger)==null||p.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);if((l=this.logger)==null||l.call(this,{requestId:a,path:s,...o,responseData:i.data}),typeof i.total<"u"&&i.total>1)throw new B(i.total,e);let[d]=i.data,c=new m(d);return c.init(this),c},set:async({target:e,label:t,data:r,options:s},o)=>{var h,u;let a=g(o),d=`/records/${D(e)}`,c={headers:Object.assign({},f(a)),method:"PUT",requestData:{}},p=typeof this.logger=="function"?y():"";if(S(r)&&r.every(C))c.requestData={label:t,properties:r};else if(L(r))c.requestData={label:t,data:r,options:s};else if(R(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(h=this.logger)==null||h.call(this,{requestId:p,path:d,...c});let l=await this.fetcher(d,c);if((u=this.logger)==null||u.call(this,{requestId:p,path:d,...c,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)){let x=new m(l.data);return x.init(this),x}return new m},update:async({target:e,label:t,data:r,options:s},o)=>{var h,u;let a=g(o),d=`/records/${D(e)}`,c={headers:Object.assign({},f(a)),method:"PATCH",requestData:{}},p=typeof this.logger=="function"?y():"";if(S(r)&&r.every(C))c.requestData={label:t,properties:r};else if(L(r))c.requestData={label:t,data:r,options:s};else if(R(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(h=this.logger)==null||h.call(this,{requestId:p,path:d,...c});let l=await this.fetcher(d,c);if((u=this.logger)==null||u.call(this,{requestId:p,path:d,...c,responseData:l.data}),l!=null&&l.success&&(l!=null&&l.data)){let x=new m(l.data);return x.init(this),x}return new m}};this.relationships={find:async(e,t)=>{var p,l;let r=g(t),s=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&s.append("limit",e.limit.toString()),(e==null?void 0:e.skip)!==void 0&&s.append("skip",e.skip.toString());let a=`/relationships/search${s.toString()?"?"+s.toString():""}`,i={headers:Object.assign({},f(r)),method:"POST",requestData:e},d=typeof this.logger=="function"?y():"";(p=this.logger)==null||p.call(this,{requestId:d,path:a,...i});let c=await this.fetcher(a,i);return(l=this.logger)==null||l.call(this,{requestId:d,path:a,...i,responseData:c.data}),c}};this.properties={delete:async(e,t)=>{var d,c;let r=g(t),s=`/properties/${e}`,o={headers:Object.assign({},f(r)),method:"DELETE"},a=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},find:async(e,t)=>{var d,c;let r=g(t),s="/properties/search",o={headers:Object.assign({},f(r)),method:"POST",requestData:e},a=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},findById:async(e,t)=>{var d,c;let r=g(t),s=`/properties/${e}`,o={headers:Object.assign({},f(r)),method:"GET"},a=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i},values:async(e,t,r)=>{var c,p;let s=g(r),o=`/properties/${e}/values`,a={headers:Object.assign({},f(s)),method:"POST",requestData:t},i=typeof this.logger=="function"?y():"";(c=this.logger)==null||c.call(this,{requestId:i,path:o,...a});let d=await this.fetcher(o,a);return(p=this.logger)==null||p.call(this,{requestId:i,path:o,...a,responseData:d.data}),d}};this.labels={find:async(e,t)=>{var d,c;let r=g(t),s="/labels/search",o={headers:Object.assign({},f(r)),method:"POST",requestData:e},a=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:a,path:s,...o});let i=await this.fetcher(s,o);return(c=this.logger)==null||c.call(this,{requestId:a,path:s,...o,responseData:i.data}),i}};this.tx={begin:async e=>{var i,d;let t="/tx",r={method:"POST",requestData:e},s=typeof this.logger=="function"?y():"";(i=this.logger)==null||i.call(this,{requestId:s,path:t,...r});let o=await this.fetcher(t,r);(d=this.logger)==null||d.call(this,{requestId:s,path:t,...r,responseData:o.data});let a=new A(o.data.id);return a.init(this),a},commit:async e=>{var i,d;let r=`/tx/${g(e)}/commit`,s={method:"POST",requestData:{}},o=typeof this.logger=="function"?y():"";(i=this.logger)==null||i.call(this,{requestId:o,path:r,...s});let a=await this.fetcher(r,s);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...s,responseData:a.data}),a},get:async e=>{var d,c;let r=`/tx/${g(e)}`,s={method:"GET"},o=typeof this.logger=="function"?y():"";(d=this.logger)==null||d.call(this,{requestId:o,path:r,...s});let a=await this.fetcher(r,s);(c=this.logger)==null||c.call(this,{requestId:o,path:r,...s,responseData:a.data});let i=new A(a.data.id);return i.init(this),i},rollback:async e=>{var i,d;let r=`/tx/${g(e)}/rollback`,s={method:"POST",requestData:{}},o=typeof this.logger=="function"?y():"";(i=this.logger)==null||i.call(this,{requestId:o,path:r,...s});let a=await this.fetcher(r,s);return(d=this.logger)==null||d.call(this,{requestId:o,path:r,...s,responseData:a.data}),a}};if(this.fetcher=null,t!=null&&t.httpClient){let r=le(t);this.fetcher=oe({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=D(e);if(!s)throw new T(`${t} error: Target id is empty`);return[s]}if(S(e)&&e.every(s=>s instanceof m)){let s=e.map(D).filter(F);if(!s.length)throw new T(`${t} error: Target ids are empty`);return s}if(e instanceof O){let s=(r=e.data)==null?void 0:r.map(D).filter(F);if(!(s!=null&&s.length))throw new T(`${t} error: Target ids are empty`);return s}if(R(e)&&"__id"in e)return[e.__id];if(S(e)&&e.every(s=>R(s)&&"__id"in s)){let s=e.map(D).filter(F);if(!s.length)throw new T(`${t} error: Target ids are empty`);return s}return S(e)?e:b(e)?[e]:[]}};var G=n=>{class e extends _{constructor(r,s){var a;let o=V(s);super(r,{...o,httpClient:(a=o.httpClient)!=null?a:n}),this.state={debug:!1,timeout:J("timeout",o.timeout,8e4),token:r},this.models=new Map,e.instance=this}static getInstance(){return e.instance}registerModel(r){let s=r.getLabel();return r.init(this),this.models.set(s,r),r}getModels(){return this.models}getModel(r){return this.models.get(r)}toInstance(r){let s=new m(r);return s.init(this),s}}return e};var X=class extends P{constructor(e,t,r){super(),this.label=e,this.schema=t,this.rushDBInstance=r,r==null||r.registerModel(this)}getLabel(){return this.label}toInstance(e){if(this.rushDBInstance)return this.rushDBInstance.toInstance(e);throw new Error("No RushDB instance was provided during model initialization.")}async find(e,t){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.find({...r,labels:[this.label]},t)}async findOne(e,t){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.findOne({...r,labels:[this.label]},t)}async findById(e,t){return this.findOne({where:{$id:e}},t)}async findUniq(e,t){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.findUniq({...r,labels:[this.label]},t)}async create(e,t){var o;let r=await q(this.schema,e),s=H(this.schema,r);if(!E(s)){let a=t!=null?t:await this.apiProxy.tx.begin(),i=await this.find({where:s},a),d=typeof t<"u";if(!((o=i==null?void 0:i.data)!=null&&o.length)){let p=await this.apiProxy.records.create({label:this.label,data:r},a);return d||await a.commit(),p}else throw d||await a.commit(),new I(this.label,s)}return await this.apiProxy.records.create({label:this.label,data:r},t)}attach({source:e,target:t,options:r},s){return this.apiProxy.records.attach({source:e,target:t,options:r},s)}detach({source:e,target:t,options:r},s){return this.apiProxy.records.detach({source:e,target:t,options:r},s)}async handleSetOrUpdate(e,t,r,s){var i,d;if(S(t)&&t.every(C))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let o=await q(this.schema,t),a=H(this.schema,o);if(!E(a)){let c=s!=null?s:await this.apiProxy.tx.begin(),p=await this.find({where:a},c),l=typeof s<"u";if(!((i=p==null?void 0:p.data)!=null&&i.length)||p.data.length===1&&((d=p.data[0])==null?void 0:d.id())===D(e)){let u=await this.apiProxy.records[r]({target:e,label:this.label,data:o},c);return l||await c.commit(),u}else throw l||await c.commit(),new I(this.label,a)}return await this.apiProxy.records[r]({label:this.label,target:e,data:o},s)}async set(e,t,r){return await this.handleSetOrUpdate(e,t,"set",r)}async update(e,t,r){return await this.handleSetOrUpdate(e,t,"update",r)}async createMany(e,t){var o;let r=typeof t<"u",s=t!=null?t:await this.apiProxy.tx.begin();try{let a=await Promise.all(e.map(async c=>await q(this.schema,c))),i=Y(a,this.schema,this.label);if(!E(i)){let c=Object.entries(i).map(([l,h])=>({[l]:{$in:h}})),p=await this.find({where:{$or:c}},s);if((o=p==null?void 0:p.data)!=null&&o.length)throw new I(this.label,Object.keys(i))}let d=await this.apiProxy.records.createMany({label:this.label,data:a},s);return r||await s.commit(),d}catch(a){throw r||await s.rollback(),a}}async delete(e,t){if(E(e.where))throw new T(`You must specify criteria to delete records of type '${this.label}'. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.`);return await this.apiProxy.records.delete({...e,labels:[this.label]},t)}async deleteById(e,t){return await this.apiProxy.records.deleteById(e,t)}};var he=G(new U);var Be=he;0&&(module.exports={DBRecordInstance,DBRecordsArrayInstance,EmptyTargetError,HttpClient,HttpClientResponse,Model,NonUniqueResultError,RestAPI,RushDB,Transaction,UniquenessError,idToDate,idToTimestamp,initSDK,mergeDefaultsWithPayload,parseConfig,pickUniqFieldsFromRecord,pickUniqFieldsFromRecords,validateInteger});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var me=Object.defineProperty,fe=Object.defineProperties;var ge=Object.getOwnPropertyDescriptors;var U=Object.getOwnPropertySymbols;var X=Object.prototype.hasOwnProperty,ee=Object.prototype.propertyIsEnumerable;var Z=(n,e,t)=>e in n?me(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,p=(n,e)=>{for(var t in e||(e={}))X.call(e,t)&&Z(n,t,e[t]);if(U)for(var t of U(e))ee.call(e,t)&&Z(n,t,e[t]);return n},m=(n,e)=>fe(n,ge(e));var F=(n,e)=>{var t={};for(var r in n)X.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&U)for(var r of U(n))e.indexOf(r)<0&&ee.call(n,r)&&(t[r]=n[r]);return t};var u=(n,e,t)=>new Promise((r,s)=>{var a=c=>{try{i(t.next(c))}catch(d){s(d)}},o=c=>{try{i(t.throw(c))}catch(d){s(d)}},i=c=>c.done?r(c.value):Promise.resolve(c.value).then(a,o);i((t=t.apply(n,e)).next())});var Se="string",Re="datetime",Te="boolean",be="number",De="null",xe="vector",te=[Se,Re,Te,be,De,xe];var O=class n{makeRequest(e,{headers:t,method:r,protocol:s,requestData:a,timeout:o}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(n.TIMEOUT_ERROR_CODE);return e.code=n.TIMEOUT_ERROR_CODE,e}};O.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];O.TIMEOUT_ERROR_CODE="ETIMEDOUT";var H=class{constructor(e,t){this._statusCode=e,this._headers=t}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}},N=class{constructor(e){this._res=e}getStatusCode(){throw new Error("getStatusCode not implemented.")}getHeaders(){throw new Error("getHeaders not implemented.")}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}};var L=class n extends O{constructor(e){if(super(),!e){if(!globalThis.fetch)throw new Error("fetch() function not provided and is not defined in the global scope. You must provide a fetch implementation.");e=globalThis.fetch}globalThis.AbortController?this._fetchFn=n.makeFetchWithAbortTimeout(e):this._fetchFn=n.makeFetchWithRaceTimeout(e)}static makeFetchWithRaceTimeout(e){return(t,r,s)=>{let a,o=new Promise((c,d)=>{a=setTimeout(()=>{a=null,d(O.makeTimeoutError())},s)}),i=e(t,r);return Promise.race([i,o]).finally(()=>{a&&clearTimeout(a)})}}static makeFetchWithAbortTimeout(e){return(t,r,s)=>u(this,null,function*(){let a=new AbortController,o=setTimeout(()=>{o=null,a.abort(O.makeTimeoutError())},s);try{return yield e(t,m(p({},r),{signal:a.signal}))}catch(i){throw i.name==="AbortError"?O.makeTimeoutError():i}finally{o&&clearTimeout(o)}})}makeRequest(i,c){return u(this,arguments,function*(e,{headers:t,method:r,protocol:s,requestData:a,timeout:o}){let d=r=="POST"||r=="PUT"||r=="PATCH",l=JSON.stringify(a)||(d?"":void 0),h=yield this._fetchFn(e,{body:l,headers:t,method:r},o!=null?o:8e4);return new K(h)})}},K=class n extends H{constructor(e){super(e.status,n._transformHeadersToObject(e.headers)),this._res=e}getRawResponse(){return this._res}toStream(e){return e(),this._res.body}toJSON(){return this._res.json()}static _transformHeadersToObject(e){let t={};for(let r of e){if(!Array.isArray(r)||r.length!=2)throw new Error("Response objects produced by the fetch function given to FetchHttpClient do not have an iterable headers map. Response#headers should be an iterable object.");t[r[0]]=r[1]}return t}};var D=n=>typeof n=="object"&&Array.isArray(n)&&n!==null,x=n=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",j=n=>x(n)&&Object.keys(n).length===0,re=n=>typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null,V=n=>D(n)?n.every(re):re(n),v=n=>x(n)&&Object.values(n).every(V),A=n=>typeof n=="string",Q=n=>{if(typeof n=="string"){if(n.toLowerCase()==="true")return!0;if(n.toLowerCase()==="false")return!1}return D(n)&&n.length===0||x(n)&&Object.keys(n).length===0?!1:!!n};var Ie={"Content-Type":"application/json"},se=({httpClient:n,token:e,url:t})=>(r,o)=>u(void 0,null,function*(){var i=o,{headers:s}=i,a=F(i,["headers"]);let c=yield n.makeRequest(`${t}${r}`,p({credentials:"omit",headers:Object.assign(p(p({},Ie),s),typeof e!="undefined"?{token:e}:{})},a));if(c.getStatusCode()>=200&&c.getStatusCode()<300)return yield c.toJSON();throw new Error(`${c.getStatusCode()}`)});var B=class n extends Error{constructor(e,t){super(`Record with label "${e}" and properties ${JSON.stringify(t)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,n.prototype)}},E=class n extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,n.prototype)}},$=class n extends Error{constructor(e,t){super(`Expected a unique result but found ${e} matches for the provided SearchQuery: ${JSON.stringify(t)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,n.prototype)}};var C=class{constructor(){this.apiProxy={};return new Proxy(this,{get:(e,t,r)=>{if(t in e)return Reflect.get(e,t,r);if(this.apiProxy&&t in this.apiProxy)return Reflect.get(this.apiProxy,t,r)}})}init(e){this.apiProxy=e}};var Y=["httpClient","timeout","host","port","protocol","url","logger","options"];var W=(n,e)=>u(void 0,null,function*(){let t=Object.entries(n).map(i=>u(void 0,[i],function*([a,o]){return o.default&&typeof o.default!="undefined"&&typeof e[a]=="undefined"?{key:a,value:typeof o.default=="function"?yield o.default():o.default}:{key:a,value:void 0}})),s=(yield Promise.all(t)).reduce((a,{key:o,value:i})=>(i!==void 0&&(a[o]=i),a),{});return p(p({},s),e)}),J=(n,e)=>Object.entries(e).filter(([t])=>{var r;return(r=n[t])==null?void 0:r.uniq}).reduce((t,[r,s])=>(r in n&&(t[r]=s),t),{}),ne=(n,e,t)=>{let r={},s=Object.entries(e).filter(([,a])=>a.uniq).reduce((a,[o])=>(a[o]=!0,a),{});return n.forEach(a=>{Object.entries(a).forEach(([o,i])=>{if(o in s)if(r[o]){if(r[o].includes(i))throw new B(t,{[o]:i});r[o]=[...r[o],i]}else r[o]=[i]})}),r},ae=n=>{if(!n)return{};if(!x(n))throw new Error("Config must be an object");if(Object.keys(n).filter(t=>!Y.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${Y.join(", ")}`);return n};function oe(n,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${n} must be an integer`)}return e}function G(n){let e=n.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function ie(n){return new Date(G(n))}var R=class extends C{constructor(e){super(),this.data=e}id(){try{return this.data.__id}catch(e){throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.")}}label(){try{return this.data.__label}catch(e){throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.")}}proptypes(){try{return this.data.__proptypes}catch(e){throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.")}}date(){try{return ie(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return G(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}delete(e){return u(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return yield this.apiProxy.records.deleteById(this.id(),e)})}update(e,t){return u(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return this.apiProxy.records.update({label:this.label(),target:this.id(),data:e},t)})}set(e,t){return u(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return this.apiProxy.records.set({label:this.label(),target:this.id(),data:e},t)})}attach(e,t,r){return u(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return this.apiProxy.records.attach({source:this.id(),target:e,options:t},r)})}detach(e,t,r){return u(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return this.apiProxy.records.detach({source:this.id(),target:e,options:t},r)})}},q=class extends C{constructor(e,t,r){super(),this.data=e,this.total=t,this.searchQuery=r}};var _=class extends C{constructor(e){super(),this.id=e}rollback(){return u(this,null,function*(){return yield this.apiProxy.tx.rollback(this.id)})}commit(){return u(this,null,function*(){return yield this.apiProxy.tx.commit(this.id)})}};var ce="api.rushdb.com";var de="https",pe="/api/v1";var b=n=>n?{"x-transaction-id":n}:void 0,Oe=n=>A(n)||n instanceof _,S=n=>Oe(n)?n instanceof _?n.id:n:void 0,le=n=>/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(n),I=n=>{if(A(n)&&le(n))return n;if(n instanceof R&&n.data)return n.data.__id;if(x(n)&&"__id"in n&&le(n.__id))return n.__id},k=n=>!(!x(n)||x(n)&&"name"in n&&!A(n.name)||x(n)&&"type"in n&&(!A(n.type)||!te.includes(n.type))||!("value"in n)||!V(n.value)||"metadata"in n&&!A(n.metadata)||"valueSeparator"in n&&!A(n.valueSeparator)),he=n=>{let e=de,t=ce,r=443,s=pe;if("url"in n){let o=new URL(n.url);e=o.protocol.replace(":",""),t=o.hostname,r=parseInt(o.port||(e==="http"?"80":e==="https"?"443":""))}"host"in n&&"port"in n&&"protocol"in n&&(e=n.protocol.replace(":",""),t=n.host,r=n.port),s&&!s.startsWith("/")&&(s="/"+s);let a="";return e==="http"&&r===80||e==="https"&&r===443||(a=":"+r),`${e}://${t}${a}${s}`},g=(n=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let r=0;r<n;r++){let s=Math.floor(Math.random()*e.length);t+=e[s]}return t};var M=class{constructor(e,t){this.records={attach:(a,o)=>u(this,[a,o],function*({source:e,target:t,options:r},s){var y,T;let i=S(s),d=`/relationships/${I(e)}`,l={headers:Object.assign({},b(i)),method:"POST",requestData:p(p({targetIds:this._extractTargetIds(t,"Attach")},(r==null?void 0:r.type)&&{type:r.type}),(r==null?void 0:r.direction)&&{direction:r.direction})},h=typeof this.logger=="function"?g():"";(y=this.logger)==null||y.call(this,p({requestId:h,path:d},l));let f=yield this.fetcher(d,l);return(T=this.logger)==null||T.call(this,m(p({requestId:h,path:d},l),{responseData:f.data})),f}),detach:(a,o)=>u(this,[a,o],function*({source:e,target:t,options:r},s){var y,T;let i=S(s),d=`/relationships/${I(e)}`,l={headers:Object.assign({},b(i)),method:"PUT",requestData:p(p({targetIds:this._extractTargetIds(t,"Detach")},(r==null?void 0:r.typeOrTypes)&&{typeOrTypes:r.typeOrTypes}),(r==null?void 0:r.direction)&&{direction:r.direction})},h=typeof this.logger=="function"?g():"";(y=this.logger)==null||y.call(this,p({requestId:h,path:d},l));let f=yield this.fetcher(d,l);return(T=this.logger)==null||T.call(this,m(p({requestId:h,path:d},l),{responseData:f.data})),f}),create:(a,o)=>u(this,[a,o],function*({label:e,data:t,options:r},s){var f,y;let i=S(s),c="/records",d={headers:Object.assign({},b(i)),method:"POST",requestData:{}},l=typeof this.logger=="function"?g():"";if(D(t)&&t.every(k))d.requestData={label:e,properties:t};else if(v(t))d.requestData={label:e,data:t,options:r};else if(x(t))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(f=this.logger)==null||f.call(this,p({requestId:l,path:c},d));let h=yield this.fetcher(c,d);if((y=this.logger)==null||y.call(this,m(p({requestId:l,path:c},d),{responseData:h.data})),h!=null&&h.success&&(h!=null&&h.data)){let T=new R(h.data);return T.init(this),T}return new R}),createMany:(e,t)=>u(this,null,function*(){var c,d;let r=S(t),s="/records/import/json",a={headers:Object.assign({},b(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);if((d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i!=null&&i.success&&(i!=null&&i.data)){let l=i.data.map(f=>{let y=new R(f);return y.init(this),y}),h=new q(l,i.total);return h.init(this),h}return new q([])}),delete:(e,t)=>u(this,null,function*(){var c,d,l;if(j(e.where)&&!((c=this==null?void 0:this.options)!=null&&c.allowForceDelete))throw new E("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let r=S(t),s="/records/delete",a={headers:Object.assign({},b(r)),method:"PUT",requestData:e},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(l=this.logger)==null||l.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),deleteById:(e,t)=>u(this,null,function*(){var d,l;let r=S(t),s=D(e),a=s?"/records/delete":`/records/${e}`,o={headers:Object.assign({},b(r)),method:s?"PUT":"DELETE",requestData:s?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:a},o));let c=yield this.fetcher(a,o);return(l=this.logger)==null||l.call(this,m(p({requestId:i,path:a},o),{responseData:c.data})),c}),export:(e,t)=>u(this,null,function*(){var c,d;let r=S(t),s="/records/export/csv",a={headers:Object.assign({},b(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),find:(e,t)=>u(this,null,function*(){var y,T;let f=e,{id:r}=f,s=F(f,["id"]),a=S(t),o=r?`/records/${r}/search`:"/records/search",i={headers:Object.assign({},b(a)),method:"POST",requestData:s},c=typeof this.logger=="function"?g():"";(y=this.logger)==null||y.call(this,p({requestId:c,path:o},i));let d=yield this.fetcher(o,i);(T=this.logger)==null||T.call(this,m(p({requestId:c,path:o},i),{responseData:d.data}));let l=d.data.map(P=>{let w=new R(P);return w.init(this),w}),h=new q(l,d.total,e);return h.init(this),h}),findById:(e,t)=>u(this,null,function*(){var c,d;let r=S(t),s=D(e)?"/records":`/records/${e}`,a={headers:Object.assign({},b(r)),method:D(e)?"POST":"GET",requestData:D(e)?{ids:e}:void 0},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);if((d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),D(e)){let l=i.data.map(f=>{let y=new R(f);return y.init(this),y}),h=new q(l,i.total);return h.init(this),h}else{let l=new R(i.data);return l.init(this),l}}),findOne:(e,t)=>u(this,null,function*(){var l,h;let r=S(t),s="/records/search",a={headers:Object.assign({},b(r)),method:"POST",requestData:m(p({},e),{limit:1,skip:0})},o=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);(h=this.logger)==null||h.call(this,m(p({requestId:o,path:s},a),{responseData:i.data}));let[c]=i.data,d=new R(c);return d.init(this),d}),findUniq:(e,t)=>u(this,null,function*(){var l,h;let r=S(t),s="/records/search",a={headers:Object.assign({},b(r)),method:"POST",requestData:m(p({},e),{limit:1,skip:0})},o=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);if((h=this.logger)==null||h.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),typeof i.total!="undefined"&&i.total>1)throw new $(i.total,e);let[c]=i.data,d=new R(c);return d.init(this),d}),set:(o,i)=>u(this,[o,i],function*({target:e,label:t,data:r,options:s},a){var T,P;let c=S(a),l=`/records/${I(e)}`,h={headers:Object.assign({},b(c)),method:"PUT",requestData:{}},f=typeof this.logger=="function"?g():"";if(D(r)&&r.every(k))h.requestData={label:t,properties:r};else if(v(r))h.requestData={label:t,data:r,options:s};else if(x(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(T=this.logger)==null||T.call(this,p({requestId:f,path:l},h));let y=yield this.fetcher(l,h);if((P=this.logger)==null||P.call(this,m(p({requestId:f,path:l},h),{responseData:y.data})),y!=null&&y.success&&(y!=null&&y.data)){let w=new R(y.data);return w.init(this),w}return new R}),update:(o,i)=>u(this,[o,i],function*({target:e,label:t,data:r,options:s},a){var T,P;let c=S(a),l=`/records/${I(e)}`,h={headers:Object.assign({},b(c)),method:"PATCH",requestData:{}},f=typeof this.logger=="function"?g():"";if(D(r)&&r.every(k))h.requestData={label:t,properties:r};else if(v(r))h.requestData={label:t,data:r,options:s};else if(x(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(T=this.logger)==null||T.call(this,p({requestId:f,path:l},h));let y=yield this.fetcher(l,h);if((P=this.logger)==null||P.call(this,m(p({requestId:f,path:l},h),{responseData:y.data})),y!=null&&y.success&&(y!=null&&y.data)){let w=new R(y.data);return w.init(this),w}return new R})};this.relationships={find:(e,t)=>u(this,null,function*(){var l,h;let r=S(t),s=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&s.append("limit",e.limit.toString()),(e==null?void 0:e.skip)!==void 0&&s.append("skip",e.skip.toString());let o=`/relationships/search${s.toString()?"?"+s.toString():""}`,i={headers:Object.assign({},b(r)),method:"POST",requestData:e},c=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,p({requestId:c,path:o},i));let d=yield this.fetcher(o,i);return(h=this.logger)==null||h.call(this,m(p({requestId:c,path:o},i),{responseData:d.data})),d})};this.properties={delete:(e,t)=>u(this,null,function*(){var c,d;let r=S(t),s=`/properties/${e}`,a={headers:Object.assign({},b(r)),method:"DELETE"},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),find:(e,t)=>u(this,null,function*(){var c,d;let r=S(t),s="/properties/search",a={headers:Object.assign({},b(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),findById:(e,t)=>u(this,null,function*(){var c,d;let r=S(t),s=`/properties/${e}`,a={headers:Object.assign({},b(r)),method:"GET"},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),values:(e,t,r)=>u(this,null,function*(){var w,z;let s=S(r),a=`/properties/${e}/values`,{sort:o,skip:i,limit:c,query:d}=t!=null?t:{},l=new URLSearchParams;o!==void 0&&l.append("sort",o),i!==void 0&&l.append("skip",i.toString()),c!==void 0&&l.append("limit",c.toString()),d!==void 0&&l.append("query",d);let h=l.toString(),f=h?`${a}?${h}`:a,y={headers:Object.assign({},b(s)),method:"GET"},T=typeof this.logger=="function"?g():"";(w=this.logger)==null||w.call(this,p({requestId:T,path:a},y));let P=yield this.fetcher(f,y);return(z=this.logger)==null||z.call(this,m(p({requestId:T,path:f},y),{responseData:P.data})),P})};this.labels={find:(e,t)=>u(this,null,function*(){var c,d;let r=S(t),s="/labels/search",a={headers:Object.assign({},b(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i})};this.tx={begin:e=>u(this,null,function*(){var i,c;let t="/tx",r={method:"POST",requestData:e},s=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,p({requestId:s,path:t},r));let a=yield this.fetcher(t,r);(c=this.logger)==null||c.call(this,m(p({requestId:s,path:t},r),{responseData:a.data}));let o=new _(a.data.id);return o.init(this),o}),commit:e=>u(this,null,function*(){var i,c;let r=`/tx/${S(e)}/commit`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,p({requestId:a,path:r},s));let o=yield this.fetcher(r,s);return(c=this.logger)==null||c.call(this,m(p({requestId:a,path:r},s),{responseData:o.data})),o}),get:e=>u(this,null,function*(){var c,d;let r=`/tx/${S(e)}`,s={method:"GET"},a=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:a,path:r},s));let o=yield this.fetcher(r,s);(d=this.logger)==null||d.call(this,m(p({requestId:a,path:r},s),{responseData:o.data}));let i=new _(o.data.id);return i.init(this),i}),rollback:e=>u(this,null,function*(){var i,c;let r=`/tx/${S(e)}/rollback`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,p({requestId:a,path:r},s));let o=yield this.fetcher(r,s);return(c=this.logger)==null||c.call(this,m(p({requestId:a,path:r},s),{responseData:o.data})),o})};if(this.fetcher=null,t!=null&&t.httpClient){let r=he(t);this.fetcher=se({httpClient:t.httpClient,token:e,url:r})}t!=null&&t.options&&(this.options=t==null?void 0:t.options),t!=null&&t.logger&&(this.logger=t==null?void 0:t.logger)}_extractTargetIds(e,t){var r;if(e instanceof R){let s=I(e);if(!s)throw new E(`${t} error: Target id is empty`);return[s]}if(D(e)&&e.every(s=>s instanceof R)){let s=e.map(I).filter(Q);if(!s.length)throw new E(`${t} error: Target ids are empty`);return s}if(e instanceof q){let s=(r=e.data)==null?void 0:r.map(I).filter(Q);if(!(s!=null&&s.length))throw new E(`${t} error: Target ids are empty`);return s}if(x(e)&&"__id"in e)return[e.__id];if(D(e)&&e.every(s=>x(s)&&"__id"in s)){let s=e.map(I).filter(Q);if(!s.length)throw new E(`${t} error: Target ids are empty`);return s}return D(e)?e:A(e)?[e]:[]}};var ue=n=>{class e extends M{constructor(r,s){var o;let a=ae(s);super(r,m(p({},a),{httpClient:(o=a.httpClient)!=null?o:n})),this.state={debug:!1,timeout:oe("timeout",a.timeout,8e4),token:r},this.models=new Map,e.instance=this}static getInstance(){return e.instance}registerModel(r){let s=r.getLabel();return r.init(this),this.models.set(s,r),r}getModels(){return this.models}getModel(r){return this.models.get(r)}toInstance(r){let s=new R(r);return s.init(this),s}}return e};var ye=class extends C{constructor(e,t,r){super(),this.label=e,this.schema=t,this.rushDBInstance=r,r==null||r.registerModel(this)}getLabel(){return this.label}toInstance(e){if(this.rushDBInstance)return this.rushDBInstance.toInstance(e);throw new Error("No RushDB instance was provided during model initialization.")}find(e,t){return u(this,null,function*(){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.find(m(p({},r),{labels:[this.label]}),t)})}findOne(e,t){return u(this,null,function*(){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.findOne(m(p({},r),{labels:[this.label]}),t)})}findById(e,t){return u(this,null,function*(){return this.findOne({where:{$id:e}},t)})}findUniq(e,t){return u(this,null,function*(){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.findUniq(m(p({},r),{labels:[this.label]}),t)})}create(e,t){return u(this,null,function*(){var a;let r=yield W(this.schema,e),s=J(this.schema,r);if(!j(s)){let o=t!=null?t:yield this.apiProxy.tx.begin(),i=yield this.find({where:s},o),c=typeof t!="undefined";if(!((a=i==null?void 0:i.data)!=null&&a.length)){let l=yield this.apiProxy.records.create({label:this.label,data:r},o);return c||(yield o.commit()),l}else throw c||(yield o.commit()),new B(this.label,s)}return yield this.apiProxy.records.create({label:this.label,data:r},t)})}attach({source:e,target:t,options:r},s){return this.apiProxy.records.attach({source:e,target:t,options:r},s)}detach({source:e,target:t,options:r},s){return this.apiProxy.records.detach({source:e,target:t,options:r},s)}handleSetOrUpdate(e,t,r,s){return u(this,null,function*(){var i,c;if(D(t)&&t.every(k))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let a=yield W(this.schema,t),o=J(this.schema,a);if(!j(o)){let d=s!=null?s:yield this.apiProxy.tx.begin(),l=yield this.find({where:o},d),h=typeof s!="undefined";if(!((i=l==null?void 0:l.data)!=null&&i.length)||l.data.length===1&&((c=l.data[0])==null?void 0:c.id())===I(e)){let y=yield this.apiProxy.records[r]({target:e,label:this.label,data:a},d);return h||(yield d.commit()),y}else throw h||(yield d.commit()),new B(this.label,o)}return yield this.apiProxy.records[r]({label:this.label,target:e,data:a},s)})}set(e,t,r){return u(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"set",r)})}update(e,t,r){return u(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"update",r)})}createMany(e,t){return u(this,null,function*(){var a;let r=typeof t!="undefined",s=t!=null?t:yield this.apiProxy.tx.begin();try{let o=yield Promise.all(e.map(d=>u(this,null,function*(){return yield W(this.schema,d)}))),i=ne(o,this.schema,this.label);if(!j(i)){let d=Object.entries(i).map(([h,f])=>({[h]:{$in:f}})),l=yield this.find({where:{$or:d}},s);if((a=l==null?void 0:l.data)!=null&&a.length)throw new B(this.label,Object.keys(i))}let c=yield this.apiProxy.records.createMany({label:this.label,data:o},s);return r||(yield s.commit()),c}catch(o){throw r||(yield s.rollback()),o}})}delete(e,t){return u(this,null,function*(){if(j(e.where))throw new E(`You must specify criteria to delete records of type '${this.label}'. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.`);return yield this.apiProxy.records.delete(m(p({},e),{labels:[this.label]}),t)})}deleteById(e,t){return u(this,null,function*(){return yield this.apiProxy.records.deleteById(e,t)})}};var Ee=ue(new L);var qt=Ee;export{R as DBRecordInstance,q as DBRecordsArrayInstance,E as EmptyTargetError,O as HttpClient,N as HttpClientResponse,ye as Model,$ as NonUniqueResultError,M as RestAPI,Ee as RushDB,_ as Transaction,B as UniquenessError,qt as default,ie as idToDate,G as idToTimestamp,ue as initSDK,W as mergeDefaultsWithPayload,ae as parseConfig,J as pickUniqFieldsFromRecord,ne as pickUniqFieldsFromRecords,oe as validateInteger};
|
|
1
|
+
var ue=Object.defineProperty,me=Object.defineProperties;var fe=Object.getOwnPropertyDescriptors;var U=Object.getOwnPropertySymbols;var Z=Object.prototype.hasOwnProperty,X=Object.prototype.propertyIsEnumerable;var G=(n,e,t)=>e in n?ue(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,p=(n,e)=>{for(var t in e||(e={}))Z.call(e,t)&&G(n,t,e[t]);if(U)for(var t of U(e))X.call(e,t)&&G(n,t,e[t]);return n},m=(n,e)=>me(n,fe(e));var F=(n,e)=>{var t={};for(var r in n)Z.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&U)for(var r of U(n))e.indexOf(r)<0&&X.call(n,r)&&(t[r]=n[r]);return t};var h=(n,e,t)=>new Promise((r,s)=>{var a=c=>{try{i(t.next(c))}catch(d){s(d)}},o=c=>{try{i(t.throw(c))}catch(d){s(d)}},i=c=>c.done?r(c.value):Promise.resolve(c.value).then(a,o);i((t=t.apply(n,e)).next())});var ge="string",Se="datetime",Re="boolean",Te="number",be="null",De="vector",ee=[ge,Se,Re,Te,be,De];var I=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}};I.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];I.TIMEOUT_ERROR_CODE="ETIMEDOUT";var H=class{constructor(e,t){this._statusCode=e,this._headers=t}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}},N=class{constructor(e){this._res=e}getStatusCode(){throw new Error("getStatusCode not implemented.")}getHeaders(){throw new Error("getHeaders not implemented.")}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}};var v=class n extends I{constructor(e){if(super(),!e){if(!globalThis.fetch)throw new Error("fetch() function not provided and is not defined in the global scope. You must provide a fetch implementation.");e=globalThis.fetch}globalThis.AbortController?this._fetchFn=n.makeFetchWithAbortTimeout(e):this._fetchFn=n.makeFetchWithRaceTimeout(e)}static makeFetchWithRaceTimeout(e){return(t,r,s)=>{let a,o=new Promise((c,d)=>{a=setTimeout(()=>{a=null,d(I.makeTimeoutError())},s)}),i=e(t,r);return Promise.race([i,o]).finally(()=>{a&&clearTimeout(a)})}}static makeFetchWithAbortTimeout(e){return(t,r,s)=>h(this,null,function*(){let a=new AbortController,o=setTimeout(()=>{o=null,a.abort(I.makeTimeoutError())},s);try{return yield e(t,m(p({},r),{signal:a.signal}))}catch(i){throw i.name==="AbortError"?I.makeTimeoutError():i}finally{o&&clearTimeout(o)}})}makeRequest(i,c){return h(this,arguments,function*(e,{headers:t,method:r,protocol:s,requestData:a,timeout:o}){let d=r=="POST"||r=="PUT"||r=="PATCH",l=JSON.stringify(a)||(d?"":void 0),y=yield this._fetchFn(e,{body:l,headers:t,method:r},o!=null?o:8e4);return new K(y)})}},K=class n extends H{constructor(e){super(e.status,n._transformHeadersToObject(e.headers)),this._res=e}getRawResponse(){return this._res}toStream(e){return e(),this._res.body}toJSON(){return this._res.json()}static _transformHeadersToObject(e){let t={};for(let r of e){if(!Array.isArray(r)||r.length!=2)throw new Error("Response objects produced by the fetch function given to FetchHttpClient do not have an iterable headers map. Response#headers should be an iterable object.");t[r[0]]=r[1]}return t}};var D=n=>typeof n=="object"&&Array.isArray(n)&&n!==null,x=n=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",j=n=>x(n)&&Object.keys(n).length===0,te=n=>typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null,Y=n=>D(n)?n.every(te):te(n),L=n=>x(n)&&Object.values(n).every(Y),O=n=>typeof n=="string",Q=n=>{if(typeof n=="string"){if(n.toLowerCase()==="true")return!0;if(n.toLowerCase()==="false")return!1}return D(n)&&n.length===0||x(n)&&Object.keys(n).length===0?!1:!!n};var we={"Content-Type":"application/json"},re=({httpClient:n,token:e,url:t})=>(r,o)=>h(void 0,null,function*(){var i=o,{headers:s}=i,a=F(i,["headers"]);let c=yield n.makeRequest(`${t}${r}`,p({credentials:"omit",headers:Object.assign(p(p({},we),s),typeof e!="undefined"?{token:e}:{})},a));if(c.getStatusCode()>=200&&c.getStatusCode()<300)return yield c.toJSON();throw new Error(`${c.getStatusCode()}`)});var C=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)}},P=class n extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,n.prototype)}},$=class n extends Error{constructor(e,t){super(`Expected a unique result but found ${e} matches for the provided SearchQuery: ${JSON.stringify(t)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,n.prototype)}};var E=class{constructor(){this.apiProxy={};return new Proxy(this,{get:(e,t,r)=>{if(t in e)return Reflect.get(e,t,r);if(this.apiProxy&&t in this.apiProxy)return Reflect.get(this.apiProxy,t,r)}})}init(e){this.apiProxy=e}};var V=["httpClient","timeout","host","port","protocol","url","logger","options"];var W=(n,e)=>h(void 0,null,function*(){let t=Object.entries(n).map(i=>h(void 0,[i],function*([a,o]){return o.default&&typeof o.default!="undefined"&&typeof e[a]=="undefined"?{key:a,value:typeof o.default=="function"?yield o.default():o.default}:{key:a,value:void 0}})),s=(yield Promise.all(t)).reduce((a,{key:o,value:i})=>(i!==void 0&&(a[o]=i),a),{});return p(p({},s),e)}),J=(n,e)=>Object.entries(e).filter(([t])=>{var r;return(r=n[t])==null?void 0:r.uniq}).reduce((t,[r,s])=>(r in n&&(t[r]=s),t),{}),se=(n,e,t)=>{let r={},s=Object.entries(e).filter(([,a])=>a.uniq).reduce((a,[o])=>(a[o]=!0,a),{});return n.forEach(a=>{Object.entries(a).forEach(([o,i])=>{if(o in s)if(r[o]){if(r[o].includes(i))throw new C(t,{[o]:i});r[o]=[...r[o],i]}else r[o]=[i]})}),r},ne=n=>{if(!n)return{};if(!x(n))throw new Error("Config must be an object");if(Object.keys(n).filter(t=>!V.includes(t)).length>0)throw new Error(`Config object may only contain the following: ${V.join(", ")}`);return n};function ae(n,e,t){if(!Number.isInteger(e)){if(t!==void 0)return t;throw new Error(`${n} must be an integer`)}return e}function z(n){let e=n.split("-"),t=e[0]+e[1].slice(0,4);return parseInt(t,16)}function oe(n){return new Date(z(n))}var R=class extends E{constructor(e){super(),this.data=e}id(){try{return this.data.__id}catch(e){throw new Error("DBRecordInstance: Unable to access 'id'. The Record's `data.__id` is missing or incorrect.")}}label(){try{return this.data.__label}catch(e){throw new Error("DBRecordInstance: Unable to access 'label'. The Record's `data.__label` is missing or incorrect.")}}proptypes(){try{return this.data.__proptypes}catch(e){throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record's `data.__proptypes` is missing or incorrect.")}}date(){try{return oe(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'date'. The Record's `data.__id` is missing or incorrect.")}}timestamp(){try{return z(this.id())}catch(e){throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record's `data.__id` is missing or incorrect.")}}delete(e){return h(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return yield this.apiProxy.records.deleteById(this.id(),e)})}update(e,t){return h(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return this.apiProxy.records.update({label:this.label(),target:this.id(),data:e},t)})}set(e,t){return h(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return this.apiProxy.records.set({label:this.label(),target:this.id(),data:e},t)})}attach(e,t,r){return h(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return this.apiProxy.records.attach({source:this.id(),target:e,options:t},r)})}detach(e,t,r){return h(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return this.apiProxy.records.detach({source:this.id(),target:e,options:t},r)})}},B=class extends E{constructor(e,t,r){super(),this.data=e,this.total=t,this.searchQuery=r}};var q=class extends E{constructor(e){super(),this.id=e}rollback(){return h(this,null,function*(){return yield this.apiProxy.tx.rollback(this.id)})}commit(){return h(this,null,function*(){return yield this.apiProxy.tx.commit(this.id)})}};var ie="api.rushdb.com";var ce="https",de="/api/v1";var T=n=>n?{"x-transaction-id":n}:void 0,Pe=n=>O(n)||n instanceof q,S=n=>Pe(n)?n instanceof q?n.id:n:void 0,pe=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),w=n=>{if(O(n)&&pe(n))return n;if(n instanceof R&&n.data)return n.data.__id;if(x(n)&&"__id"in n&&pe(n.__id))return n.__id},k=n=>!(!x(n)||x(n)&&"name"in n&&!O(n.name)||x(n)&&"type"in n&&(!O(n.type)||!ee.includes(n.type))||!("value"in n)||!Y(n.value)||"metadata"in n&&!O(n.metadata)||"valueSeparator"in n&&!O(n.valueSeparator)),le=n=>{let e=ce,t=ie,r=443,s=de;if("url"in n){let o=new URL(n.url);e=o.protocol.replace(":",""),t=o.hostname,r=parseInt(o.port||(e==="http"?"80":e==="https"?"443":""))}"host"in n&&"port"in n&&"protocol"in n&&(e=n.protocol.replace(":",""),t=n.host,r=n.port),s&&!s.startsWith("/")&&(s="/"+s);let a="";return e==="http"&&r===80||e==="https"&&r===443||(a=":"+r),`${e}://${t}${a}${s}`},g=(n=8)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let r=0;r<n;r++){let s=Math.floor(Math.random()*e.length);t+=e[s]}return t};var M=class{constructor(e,t){this.records={attach:(a,o)=>h(this,[a,o],function*({source:e,target:t,options:r},s){var u,b;let i=S(s),d=`/relationships/${w(e)}`,l={headers:Object.assign({},T(i)),method:"POST",requestData:p(p({targetIds:this._extractTargetIds(t,"Attach")},(r==null?void 0:r.type)&&{type:r.type}),(r==null?void 0:r.direction)&&{direction:r.direction})},y=typeof this.logger=="function"?g():"";(u=this.logger)==null||u.call(this,p({requestId:y,path:d},l));let f=yield this.fetcher(d,l);return(b=this.logger)==null||b.call(this,m(p({requestId:y,path:d},l),{responseData:f.data})),f}),detach:(a,o)=>h(this,[a,o],function*({source:e,target:t,options:r},s){var u,b;let i=S(s),d=`/relationships/${w(e)}`,l={headers:Object.assign({},T(i)),method:"PUT",requestData:p(p({targetIds:this._extractTargetIds(t,"Detach")},(r==null?void 0:r.typeOrTypes)&&{typeOrTypes:r.typeOrTypes}),(r==null?void 0:r.direction)&&{direction:r.direction})},y=typeof this.logger=="function"?g():"";(u=this.logger)==null||u.call(this,p({requestId:y,path:d},l));let f=yield this.fetcher(d,l);return(b=this.logger)==null||b.call(this,m(p({requestId:y,path:d},l),{responseData:f.data})),f}),create:(a,o)=>h(this,[a,o],function*({label:e,data:t,options:r},s){var f,u;let i=S(s),c="/records",d={headers:Object.assign({},T(i)),method:"POST",requestData:{}},l=typeof this.logger=="function"?g():"";if(D(t)&&t.every(k))d.requestData={label:e,properties:t};else if(L(t))d.requestData={label:e,data:t,options:r};else if(x(t))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(f=this.logger)==null||f.call(this,p({requestId:l,path:c},d));let y=yield this.fetcher(c,d);if((u=this.logger)==null||u.call(this,m(p({requestId:l,path:c},d),{responseData:y.data})),y!=null&&y.success&&(y!=null&&y.data)){let b=new R(y.data);return b.init(this),b}return new R}),createMany:(e,t)=>h(this,null,function*(){var c,d;let r=S(t),s="/records/import/json",a={headers:Object.assign({},T(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);if((d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i!=null&&i.success&&(i!=null&&i.data)){let l=i.data.map(f=>{let u=new R(f);return u.init(this),u}),y=new B(l,i.total);return y.init(this),y}return new B([])}),delete:(e,t)=>h(this,null,function*(){var c,d,l;if(j(e.where)&&!((c=this==null?void 0:this.options)!=null&&c.allowForceDelete))throw new P("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");let r=S(t),s="/records/delete",a={headers:Object.assign({},T(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(l=this.logger)==null||l.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),deleteById:(e,t)=>h(this,null,function*(){var d,l;let r=S(t),s=D(e),a=s?"/records/delete":`/records/${e}`,o={headers:Object.assign({},T(r)),method:s?"PUT":"DELETE",requestData:s?{limit:1e3,where:{$id:{$in:e}}}:void 0},i=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:a},o));let c=yield this.fetcher(a,o);return(l=this.logger)==null||l.call(this,m(p({requestId:i,path:a},o),{responseData:c.data})),c}),export:(e,t)=>h(this,null,function*(){var c,d;let r=S(t),s="/records/export/csv",a={headers:Object.assign({},T(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),find:(e,t)=>h(this,null,function*(){var u,b;let f=e,{id:r}=f,s=F(f,["id"]),a=S(t),o=r?`/records/${r}/search`:"/records/search",i={headers:Object.assign({},T(a)),method:"POST",requestData:s},c=typeof this.logger=="function"?g():"";(u=this.logger)==null||u.call(this,p({requestId:c,path:o},i));let d=yield this.fetcher(o,i);(b=this.logger)==null||b.call(this,m(p({requestId:c,path:o},i),{responseData:d.data}));let l=d.data.map(_=>{let A=new R(_);return A.init(this),A}),y=new B(l,d.total,e);return y.init(this),y}),findById:(e,t)=>h(this,null,function*(){var c,d;let r=S(t),s=D(e)?"/records":`/records/${e}`,a={headers:Object.assign({},T(r)),method:D(e)?"POST":"GET",requestData:D(e)?{ids:e}:void 0},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);if((d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),D(e)){let l=i.data.map(f=>{let u=new R(f);return u.init(this),u}),y=new B(l,i.total);return y.init(this),y}else{let l=new R(i.data);return l.init(this),l}}),findOne:(e,t)=>h(this,null,function*(){var l,y;let r=S(t),s="/records/search",a={headers:Object.assign({},T(r)),method:"POST",requestData:m(p({},e),{limit:1,skip:0})},o=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);(y=this.logger)==null||y.call(this,m(p({requestId:o,path:s},a),{responseData:i.data}));let[c]=i.data,d=new R(c);return d.init(this),d}),findUniq:(e,t)=>h(this,null,function*(){var l,y;let r=S(t),s="/records/search",a={headers:Object.assign({},T(r)),method:"POST",requestData:m(p({},e),{limit:1,skip:0})},o=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);if((y=this.logger)==null||y.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),typeof i.total!="undefined"&&i.total>1)throw new $(i.total,e);let[c]=i.data,d=new R(c);return d.init(this),d}),set:(o,i)=>h(this,[o,i],function*({target:e,label:t,data:r,options:s},a){var b,_;let c=S(a),l=`/records/${w(e)}`,y={headers:Object.assign({},T(c)),method:"PUT",requestData:{}},f=typeof this.logger=="function"?g():"";if(D(r)&&r.every(k))y.requestData={label:t,properties:r};else if(L(r))y.requestData={label:t,data:r,options:s};else if(x(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(b=this.logger)==null||b.call(this,p({requestId:f,path:l},y));let u=yield this.fetcher(l,y);if((_=this.logger)==null||_.call(this,m(p({requestId:f,path:l},y),{responseData:u.data})),u!=null&&u.success&&(u!=null&&u.data)){let A=new R(u.data);return A.init(this),A}return new R}),update:(o,i)=>h(this,[o,i],function*({target:e,label:t,data:r,options:s},a){var b,_;let c=S(a),l=`/records/${w(e)}`,y={headers:Object.assign({},T(c)),method:"PATCH",requestData:{}},f=typeof this.logger=="function"?g():"";if(D(r)&&r.every(k))y.requestData={label:t,properties:r};else if(L(r))y.requestData={label:t,data:r,options:s};else if(x(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");(b=this.logger)==null||b.call(this,p({requestId:f,path:l},y));let u=yield this.fetcher(l,y);if((_=this.logger)==null||_.call(this,m(p({requestId:f,path:l},y),{responseData:u.data})),u!=null&&u.success&&(u!=null&&u.data)){let A=new R(u.data);return A.init(this),A}return new R})};this.relationships={find:(e,t)=>h(this,null,function*(){var l,y;let r=S(t),s=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&s.append("limit",e.limit.toString()),(e==null?void 0:e.skip)!==void 0&&s.append("skip",e.skip.toString());let o=`/relationships/search${s.toString()?"?"+s.toString():""}`,i={headers:Object.assign({},T(r)),method:"POST",requestData:e},c=typeof this.logger=="function"?g():"";(l=this.logger)==null||l.call(this,p({requestId:c,path:o},i));let d=yield this.fetcher(o,i);return(y=this.logger)==null||y.call(this,m(p({requestId:c,path:o},i),{responseData:d.data})),d})};this.properties={delete:(e,t)=>h(this,null,function*(){var c,d;let r=S(t),s=`/properties/${e}`,a={headers:Object.assign({},T(r)),method:"DELETE"},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),find:(e,t)=>h(this,null,function*(){var c,d;let r=S(t),s="/properties/search",a={headers:Object.assign({},T(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),findById:(e,t)=>h(this,null,function*(){var c,d;let r=S(t),s=`/properties/${e}`,a={headers:Object.assign({},T(r)),method:"GET"},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i}),values:(e,t,r)=>h(this,null,function*(){var d,l;let s=S(r),a=`/properties/${e}/values`,o={headers:Object.assign({},T(s)),method:"POST",requestData:t},i=typeof this.logger=="function"?g():"";(d=this.logger)==null||d.call(this,p({requestId:i,path:a},o));let c=yield this.fetcher(a,o);return(l=this.logger)==null||l.call(this,m(p({requestId:i,path:a},o),{responseData:c.data})),c})};this.labels={find:(e,t)=>h(this,null,function*(){var c,d;let r=S(t),s="/labels/search",a={headers:Object.assign({},T(r)),method:"POST",requestData:e},o=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:o,path:s},a));let i=yield this.fetcher(s,a);return(d=this.logger)==null||d.call(this,m(p({requestId:o,path:s},a),{responseData:i.data})),i})};this.tx={begin:e=>h(this,null,function*(){var i,c;let t="/tx",r={method:"POST",requestData:e},s=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,p({requestId:s,path:t},r));let a=yield this.fetcher(t,r);(c=this.logger)==null||c.call(this,m(p({requestId:s,path:t},r),{responseData:a.data}));let o=new q(a.data.id);return o.init(this),o}),commit:e=>h(this,null,function*(){var i,c;let r=`/tx/${S(e)}/commit`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,p({requestId:a,path:r},s));let o=yield this.fetcher(r,s);return(c=this.logger)==null||c.call(this,m(p({requestId:a,path:r},s),{responseData:o.data})),o}),get:e=>h(this,null,function*(){var c,d;let r=`/tx/${S(e)}`,s={method:"GET"},a=typeof this.logger=="function"?g():"";(c=this.logger)==null||c.call(this,p({requestId:a,path:r},s));let o=yield this.fetcher(r,s);(d=this.logger)==null||d.call(this,m(p({requestId:a,path:r},s),{responseData:o.data}));let i=new q(o.data.id);return i.init(this),i}),rollback:e=>h(this,null,function*(){var i,c;let r=`/tx/${S(e)}/rollback`,s={method:"POST",requestData:{}},a=typeof this.logger=="function"?g():"";(i=this.logger)==null||i.call(this,p({requestId:a,path:r},s));let o=yield this.fetcher(r,s);return(c=this.logger)==null||c.call(this,m(p({requestId:a,path:r},s),{responseData:o.data})),o})};if(this.fetcher=null,t!=null&&t.httpClient){let r=le(t);this.fetcher=re({httpClient:t.httpClient,token:e,url:r})}t!=null&&t.options&&(this.options=t==null?void 0:t.options),t!=null&&t.logger&&(this.logger=t==null?void 0:t.logger)}_extractTargetIds(e,t){var r;if(e instanceof R){let s=w(e);if(!s)throw new P(`${t} error: Target id is empty`);return[s]}if(D(e)&&e.every(s=>s instanceof R)){let s=e.map(w).filter(Q);if(!s.length)throw new P(`${t} error: Target ids are empty`);return s}if(e instanceof B){let s=(r=e.data)==null?void 0:r.map(w).filter(Q);if(!(s!=null&&s.length))throw new P(`${t} error: Target ids are empty`);return s}if(x(e)&&"__id"in e)return[e.__id];if(D(e)&&e.every(s=>x(s)&&"__id"in s)){let s=e.map(w).filter(Q);if(!s.length)throw new P(`${t} error: Target ids are empty`);return s}return D(e)?e:O(e)?[e]:[]}};var he=n=>{class e extends M{constructor(r,s){var o;let a=ne(s);super(r,m(p({},a),{httpClient:(o=a.httpClient)!=null?o:n})),this.state={debug:!1,timeout:ae("timeout",a.timeout,8e4),token:r},this.models=new Map,e.instance=this}static getInstance(){return e.instance}registerModel(r){let s=r.getLabel();return r.init(this),this.models.set(s,r),r}getModels(){return this.models}getModel(r){return this.models.get(r)}toInstance(r){let s=new R(r);return s.init(this),s}}return e};var ye=class extends E{constructor(e,t,r){super(),this.label=e,this.schema=t,this.rushDBInstance=r,r==null||r.registerModel(this)}getLabel(){return this.label}toInstance(e){if(this.rushDBInstance)return this.rushDBInstance.toInstance(e);throw new Error("No RushDB instance was provided during model initialization.")}find(e,t){return h(this,null,function*(){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.find(m(p({},r),{labels:[this.label]}),t)})}findOne(e,t){return h(this,null,function*(){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.findOne(m(p({},r),{labels:[this.label]}),t)})}findById(e,t){return h(this,null,function*(){return this.findOne({where:{$id:e}},t)})}findUniq(e,t){return h(this,null,function*(){var s;let r=e!=null?e:{};return(s=this.apiProxy)==null?void 0:s.records.findUniq(m(p({},r),{labels:[this.label]}),t)})}create(e,t){return h(this,null,function*(){var a;let r=yield W(this.schema,e),s=J(this.schema,r);if(!j(s)){let o=t!=null?t:yield this.apiProxy.tx.begin(),i=yield this.find({where:s},o),c=typeof t!="undefined";if(!((a=i==null?void 0:i.data)!=null&&a.length)){let l=yield this.apiProxy.records.create({label:this.label,data:r},o);return c||(yield o.commit()),l}else throw c||(yield o.commit()),new C(this.label,s)}return yield this.apiProxy.records.create({label:this.label,data:r},t)})}attach({source:e,target:t,options:r},s){return this.apiProxy.records.attach({source:e,target:t,options:r},s)}detach({source:e,target:t,options:r},s){return this.apiProxy.records.detach({source:e,target:t,options:r},s)}handleSetOrUpdate(e,t,r,s){return h(this,null,function*(){var i,c;if(D(t)&&t.every(k))throw new Error(`Model.${r} with Array<PropertyDraft> as payload is not implemented yet.`);let a=yield W(this.schema,t),o=J(this.schema,a);if(!j(o)){let d=s!=null?s:yield this.apiProxy.tx.begin(),l=yield this.find({where:o},d),y=typeof s!="undefined";if(!((i=l==null?void 0:l.data)!=null&&i.length)||l.data.length===1&&((c=l.data[0])==null?void 0:c.id())===w(e)){let u=yield this.apiProxy.records[r]({target:e,label:this.label,data:a},d);return y||(yield d.commit()),u}else throw y||(yield d.commit()),new C(this.label,o)}return yield this.apiProxy.records[r]({label:this.label,target:e,data:a},s)})}set(e,t,r){return h(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"set",r)})}update(e,t,r){return h(this,null,function*(){return yield this.handleSetOrUpdate(e,t,"update",r)})}createMany(e,t){return h(this,null,function*(){var a;let r=typeof t!="undefined",s=t!=null?t:yield this.apiProxy.tx.begin();try{let o=yield Promise.all(e.map(d=>h(this,null,function*(){return yield W(this.schema,d)}))),i=se(o,this.schema,this.label);if(!j(i)){let d=Object.entries(i).map(([y,f])=>({[y]:{$in:f}})),l=yield this.find({where:{$or:d}},s);if((a=l==null?void 0:l.data)!=null&&a.length)throw new C(this.label,Object.keys(i))}let c=yield this.apiProxy.records.createMany({label:this.label,data:o},s);return r||(yield s.commit()),c}catch(o){throw r||(yield s.rollback()),o}})}delete(e,t){return h(this,null,function*(){if(j(e.where))throw new P(`You must specify criteria to delete records of type '${this.label}'. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.`);return yield this.apiProxy.records.delete(m(p({},e),{labels:[this.label]}),t)})}deleteById(e,t){return h(this,null,function*(){return yield this.apiProxy.records.deleteById(e,t)})}};var Oe=he(new v);var Bt=Oe;export{R as DBRecordInstance,B as DBRecordsArrayInstance,P as EmptyTargetError,I as HttpClient,N as HttpClientResponse,ye as Model,$ as NonUniqueResultError,M as RestAPI,Oe as RushDB,q as Transaction,C as UniquenessError,Bt as default,oe as idToDate,z as idToTimestamp,he as initSDK,W as mergeDefaultsWithPayload,ne as parseConfig,J as pickUniqFieldsFromRecord,se as pickUniqFieldsFromRecords,ae as validateInteger};
|
package/dist/index.node.d.ts
CHANGED
|
@@ -161,7 +161,10 @@ declare const RushDB: {
|
|
|
161
161
|
delete: (id: string, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<import("./types/value.js").Property>>;
|
|
162
162
|
find: <S extends import("./types/schema.js").Schema = any>(searchQuery: import("./types/query.js").SearchQuery<S>, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<import("./types/value.js").Property[]>>;
|
|
163
163
|
findById: (id: string, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<import("./types/value.js").Property>>;
|
|
164
|
-
values: (id: string,
|
|
164
|
+
values: (id: string, searchQuery?: import("./types/query.js").SearchQuery & {
|
|
165
|
+
query?: string;
|
|
166
|
+
orderBy?: import("./types/query.js").OrderDirection;
|
|
167
|
+
}, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<{
|
|
165
168
|
metadata?: string;
|
|
166
169
|
name: string;
|
|
167
170
|
type: import("./types/value.js").PropertyType;
|
|
@@ -345,7 +348,10 @@ declare const RushDB: {
|
|
|
345
348
|
delete: (id: string, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<import("./types/value.js").Property>>;
|
|
346
349
|
find: <S extends import("./types/schema.js").Schema = any>(searchQuery: import("./types/query.js").SearchQuery<S>, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<import("./types/value.js").Property[]>>;
|
|
347
350
|
findById: (id: string, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<import("./types/value.js").Property>>;
|
|
348
|
-
values: (id: string,
|
|
351
|
+
values: (id: string, searchQuery?: import("./types/query.js").SearchQuery & {
|
|
352
|
+
query?: string;
|
|
353
|
+
orderBy?: import("./types/query.js").OrderDirection;
|
|
354
|
+
}, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<{
|
|
349
355
|
metadata?: string;
|
|
350
356
|
name: string;
|
|
351
357
|
type: import("./types/value.js").PropertyType;
|
|
@@ -529,7 +535,10 @@ declare const RushDB: {
|
|
|
529
535
|
delete: (id: string, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<import("./types/value.js").Property>>;
|
|
530
536
|
find: <S extends import("./types/schema.js").Schema = any>(searchQuery: import("./types/query.js").SearchQuery<S>, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<import("./types/value.js").Property[]>>;
|
|
531
537
|
findById: (id: string, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<import("./types/value.js").Property>>;
|
|
532
|
-
values: (id: string,
|
|
538
|
+
values: (id: string, searchQuery?: import("./types/query.js").SearchQuery & {
|
|
539
|
+
query?: string;
|
|
540
|
+
orderBy?: import("./types/query.js").OrderDirection;
|
|
541
|
+
}, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<{
|
|
533
542
|
metadata?: string;
|
|
534
543
|
name: string;
|
|
535
544
|
type: import("./types/value.js").PropertyType;
|
package/dist/index.worker.d.ts
CHANGED
|
@@ -161,7 +161,10 @@ declare const RushDB: {
|
|
|
161
161
|
delete: (id: string, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<import("./types/value.js").Property>>;
|
|
162
162
|
find: <S extends import("./types/schema.js").Schema = any>(searchQuery: import("./types/query.js").SearchQuery<S>, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<import("./types/value.js").Property[]>>;
|
|
163
163
|
findById: (id: string, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<import("./types/value.js").Property>>;
|
|
164
|
-
values: (id: string,
|
|
164
|
+
values: (id: string, searchQuery?: import("./types/query.js").SearchQuery & {
|
|
165
|
+
query?: string;
|
|
166
|
+
orderBy?: import("./types/query.js").OrderDirection;
|
|
167
|
+
}, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<{
|
|
165
168
|
metadata?: string;
|
|
166
169
|
name: string;
|
|
167
170
|
type: import("./types/value.js").PropertyType;
|
|
@@ -345,7 +348,10 @@ declare const RushDB: {
|
|
|
345
348
|
delete: (id: string, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<import("./types/value.js").Property>>;
|
|
346
349
|
find: <S extends import("./types/schema.js").Schema = any>(searchQuery: import("./types/query.js").SearchQuery<S>, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<import("./types/value.js").Property[]>>;
|
|
347
350
|
findById: (id: string, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<import("./types/value.js").Property>>;
|
|
348
|
-
values: (id: string,
|
|
351
|
+
values: (id: string, searchQuery?: import("./types/query.js").SearchQuery & {
|
|
352
|
+
query?: string;
|
|
353
|
+
orderBy?: import("./types/query.js").OrderDirection;
|
|
354
|
+
}, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<{
|
|
349
355
|
metadata?: string;
|
|
350
356
|
name: string;
|
|
351
357
|
type: import("./types/value.js").PropertyType;
|
|
@@ -529,7 +535,10 @@ declare const RushDB: {
|
|
|
529
535
|
delete: (id: string, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<import("./types/value.js").Property>>;
|
|
530
536
|
find: <S extends import("./types/schema.js").Schema = any>(searchQuery: import("./types/query.js").SearchQuery<S>, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<import("./types/value.js").Property[]>>;
|
|
531
537
|
findById: (id: string, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<import("./types/value.js").Property>>;
|
|
532
|
-
values: (id: string,
|
|
538
|
+
values: (id: string, searchQuery?: import("./types/query.js").SearchQuery & {
|
|
539
|
+
query?: string;
|
|
540
|
+
orderBy?: import("./types/query.js").OrderDirection;
|
|
541
|
+
}, transaction?: import("./sdk/transaction.js").Transaction | string) => Promise<ApiResponse<{
|
|
533
542
|
metadata?: string;
|
|
534
543
|
name: string;
|
|
535
544
|
type: import("./types/value.js").PropertyType;
|
package/dist/sdk/sdk.d.ts
CHANGED
|
@@ -164,7 +164,10 @@ export declare const initSDK: (httpClient: HttpClient) => {
|
|
|
164
164
|
delete: (id: string, transaction?: import("./transaction.js").Transaction | string) => Promise<import("../index.node.js").ApiResponse<import("../types/value.js").Property>>;
|
|
165
165
|
find: <S extends Schema = any>(searchQuery: import("../types/query.js").SearchQuery<S>, transaction?: import("./transaction.js").Transaction | string) => Promise<import("../index.node.js").ApiResponse<import("../types/value.js").Property[]>>;
|
|
166
166
|
findById: (id: string, transaction?: import("./transaction.js").Transaction | string) => Promise<import("../index.node.js").ApiResponse<import("../types/value.js").Property>>;
|
|
167
|
-
values: (id: string,
|
|
167
|
+
values: (id: string, searchQuery?: import("../types/query.js").SearchQuery & {
|
|
168
|
+
query?: string;
|
|
169
|
+
orderBy?: import("../types/query.js").OrderDirection;
|
|
170
|
+
}, transaction?: import("./transaction.js").Transaction | string) => Promise<import("../index.node.js").ApiResponse<{
|
|
168
171
|
metadata?: string;
|
|
169
172
|
name: string;
|
|
170
173
|
type: import("../types/value.js").PropertyType;
|
|
@@ -348,7 +351,10 @@ export declare const initSDK: (httpClient: HttpClient) => {
|
|
|
348
351
|
delete: (id: string, transaction?: import("./transaction.js").Transaction | string) => Promise<import("../index.node.js").ApiResponse<import("../types/value.js").Property>>;
|
|
349
352
|
find: <S extends Schema = any>(searchQuery: import("../types/query.js").SearchQuery<S>, transaction?: import("./transaction.js").Transaction | string) => Promise<import("../index.node.js").ApiResponse<import("../types/value.js").Property[]>>;
|
|
350
353
|
findById: (id: string, transaction?: import("./transaction.js").Transaction | string) => Promise<import("../index.node.js").ApiResponse<import("../types/value.js").Property>>;
|
|
351
|
-
values: (id: string,
|
|
354
|
+
values: (id: string, searchQuery?: import("../types/query.js").SearchQuery & {
|
|
355
|
+
query?: string;
|
|
356
|
+
orderBy?: import("../types/query.js").OrderDirection;
|
|
357
|
+
}, transaction?: import("./transaction.js").Transaction | string) => Promise<import("../index.node.js").ApiResponse<{
|
|
352
358
|
metadata?: string;
|
|
353
359
|
name: string;
|
|
354
360
|
type: import("../types/value.js").PropertyType;
|
|
@@ -532,7 +538,10 @@ export declare const initSDK: (httpClient: HttpClient) => {
|
|
|
532
538
|
delete: (id: string, transaction?: import("./transaction.js").Transaction | string) => Promise<import("../index.node.js").ApiResponse<import("../types/value.js").Property>>;
|
|
533
539
|
find: <S extends Schema = any>(searchQuery: import("../types/query.js").SearchQuery<S>, transaction?: import("./transaction.js").Transaction | string) => Promise<import("../index.node.js").ApiResponse<import("../types/value.js").Property[]>>;
|
|
534
540
|
findById: (id: string, transaction?: import("./transaction.js").Transaction | string) => Promise<import("../index.node.js").ApiResponse<import("../types/value.js").Property>>;
|
|
535
|
-
values: (id: string,
|
|
541
|
+
values: (id: string, searchQuery?: import("../types/query.js").SearchQuery & {
|
|
542
|
+
query?: string;
|
|
543
|
+
orderBy?: import("../types/query.js").OrderDirection;
|
|
544
|
+
}, transaction?: import("./transaction.js").Transaction | string) => Promise<import("../index.node.js").ApiResponse<{
|
|
536
545
|
metadata?: string;
|
|
537
546
|
name: string;
|
|
538
547
|
type: import("../types/value.js").PropertyType;
|
package/dist/types/value.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import type { PROPERTY_TYPE_BOOLEAN, PROPERTY_TYPE_DATETIME, PROPERTY_TYPE_NULL, PROPERTY_TYPE_NUMBER, PROPERTY_TYPE_STRING, PROPERTY_TYPE_VECTOR } from '../common/constants.js';
|
|
2
2
|
import type { MaybeArray } from './utils.js';
|
|
3
|
-
import type { OrderDirection } from './query.js';
|
|
4
3
|
export type DatetimeObject = {
|
|
5
4
|
$day?: number;
|
|
6
5
|
$hour?: number;
|
|
@@ -38,12 +37,6 @@ export type PropertyValuesData = {
|
|
|
38
37
|
export type PropertyDraft = Omit<PropertyWithValue, 'id'> & {
|
|
39
38
|
valueSeparator?: string;
|
|
40
39
|
};
|
|
41
|
-
export type PropertyValuesOptions = {
|
|
42
|
-
sort?: OrderDirection;
|
|
43
|
-
skip?: number;
|
|
44
|
-
limit?: number;
|
|
45
|
-
query?: string;
|
|
46
|
-
};
|
|
47
40
|
export type PropertySingleValue<TType extends PropertyType = PropertyType> = TType extends typeof PROPERTY_TYPE_DATETIME ? DatetimeValue : TType extends typeof PROPERTY_TYPE_NUMBER ? NumberValue : TType extends typeof PROPERTY_TYPE_STRING ? StringValue : TType extends typeof PROPERTY_TYPE_NULL ? NullValue : TType extends typeof PROPERTY_TYPE_BOOLEAN ? BooleanValue : TType extends typeof PROPERTY_TYPE_VECTOR ? Array<number> : StringValue;
|
|
48
41
|
export type PropertyValue<TType extends PropertyType = PropertyType> = TType extends typeof PROPERTY_TYPE_VECTOR ? Array<number> : MaybeArray<PropertySingleValue<TType>>;
|
|
49
42
|
export {};
|