@rushdb/javascript-sdk 0.9.5 → 0.10.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.
@@ -1,5 +1,5 @@
1
1
  import type { createFetcher } from '../network/index.js';
2
- import type { DBRecord, DBRecordTarget, Relation, RelationDetachOptions, RelationOptions } from '../sdk/record.js';
2
+ import type { DBRecord, DBRecordInferred, DBRecordTarget, Relation, RelationDetachOptions, RelationOptions } from '../sdk/record.js';
3
3
  import type { Transaction } from '../sdk/transaction.js';
4
4
  import type { Property, PropertyValuesData, SearchQuery, Schema, MaybeArray, OrderDirection } from '../types/index.js';
5
5
  import type { ApiResponse } from './types.js';
@@ -38,13 +38,13 @@ export declare const createApi: (fetcher: ReturnType<typeof createFetcher>, logg
38
38
  dateTime: string;
39
39
  fileContent: string;
40
40
  }>>;
41
- find<S extends Schema = any>(params?: {
41
+ find<S extends Schema = any, Q extends SearchQuery<S> = SearchQuery<S>>(params?: {
42
42
  id?: string;
43
- searchParams: SearchQuery<S>;
44
- }, transaction?: Transaction | string): Promise<ApiResponse<DBRecord<S>[]>>;
43
+ searchParams: Q;
44
+ }, transaction?: Transaction | string): Promise<ApiResponse<DBRecordInferred<S, Q>[]>>;
45
45
  findById<S extends Schema = any>(idOrIds: MaybeArray<string>, transaction?: Transaction | string): Promise<ApiResponse<DBRecord<S> | DBRecord<S>[]>>;
46
- findOne<S extends Schema = any>(searchParams: SearchQuery<S>, transaction?: Transaction | string): Promise<ApiResponse<DBRecord<S>>>;
47
- findUniq<S extends Schema = any>(searchParams: SearchQuery<S>, transaction?: Transaction | string): Promise<ApiResponse<DBRecord<S>>>;
46
+ findOne<S extends Schema = any, Q extends SearchQuery<S> = SearchQuery<S>>(searchParams: Q, transaction?: Transaction | string): Promise<ApiResponse<DBRecordInferred<S, Q>>>;
47
+ findUniq<S extends Schema = any, Q extends SearchQuery<S> = SearchQuery<S>>(searchParams: Q, transaction?: Transaction | string): Promise<ApiResponse<DBRecordInferred<S, Q>>>;
48
48
  properties(target: string, transaction?: Transaction | string): Promise<ApiResponse<Property[]>>;
49
49
  relations(target: DBRecordTarget, transaction?: Transaction | string): Promise<ApiResponse<Relation[]>>;
50
50
  set<S extends Schema = any>(target: DBRecordTarget, data: DBRecordDraft | S, transaction?: Transaction | string): Promise<ApiResponse<DBRecord<S>>>;
@@ -1,6 +1,6 @@
1
- import type { DBRecordsBatchDraft, DBRecordDraft, DBRecordInstance, DBRecordTarget, DBRecordsArrayInstance, Relation, RelationDetachOptions, RelationOptions, RelationTarget } from '../sdk/record.js';
1
+ import type { DBRecordDraft, DBRecordInstance, DBRecordsArrayInstance, DBRecordsBatchDraft, DBRecordTarget, Relation, RelationDetachOptions, RelationOptions, RelationTarget } from '../sdk/record.js';
2
2
  import type { Transaction } from '../sdk/transaction.js';
3
- import type { Property, SearchQuery, Schema, InferSchemaTypesWrite, MaybeArray } from '../types/index.js';
3
+ import type { InferSchemaTypesWrite, MaybeArray, Property, Schema, SearchQuery } from '../types/index.js';
4
4
  export type ApiResponse<T, E = Record<string, any>> = {
5
5
  data: T;
6
6
  success: boolean;
@@ -27,37 +27,37 @@ export type RecordsApi = {
27
27
  dateTime: string;
28
28
  fileContent: string;
29
29
  }>>;
30
- find<S extends Schema = any>(label: string, searchParams?: SearchQuery<S>, transaction?: Transaction | string): Promise<DBRecordsArrayInstance<S>>;
31
- find<S extends Schema = any>(labelOrSearchParams: SearchQuery<S> | string, transaction?: Transaction | string): Promise<DBRecordsArrayInstance<S>>;
32
- find<S extends Schema = any>(searchParams: SearchQuery<S>, transaction?: Transaction | string): Promise<DBRecordsArrayInstance<S>>;
30
+ find<S extends Schema = any, Q extends SearchQuery<S> = SearchQuery<S>>(label: string, searchParams?: Q, transaction?: Transaction | string): Promise<DBRecordsArrayInstance<S, Q>>;
31
+ find<S extends Schema = any, Q extends SearchQuery<S> = SearchQuery<S>>(labelOrSearchParams: Q | string, transaction?: Transaction | string): Promise<DBRecordsArrayInstance<S, Q>>;
32
+ find<S extends Schema = any, Q extends SearchQuery<S> = SearchQuery<S>>(searchParams: Q, transaction?: Transaction | string): Promise<DBRecordsArrayInstance<S, Q>>;
33
33
  findById<S extends Schema = any>(id: string, transaction?: Transaction | string): Promise<DBRecordInstance<S>>;
34
34
  findById<S extends Schema = any>(ids: string[], transaction?: Transaction | string): Promise<DBRecordsArrayInstance<S>>;
35
- findOne<S extends Schema = any>(label: string, searchParams: SearchQuery<S> & {
35
+ findOne<S extends Schema = any, Q extends SearchQuery<S> = SearchQuery<S>>(label: string, searchParams: Q & {
36
36
  labels?: never;
37
37
  limit?: never;
38
38
  skip?: never;
39
- }, transaction?: Transaction | string): Promise<DBRecordInstance<S>>;
40
- findOne<S extends Schema = any>(labelOrSearchParams: (SearchQuery<S> & {
39
+ }, transaction?: Transaction | string): Promise<DBRecordInstance<S, Q>>;
40
+ findOne<S extends Schema = any, Q extends SearchQuery<S> = SearchQuery<S>>(labelOrSearchParams: (Q & {
41
41
  limit?: never;
42
42
  skip?: never;
43
- }) | string, transaction?: Transaction | string): Promise<DBRecordInstance<S>>;
44
- findOne<S extends Schema = any>(searchParams: SearchQuery<S> & {
43
+ }) | string, transaction?: Transaction | string): Promise<DBRecordInstance<S, Q>>;
44
+ findOne<S extends Schema = any, Q extends SearchQuery<S> = SearchQuery<S>>(searchParams: Q & {
45
45
  limit?: never;
46
46
  skip?: never;
47
- }, transaction?: Transaction | string): Promise<DBRecordInstance<S>>;
48
- findUniq<S extends Schema = any>(label: string, searchParams: SearchQuery<S> & {
47
+ }, transaction?: Transaction | string): Promise<DBRecordInstance<S, Q>>;
48
+ findUniq<S extends Schema = any, Q extends SearchQuery<S> = SearchQuery<S>>(label: string, searchParams: Q & {
49
49
  labels?: never;
50
50
  limit?: never;
51
51
  skip?: never;
52
- }, transaction?: Transaction | string): Promise<DBRecordInstance<S>>;
53
- findUniq<S extends Schema = any>(labelOrSearchParams: (SearchQuery<S> & {
52
+ }, transaction?: Transaction | string): Promise<DBRecordInstance<S, Q>>;
53
+ findUniq<S extends Schema = any, Q extends SearchQuery<S> = SearchQuery<S>>(labelOrSearchParams: (Q & {
54
54
  limit?: never;
55
55
  skip?: never;
56
- }) | string, transaction?: Transaction | string): Promise<DBRecordInstance<S>>;
57
- findUniq<S extends Schema = any>(searchParams: SearchQuery<S> & {
56
+ }) | string, transaction?: Transaction | string): Promise<DBRecordInstance<S, Q>>;
57
+ findUniq<S extends Schema = any, Q extends SearchQuery<S> = SearchQuery<S>>(searchParams: Q & {
58
58
  limit?: never;
59
59
  skip?: never;
60
- }, transaction?: Transaction | string): Promise<DBRecordInstance<S>>;
60
+ }, transaction?: Transaction | string): Promise<DBRecordInstance<S, Q>>;
61
61
  properties(target: DBRecordTarget, transaction?: Transaction | string): Promise<ApiResponse<Property[]>>;
62
62
  relations(target: DBRecordTarget, transaction?: Transaction | string): Promise<ApiResponse<Array<Relation>>>;
63
63
  set<S extends Schema = any>(target: DBRecordTarget, data: DBRecordDraft | InferSchemaTypesWrite<S>, transaction?: Transaction | string): Promise<DBRecordInstance<S>>;
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var we=Object.create;var k=Object.defineProperty;var be=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var De=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var Ee=(a,e)=>{for(var s in e)k(a,s,{get:e[s],enumerable:!0})},te=(a,e,s,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Pe(e))!Ie.call(a,r)&&r!==s&&k(a,r,{get:()=>e[r],enumerable:!(t=be(e,r))||t.enumerable});return a};var re=(a,e,s)=>(s=a!=null?we(De(a)):{},te(e||!a||!a.__esModule?k(s,"default",{value:a,enumerable:!0}):s,a)),Ae=a=>te(k({},"__esModule",{value:!0}),a);var Fe={};Ee(Fe,{DBRecordDraft:()=>T,DBRecordInstance:()=>h,DBRecordsArrayInstance:()=>x,DBRecordsBatchDraft:()=>E,EmptyTargetError:()=>R,HttpClient:()=>D,HttpClientResponse:()=>L,Model:()=>N,NonUniqueResultError:()=>j,RestAPI:()=>C,RushDB:()=>xe,Transaction:()=>b,UniquenessError:()=>w,default:()=>Le,idToDate:()=>Q,idToTimestamp:()=>M});module.exports=Ae(Fe);var D=class a{makeRequest(e,{headers:s,method:t,protocol:r,requestData:i,timeout:n}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(a.TIMEOUT_ERROR_CODE);return e.code=a.TIMEOUT_ERROR_CODE,e}};D.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];D.TIMEOUT_ERROR_CODE="ETIMEDOUT";var q=class{constructor(e,s){this._statusCode=e,this._headers=s}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.")}},L=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 G=re(require("http"),1),z=re(require("https"),1);var se=/^(?:\d{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:\d{2}(?:[02468][048]|[13579][26])-02-29))Schema(0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9])?(?:\.([0-9]{1,9}))?([zZ]?|([\+-])(((([0][0-9])|([1][0-3])):?(([03][0])|([14][5])))|14:00)?)$/;var A="string",ne="datetime",V="boolean",Y="number",J="null";var ae=G.default||G,ie=z.default||z,Oe=new ae.Agent({keepAlive:!0}),ge=new ie.Agent({keepAlive:!0}),F=class extends D{constructor(e){super(),this._agent=e}makeRequest(e,{headers:s,method:t,protocol:r,requestData:i,timeout:n}){let c=new URL(e),d=r==="http"||c.protocol==="http:",o=this._agent;return o||(o=d?Oe:ge),new Promise((p,y)=>{let m=(d?ae:ie).request({agent:o,ciphers:"DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5",headers:s,host:c.hostname,method:t,path:c.pathname+c.search,port:c.port});m.setTimeout(n!=null?n:8e4,()=>{m.destroy(D.makeTimeoutError())}),m.on("response",P=>{p(new K(P))}),m.on("error",P=>{y(P)}),m.once("socket",P=>{let ee=i?JSON.stringify(i):"";P.connecting?P.once(d?"connect":"secureConnect",()=>{m.write(ee),m.end()}):(m.write(ee),m.end())})})}},K=class extends q{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,s)=>{let t="";this._res.setEncoding("utf8"),this._res.on("data",r=>{t+=r}),this._res.once("end",()=>{try{e(JSON.parse(t))}catch(r){s(r)}})})}};var f=a=>typeof a=="object"&&Array.isArray(a)&&a!==null,S=a=>a!==null&&Object.prototype.toString.call(a)==="[object Object]",_=a=>S(a)&&Object.keys(a).length===0,H=a=>S(a)&&Object.keys(a).every(e=>{let s=a[e];return f(s)?s.every(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t===null):!(s&&typeof s=="object")}),O=a=>typeof a=="string",oe=a=>{if(typeof a=="string"){if(a.toLowerCase()==="true")return!0;if(a.toLowerCase()==="false")return!1}return f(a)&&a.length===0||S(a)&&Object.keys(a).length===0?!1:!!a};var Be={"Content-Type":"application/json"},ce=({httpClient:a,token:e,url:s})=>async(t,{headers:r,...i})=>{let n=await a.makeRequest(`${s}${t}`,{credentials:"omit",headers:Object.assign({...Be,...r},typeof e<"u"?{token:e}:{}),...i});if(n.getStatusCode()>=200&&n.getStatusCode()<300)return await n.toJSON();throw new Error(`${n.getStatusCode()}`)};var w=class a extends Error{constructor(e,s){super(`Record with label "${e}" and properties ${JSON.stringify(s)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,a.prototype)}},R=class a extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,a.prototype)}},j=class a extends Error{constructor(e,s){super(`Expected a unique result but found ${e} matches for the provided search parameters: ${JSON.stringify(s)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,a.prototype)}};var I=class{constructor(){this.apiProxy={};return new Proxy(this,{get:(e,s,t)=>{if(s in e)return Reflect.get(e,s,t);if(this.apiProxy&&s in this.apiProxy)return Reflect.get(this.apiProxy,s,t)}})}init(e,s){this.apiProxy=e}};var X=["httpClient","timeout","host","port","protocol","url","validator","logger"];var $=async(a,e)=>{let s=Object.entries(a).map(async([i,n])=>n.default&&typeof n.default<"u"&&typeof e[i]>"u"?{key:i,value:typeof n.default=="function"?await n.default():n.default}:{key:i,value:void 0});return{...(await Promise.all(s)).reduce((i,{key:n,value:c})=>(c!==void 0&&(i[n]=c),i),{}),...e}},Z=(a,e)=>Object.entries(e).filter(([s])=>{var t;return(t=a[s])==null?void 0:t.uniq}).reduce((s,[t,r])=>(t in a&&(s[t]=r),s),{}),de=(a,e,s)=>{let t={},r=Object.entries(e).filter(([i,n])=>n.uniq).reduce((i,[n])=>(i[n]=!0,i),{});return a.forEach(i=>{Object.entries(i).forEach(([n,c])=>{if(n in r)if(t[n]){if(t[n].includes(c))throw new w(s,{[n]:c});t[n]=[...t[n],c]}else t[n]=[c]})}),t},pe=a=>{if(!a)return{};if(!S(a))throw new Error("Config must be an object");if(Object.keys(a).filter(s=>!X.includes(s)).length>0)throw new Error(`Config object may only contain the following: ${X.join(", ")}`);return a};function ye(a,e,s){if(!Number.isInteger(e)){if(s!==void 0)return s;throw new Error(`${a} must be an integer`)}return e}function M(a){let e=a.split("-"),s=e[0]+e[1].slice(0,4);return parseInt(s,16)}function Q(a){return new Date(M(a))}var E=class{constructor({label:e,options:s={returnResult:!0,suggestTypes:!0},payload:t}){this.label=e,this.options=s,this.payload=t}toJson(){return{label:this.label,options:this.options,payload:this.payload}}},T=class{constructor({label:e,properties:s=[]}){this.label=e,this.properties=s}toJson(){return{label:this.label,properties:this.properties}}},h=class extends I{constructor(e){super(),this.data=e}get id(){try{return this.data.__id}catch{throw new Error("DBRecordInstance: Unable to access 'id'. The Record data is undefined.")}}get label(){try{return this.data.__label}catch{throw new Error("DBRecordInstance: Unable to access 'label'. The Record data is undefined.")}}get proptypes(){try{return this.data.__proptypes}catch{throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record data' is undefined.")}}get date(){try{return Q(this.data.__id)}catch{throw new Error("DBRecordInstance: Unable to access 'date'. The Record data is undefined.")}}get timestamp(){try{return M(this.data.__id)}catch{throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record data is undefined.")}}async delete(e){if(!this.data)throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return await this.apiProxy.records.deleteById(this.data.__id,e)}async update(e,s){if(!this.data)throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return this.apiProxy.records.update(this.data.__id,e,s)}async set(e,s){if(!this.data)throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return this.apiProxy.records.set(this.data.__id,e,s)}async attach(e,s,t){if(!this.data)throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return this.apiProxy.records.attach(this.data.__id,e,s,t)}async detach(e,s,t){if(!this.data)throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return this.apiProxy.records.detach(this.data.__id,e,s,t)}},x=class extends I{constructor(e,s,t){super(),this.data=e,this.total=s,this.searchParams=t}};var b=class extends I{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 he="api.rushdb.com";var ue="https",le="/api/v1";var u=a=>a?{"x-transaction-id":a}:void 0,g=a=>O(a)||a instanceof b,W=a=>g(a)?a:void 0,l=a=>g(a)?a instanceof b?a.id:a:void 0,B=a=>{if(O(a))return a;if(a instanceof h&&a.data)return a.data.__id;if("__id"in a)return a.__id},U=(a,e)=>{var n,c,d;let s=O(a),t=je(a),i=g(e)||!S(e);if(s){let o=t?{id:a}:{searchParams:{labels:[a]}};return i?{...o,searchParams:{...o.searchParams}}:{...o,searchParams:{...e,labels:[...(c=(n=o.searchParams)==null?void 0:n.labels)!=null?c:[],...(d=e.labels)!=null?d:[]]}}}else return{searchParams:a!=null?a:{}}},je=a=>/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(a),Me=a=>a.every(e=>typeof e==typeof a[0]),Ue=a=>Array.isArray(a)?{isEmptyArray:a.length===0,isEmptyStringsArray:a.every(e=>e===""),isInconsistentArray:!Me(a)}:{isEmptyString:a===""},me=a=>typeof a===A?se.test(a)?ne:A:typeof a===Y?Y:typeof a===V?V:a===null?J:A,ke=(a,e)=>{let{isEmptyArray:s,isInconsistentArray:t}=Ue(a);return s?{type:A,value:[]}:t||!e?{type:A,value:a.map(String)}:{type:me(a[0]),value:a}},qe=(a,e)=>{if(!e)return{type:A,value:String(a)};let s=me(a);return{type:s,value:s===J?null:a}},v=(a,e={suggestTypes:!0})=>Object.entries(a).map(([s,t])=>{let{type:r,value:i}=f(t)?ke(t,e.suggestTypes):qe(t,e.suggestTypes);return{name:s,type:r,value:i}}),fe=({label:a,options:e={suggestTypes:!0},payload:s})=>({label:a,properties:v(s,e)}),Se=a=>{let e=ue,s=he,t=443,r=le;if("url"in a){let n=new URL(a.url);e=n.protocol.replace(":",""),s=n.hostname,t=parseInt(n.port||(e==="http"?"80":e==="https"?"443":""))}"host"in a&&"port"in a&&"protocol"in a&&(e=a.protocol.replace(":",""),s=a.host,t=a.port),r&&!r.startsWith("/")&&(r="/"+r);let i="";return e==="http"&&t===80||e==="https"&&t===443||(i=":"+t),`${e}://${s}${i}${r}`};var Re=(a,e)=>({labels:{async find(s,t){let r=l(t),i="/labels",n={headers:Object.assign({},u(r)),method:"POST",requestData:s};return e==null||e({path:i,...n}),a(i,n)}},properties:{delete:(s,t)=>{let r=l(t),i=`/properties/${s}`,n={headers:Object.assign({},u(r)),method:"DELETE"};return e==null||e({path:i,...n}),a(i,n)},find:(s,t)=>{let r=l(t),i="/properties",n={headers:Object.assign({},u(r)),method:"POST",requestData:s};return e==null||e({path:i,...n}),a(i,n)},findById:(s,t)=>{let r=l(t),i=`/properties/${s}`,n={headers:Object.assign({},u(r)),method:"GET"};return e==null||e({path:i,...n}),a(i,n)},values:(s,t,r)=>{let i=l(r),n=`/properties/${s}/values`,{sort:c,skip:d,limit:o}=t!=null?t:{},p=new URLSearchParams;c&&p.append("sort",c),d!==void 0&&p.append("skip",d.toString()),o!==void 0&&p.append("limit",o.toString());let y=p.toString(),m=y?`${n}?${y}`:n,P={headers:Object.assign({},u(i)),method:"GET"};return e==null||e({path:m,...P}),a(m,P)}},records:{async attach(s,t,r,i){let n=l(i),d=`/records/${B(s)}/relations`,o={headers:Object.assign({},u(n)),method:"POST",requestData:{targetIds:t,...(r==null?void 0:r.type)&&{type:r.type},...(r==null?void 0:r.direction)&&{direction:r.direction}}};return e==null||e({path:d,...o}),a(d,o)},async create(s,t){let r=l(t),i="/records",n={headers:Object.assign({},u(r)),method:"POST",requestData:s instanceof T?s.toJson():s};return e==null||e({path:i,...n}),a(i,n)},async createMany(s,t){let r=l(t),i="/records/import/json",n={headers:Object.assign({},u(r)),method:"POST",requestData:s instanceof E?s.toJson():s};return e==null||e({path:i,...n}),a(i,n)},delete(s,t){let r=l(t),i="/records/delete",n={headers:Object.assign({},u(r)),method:"PUT",requestData:s};return e==null||e({path:i,...n}),a(i,n)},deleteById(s,t){let r=l(t),i=f(s),n=i?"/records/delete":`/records/${s}`,c={headers:Object.assign({},u(r)),method:i?"PUT":"DELETE",requestData:i?{limit:1e3,where:{$id:{$in:s}}}:void 0};return e==null||e({path:n,...c}),a(n,c)},async detach(s,t,r,i){let n=l(i),d=`/records/${B(s)}/relations`,o={headers:Object.assign({},u(n)),method:"PUT",requestData:{targetIds:t,...(r==null?void 0:r.typeOrTypes)&&{typeOrTypes:r.typeOrTypes},...(r==null?void 0:r.direction)&&{direction:r.direction}}};return e==null||e({path:d,...o}),a(d,o)},export(s,t){let r=l(t),i="/records/export/csv",n={headers:Object.assign({},u(r)),method:"POST",requestData:s};return e==null||e({path:i,...n}),a(i,n)},find(s,t){let r=l(t),i=s!=null&&s.id?`/records/${s.id}/search`:"/records/search",n={headers:Object.assign({},u(r)),method:"POST",requestData:s==null?void 0:s.searchParams};return e==null||e({path:i,...n}),a(i,n)},findById(s,t){let r=l(t),i=f(s)?"/records":`/records/${s}`,n={headers:Object.assign({},u(r)),method:f(s)?"POST":"GET",requestData:f(s)?{ids:s}:void 0};return e==null||e({path:i,...n}),a(i,n)},async findOne(s,t){let r=l(t),i="/records/search",n={headers:Object.assign({},u(r)),method:"POST",requestData:{...s,limit:1,skip:0}};e==null||e({path:i,...n});let c=await a(i,n),[d]=c.data;return{...c,data:d}},async findUniq(s,t){let r=l(t),i="/records/search",n={headers:Object.assign({},u(r)),method:"POST",requestData:{...s,limit:1,skip:0}};e==null||e({path:i,...n});let c=await a(i,n);if(typeof c.total<"u"&&c.total>1)throw new j(c.total,s);let[d]=c.data;return{...c,data:d}},properties(s,t){let r=l(t),n=`/records/${B(s)}/properties`,c={headers:Object.assign({},u(r)),method:"GET"};return e==null||e({path:n,...c}),a(n,c)},async relations(s,t){let r=l(t),n=`/records/${B(s)}/relations`,c={headers:Object.assign({},u(r)),method:"GET"};return e==null||e({path:n,...c}),a(n,c)},set(s,t,r){let i=l(r),c=`/records/${B(s)}`,d={headers:Object.assign({},u(i)),method:"PUT",requestData:t instanceof T?t.toJson():t};return e==null||e({path:c,...d}),a(c,d)},update(s,t,r){let i=l(r),c=`/records/${B(s)}`,d={headers:Object.assign({},u(i)),method:"PATCH",requestData:t instanceof T?t.toJson():t};return e==null||e({path:c,...d}),a(c,d)}},relations:{async find(s,t,r){let i=l(r),n=new URLSearchParams;(t==null?void 0:t.limit)!==void 0&&n.append("limit",t.limit.toString()),(t==null?void 0:t.skip)!==void 0&&n.append("skip",t.skip.toString());let d=`/records/relations/search${n.toString()?"?"+n.toString():""}`,o={headers:Object.assign({},u(i)),method:"POST",requestData:s};return e==null||e({path:d,...o}),a(d,o)}},tx:{begin(s={}){let t="/tx",r={method:"POST",requestData:s};return e==null||e({path:t,...r}),a(t,r)},commit(s){let t=`/tx/${s}/commit`,r={method:"POST",requestData:{}};return e==null||e({path:t,...r}),a(t,r)},get(s){let t=`/tx/${s}`,r={method:"GET"};return e==null||e({path:t,...r}),a(t,r)},rollback(s){let t=`/tx/${s}/rollback`,r={method:"POST",requestData:{}};return e==null||e({path:t,...r}),a(t,r)}}});var C=class{constructor(e,s){this.relations={find:async({pagination:e,search:s,transaction:t})=>{let{searchParams:r}=U(s),i=W(t);return await this.api.relations.find(r,e,i)}};this.properties={delete:async(e,s)=>{var t;return(t=this.api)==null?void 0:t.properties.delete(e,s)},find:async(e,s)=>{var t;return(t=this.api)==null?void 0:t.properties.find(e,s)},findById:async(e,s)=>{var t;return(t=this.api)==null?void 0:t.properties.findById(e,s)},values:async(e,s)=>{var t;return(t=this.api)==null?void 0:t.properties.values(e,{},s)}};this.labels={find:async(e,s)=>this.api.labels.find(e,s)};this.tx={begin:async e=>{var r;let s=await((r=this.api)==null?void 0:r.tx.begin(e)),t=new b(s.data.id);return t.init(this),t},commit:async e=>{var s;return(s=this.api)==null?void 0:s.tx.commit(e)},get:async e=>{var r;let s=await((r=this.api)==null?void 0:r.tx.get(e)),t=new b(s.data.id);return t.init(this),t},rollback:async e=>{var s;return(s=this.api)==null?void 0:s.tx.commit(e)}};if(this.fetcher=null,s!=null&&s.httpClient){let t=Se(s);this.fetcher=ce({httpClient:s.httpClient,token:e,url:t})}this.api=Re(this.fetcher,s==null?void 0:s.logger),this.records={attach:async(t,r,i,n)=>{var c,d;if(r instanceof h){let o=(c=r.data)==null?void 0:c.__id;if(o)return await this.api.records.attach(t,o,i,n);throw new R("Attach error: Target id is empty")}else if(f(r)&&r.every(o=>o instanceof h)){let o=r.map(p=>{var y;return(y=p.data)==null?void 0:y.__id}).filter(oe);if(o.length)return await this.api.records.attach(t,o,i,n);throw new R("Attach error: Target ids are empty")}else if(r instanceof x){let o=(d=r.data)==null?void 0:d.map(p=>p.__id).filter(Boolean);if(o!=null&&o.length)return await this.api.records.attach(t,o,i,n);throw new R("Attach error: Target ids are empty")}else{if(S(r)&&"__id"in r)return await this.api.records.attach(t,r.__id,i,n);if(f(r)&&r.every(o=>S(o)&&"__id"in o)){let o=r==null?void 0:r.map(p=>p.__id).filter(Boolean);if(o!=null&&o.length)return await this.api.records.attach(t,o,i,n);throw new R("Attach error: Target ids are empty")}else return await this.api.records.attach(t,r,i,n)}},create:async(t,r,i)=>{var c,d;let n;if(t instanceof T&&(n=await((c=this.api)==null?void 0:c.records.create(t,W(r)))),!n&&O(t)){if(H(r)){let o=fe({label:t,payload:r});n=await((d=this.api)==null?void 0:d.records.create(new T(o),i))}else if(S(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.")}if(n!=null&&n.success&&(n!=null&&n.data)){let o=new h(n.data);return o.init(this),o}return new h},createMany:async(t,r,i)=>{var c,d;let n;if(t instanceof E&&(n=await((c=this.api)==null?void 0:c.records.createMany(t,W(r)))),!n&&O(t)&&(f(r)||S(r))){let o=new E({label:t,payload:r});n=await((d=this.api)==null?void 0:d.records.createMany(o,i))}if(n!=null&&n.success&&(n!=null&&n.data)){let o=new x(n.data,n.total);return o.init(this),o}return new x([])},delete:async(t,r)=>{var i;if(_(t.where))throw new R("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");return(i=this.api)==null?void 0:i.records.delete(t,r)},deleteById:async(t,r)=>{var i;return(i=this.api)==null?void 0:i.records.deleteById(t,r)},detach:async(t,r,i,n)=>{var c,d;if(r instanceof h){let o=(c=r.data)==null?void 0:c.__id;if(o)return await this.api.records.detach(t,o,i,n);throw new R("Detach error: Target id is empty")}else if(f(r)&&r.every(o=>o instanceof h)){let o=r.map(p=>{var y;return(y=p.data)==null?void 0:y.__id}).filter(Boolean);if(o.length)return await this.api.records.detach(t,o,i,n);throw new R("Detach error: Target ids are empty")}else if(r instanceof x){let o=(d=r.data)==null?void 0:d.map(p=>p.__id).filter(Boolean);if(o!=null&&o.length)return await this.api.records.detach(t,o,i,n);throw new R("Detach error: Target ids are empty")}else{if(S(r)&&"__id"in r)return await this.api.records.detach(t,r.__id,i,n);if(f(r)&&r.every(o=>S(o)&&"__id"in o)){let o=r==null?void 0:r.map(p=>p.__id).filter(Boolean);if(o!=null&&o.length)return await this.api.records.detach(t,o,i,n);throw new R("Detach error: Target ids are empty")}else return await this.api.records.detach(t,r,i,n)}},export:async(t,r)=>{var i;return(i=this.api)==null?void 0:i.records.export(t,r)},find:async(t,r,i)=>{var m;let n=g(r),{id:c,searchParams:d}=U(t,r),o=n?r:i,p=await((m=this.api)==null?void 0:m.records.find({id:c,searchParams:d},o)),y=new x(p.data,p.total,r);return y.init(this),y},findById:async(t,r)=>{var i,n;if(f(t)){let c=await((i=this.api)==null?void 0:i.records.findById(t,r)),d=new x(c.data,c.total);return d.init(this),d}else{let c=await((n=this.api)==null?void 0:n.records.findById(t,r)),d=new h(c.data);return d.init(this),d}},findOne:async(t,r,i)=>{var y;let n=g(r),{searchParams:c}=U(t,r),d=n?r:i,o=await((y=this.api)==null?void 0:y.records.findOne(c,d)),p=new h(o.data);return p.init(this),p},findUniq:async(t,r,i)=>{var y;let n=g(r),{searchParams:c}=U(t,r),d=n?r:i,o=await((y=this.api)==null?void 0:y.records.findUniq(c,d)),p=new h(o.data);return p.init(this),p},properties:async(t,r)=>{var i;return(i=this.api)==null?void 0:i.records.properties(t,r)},relations:async(t,r)=>await this.api.records.relations(t,r),set:async(t,r,i)=>{var c,d;let n;if(r instanceof T)n=await((c=this.api)==null?void 0:c.records.set(t,r,i));else if(H(r)){let o=v(r);n=await((d=this.api)==null?void 0:d.records.set(t,new T({properties:o}),i))}else if(S(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");if(n!=null&&n.success&&(n!=null&&n.data)){let o=new h(n.data);return o.init(this),o}return new h},update:async(t,r,i)=>{var c,d;let n;if(r instanceof T)n=await((c=this.api)==null?void 0:c.records.update(t,r,i));else if(H(r)){let o=v(r),p=new T({properties:o});n=await((d=this.api)==null?void 0:d.records.update(t,p,i))}else if(S(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");if(n!=null&&n.success&&(n!=null&&n.data)){let o=new h(n.data);return o.init(this),o}return new h}}}};var Te=a=>{class e extends C{constructor(t,r){var n;let i=pe(r);super(t,{...i,httpClient:(n=i.httpClient)!=null?n:a}),this.state={debug:!1,timeout:ye("timeout",i.timeout,8e4),token:t},this.models=new Map,e.instance=this}static getInstance(){return e.instance}registerModel(t){let r=t.getLabel();return t.init(this),this.models.set(r,t),t}getModels(){return this.models}getModel(t){return this.models.get(t)}toInstance(t){let r=new h(t);return r.init(this),r}}return e};var N=class extends I{constructor(e,s,t){super(),this.label=e,this.schema=s,t==null||t.registerModel(this)}getLabel(){return this.label}async find(e={},s){var t;return(t=this.apiProxy)==null?void 0:t.records.find(this.label,e,s)}async findOne(e={},s){var t;return(t=this.apiProxy)==null?void 0:t.records.findOne(this.label,{...e},s)}async findById(e,s){return this.findOne({where:{$id:e}},s)}async findUniq(e={},s){var t;return(t=this.apiProxy)==null?void 0:t.records.findUniq(this.label,{...e},s)}async create(e,s){var i;let t=await $(this.schema,e),r=Z(this.schema,t);if(!_(r)){let n=s!=null?s:await this.apiProxy.tx.begin(),c=await this.find({where:r},n),d=typeof s<"u";if(!((i=c==null?void 0:c.data)!=null&&i.length)){let p=await this.apiProxy.records.create(this.label,t,n);return d||await n.commit(),p}else throw d||await n.commit(),new w(this.label,r)}return await this.apiProxy.records.create(this.label,t,s)}attach(e,s,t,r){return this.apiProxy.records.attach(e,s,t,r)}detach(e,s,t,r){return this.apiProxy.records.detach(e,s,t,r)}async handleSetOrUpdate(e,s,t,r){var c;let i=await $(this.schema,s),n=Z(this.schema,i);if(!_(n)){let d=r!=null?r:await this.apiProxy.tx.begin(),o=await this.find({where:n},d),p=typeof r<"u";if(!((c=o==null?void 0:o.data)!=null&&c.length)||o.data.length===1&&o.data[0].__id===e){let m=await this.apiProxy.records[t](e,i,d);return p||await d.commit(),m}else throw p||await d.commit(),new w(this.label,n)}return await this.apiProxy.records[t](e,i,r)}async set(e,s,t){return await this.handleSetOrUpdate(e,s,"set",t)}async update(e,s,t){return await this.handleSetOrUpdate(e,s,"update",t)}async createMany(e,s){var i;let t=typeof s<"u",r=s!=null?s:await this.apiProxy.tx.begin();try{let n=await Promise.all(e.map(async o=>await $(this.schema,o))),c=de(n,this.schema,this.label);if(!_(c)){let o=Object.entries(c).map(([y,m])=>({[y]:{$in:m}})),p=await this.find({where:{$or:o}},r);if((i=p==null?void 0:p.data)!=null&&i.length)throw new w(this.label,Object.keys(c))}let d=await this.apiProxy.records.createMany(this.label,n,r);return t||await r.commit(),d}catch(n){throw t||await r.rollback(),n}}async delete(e,s){if(_(e.where))throw new R(`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]},s)}async deleteById(e,s){return await this.apiProxy.records.deleteById(e,s)}};var xe=Te(new F);var Le=xe;0&&(module.exports={DBRecordDraft,DBRecordInstance,DBRecordsArrayInstance,DBRecordsBatchDraft,EmptyTargetError,HttpClient,HttpClientResponse,Model,NonUniqueResultError,RestAPI,RushDB,Transaction,UniquenessError,idToDate,idToTimestamp});
1
+ "use strict";var we=Object.create;var U=Object.defineProperty;var be=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var De=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var Ee=(a,e)=>{for(var s in e)U(a,s,{get:e[s],enumerable:!0})},te=(a,e,s,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Pe(e))!Ie.call(a,r)&&r!==s&&U(a,r,{get:()=>e[r],enumerable:!(t=be(e,r))||t.enumerable});return a};var re=(a,e,s)=>(s=a!=null?we(De(a)):{},te(e||!a||!a.__esModule?U(s,"default",{value:a,enumerable:!0}):s,a)),Ae=a=>te(U({},"__esModule",{value:!0}),a);var Le={};Ee(Le,{DBRecordDraft:()=>T,DBRecordInstance:()=>h,DBRecordsArrayInstance:()=>x,DBRecordsBatchDraft:()=>E,EmptyTargetError:()=>R,HttpClient:()=>D,HttpClientResponse:()=>q,Model:()=>N,NonUniqueResultError:()=>C,RestAPI:()=>Q,RushDB:()=>xe,Transaction:()=>b,UniquenessError:()=>w,default:()=>qe,idToDate:()=>v,idToTimestamp:()=>j});module.exports=Ae(Le);var D=class a{makeRequest(e,{headers:s,method:t,protocol:r,requestData:i,timeout:n}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(a.TIMEOUT_ERROR_CODE);return e.code=a.TIMEOUT_ERROR_CODE,e}};D.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];D.TIMEOUT_ERROR_CODE="ETIMEDOUT";var k=class{constructor(e,s){this._statusCode=e,this._headers=s}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}},q=class{constructor(e){this._res=e}getStatusCode(){throw new Error("getStatusCode not implemented.")}getHeaders(){throw new Error("getHeaders not implemented.")}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}};var G=re(require("http"),1),z=re(require("https"),1);var se=/^(?:\d{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:\d{2}(?:[02468][048]|[13579][26])-02-29))Schema(0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9])?(?:\.([0-9]{1,9}))?([zZ]?|([\+-])(((([0][0-9])|([1][0-3])):?(([03][0])|([14][5])))|14:00)?)$/;var A="string",ne="datetime",V="boolean",Y="number",J="null";var ae=G.default||G,ie=z.default||z,Oe=new ae.Agent({keepAlive:!0}),ge=new ie.Agent({keepAlive:!0}),L=class extends D{constructor(e){super(),this._agent=e}makeRequest(e,{headers:s,method:t,protocol:r,requestData:i,timeout:n}){let c=new URL(e),d=r==="http"||c.protocol==="http:",o=this._agent;return o||(o=d?Oe:ge),new Promise((p,y)=>{let m=(d?ae:ie).request({agent:o,ciphers:"DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2:!MD5",headers:s,host:c.hostname,method:t,path:c.pathname+c.search,port:c.port});m.setTimeout(n!=null?n:8e4,()=>{m.destroy(D.makeTimeoutError())}),m.on("response",P=>{p(new K(P))}),m.on("error",P=>{y(P)}),m.once("socket",P=>{let ee=i?JSON.stringify(i):"";P.connecting?P.once(d?"connect":"secureConnect",()=>{m.write(ee),m.end()}):(m.write(ee),m.end())})})}},K=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,s)=>{let t="";this._res.setEncoding("utf8"),this._res.on("data",r=>{t+=r}),this._res.once("end",()=>{try{e(JSON.parse(t))}catch(r){s(r)}})})}};var f=a=>typeof a=="object"&&Array.isArray(a)&&a!==null,S=a=>a!==null&&Object.prototype.toString.call(a)==="[object Object]",_=a=>S(a)&&Object.keys(a).length===0,F=a=>S(a)&&Object.keys(a).every(e=>{let s=a[e];return f(s)?s.every(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t===null):!(s&&typeof s=="object")}),O=a=>typeof a=="string",oe=a=>{if(typeof a=="string"){if(a.toLowerCase()==="true")return!0;if(a.toLowerCase()==="false")return!1}return f(a)&&a.length===0||S(a)&&Object.keys(a).length===0?!1:!!a};var Be={"Content-Type":"application/json"},ce=({httpClient:a,token:e,url:s})=>async(t,{headers:r,...i})=>{let n=await a.makeRequest(`${s}${t}`,{credentials:"omit",headers:Object.assign({...Be,...r},typeof e<"u"?{token:e}:{}),...i});if(n.getStatusCode()>=200&&n.getStatusCode()<300)return await n.toJSON();throw new Error(`${n.getStatusCode()}`)};var w=class a extends Error{constructor(e,s){super(`Record with label "${e}" and properties ${JSON.stringify(s)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,a.prototype)}},R=class a extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,a.prototype)}},C=class a extends Error{constructor(e,s){super(`Expected a unique result but found ${e} matches for the provided search parameters: ${JSON.stringify(s)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,a.prototype)}};var I=class{constructor(){this.apiProxy={};return new Proxy(this,{get:(e,s,t)=>{if(s in e)return Reflect.get(e,s,t);if(this.apiProxy&&s in this.apiProxy)return Reflect.get(this.apiProxy,s,t)}})}init(e,s){this.apiProxy=e}};var X=["httpClient","timeout","host","port","protocol","url","validator","logger"];var H=async(a,e)=>{let s=Object.entries(a).map(async([i,n])=>n.default&&typeof n.default<"u"&&typeof e[i]>"u"?{key:i,value:typeof n.default=="function"?await n.default():n.default}:{key:i,value:void 0});return{...(await Promise.all(s)).reduce((i,{key:n,value:c})=>(c!==void 0&&(i[n]=c),i),{}),...e}},Z=(a,e)=>Object.entries(e).filter(([s])=>{var t;return(t=a[s])==null?void 0:t.uniq}).reduce((s,[t,r])=>(t in a&&(s[t]=r),s),{}),de=(a,e,s)=>{let t={},r=Object.entries(e).filter(([i,n])=>n.uniq).reduce((i,[n])=>(i[n]=!0,i),{});return a.forEach(i=>{Object.entries(i).forEach(([n,c])=>{if(n in r)if(t[n]){if(t[n].includes(c))throw new w(s,{[n]:c});t[n]=[...t[n],c]}else t[n]=[c]})}),t},pe=a=>{if(!a)return{};if(!S(a))throw new Error("Config must be an object");if(Object.keys(a).filter(s=>!X.includes(s)).length>0)throw new Error(`Config object may only contain the following: ${X.join(", ")}`);return a};function ye(a,e,s){if(!Number.isInteger(e)){if(s!==void 0)return s;throw new Error(`${a} must be an integer`)}return e}function j(a){let e=a.split("-"),s=e[0]+e[1].slice(0,4);return parseInt(s,16)}function v(a){return new Date(j(a))}var E=class{constructor({label:e,options:s={returnResult:!0,suggestTypes:!0},payload:t}){this.label=e,this.options=s,this.payload=t}toJson(){return{label:this.label,options:this.options,payload:this.payload}}},T=class{constructor({label:e,properties:s=[]}){this.label=e,this.properties=s}toJson(){return{label:this.label,properties:this.properties}}},h=class extends I{constructor(e){super(),this.data=e}get id(){try{return this.data.__id}catch{throw new Error("DBRecordInstance: Unable to access 'id'. The Record data is undefined.")}}get label(){try{return this.data.__label}catch{throw new Error("DBRecordInstance: Unable to access 'label'. The Record data is undefined.")}}get proptypes(){try{return this.data.__proptypes}catch{throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record data' is undefined.")}}get date(){try{return v(this.data.__id)}catch{throw new Error("DBRecordInstance: Unable to access 'date'. The Record data is undefined.")}}get timestamp(){try{return j(this.data.__id)}catch{throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record data is undefined.")}}async delete(e){if(!this.data)throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return await this.apiProxy.records.deleteById(this.data.__id,e)}async update(e,s){if(!this.data)throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return this.apiProxy.records.update(this.data.__id,e,s)}async set(e,s){if(!this.data)throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return this.apiProxy.records.set(this.data.__id,e,s)}async attach(e,s,t){if(!this.data)throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return this.apiProxy.records.attach(this.data.__id,e,s,t)}async detach(e,s,t){if(!this.data)throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return this.apiProxy.records.detach(this.data.__id,e,s,t)}},x=class extends I{constructor(e,s,t){super(),this.data=e,this.total=s,this.searchParams=t}};var b=class extends I{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 he="api.rushdb.com";var ue="https",le="/api/v1";var u=a=>a?{"x-transaction-id":a}:void 0,g=a=>O(a)||a instanceof b,$=a=>g(a)?a:void 0,l=a=>g(a)?a instanceof b?a.id:a:void 0,B=a=>{if(O(a))return a;if(a instanceof h&&a.data)return a.data.__id;if("__id"in a)return a.__id},M=(a,e)=>{var n,c,d;let s=O(a),t=Ce(a),i=g(e)||!S(e);if(s){let o=t?{id:a}:{searchParams:{labels:[a]}};return i?{...o,searchParams:{...o.searchParams}}:{...o,searchParams:{...e,labels:[...(c=(n=o.searchParams)==null?void 0:n.labels)!=null?c:[],...(d=e.labels)!=null?d:[]]}}}else return{searchParams:a!=null?a:{}}},Ce=a=>/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(a),je=a=>a.every(e=>typeof e==typeof a[0]),Me=a=>Array.isArray(a)?{isEmptyArray:a.length===0,isEmptyStringsArray:a.every(e=>e===""),isInconsistentArray:!je(a)}:{isEmptyString:a===""},me=a=>typeof a===A?se.test(a)?ne:A:typeof a===Y?Y:typeof a===V?V:a===null?J:A,Ue=(a,e)=>{let{isEmptyArray:s,isInconsistentArray:t}=Me(a);return s?{type:A,value:[]}:t||!e?{type:A,value:a.map(String)}:{type:me(a[0]),value:a}},ke=(a,e)=>{if(!e)return{type:A,value:String(a)};let s=me(a);return{type:s,value:s===J?null:a}},W=(a,e={suggestTypes:!0})=>Object.entries(a).map(([s,t])=>{let{type:r,value:i}=f(t)?Ue(t,e.suggestTypes):ke(t,e.suggestTypes);return{name:s,type:r,value:i}}),fe=({label:a,options:e={suggestTypes:!0},payload:s})=>({label:a,properties:W(s,e)}),Se=a=>{let e=ue,s=he,t=443,r=le;if("url"in a){let n=new URL(a.url);e=n.protocol.replace(":",""),s=n.hostname,t=parseInt(n.port||(e==="http"?"80":e==="https"?"443":""))}"host"in a&&"port"in a&&"protocol"in a&&(e=a.protocol.replace(":",""),s=a.host,t=a.port),r&&!r.startsWith("/")&&(r="/"+r);let i="";return e==="http"&&t===80||e==="https"&&t===443||(i=":"+t),`${e}://${s}${i}${r}`};var Re=(a,e)=>({labels:{async find(s,t){let r=l(t),i="/labels",n={headers:Object.assign({},u(r)),method:"POST",requestData:s};return e==null||e({path:i,...n}),a(i,n)}},properties:{delete:(s,t)=>{let r=l(t),i=`/properties/${s}`,n={headers:Object.assign({},u(r)),method:"DELETE"};return e==null||e({path:i,...n}),a(i,n)},find:(s,t)=>{let r=l(t),i="/properties",n={headers:Object.assign({},u(r)),method:"POST",requestData:s};return e==null||e({path:i,...n}),a(i,n)},findById:(s,t)=>{let r=l(t),i=`/properties/${s}`,n={headers:Object.assign({},u(r)),method:"GET"};return e==null||e({path:i,...n}),a(i,n)},values:(s,t,r)=>{let i=l(r),n=`/properties/${s}/values`,{sort:c,skip:d,limit:o}=t!=null?t:{},p=new URLSearchParams;c&&p.append("sort",c),d!==void 0&&p.append("skip",d.toString()),o!==void 0&&p.append("limit",o.toString());let y=p.toString(),m=y?`${n}?${y}`:n,P={headers:Object.assign({},u(i)),method:"GET"};return e==null||e({path:m,...P}),a(m,P)}},records:{async attach(s,t,r,i){let n=l(i),d=`/records/${B(s)}/relations`,o={headers:Object.assign({},u(n)),method:"POST",requestData:{targetIds:t,...(r==null?void 0:r.type)&&{type:r.type},...(r==null?void 0:r.direction)&&{direction:r.direction}}};return e==null||e({path:d,...o}),a(d,o)},async create(s,t){let r=l(t),i="/records",n={headers:Object.assign({},u(r)),method:"POST",requestData:s instanceof T?s.toJson():s};return e==null||e({path:i,...n}),a(i,n)},async createMany(s,t){let r=l(t),i="/records/import/json",n={headers:Object.assign({},u(r)),method:"POST",requestData:s instanceof E?s.toJson():s};return e==null||e({path:i,...n}),a(i,n)},delete(s,t){let r=l(t),i="/records/delete",n={headers:Object.assign({},u(r)),method:"PUT",requestData:s};return e==null||e({path:i,...n}),a(i,n)},deleteById(s,t){let r=l(t),i=f(s),n=i?"/records/delete":`/records/${s}`,c={headers:Object.assign({},u(r)),method:i?"PUT":"DELETE",requestData:i?{limit:1e3,where:{$id:{$in:s}}}:void 0};return e==null||e({path:n,...c}),a(n,c)},async detach(s,t,r,i){let n=l(i),d=`/records/${B(s)}/relations`,o={headers:Object.assign({},u(n)),method:"PUT",requestData:{targetIds:t,...(r==null?void 0:r.typeOrTypes)&&{typeOrTypes:r.typeOrTypes},...(r==null?void 0:r.direction)&&{direction:r.direction}}};return e==null||e({path:d,...o}),a(d,o)},export(s,t){let r=l(t),i="/records/export/csv",n={headers:Object.assign({},u(r)),method:"POST",requestData:s};return e==null||e({path:i,...n}),a(i,n)},find(s,t){let r=l(t),i=s!=null&&s.id?`/records/${s.id}/search`:"/records/search",n={headers:Object.assign({},u(r)),method:"POST",requestData:s==null?void 0:s.searchParams};return e==null||e({path:i,...n}),a(i,n)},findById(s,t){let r=l(t),i=f(s)?"/records":`/records/${s}`,n={headers:Object.assign({},u(r)),method:f(s)?"POST":"GET",requestData:f(s)?{ids:s}:void 0};return e==null||e({path:i,...n}),a(i,n)},async findOne(s,t){let r=l(t),i="/records/search",n={headers:Object.assign({},u(r)),method:"POST",requestData:{...s,limit:1,skip:0}};e==null||e({path:i,...n});let c=await a(i,n),[d]=c.data;return{...c,data:d}},async findUniq(s,t){let r=l(t),i="/records/search",n={headers:Object.assign({},u(r)),method:"POST",requestData:{...s,limit:1,skip:0}};e==null||e({path:i,...n});let c=await a(i,n);if(typeof c.total<"u"&&c.total>1)throw new C(c.total,s);let[d]=c.data;return{...c,data:d}},properties(s,t){let r=l(t),n=`/records/${B(s)}/properties`,c={headers:Object.assign({},u(r)),method:"GET"};return e==null||e({path:n,...c}),a(n,c)},async relations(s,t){let r=l(t),n=`/records/${B(s)}/relations`,c={headers:Object.assign({},u(r)),method:"GET"};return e==null||e({path:n,...c}),a(n,c)},set(s,t,r){let i=l(r),c=`/records/${B(s)}`,d={headers:Object.assign({},u(i)),method:"PUT",requestData:t instanceof T?t.toJson():t};return e==null||e({path:c,...d}),a(c,d)},update(s,t,r){let i=l(r),c=`/records/${B(s)}`,d={headers:Object.assign({},u(i)),method:"PATCH",requestData:t instanceof T?t.toJson():t};return e==null||e({path:c,...d}),a(c,d)}},relations:{async find(s,t,r){let i=l(r),n=new URLSearchParams;(t==null?void 0:t.limit)!==void 0&&n.append("limit",t.limit.toString()),(t==null?void 0:t.skip)!==void 0&&n.append("skip",t.skip.toString());let d=`/records/relations/search${n.toString()?"?"+n.toString():""}`,o={headers:Object.assign({},u(i)),method:"POST",requestData:s};return e==null||e({path:d,...o}),a(d,o)}},tx:{begin(s={}){let t="/tx",r={method:"POST",requestData:s};return e==null||e({path:t,...r}),a(t,r)},commit(s){let t=`/tx/${s}/commit`,r={method:"POST",requestData:{}};return e==null||e({path:t,...r}),a(t,r)},get(s){let t=`/tx/${s}`,r={method:"GET"};return e==null||e({path:t,...r}),a(t,r)},rollback(s){let t=`/tx/${s}/rollback`,r={method:"POST",requestData:{}};return e==null||e({path:t,...r}),a(t,r)}}});var Q=class{constructor(e,s){this.relations={find:async({pagination:e,search:s,transaction:t})=>{let{searchParams:r}=M(s),i=$(t);return await this.api.relations.find(r,e,i)}};this.properties={delete:async(e,s)=>{var t;return(t=this.api)==null?void 0:t.properties.delete(e,s)},find:async(e,s)=>{var t;return(t=this.api)==null?void 0:t.properties.find(e,s)},findById:async(e,s)=>{var t;return(t=this.api)==null?void 0:t.properties.findById(e,s)},values:async(e,s)=>{var t;return(t=this.api)==null?void 0:t.properties.values(e,{},s)}};this.labels={find:async(e,s)=>this.api.labels.find(e,s)};this.tx={begin:async e=>{var r;let s=await((r=this.api)==null?void 0:r.tx.begin(e)),t=new b(s.data.id);return t.init(this),t},commit:async e=>{var s;return(s=this.api)==null?void 0:s.tx.commit(e)},get:async e=>{var r;let s=await((r=this.api)==null?void 0:r.tx.get(e)),t=new b(s.data.id);return t.init(this),t},rollback:async e=>{var s;return(s=this.api)==null?void 0:s.tx.commit(e)}};if(this.fetcher=null,s!=null&&s.httpClient){let t=Se(s);this.fetcher=ce({httpClient:s.httpClient,token:e,url:t})}this.api=Re(this.fetcher,s==null?void 0:s.logger),this.records={attach:async(t,r,i,n)=>{var c,d;if(r instanceof h){let o=(c=r.data)==null?void 0:c.__id;if(o)return await this.api.records.attach(t,o,i,n);throw new R("Attach error: Target id is empty")}else if(f(r)&&r.every(o=>o instanceof h)){let o=r.map(p=>{var y;return(y=p.data)==null?void 0:y.__id}).filter(oe);if(o.length)return await this.api.records.attach(t,o,i,n);throw new R("Attach error: Target ids are empty")}else if(r instanceof x){let o=(d=r.data)==null?void 0:d.map(p=>p.__id).filter(Boolean);if(o!=null&&o.length)return await this.api.records.attach(t,o,i,n);throw new R("Attach error: Target ids are empty")}else{if(S(r)&&"__id"in r)return await this.api.records.attach(t,r.__id,i,n);if(f(r)&&r.every(o=>S(o)&&"__id"in o)){let o=r==null?void 0:r.map(p=>p.__id).filter(Boolean);if(o!=null&&o.length)return await this.api.records.attach(t,o,i,n);throw new R("Attach error: Target ids are empty")}else return await this.api.records.attach(t,r,i,n)}},create:async(t,r,i)=>{var c,d;let n;if(t instanceof T&&(n=await((c=this.api)==null?void 0:c.records.create(t,$(r)))),!n&&O(t)){if(F(r)){let o=fe({label:t,payload:r});n=await((d=this.api)==null?void 0:d.records.create(new T(o),i))}else if(S(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.")}if(n!=null&&n.success&&(n!=null&&n.data)){let o=new h(n.data);return o.init(this),o}return new h},createMany:async(t,r,i)=>{var c,d;let n;if(t instanceof E&&(n=await((c=this.api)==null?void 0:c.records.createMany(t,$(r)))),!n&&O(t)&&(f(r)||S(r))){let o=new E({label:t,payload:r});n=await((d=this.api)==null?void 0:d.records.createMany(o,i))}if(n!=null&&n.success&&(n!=null&&n.data)){let o=new x(n.data,n.total);return o.init(this),o}return new x([])},delete:async(t,r)=>{var i;if(_(t.where))throw new R("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");return(i=this.api)==null?void 0:i.records.delete(t,r)},deleteById:async(t,r)=>{var i;return(i=this.api)==null?void 0:i.records.deleteById(t,r)},detach:async(t,r,i,n)=>{var c,d;if(r instanceof h){let o=(c=r.data)==null?void 0:c.__id;if(o)return await this.api.records.detach(t,o,i,n);throw new R("Detach error: Target id is empty")}else if(f(r)&&r.every(o=>o instanceof h)){let o=r.map(p=>{var y;return(y=p.data)==null?void 0:y.__id}).filter(Boolean);if(o.length)return await this.api.records.detach(t,o,i,n);throw new R("Detach error: Target ids are empty")}else if(r instanceof x){let o=(d=r.data)==null?void 0:d.map(p=>p.__id).filter(Boolean);if(o!=null&&o.length)return await this.api.records.detach(t,o,i,n);throw new R("Detach error: Target ids are empty")}else{if(S(r)&&"__id"in r)return await this.api.records.detach(t,r.__id,i,n);if(f(r)&&r.every(o=>S(o)&&"__id"in o)){let o=r==null?void 0:r.map(p=>p.__id).filter(Boolean);if(o!=null&&o.length)return await this.api.records.detach(t,o,i,n);throw new R("Detach error: Target ids are empty")}else return await this.api.records.detach(t,r,i,n)}},export:async(t,r)=>{var i;return(i=this.api)==null?void 0:i.records.export(t,r)},find:async(t,r,i)=>{var m;let n=g(r),{id:c,searchParams:d}=M(t,r),o=n?r:i,p=await((m=this.api)==null?void 0:m.records.find({id:c,searchParams:d},o)),y=new x(p.data,p.total,r);return y.init(this),y},findById:async(t,r)=>{var i,n;if(f(t)){let c=await((i=this.api)==null?void 0:i.records.findById(t,r)),d=new x(c.data,c.total);return d.init(this),d}else{let c=await((n=this.api)==null?void 0:n.records.findById(t,r)),d=new h(c.data);return d.init(this),d}},findOne:async(t,r,i)=>{var y;let n=g(r),{searchParams:c}=M(t,r),d=n?r:i,o=await((y=this.api)==null?void 0:y.records.findOne(c,d)),p=new h(o.data);return p.init(this),p},findUniq:async(t,r,i)=>{var y;let n=g(r),{searchParams:c}=M(t,r),d=n?r:i,o=await((y=this.api)==null?void 0:y.records.findUniq(c,d)),p=new h(o.data);return p.init(this),p},properties:async(t,r)=>{var i;return(i=this.api)==null?void 0:i.records.properties(t,r)},relations:async(t,r)=>await this.api.records.relations(t,r),set:async(t,r,i)=>{var c,d;let n;if(r instanceof T)n=await((c=this.api)==null?void 0:c.records.set(t,r,i));else if(F(r)){let o=W(r);n=await((d=this.api)==null?void 0:d.records.set(t,new T({properties:o}),i))}else if(S(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");if(n!=null&&n.success&&(n!=null&&n.data)){let o=new h(n.data);return o.init(this),o}return new h},update:async(t,r,i)=>{var c,d;let n;if(r instanceof T)n=await((c=this.api)==null?void 0:c.records.update(t,r,i));else if(F(r)){let o=W(r),p=new T({properties:o});n=await((d=this.api)==null?void 0:d.records.update(t,p,i))}else if(S(r))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");if(n!=null&&n.success&&(n!=null&&n.data)){let o=new h(n.data);return o.init(this),o}return new h}}}};var Te=a=>{class e extends Q{constructor(t,r){var n;let i=pe(r);super(t,{...i,httpClient:(n=i.httpClient)!=null?n:a}),this.state={debug:!1,timeout:ye("timeout",i.timeout,8e4),token:t},this.models=new Map,e.instance=this}static getInstance(){return e.instance}registerModel(t){let r=t.getLabel();return t.init(this),this.models.set(r,t),t}getModels(){return this.models}getModel(t){return this.models.get(t)}toInstance(t){let r=new h(t);return r.init(this),r}}return e};var N=class extends I{constructor(e,s,t){super(),this.label=e,this.schema=s,t==null||t.registerModel(this)}getLabel(){return this.label}async find(e,s){var r;let t=e!=null?e:{};return(r=this.apiProxy)==null?void 0:r.records.find(this.label,t,s)}async findOne(e,s){var r;let t=e!=null?e:{};return(r=this.apiProxy)==null?void 0:r.records.findOne(this.label,t,s)}async findById(e,s){return this.findOne({where:{$id:e}},s)}async findUniq(e,s){var r;let t=e!=null?e:{};return(r=this.apiProxy)==null?void 0:r.records.findUniq(this.label,t,s)}async create(e,s){var i;let t=await H(this.schema,e),r=Z(this.schema,t);if(!_(r)){let n=s!=null?s:await this.apiProxy.tx.begin(),c=await this.find({where:r},n),d=typeof s<"u";if(!((i=c==null?void 0:c.data)!=null&&i.length)){let p=await this.apiProxy.records.create(this.label,t,n);return d||await n.commit(),p}else throw d||await n.commit(),new w(this.label,r)}return await this.apiProxy.records.create(this.label,t,s)}attach(e,s,t,r){return this.apiProxy.records.attach(e,s,t,r)}detach(e,s,t,r){return this.apiProxy.records.detach(e,s,t,r)}async handleSetOrUpdate(e,s,t,r){var c;let i=await H(this.schema,s),n=Z(this.schema,i);if(!_(n)){let d=r!=null?r:await this.apiProxy.tx.begin(),o=await this.find({where:n},d),p=typeof r<"u";if(!((c=o==null?void 0:o.data)!=null&&c.length)||o.data.length===1&&o.data[0].__id===e){let m=await this.apiProxy.records[t](e,i,d);return p||await d.commit(),m}else throw p||await d.commit(),new w(this.label,n)}return await this.apiProxy.records[t](e,i,r)}async set(e,s,t){return await this.handleSetOrUpdate(e,s,"set",t)}async update(e,s,t){return await this.handleSetOrUpdate(e,s,"update",t)}async createMany(e,s){var i;let t=typeof s<"u",r=s!=null?s:await this.apiProxy.tx.begin();try{let n=await Promise.all(e.map(async o=>await H(this.schema,o))),c=de(n,this.schema,this.label);if(!_(c)){let o=Object.entries(c).map(([y,m])=>({[y]:{$in:m}})),p=await this.find({where:{$or:o}},r);if((i=p==null?void 0:p.data)!=null&&i.length)throw new w(this.label,Object.keys(c))}let d=await this.apiProxy.records.createMany(this.label,n,r);return t||await r.commit(),d}catch(n){throw t||await r.rollback(),n}}async delete(e,s){if(_(e.where))throw new R(`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]},s)}async deleteById(e,s){return await this.apiProxy.records.deleteById(e,s)}};var xe=Te(new L);var qe=xe;0&&(module.exports={DBRecordDraft,DBRecordInstance,DBRecordsArrayInstance,DBRecordsBatchDraft,EmptyTargetError,HttpClient,HttpClientResponse,Model,NonUniqueResultError,RestAPI,RushDB,Transaction,UniquenessError,idToDate,idToTimestamp});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- var Pe=Object.defineProperty,De=Object.defineProperties;var Ee=Object.getOwnPropertyDescriptors;var F=Object.getOwnPropertySymbols;var ae=Object.prototype.hasOwnProperty,ie=Object.prototype.propertyIsEnumerable;var ne=(s,e,a)=>e in s?Pe(s,e,{enumerable:!0,configurable:!0,writable:!0,value:a}):s[e]=a,h=(s,e)=>{for(var a in e||(e={}))ae.call(e,a)&&ne(s,a,e[a]);if(F)for(var a of F(e))ie.call(e,a)&&ne(s,a,e[a]);return s},b=(s,e)=>De(s,Ee(e));var oe=(s,e)=>{var a={};for(var r in s)ae.call(s,r)&&e.indexOf(r)<0&&(a[r]=s[r]);if(s!=null&&F)for(var r of F(s))e.indexOf(r)<0&&ie.call(s,r)&&(a[r]=s[r]);return a};var p=(s,e,a)=>new Promise((r,o)=>{var n=d=>{try{c(a.next(d))}catch(i){o(i)}},t=d=>{try{c(a.throw(d))}catch(i){o(i)}},c=d=>d.done?r(d.value):Promise.resolve(d.value).then(n,t);c((a=a.apply(s,e)).next())});var ce=/^(?:\d{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:\d{2}(?:[02468][048]|[13579][26])-02-29))Schema(0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9])?(?:\.([0-9]{1,9}))?([zZ]?|([\+-])(((([0][0-9])|([1][0-3])):?(([03][0])|([14][5])))|14:00)?)$/;var _="string",de="datetime",V="boolean",Y="number",J="null";var P=class s{makeRequest(e,{headers:a,method:r,protocol:o,requestData:n,timeout:t}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(s.TIMEOUT_ERROR_CODE);return e.code=s.TIMEOUT_ERROR_CODE,e}};P.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];P.TIMEOUT_ERROR_CODE="ETIMEDOUT";var H=class{constructor(e,a){this._statusCode=e,this._headers=a}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}},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 L=class s extends P{constructor(e){if(super(),!e){if(!globalThis.fetch)throw new Error("fetch() function not provided and is not defined in the global scope. You must provide a fetch implementation.");e=globalThis.fetch}globalThis.AbortController?this._fetchFn=s.makeFetchWithAbortTimeout(e):this._fetchFn=s.makeFetchWithRaceTimeout(e)}static makeFetchWithRaceTimeout(e){return(a,r,o)=>{let n,t=new Promise((d,i)=>{n=setTimeout(()=>{n=null,i(P.makeTimeoutError())},o)}),c=e(a,r);return Promise.race([c,t]).finally(()=>{n&&clearTimeout(n)})}}static makeFetchWithAbortTimeout(e){return(a,r,o)=>p(this,null,function*(){let n=new AbortController,t=setTimeout(()=>{t=null,n.abort(P.makeTimeoutError())},o);try{return yield e(a,b(h({},r),{signal:n.signal}))}catch(c){throw c.name==="AbortError"?P.makeTimeoutError():c}finally{t&&clearTimeout(t)}})}makeRequest(c,d){return p(this,arguments,function*(e,{headers:a,method:r,protocol:o,requestData:n,timeout:t}){let i=r=="POST"||r=="PUT"||r=="PATCH",y=JSON.stringify(n)||(i?"":void 0),u=yield this._fetchFn(e,{body:y,headers:a,method:r},t!=null?t:8e4);return new G(u)})}},G=class s extends H{constructor(e){super(e.status,s._transformHeadersToObject(e.headers)),this._res=e}getRawResponse(){return this._res}toStream(e){return e(),this._res.body}toJSON(){return this._res.json()}static _transformHeadersToObject(e){let a={};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.");a[r[0]]=r[1]}return a}};var R=s=>typeof s=="object"&&Array.isArray(s)&&s!==null,T=s=>s!==null&&Object.prototype.toString.call(s)==="[object Object]",B=s=>T(s)&&Object.keys(s).length===0,W=s=>T(s)&&Object.keys(s).every(e=>{let a=s[e];return R(a)?a.every(r=>typeof r=="string"||typeof r=="number"||typeof r=="boolean"||r===null):!(a&&typeof a=="object")}),g=s=>typeof s=="string",pe=s=>{if(typeof s=="string"){if(s.toLowerCase()==="true")return!0;if(s.toLowerCase()==="false")return!1}return R(s)&&s.length===0||T(s)&&Object.keys(s).length===0?!1:!!s};var Ae={"Content-Type":"application/json"},ye=({httpClient:s,token:e,url:a})=>(r,t)=>p(void 0,null,function*(){var c=t,{headers:o}=c,n=oe(c,["headers"]);let d=yield s.makeRequest(`${a}${r}`,h({credentials:"omit",headers:Object.assign(h(h({},Ae),o),typeof e!="undefined"?{token:e}:{})},n));if(d.getStatusCode()>=200&&d.getStatusCode()<300)return yield d.toJSON();throw new Error(`${d.getStatusCode()}`)});var E=class s extends Error{constructor(e,a){super(`Record with label "${e}" and properties ${JSON.stringify(a)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,s.prototype)}},x=class s extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,s.prototype)}},M=class s extends Error{constructor(e,a){super(`Expected a unique result but found ${e} matches for the provided search parameters: ${JSON.stringify(a)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,s.prototype)}};var I=class{constructor(){this.apiProxy={};return new Proxy(this,{get:(e,a,r)=>{if(a in e)return Reflect.get(e,a,r);if(this.apiProxy&&a in this.apiProxy)return Reflect.get(this.apiProxy,a,r)}})}init(e,a){this.apiProxy=e}};var z=["httpClient","timeout","host","port","protocol","url","validator","logger"];var v=(s,e)=>p(void 0,null,function*(){let a=Object.entries(s).map(c=>p(void 0,[c],function*([n,t]){return t.default&&typeof t.default!="undefined"&&typeof e[n]=="undefined"?{key:n,value:typeof t.default=="function"?yield t.default():t.default}:{key:n,value:void 0}})),o=(yield Promise.all(a)).reduce((n,{key:t,value:c})=>(c!==void 0&&(n[t]=c),n),{});return h(h({},o),e)}),Z=(s,e)=>Object.entries(e).filter(([a])=>{var r;return(r=s[a])==null?void 0:r.uniq}).reduce((a,[r,o])=>(r in s&&(a[r]=o),a),{}),he=(s,e,a)=>{let r={},o=Object.entries(e).filter(([n,t])=>t.uniq).reduce((n,[t])=>(n[t]=!0,n),{});return s.forEach(n=>{Object.entries(n).forEach(([t,c])=>{if(t in o)if(r[t]){if(r[t].includes(c))throw new E(a,{[t]:c});r[t]=[...r[t],c]}else r[t]=[c]})}),r},ue=s=>{if(!s)return{};if(!T(s))throw new Error("Config must be an object");if(Object.keys(s).filter(a=>!z.includes(a)).length>0)throw new Error(`Config object may only contain the following: ${z.join(", ")}`);return s};function le(s,e,a){if(!Number.isInteger(e)){if(a!==void 0)return a;throw new Error(`${s} must be an integer`)}return e}function $(s){let e=s.split("-"),a=e[0]+e[1].slice(0,4);return parseInt(a,16)}function X(s){return new Date($(s))}var O=class{constructor({label:e,options:a={returnResult:!0,suggestTypes:!0},payload:r}){this.label=e,this.options=a,this.payload=r}toJson(){return{label:this.label,options:this.options,payload:this.payload}}},w=class{constructor({label:e,properties:a=[]}){this.label=e,this.properties=a}toJson(){return{label:this.label,properties:this.properties}}},f=class extends I{constructor(e){super(),this.data=e}get id(){try{return this.data.__id}catch(e){throw new Error("DBRecordInstance: Unable to access 'id'. The Record data is undefined.")}}get label(){try{return this.data.__label}catch(e){throw new Error("DBRecordInstance: Unable to access 'label'. The Record data is undefined.")}}get proptypes(){try{return this.data.__proptypes}catch(e){throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record data' is undefined.")}}get date(){try{return X(this.data.__id)}catch(e){throw new Error("DBRecordInstance: Unable to access 'date'. The Record data is undefined.")}}get timestamp(){try{return $(this.data.__id)}catch(e){throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record data is undefined.")}}delete(e){return p(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return yield this.apiProxy.records.deleteById(this.data.__id,e)})}update(e,a){return p(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return this.apiProxy.records.update(this.data.__id,e,a)})}set(e,a){return p(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return this.apiProxy.records.set(this.data.__id,e,a)})}attach(e,a,r){return p(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return this.apiProxy.records.attach(this.data.__id,e,a,r)})}detach(e,a,r){return p(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return this.apiProxy.records.detach(this.data.__id,e,a,r)})}},D=class extends I{constructor(e,a,r){super(),this.data=e,this.total=a,this.searchParams=r}};var A=class extends I{constructor(e){super(),this.id=e}rollback(){return p(this,null,function*(){return yield this.apiProxy.tx.rollback(this.id)})}commit(){return p(this,null,function*(){return yield this.apiProxy.tx.commit(this.id)})}};var me="api.rushdb.com";var fe="https",Se="/api/v1";var l=s=>s?{"x-transaction-id":s}:void 0,j=s=>g(s)||s instanceof A,Q=s=>j(s)?s:void 0,m=s=>j(s)?s instanceof A?s.id:s:void 0,C=s=>{if(g(s))return s;if(s instanceof f&&s.data)return s.data.__id;if("__id"in s)return s.__id},k=(s,e)=>{var t,c,d;let a=g(s),r=_e(s),n=j(e)||!T(e);if(a){let i=r?{id:s}:{searchParams:{labels:[s]}};return n?b(h({},i),{searchParams:h({},i.searchParams)}):b(h({},i),{searchParams:b(h({},e),{labels:[...(c=(t=i.searchParams)==null?void 0:t.labels)!=null?c:[],...(d=e.labels)!=null?d:[]]})})}else return{searchParams:s!=null?s:{}}},_e=s=>/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(s),Be=s=>s.every(e=>typeof e==typeof s[0]),ge=s=>Array.isArray(s)?{isEmptyArray:s.length===0,isEmptyStringsArray:s.every(e=>e===""),isInconsistentArray:!Be(s)}:{isEmptyString:s===""},Re=s=>typeof s===_?ce.test(s)?de:_:typeof s===Y?Y:typeof s===V?V:s===null?J:_,je=(s,e)=>{let{isEmptyArray:a,isInconsistentArray:r}=ge(s);return a?{type:_,value:[]}:r||!e?{type:_,value:s.map(String)}:{type:Re(s[0]),value:s}},Ce=(s,e)=>{if(!e)return{type:_,value:String(s)};let a=Re(s);return{type:a,value:a===J?null:s}},N=(s,e={suggestTypes:!0})=>Object.entries(s).map(([a,r])=>{let{type:o,value:n}=R(r)?je(r,e.suggestTypes):Ce(r,e.suggestTypes);return{name:a,type:o,value:n}}),Te=({label:s,options:e={suggestTypes:!0},payload:a})=>({label:s,properties:N(a,e)}),be=s=>{let e=fe,a=me,r=443,o=Se;if("url"in s){let t=new URL(s.url);e=t.protocol.replace(":",""),a=t.hostname,r=parseInt(t.port||(e==="http"?"80":e==="https"?"443":""))}"host"in s&&"port"in s&&"protocol"in s&&(e=s.protocol.replace(":",""),a=s.host,r=s.port),o&&!o.startsWith("/")&&(o="/"+o);let n="";return e==="http"&&r===80||e==="https"&&r===443||(n=":"+r),`${e}://${a}${n}${o}`};var xe=(s,e)=>({labels:{find(n,t){return p(this,null,function*(){let c=m(t),d="/labels",i={headers:Object.assign({},l(c)),method:"POST",requestData:n};return e==null||e(h({path:d},i)),s(d,i)})}},properties:{delete:(n,t)=>{let c=m(t),d=`/properties/${n}`,i={headers:Object.assign({},l(c)),method:"DELETE"};return e==null||e(h({path:d},i)),s(d,i)},find:(n,t)=>{let c=m(t),d="/properties",i={headers:Object.assign({},l(c)),method:"POST",requestData:n};return e==null||e(h({path:d},i)),s(d,i)},findById:(n,t)=>{let c=m(t),d=`/properties/${n}`,i={headers:Object.assign({},l(c)),method:"GET"};return e==null||e(h({path:d},i)),s(d,i)},values:(n,t,c)=>{let d=m(c),i=`/properties/${n}/values`,{sort:y,skip:u,limit:S}=t!=null?t:{},q=new URLSearchParams;y&&q.append("sort",y),u!==void 0&&q.append("skip",u.toString()),S!==void 0&&q.append("limit",S.toString());let te=q.toString(),re=te?`${i}?${te}`:i,se={headers:Object.assign({},l(d)),method:"GET"};return e==null||e(h({path:re},se)),s(re,se)}},records:{attach(n,t,c,d){return p(this,null,function*(){let i=m(d),u=`/records/${C(n)}/relations`,S={headers:Object.assign({},l(i)),method:"POST",requestData:h(h({targetIds:t},(c==null?void 0:c.type)&&{type:c.type}),(c==null?void 0:c.direction)&&{direction:c.direction})};return e==null||e(h({path:u},S)),s(u,S)})},create(n,t){return p(this,null,function*(){let c=m(t),d="/records",i={headers:Object.assign({},l(c)),method:"POST",requestData:n instanceof w?n.toJson():n};return e==null||e(h({path:d},i)),s(d,i)})},createMany(n,t){return p(this,null,function*(){let c=m(t),d="/records/import/json",i={headers:Object.assign({},l(c)),method:"POST",requestData:n instanceof O?n.toJson():n};return e==null||e(h({path:d},i)),s(d,i)})},delete(n,t){let c=m(t),d="/records/delete",i={headers:Object.assign({},l(c)),method:"PUT",requestData:n};return e==null||e(h({path:d},i)),s(d,i)},deleteById(n,t){let c=m(t),d=R(n),i=d?"/records/delete":`/records/${n}`,y={headers:Object.assign({},l(c)),method:d?"PUT":"DELETE",requestData:d?{limit:1e3,where:{$id:{$in:n}}}:void 0};return e==null||e(h({path:i},y)),s(i,y)},detach(n,t,c,d){return p(this,null,function*(){let i=m(d),u=`/records/${C(n)}/relations`,S={headers:Object.assign({},l(i)),method:"PUT",requestData:h(h({targetIds:t},(c==null?void 0:c.typeOrTypes)&&{typeOrTypes:c.typeOrTypes}),(c==null?void 0:c.direction)&&{direction:c.direction})};return e==null||e(h({path:u},S)),s(u,S)})},export(n,t){let c=m(t),d="/records/export/csv",i={headers:Object.assign({},l(c)),method:"POST",requestData:n};return e==null||e(h({path:d},i)),s(d,i)},find(n,t){let c=m(t),d=n!=null&&n.id?`/records/${n.id}/search`:"/records/search",i={headers:Object.assign({},l(c)),method:"POST",requestData:n==null?void 0:n.searchParams};return e==null||e(h({path:d},i)),s(d,i)},findById(n,t){let c=m(t),d=R(n)?"/records":`/records/${n}`,i={headers:Object.assign({},l(c)),method:R(n)?"POST":"GET",requestData:R(n)?{ids:n}:void 0};return e==null||e(h({path:d},i)),s(d,i)},findOne(n,t){return p(this,null,function*(){let c=m(t),d="/records/search",i={headers:Object.assign({},l(c)),method:"POST",requestData:b(h({},n),{limit:1,skip:0})};e==null||e(h({path:d},i));let y=yield s(d,i),[u]=y.data;return b(h({},y),{data:u})})},findUniq(n,t){return p(this,null,function*(){let c=m(t),d="/records/search",i={headers:Object.assign({},l(c)),method:"POST",requestData:b(h({},n),{limit:1,skip:0})};e==null||e(h({path:d},i));let y=yield s(d,i);if(typeof y.total!="undefined"&&y.total>1)throw new M(y.total,n);let[u]=y.data;return b(h({},y),{data:u})})},properties(n,t){let c=m(t),i=`/records/${C(n)}/properties`,y={headers:Object.assign({},l(c)),method:"GET"};return e==null||e(h({path:i},y)),s(i,y)},relations(n,t){return p(this,null,function*(){let c=m(t),i=`/records/${C(n)}/relations`,y={headers:Object.assign({},l(c)),method:"GET"};return e==null||e(h({path:i},y)),s(i,y)})},set(n,t,c){let d=m(c),y=`/records/${C(n)}`,u={headers:Object.assign({},l(d)),method:"PUT",requestData:t instanceof w?t.toJson():t};return e==null||e(h({path:y},u)),s(y,u)},update(n,t,c){let d=m(c),y=`/records/${C(n)}`,u={headers:Object.assign({},l(d)),method:"PATCH",requestData:t instanceof w?t.toJson():t};return e==null||e(h({path:y},u)),s(y,u)}},relations:{find(n,t,c){return p(this,null,function*(){let d=m(c),i=new URLSearchParams;(t==null?void 0:t.limit)!==void 0&&i.append("limit",t.limit.toString()),(t==null?void 0:t.skip)!==void 0&&i.append("skip",t.skip.toString());let u=`/records/relations/search${i.toString()?"?"+i.toString():""}`,S={headers:Object.assign({},l(d)),method:"POST",requestData:n};return e==null||e(h({path:u},S)),s(u,S)})}},tx:{begin(n={}){let t="/tx",c={method:"POST",requestData:n};return e==null||e(h({path:t},c)),s(t,c)},commit(n){let t=`/tx/${n}/commit`,c={method:"POST",requestData:{}};return e==null||e(h({path:t},c)),s(t,c)},get(n){let t=`/tx/${n}`,c={method:"GET"};return e==null||e(h({path:t},c)),s(t,c)},rollback(n){let t=`/tx/${n}/rollback`,c={method:"POST",requestData:{}};return e==null||e(h({path:t},c)),s(t,c)}}});var U=class{constructor(e,a){this.relations={find:o=>p(this,[o],function*({pagination:e,search:a,transaction:r}){let{searchParams:n}=k(a),t=Q(r);return yield this.api.relations.find(n,e,t)})};this.properties={delete:(e,a)=>p(this,null,function*(){var r;return(r=this.api)==null?void 0:r.properties.delete(e,a)}),find:(e,a)=>p(this,null,function*(){var r;return(r=this.api)==null?void 0:r.properties.find(e,a)}),findById:(e,a)=>p(this,null,function*(){var r;return(r=this.api)==null?void 0:r.properties.findById(e,a)}),values:(e,a)=>p(this,null,function*(){var r;return(r=this.api)==null?void 0:r.properties.values(e,{},a)})};this.labels={find:(e,a)=>p(this,null,function*(){return this.api.labels.find(e,a)})};this.tx={begin:e=>p(this,null,function*(){var o;let a=yield(o=this.api)==null?void 0:o.tx.begin(e),r=new A(a.data.id);return r.init(this),r}),commit:e=>p(this,null,function*(){var a;return(a=this.api)==null?void 0:a.tx.commit(e)}),get:e=>p(this,null,function*(){var o;let a=yield(o=this.api)==null?void 0:o.tx.get(e),r=new A(a.data.id);return r.init(this),r}),rollback:e=>p(this,null,function*(){var a;return(a=this.api)==null?void 0:a.tx.commit(e)})};if(this.fetcher=null,a!=null&&a.httpClient){let r=be(a);this.fetcher=ye({httpClient:a.httpClient,token:e,url:r})}this.api=xe(this.fetcher,a==null?void 0:a.logger),this.records={attach:(r,o,n,t)=>p(this,null,function*(){var c,d;if(o instanceof f){let i=(c=o.data)==null?void 0:c.__id;if(i)return yield this.api.records.attach(r,i,n,t);throw new x("Attach error: Target id is empty")}else if(R(o)&&o.every(i=>i instanceof f)){let i=o.map(y=>{var u;return(u=y.data)==null?void 0:u.__id}).filter(pe);if(i.length)return yield this.api.records.attach(r,i,n,t);throw new x("Attach error: Target ids are empty")}else if(o instanceof D){let i=(d=o.data)==null?void 0:d.map(y=>y.__id).filter(Boolean);if(i!=null&&i.length)return yield this.api.records.attach(r,i,n,t);throw new x("Attach error: Target ids are empty")}else{if(T(o)&&"__id"in o)return yield this.api.records.attach(r,o.__id,n,t);if(R(o)&&o.every(i=>T(i)&&"__id"in i)){let i=o==null?void 0:o.map(y=>y.__id).filter(Boolean);if(i!=null&&i.length)return yield this.api.records.attach(r,i,n,t);throw new x("Attach error: Target ids are empty")}else return yield this.api.records.attach(r,o,n,t)}}),create:(r,o,n)=>p(this,null,function*(){var c,d;let t;if(r instanceof w&&(t=yield(c=this.api)==null?void 0:c.records.create(r,Q(o))),!t&&g(r)){if(W(o)){let i=Te({label:r,payload:o});t=yield(d=this.api)==null?void 0:d.records.create(new w(i),n)}else if(T(o))throw Error("Provided data is not a flat object. Consider to use `createMany` method.")}if(t!=null&&t.success&&(t!=null&&t.data)){let i=new f(t.data);return i.init(this),i}return new f}),createMany:(r,o,n)=>p(this,null,function*(){var c,d;let t;if(r instanceof O&&(t=yield(c=this.api)==null?void 0:c.records.createMany(r,Q(o))),!t&&g(r)&&(R(o)||T(o))){let i=new O({label:r,payload:o});t=yield(d=this.api)==null?void 0:d.records.createMany(i,n)}if(t!=null&&t.success&&(t!=null&&t.data)){let i=new D(t.data,t.total);return i.init(this),i}return new D([])}),delete:(r,o)=>p(this,null,function*(){var n;if(B(r.where))throw new x("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");return(n=this.api)==null?void 0:n.records.delete(r,o)}),deleteById:(r,o)=>p(this,null,function*(){var n;return(n=this.api)==null?void 0:n.records.deleteById(r,o)}),detach:(r,o,n,t)=>p(this,null,function*(){var c,d;if(o instanceof f){let i=(c=o.data)==null?void 0:c.__id;if(i)return yield this.api.records.detach(r,i,n,t);throw new x("Detach error: Target id is empty")}else if(R(o)&&o.every(i=>i instanceof f)){let i=o.map(y=>{var u;return(u=y.data)==null?void 0:u.__id}).filter(Boolean);if(i.length)return yield this.api.records.detach(r,i,n,t);throw new x("Detach error: Target ids are empty")}else if(o instanceof D){let i=(d=o.data)==null?void 0:d.map(y=>y.__id).filter(Boolean);if(i!=null&&i.length)return yield this.api.records.detach(r,i,n,t);throw new x("Detach error: Target ids are empty")}else{if(T(o)&&"__id"in o)return yield this.api.records.detach(r,o.__id,n,t);if(R(o)&&o.every(i=>T(i)&&"__id"in i)){let i=o==null?void 0:o.map(y=>y.__id).filter(Boolean);if(i!=null&&i.length)return yield this.api.records.detach(r,i,n,t);throw new x("Detach error: Target ids are empty")}else return yield this.api.records.detach(r,o,n,t)}}),export:(r,o)=>p(this,null,function*(){var n;return(n=this.api)==null?void 0:n.records.export(r,o)}),find:(r,o,n)=>p(this,null,function*(){var S;let t=j(o),{id:c,searchParams:d}=k(r,o),i=t?o:n,y=yield(S=this.api)==null?void 0:S.records.find({id:c,searchParams:d},i),u=new D(y.data,y.total,o);return u.init(this),u}),findById:(r,o)=>p(this,null,function*(){var n,t;if(R(r)){let c=yield(n=this.api)==null?void 0:n.records.findById(r,o),d=new D(c.data,c.total);return d.init(this),d}else{let c=yield(t=this.api)==null?void 0:t.records.findById(r,o),d=new f(c.data);return d.init(this),d}}),findOne:(r,o,n)=>p(this,null,function*(){var u;let t=j(o),{searchParams:c}=k(r,o),d=t?o:n,i=yield(u=this.api)==null?void 0:u.records.findOne(c,d),y=new f(i.data);return y.init(this),y}),findUniq:(r,o,n)=>p(this,null,function*(){var u;let t=j(o),{searchParams:c}=k(r,o),d=t?o:n,i=yield(u=this.api)==null?void 0:u.records.findUniq(c,d),y=new f(i.data);return y.init(this),y}),properties:(r,o)=>p(this,null,function*(){var n;return(n=this.api)==null?void 0:n.records.properties(r,o)}),relations:(r,o)=>p(this,null,function*(){return yield this.api.records.relations(r,o)}),set:(r,o,n)=>p(this,null,function*(){var c,d;let t;if(o instanceof w)t=yield(c=this.api)==null?void 0:c.records.set(r,o,n);else if(W(o)){let i=N(o);t=yield(d=this.api)==null?void 0:d.records.set(r,new w({properties:i}),n)}else if(T(o))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");if(t!=null&&t.success&&(t!=null&&t.data)){let i=new f(t.data);return i.init(this),i}return new f}),update:(r,o,n)=>p(this,null,function*(){var c,d;let t;if(o instanceof w)t=yield(c=this.api)==null?void 0:c.records.update(r,o,n);else if(W(o)){let i=N(o),y=new w({properties:i});t=yield(d=this.api)==null?void 0:d.records.update(r,y,n)}else if(T(o))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");if(t!=null&&t.success&&(t!=null&&t.data)){let i=new f(t.data);return i.init(this),i}return new f})}}};var we=s=>{class e extends U{constructor(r,o){var t;let n=ue(o);super(r,b(h({},n),{httpClient:(t=n.httpClient)!=null?t:s})),this.state={debug:!1,timeout:le("timeout",n.timeout,8e4),token:r},this.models=new Map,e.instance=this}static getInstance(){return e.instance}registerModel(r){let o=r.getLabel();return r.init(this),this.models.set(o,r),r}getModels(){return this.models}getModel(r){return this.models.get(r)}toInstance(r){let o=new f(r);return o.init(this),o}}return e};var ee=class extends I{constructor(e,a,r){super(),this.label=e,this.schema=a,r==null||r.registerModel(this)}getLabel(){return this.label}find(){return p(this,arguments,function*(e={},a){var r;return(r=this.apiProxy)==null?void 0:r.records.find(this.label,e,a)})}findOne(){return p(this,arguments,function*(e={},a){var r;return(r=this.apiProxy)==null?void 0:r.records.findOne(this.label,h({},e),a)})}findById(e,a){return p(this,null,function*(){return this.findOne({where:{$id:e}},a)})}findUniq(){return p(this,arguments,function*(e={},a){var r;return(r=this.apiProxy)==null?void 0:r.records.findUniq(this.label,h({},e),a)})}create(e,a){return p(this,null,function*(){var n;let r=yield v(this.schema,e),o=Z(this.schema,r);if(!B(o)){let t=a!=null?a:yield this.apiProxy.tx.begin(),c=yield this.find({where:o},t),d=typeof a!="undefined";if(!((n=c==null?void 0:c.data)!=null&&n.length)){let y=yield this.apiProxy.records.create(this.label,r,t);return d||(yield t.commit()),y}else throw d||(yield t.commit()),new E(this.label,o)}return yield this.apiProxy.records.create(this.label,r,a)})}attach(e,a,r,o){return this.apiProxy.records.attach(e,a,r,o)}detach(e,a,r,o){return this.apiProxy.records.detach(e,a,r,o)}handleSetOrUpdate(e,a,r,o){return p(this,null,function*(){var c;let n=yield v(this.schema,a),t=Z(this.schema,n);if(!B(t)){let d=o!=null?o:yield this.apiProxy.tx.begin(),i=yield this.find({where:t},d),y=typeof o!="undefined";if(!((c=i==null?void 0:i.data)!=null&&c.length)||i.data.length===1&&i.data[0].__id===e){let S=yield this.apiProxy.records[r](e,n,d);return y||(yield d.commit()),S}else throw y||(yield d.commit()),new E(this.label,t)}return yield this.apiProxy.records[r](e,n,o)})}set(e,a,r){return p(this,null,function*(){return yield this.handleSetOrUpdate(e,a,"set",r)})}update(e,a,r){return p(this,null,function*(){return yield this.handleSetOrUpdate(e,a,"update",r)})}createMany(e,a){return p(this,null,function*(){var n;let r=typeof a!="undefined",o=a!=null?a:yield this.apiProxy.tx.begin();try{let t=yield Promise.all(e.map(i=>p(this,null,function*(){return yield v(this.schema,i)}))),c=he(t,this.schema,this.label);if(!B(c)){let i=Object.entries(c).map(([u,S])=>({[u]:{$in:S}})),y=yield this.find({where:{$or:i}},o);if((n=y==null?void 0:y.data)!=null&&n.length)throw new E(this.label,Object.keys(c))}let d=yield this.apiProxy.records.createMany(this.label,t,o);return r||(yield o.commit()),d}catch(t){throw r||(yield o.rollback()),t}})}delete(e,a){return p(this,null,function*(){if(B(e.where))throw new x(`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(b(h({},e),{labels:[this.label]}),a)})}deleteById(e,a){return p(this,null,function*(){return yield this.apiProxy.records.deleteById(e,a)})}};var Ue=we(new L);var Nt=Ue;export{w as DBRecordDraft,f as DBRecordInstance,D as DBRecordsArrayInstance,O as DBRecordsBatchDraft,x as EmptyTargetError,P as HttpClient,K as HttpClientResponse,ee as Model,M as NonUniqueResultError,U as RestAPI,Ue as RushDB,A as Transaction,E as UniquenessError,Nt as default,X as idToDate,$ as idToTimestamp};
1
+ var Pe=Object.defineProperty,De=Object.defineProperties;var Ie=Object.getOwnPropertyDescriptors;var q=Object.getOwnPropertySymbols;var ae=Object.prototype.hasOwnProperty,ie=Object.prototype.propertyIsEnumerable;var ne=(r,e,a)=>e in r?Pe(r,e,{enumerable:!0,configurable:!0,writable:!0,value:a}):r[e]=a,h=(r,e)=>{for(var a in e||(e={}))ae.call(e,a)&&ne(r,a,e[a]);if(q)for(var a of q(e))ie.call(e,a)&&ne(r,a,e[a]);return r},x=(r,e)=>De(r,Ie(e));var oe=(r,e)=>{var a={};for(var s in r)ae.call(r,s)&&e.indexOf(s)<0&&(a[s]=r[s]);if(r!=null&&q)for(var s of q(r))e.indexOf(s)<0&&ie.call(r,s)&&(a[s]=r[s]);return a};var p=(r,e,a)=>new Promise((s,o)=>{var n=d=>{try{c(a.next(d))}catch(i){o(i)}},t=d=>{try{c(a.throw(d))}catch(i){o(i)}},c=d=>d.done?s(d.value):Promise.resolve(d.value).then(n,t);c((a=a.apply(r,e)).next())});var ce=/^(?:\d{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:\d{2}(?:[02468][048]|[13579][26])-02-29))Schema(0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9])?(?:\.([0-9]{1,9}))?([zZ]?|([\+-])(((([0][0-9])|([1][0-3])):?(([03][0])|([14][5])))|14:00)?)$/;var B="string",de="datetime",V="boolean",Y="number",J="null";var P=class r{makeRequest(e,{headers:a,method:s,protocol:o,requestData:n,timeout:t}){throw new Error("makeRequest not implemented.")}static makeTimeoutError(){let e=new TypeError(r.TIMEOUT_ERROR_CODE);return e.code=r.TIMEOUT_ERROR_CODE,e}};P.CONNECTION_CLOSED_ERROR_CODES=["ECONNRESET","EPIPE"];P.TIMEOUT_ERROR_CODE="ETIMEDOUT";var F=class{constructor(e,a){this._statusCode=e,this._headers=a}getStatusCode(){return this._statusCode}getHeaders(){return this._headers}getRawResponse(){throw new Error("getRawResponse not implemented.")}toStream(e){throw new Error("toStream not implemented.")}toJSON(){throw new Error("toJSON not implemented.")}},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 H=class r extends P{constructor(e){if(super(),!e){if(!globalThis.fetch)throw new Error("fetch() function not provided and is not defined in the global scope. You must provide a fetch implementation.");e=globalThis.fetch}globalThis.AbortController?this._fetchFn=r.makeFetchWithAbortTimeout(e):this._fetchFn=r.makeFetchWithRaceTimeout(e)}static makeFetchWithRaceTimeout(e){return(a,s,o)=>{let n,t=new Promise((d,i)=>{n=setTimeout(()=>{n=null,i(P.makeTimeoutError())},o)}),c=e(a,s);return Promise.race([c,t]).finally(()=>{n&&clearTimeout(n)})}}static makeFetchWithAbortTimeout(e){return(a,s,o)=>p(this,null,function*(){let n=new AbortController,t=setTimeout(()=>{t=null,n.abort(P.makeTimeoutError())},o);try{return yield e(a,x(h({},s),{signal:n.signal}))}catch(c){throw c.name==="AbortError"?P.makeTimeoutError():c}finally{t&&clearTimeout(t)}})}makeRequest(c,d){return p(this,arguments,function*(e,{headers:a,method:s,protocol:o,requestData:n,timeout:t}){let i=s=="POST"||s=="PUT"||s=="PATCH",y=JSON.stringify(n)||(i?"":void 0),u=yield this._fetchFn(e,{body:y,headers:a,method:s},t!=null?t:8e4);return new G(u)})}},G=class r extends F{constructor(e){super(e.status,r._transformHeadersToObject(e.headers)),this._res=e}getRawResponse(){return this._res}toStream(e){return e(),this._res.body}toJSON(){return this._res.json()}static _transformHeadersToObject(e){let a={};for(let s of e){if(!Array.isArray(s)||s.length!=2)throw new Error("Response objects produced by the fetch function given to FetchHttpClient do not have an iterable headers map. Response#headers should be an iterable object.");a[s[0]]=s[1]}return a}};var R=r=>typeof r=="object"&&Array.isArray(r)&&r!==null,T=r=>r!==null&&Object.prototype.toString.call(r)==="[object Object]",_=r=>T(r)&&Object.keys(r).length===0,L=r=>T(r)&&Object.keys(r).every(e=>{let a=r[e];return R(a)?a.every(s=>typeof s=="string"||typeof s=="number"||typeof s=="boolean"||s===null):!(a&&typeof a=="object")}),g=r=>typeof r=="string",pe=r=>{if(typeof r=="string"){if(r.toLowerCase()==="true")return!0;if(r.toLowerCase()==="false")return!1}return R(r)&&r.length===0||T(r)&&Object.keys(r).length===0?!1:!!r};var Ae={"Content-Type":"application/json"},ye=({httpClient:r,token:e,url:a})=>(s,t)=>p(void 0,null,function*(){var c=t,{headers:o}=c,n=oe(c,["headers"]);let d=yield r.makeRequest(`${a}${s}`,h({credentials:"omit",headers:Object.assign(h(h({},Ae),o),typeof e!="undefined"?{token:e}:{})},n));if(d.getStatusCode()>=200&&d.getStatusCode()<300)return yield d.toJSON();throw new Error(`${d.getStatusCode()}`)});var I=class r extends Error{constructor(e,a){super(`Record with label "${e}" and properties ${JSON.stringify(a)} already exists`),this.name="UniquenessError",Object.setPrototypeOf(this,r.prototype)}},b=class r extends Error{constructor(e){super(e),this.name="EmptyTarget",Object.setPrototypeOf(this,r.prototype)}},U=class r extends Error{constructor(e,a){super(`Expected a unique result but found ${e} matches for the provided search parameters: ${JSON.stringify(a)}. Ensure your search parameters uniquely identify a single result.`),this.name="NonUniqueResultError",Object.setPrototypeOf(this,r.prototype)}};var E=class{constructor(){this.apiProxy={};return new Proxy(this,{get:(e,a,s)=>{if(a in e)return Reflect.get(e,a,s);if(this.apiProxy&&a in this.apiProxy)return Reflect.get(this.apiProxy,a,s)}})}init(e,a){this.apiProxy=e}};var z=["httpClient","timeout","host","port","protocol","url","validator","logger"];var v=(r,e)=>p(void 0,null,function*(){let a=Object.entries(r).map(c=>p(void 0,[c],function*([n,t]){return t.default&&typeof t.default!="undefined"&&typeof e[n]=="undefined"?{key:n,value:typeof t.default=="function"?yield t.default():t.default}:{key:n,value:void 0}})),o=(yield Promise.all(a)).reduce((n,{key:t,value:c})=>(c!==void 0&&(n[t]=c),n),{});return h(h({},o),e)}),Z=(r,e)=>Object.entries(e).filter(([a])=>{var s;return(s=r[a])==null?void 0:s.uniq}).reduce((a,[s,o])=>(s in r&&(a[s]=o),a),{}),he=(r,e,a)=>{let s={},o=Object.entries(e).filter(([n,t])=>t.uniq).reduce((n,[t])=>(n[t]=!0,n),{});return r.forEach(n=>{Object.entries(n).forEach(([t,c])=>{if(t in o)if(s[t]){if(s[t].includes(c))throw new I(a,{[t]:c});s[t]=[...s[t],c]}else s[t]=[c]})}),s},ue=r=>{if(!r)return{};if(!T(r))throw new Error("Config must be an object");if(Object.keys(r).filter(a=>!z.includes(a)).length>0)throw new Error(`Config object may only contain the following: ${z.join(", ")}`);return r};function le(r,e,a){if(!Number.isInteger(e)){if(a!==void 0)return a;throw new Error(`${r} must be an integer`)}return e}function W(r){let e=r.split("-"),a=e[0]+e[1].slice(0,4);return parseInt(a,16)}function X(r){return new Date(W(r))}var O=class{constructor({label:e,options:a={returnResult:!0,suggestTypes:!0},payload:s}){this.label=e,this.options=a,this.payload=s}toJson(){return{label:this.label,options:this.options,payload:this.payload}}},w=class{constructor({label:e,properties:a=[]}){this.label=e,this.properties=a}toJson(){return{label:this.label,properties:this.properties}}},f=class extends E{constructor(e){super(),this.data=e}get id(){try{return this.data.__id}catch(e){throw new Error("DBRecordInstance: Unable to access 'id'. The Record data is undefined.")}}get label(){try{return this.data.__label}catch(e){throw new Error("DBRecordInstance: Unable to access 'label'. The Record data is undefined.")}}get proptypes(){try{return this.data.__proptypes}catch(e){throw new Error("DBRecordInstance: Unable to access 'proptypes'. The Record data' is undefined.")}}get date(){try{return X(this.data.__id)}catch(e){throw new Error("DBRecordInstance: Unable to access 'date'. The Record data is undefined.")}}get timestamp(){try{return W(this.data.__id)}catch(e){throw new Error("DBRecordInstance: Unable to access 'timestamp'. The Record data is undefined.")}}delete(e){return p(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to delete Record. The Record data is undefined.");return yield this.apiProxy.records.deleteById(this.data.__id,e)})}update(e,a){return p(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to update Record. The Record data is undefined.");return this.apiProxy.records.update(this.data.__id,e,a)})}set(e,a){return p(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to set. The Record data is undefined.");return this.apiProxy.records.set(this.data.__id,e,a)})}attach(e,a,s){return p(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to attach Record. The Record data is undefined.");return this.apiProxy.records.attach(this.data.__id,e,a,s)})}detach(e,a,s){return p(this,null,function*(){if(!this.data)throw new Error("DBRecordInstance: Unable to detach Record. The Record data is undefined.");return this.apiProxy.records.detach(this.data.__id,e,a,s)})}},D=class extends E{constructor(e,a,s){super(),this.data=e,this.total=a,this.searchParams=s}};var A=class extends E{constructor(e){super(),this.id=e}rollback(){return p(this,null,function*(){return yield this.apiProxy.tx.rollback(this.id)})}commit(){return p(this,null,function*(){return yield this.apiProxy.tx.commit(this.id)})}};var me="api.rushdb.com";var fe="https",Se="/api/v1";var l=r=>r?{"x-transaction-id":r}:void 0,Q=r=>g(r)||r instanceof A,$=r=>Q(r)?r:void 0,m=r=>Q(r)?r instanceof A?r.id:r:void 0,j=r=>{if(g(r))return r;if(r instanceof f&&r.data)return r.data.__id;if("__id"in r)return r.__id},k=(r,e)=>{var t,c,d;let a=g(r),s=Be(r),n=Q(e)||!T(e);if(a){let i=s?{id:r}:{searchParams:{labels:[r]}};return n?x(h({},i),{searchParams:h({},i.searchParams)}):x(h({},i),{searchParams:x(h({},e),{labels:[...(c=(t=i.searchParams)==null?void 0:t.labels)!=null?c:[],...(d=e.labels)!=null?d:[]]})})}else return{searchParams:r!=null?r:{}}},Be=r=>/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(r),_e=r=>r.every(e=>typeof e==typeof r[0]),ge=r=>Array.isArray(r)?{isEmptyArray:r.length===0,isEmptyStringsArray:r.every(e=>e===""),isInconsistentArray:!_e(r)}:{isEmptyString:r===""},Re=r=>typeof r===B?ce.test(r)?de:B:typeof r===Y?Y:typeof r===V?V:r===null?J:B,Qe=(r,e)=>{let{isEmptyArray:a,isInconsistentArray:s}=ge(r);return a?{type:B,value:[]}:s||!e?{type:B,value:r.map(String)}:{type:Re(r[0]),value:r}},je=(r,e)=>{if(!e)return{type:B,value:String(r)};let a=Re(r);return{type:a,value:a===J?null:r}},N=(r,e={suggestTypes:!0})=>Object.entries(r).map(([a,s])=>{let{type:o,value:n}=R(s)?Qe(s,e.suggestTypes):je(s,e.suggestTypes);return{name:a,type:o,value:n}}),Te=({label:r,options:e={suggestTypes:!0},payload:a})=>({label:r,properties:N(a,e)}),xe=r=>{let e=fe,a=me,s=443,o=Se;if("url"in r){let t=new URL(r.url);e=t.protocol.replace(":",""),a=t.hostname,s=parseInt(t.port||(e==="http"?"80":e==="https"?"443":""))}"host"in r&&"port"in r&&"protocol"in r&&(e=r.protocol.replace(":",""),a=r.host,s=r.port),o&&!o.startsWith("/")&&(o="/"+o);let n="";return e==="http"&&s===80||e==="https"&&s===443||(n=":"+s),`${e}://${a}${n}${o}`};var be=(r,e)=>({labels:{find(n,t){return p(this,null,function*(){let c=m(t),d="/labels",i={headers:Object.assign({},l(c)),method:"POST",requestData:n};return e==null||e(h({path:d},i)),r(d,i)})}},properties:{delete:(n,t)=>{let c=m(t),d=`/properties/${n}`,i={headers:Object.assign({},l(c)),method:"DELETE"};return e==null||e(h({path:d},i)),r(d,i)},find:(n,t)=>{let c=m(t),d="/properties",i={headers:Object.assign({},l(c)),method:"POST",requestData:n};return e==null||e(h({path:d},i)),r(d,i)},findById:(n,t)=>{let c=m(t),d=`/properties/${n}`,i={headers:Object.assign({},l(c)),method:"GET"};return e==null||e(h({path:d},i)),r(d,i)},values:(n,t,c)=>{let d=m(c),i=`/properties/${n}/values`,{sort:y,skip:u,limit:S}=t!=null?t:{},M=new URLSearchParams;y&&M.append("sort",y),u!==void 0&&M.append("skip",u.toString()),S!==void 0&&M.append("limit",S.toString());let te=M.toString(),re=te?`${i}?${te}`:i,se={headers:Object.assign({},l(d)),method:"GET"};return e==null||e(h({path:re},se)),r(re,se)}},records:{attach(n,t,c,d){return p(this,null,function*(){let i=m(d),u=`/records/${j(n)}/relations`,S={headers:Object.assign({},l(i)),method:"POST",requestData:h(h({targetIds:t},(c==null?void 0:c.type)&&{type:c.type}),(c==null?void 0:c.direction)&&{direction:c.direction})};return e==null||e(h({path:u},S)),r(u,S)})},create(n,t){return p(this,null,function*(){let c=m(t),d="/records",i={headers:Object.assign({},l(c)),method:"POST",requestData:n instanceof w?n.toJson():n};return e==null||e(h({path:d},i)),r(d,i)})},createMany(n,t){return p(this,null,function*(){let c=m(t),d="/records/import/json",i={headers:Object.assign({},l(c)),method:"POST",requestData:n instanceof O?n.toJson():n};return e==null||e(h({path:d},i)),r(d,i)})},delete(n,t){let c=m(t),d="/records/delete",i={headers:Object.assign({},l(c)),method:"PUT",requestData:n};return e==null||e(h({path:d},i)),r(d,i)},deleteById(n,t){let c=m(t),d=R(n),i=d?"/records/delete":`/records/${n}`,y={headers:Object.assign({},l(c)),method:d?"PUT":"DELETE",requestData:d?{limit:1e3,where:{$id:{$in:n}}}:void 0};return e==null||e(h({path:i},y)),r(i,y)},detach(n,t,c,d){return p(this,null,function*(){let i=m(d),u=`/records/${j(n)}/relations`,S={headers:Object.assign({},l(i)),method:"PUT",requestData:h(h({targetIds:t},(c==null?void 0:c.typeOrTypes)&&{typeOrTypes:c.typeOrTypes}),(c==null?void 0:c.direction)&&{direction:c.direction})};return e==null||e(h({path:u},S)),r(u,S)})},export(n,t){let c=m(t),d="/records/export/csv",i={headers:Object.assign({},l(c)),method:"POST",requestData:n};return e==null||e(h({path:d},i)),r(d,i)},find(n,t){let c=m(t),d=n!=null&&n.id?`/records/${n.id}/search`:"/records/search",i={headers:Object.assign({},l(c)),method:"POST",requestData:n==null?void 0:n.searchParams};return e==null||e(h({path:d},i)),r(d,i)},findById(n,t){let c=m(t),d=R(n)?"/records":`/records/${n}`,i={headers:Object.assign({},l(c)),method:R(n)?"POST":"GET",requestData:R(n)?{ids:n}:void 0};return e==null||e(h({path:d},i)),r(d,i)},findOne(n,t){return p(this,null,function*(){let c=m(t),d="/records/search",i={headers:Object.assign({},l(c)),method:"POST",requestData:x(h({},n),{limit:1,skip:0})};e==null||e(h({path:d},i));let y=yield r(d,i),[u]=y.data;return x(h({},y),{data:u})})},findUniq(n,t){return p(this,null,function*(){let c=m(t),d="/records/search",i={headers:Object.assign({},l(c)),method:"POST",requestData:x(h({},n),{limit:1,skip:0})};e==null||e(h({path:d},i));let y=yield r(d,i);if(typeof y.total!="undefined"&&y.total>1)throw new U(y.total,n);let[u]=y.data;return x(h({},y),{data:u})})},properties(n,t){let c=m(t),i=`/records/${j(n)}/properties`,y={headers:Object.assign({},l(c)),method:"GET"};return e==null||e(h({path:i},y)),r(i,y)},relations(n,t){return p(this,null,function*(){let c=m(t),i=`/records/${j(n)}/relations`,y={headers:Object.assign({},l(c)),method:"GET"};return e==null||e(h({path:i},y)),r(i,y)})},set(n,t,c){let d=m(c),y=`/records/${j(n)}`,u={headers:Object.assign({},l(d)),method:"PUT",requestData:t instanceof w?t.toJson():t};return e==null||e(h({path:y},u)),r(y,u)},update(n,t,c){let d=m(c),y=`/records/${j(n)}`,u={headers:Object.assign({},l(d)),method:"PATCH",requestData:t instanceof w?t.toJson():t};return e==null||e(h({path:y},u)),r(y,u)}},relations:{find(n,t,c){return p(this,null,function*(){let d=m(c),i=new URLSearchParams;(t==null?void 0:t.limit)!==void 0&&i.append("limit",t.limit.toString()),(t==null?void 0:t.skip)!==void 0&&i.append("skip",t.skip.toString());let u=`/records/relations/search${i.toString()?"?"+i.toString():""}`,S={headers:Object.assign({},l(d)),method:"POST",requestData:n};return e==null||e(h({path:u},S)),r(u,S)})}},tx:{begin(n={}){let t="/tx",c={method:"POST",requestData:n};return e==null||e(h({path:t},c)),r(t,c)},commit(n){let t=`/tx/${n}/commit`,c={method:"POST",requestData:{}};return e==null||e(h({path:t},c)),r(t,c)},get(n){let t=`/tx/${n}`,c={method:"GET"};return e==null||e(h({path:t},c)),r(t,c)},rollback(n){let t=`/tx/${n}/rollback`,c={method:"POST",requestData:{}};return e==null||e(h({path:t},c)),r(t,c)}}});var C=class{constructor(e,a){this.relations={find:o=>p(this,[o],function*({pagination:e,search:a,transaction:s}){let{searchParams:n}=k(a),t=$(s);return yield this.api.relations.find(n,e,t)})};this.properties={delete:(e,a)=>p(this,null,function*(){var s;return(s=this.api)==null?void 0:s.properties.delete(e,a)}),find:(e,a)=>p(this,null,function*(){var s;return(s=this.api)==null?void 0:s.properties.find(e,a)}),findById:(e,a)=>p(this,null,function*(){var s;return(s=this.api)==null?void 0:s.properties.findById(e,a)}),values:(e,a)=>p(this,null,function*(){var s;return(s=this.api)==null?void 0:s.properties.values(e,{},a)})};this.labels={find:(e,a)=>p(this,null,function*(){return this.api.labels.find(e,a)})};this.tx={begin:e=>p(this,null,function*(){var o;let a=yield(o=this.api)==null?void 0:o.tx.begin(e),s=new A(a.data.id);return s.init(this),s}),commit:e=>p(this,null,function*(){var a;return(a=this.api)==null?void 0:a.tx.commit(e)}),get:e=>p(this,null,function*(){var o;let a=yield(o=this.api)==null?void 0:o.tx.get(e),s=new A(a.data.id);return s.init(this),s}),rollback:e=>p(this,null,function*(){var a;return(a=this.api)==null?void 0:a.tx.commit(e)})};if(this.fetcher=null,a!=null&&a.httpClient){let s=xe(a);this.fetcher=ye({httpClient:a.httpClient,token:e,url:s})}this.api=be(this.fetcher,a==null?void 0:a.logger),this.records={attach:(s,o,n,t)=>p(this,null,function*(){var c,d;if(o instanceof f){let i=(c=o.data)==null?void 0:c.__id;if(i)return yield this.api.records.attach(s,i,n,t);throw new b("Attach error: Target id is empty")}else if(R(o)&&o.every(i=>i instanceof f)){let i=o.map(y=>{var u;return(u=y.data)==null?void 0:u.__id}).filter(pe);if(i.length)return yield this.api.records.attach(s,i,n,t);throw new b("Attach error: Target ids are empty")}else if(o instanceof D){let i=(d=o.data)==null?void 0:d.map(y=>y.__id).filter(Boolean);if(i!=null&&i.length)return yield this.api.records.attach(s,i,n,t);throw new b("Attach error: Target ids are empty")}else{if(T(o)&&"__id"in o)return yield this.api.records.attach(s,o.__id,n,t);if(R(o)&&o.every(i=>T(i)&&"__id"in i)){let i=o==null?void 0:o.map(y=>y.__id).filter(Boolean);if(i!=null&&i.length)return yield this.api.records.attach(s,i,n,t);throw new b("Attach error: Target ids are empty")}else return yield this.api.records.attach(s,o,n,t)}}),create:(s,o,n)=>p(this,null,function*(){var c,d;let t;if(s instanceof w&&(t=yield(c=this.api)==null?void 0:c.records.create(s,$(o))),!t&&g(s)){if(L(o)){let i=Te({label:s,payload:o});t=yield(d=this.api)==null?void 0:d.records.create(new w(i),n)}else if(T(o))throw Error("Provided data is not a flat object. Consider to use `createMany` method.")}if(t!=null&&t.success&&(t!=null&&t.data)){let i=new f(t.data);return i.init(this),i}return new f}),createMany:(s,o,n)=>p(this,null,function*(){var c,d;let t;if(s instanceof O&&(t=yield(c=this.api)==null?void 0:c.records.createMany(s,$(o))),!t&&g(s)&&(R(o)||T(o))){let i=new O({label:s,payload:o});t=yield(d=this.api)==null?void 0:d.records.createMany(i,n)}if(t!=null&&t.success&&(t!=null&&t.data)){let i=new D(t.data,t.total);return i.init(this),i}return new D([])}),delete:(s,o)=>p(this,null,function*(){var n;if(_(s.where))throw new b("You must specify criteria to delete records. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.");return(n=this.api)==null?void 0:n.records.delete(s,o)}),deleteById:(s,o)=>p(this,null,function*(){var n;return(n=this.api)==null?void 0:n.records.deleteById(s,o)}),detach:(s,o,n,t)=>p(this,null,function*(){var c,d;if(o instanceof f){let i=(c=o.data)==null?void 0:c.__id;if(i)return yield this.api.records.detach(s,i,n,t);throw new b("Detach error: Target id is empty")}else if(R(o)&&o.every(i=>i instanceof f)){let i=o.map(y=>{var u;return(u=y.data)==null?void 0:u.__id}).filter(Boolean);if(i.length)return yield this.api.records.detach(s,i,n,t);throw new b("Detach error: Target ids are empty")}else if(o instanceof D){let i=(d=o.data)==null?void 0:d.map(y=>y.__id).filter(Boolean);if(i!=null&&i.length)return yield this.api.records.detach(s,i,n,t);throw new b("Detach error: Target ids are empty")}else{if(T(o)&&"__id"in o)return yield this.api.records.detach(s,o.__id,n,t);if(R(o)&&o.every(i=>T(i)&&"__id"in i)){let i=o==null?void 0:o.map(y=>y.__id).filter(Boolean);if(i!=null&&i.length)return yield this.api.records.detach(s,i,n,t);throw new b("Detach error: Target ids are empty")}else return yield this.api.records.detach(s,o,n,t)}}),export:(s,o)=>p(this,null,function*(){var n;return(n=this.api)==null?void 0:n.records.export(s,o)}),find:(s,o,n)=>p(this,null,function*(){var S;let t=Q(o),{id:c,searchParams:d}=k(s,o),i=t?o:n,y=yield(S=this.api)==null?void 0:S.records.find({id:c,searchParams:d},i),u=new D(y.data,y.total,o);return u.init(this),u}),findById:(s,o)=>p(this,null,function*(){var n,t;if(R(s)){let c=yield(n=this.api)==null?void 0:n.records.findById(s,o),d=new D(c.data,c.total);return d.init(this),d}else{let c=yield(t=this.api)==null?void 0:t.records.findById(s,o),d=new f(c.data);return d.init(this),d}}),findOne:(s,o,n)=>p(this,null,function*(){var u;let t=Q(o),{searchParams:c}=k(s,o),d=t?o:n,i=yield(u=this.api)==null?void 0:u.records.findOne(c,d),y=new f(i.data);return y.init(this),y}),findUniq:(s,o,n)=>p(this,null,function*(){var u;let t=Q(o),{searchParams:c}=k(s,o),d=t?o:n,i=yield(u=this.api)==null?void 0:u.records.findUniq(c,d),y=new f(i.data);return y.init(this),y}),properties:(s,o)=>p(this,null,function*(){var n;return(n=this.api)==null?void 0:n.records.properties(s,o)}),relations:(s,o)=>p(this,null,function*(){return yield this.api.records.relations(s,o)}),set:(s,o,n)=>p(this,null,function*(){var c,d;let t;if(o instanceof w)t=yield(c=this.api)==null?void 0:c.records.set(s,o,n);else if(L(o)){let i=N(o);t=yield(d=this.api)==null?void 0:d.records.set(s,new w({properties:i}),n)}else if(T(o))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");if(t!=null&&t.success&&(t!=null&&t.data)){let i=new f(t.data);return i.init(this),i}return new f}),update:(s,o,n)=>p(this,null,function*(){var c,d;let t;if(o instanceof w)t=yield(c=this.api)==null?void 0:c.records.update(s,o,n);else if(L(o)){let i=N(o),y=new w({properties:i});t=yield(d=this.api)==null?void 0:d.records.update(s,y,n)}else if(T(o))throw Error("Provided data is not a flat object. Consider to use `createMany` method.");if(t!=null&&t.success&&(t!=null&&t.data)){let i=new f(t.data);return i.init(this),i}return new f})}}};var we=r=>{class e extends C{constructor(s,o){var t;let n=ue(o);super(s,x(h({},n),{httpClient:(t=n.httpClient)!=null?t:r})),this.state={debug:!1,timeout:le("timeout",n.timeout,8e4),token:s},this.models=new Map,e.instance=this}static getInstance(){return e.instance}registerModel(s){let o=s.getLabel();return s.init(this),this.models.set(o,s),s}getModels(){return this.models}getModel(s){return this.models.get(s)}toInstance(s){let o=new f(s);return o.init(this),o}}return e};var ee=class extends E{constructor(e,a,s){super(),this.label=e,this.schema=a,s==null||s.registerModel(this)}getLabel(){return this.label}find(e,a){return p(this,null,function*(){var o;let s=e!=null?e:{};return(o=this.apiProxy)==null?void 0:o.records.find(this.label,s,a)})}findOne(e,a){return p(this,null,function*(){var o;let s=e!=null?e:{};return(o=this.apiProxy)==null?void 0:o.records.findOne(this.label,s,a)})}findById(e,a){return p(this,null,function*(){return this.findOne({where:{$id:e}},a)})}findUniq(e,a){return p(this,null,function*(){var o;let s=e!=null?e:{};return(o=this.apiProxy)==null?void 0:o.records.findUniq(this.label,s,a)})}create(e,a){return p(this,null,function*(){var n;let s=yield v(this.schema,e),o=Z(this.schema,s);if(!_(o)){let t=a!=null?a:yield this.apiProxy.tx.begin(),c=yield this.find({where:o},t),d=typeof a!="undefined";if(!((n=c==null?void 0:c.data)!=null&&n.length)){let y=yield this.apiProxy.records.create(this.label,s,t);return d||(yield t.commit()),y}else throw d||(yield t.commit()),new I(this.label,o)}return yield this.apiProxy.records.create(this.label,s,a)})}attach(e,a,s,o){return this.apiProxy.records.attach(e,a,s,o)}detach(e,a,s,o){return this.apiProxy.records.detach(e,a,s,o)}handleSetOrUpdate(e,a,s,o){return p(this,null,function*(){var c;let n=yield v(this.schema,a),t=Z(this.schema,n);if(!_(t)){let d=o!=null?o:yield this.apiProxy.tx.begin(),i=yield this.find({where:t},d),y=typeof o!="undefined";if(!((c=i==null?void 0:i.data)!=null&&c.length)||i.data.length===1&&i.data[0].__id===e){let S=yield this.apiProxy.records[s](e,n,d);return y||(yield d.commit()),S}else throw y||(yield d.commit()),new I(this.label,t)}return yield this.apiProxy.records[s](e,n,o)})}set(e,a,s){return p(this,null,function*(){return yield this.handleSetOrUpdate(e,a,"set",s)})}update(e,a,s){return p(this,null,function*(){return yield this.handleSetOrUpdate(e,a,"update",s)})}createMany(e,a){return p(this,null,function*(){var n;let s=typeof a!="undefined",o=a!=null?a:yield this.apiProxy.tx.begin();try{let t=yield Promise.all(e.map(i=>p(this,null,function*(){return yield v(this.schema,i)}))),c=he(t,this.schema,this.label);if(!_(c)){let i=Object.entries(c).map(([u,S])=>({[u]:{$in:S}})),y=yield this.find({where:{$or:i}},o);if((n=y==null?void 0:y.data)!=null&&n.length)throw new I(this.label,Object.keys(c))}let d=yield this.apiProxy.records.createMany(this.label,t,o);return s||(yield o.commit()),d}catch(t){throw s||(yield o.rollback()),t}})}delete(e,a){return p(this,null,function*(){if(_(e.where))throw new b(`You must specify criteria to delete records of type '${this.label}'. Empty criteria are not allowed. If this was intentional, use the Dashboard instead.`);return yield this.apiProxy.records.delete(x(h({},e),{labels:[this.label]}),a)})}deleteById(e,a){return p(this,null,function*(){return yield this.apiProxy.records.deleteById(e,a)})}};var Ce=we(new H);var Nt=Ce;export{w as DBRecordDraft,f as DBRecordInstance,D as DBRecordsArrayInstance,O as DBRecordsBatchDraft,b as EmptyTargetError,P as HttpClient,K as HttpClientResponse,ee as Model,U as NonUniqueResultError,C as RestAPI,Ce as RushDB,A as Transaction,I as UniquenessError,Nt as default,X as idToDate,W as idToTimestamp};
@@ -12,7 +12,7 @@ declare const RushDB: {
12
12
  readonly __id: string;
13
13
  readonly __label: string;
14
14
  readonly __proptypes?: import("./types/utils.js").FlattenTypes<{ [Key in import("./types/schema.js").RequiredKeysRead<S>]: S[Key]["type"]; } & { [Key_1 in import("./types/schema.js").OptionalKeysRead<S>]?: S[Key_1]["type"] | undefined; }> | undefined;
15
- } & import("./types/utils.js").FlattenTypes<import("./sdk/record.js").RecordProps<S>>>): DBRecordInstance<S>;
15
+ } & import("./types/utils.js").FlattenTypes<import("./sdk/record.js").RecordProps<S>>>): DBRecordInstance<S, import("./types/query.js").SearchQuery<S>>;
16
16
  api: ReturnType<typeof import("./api/create-api.js").createApi>;
17
17
  fetcher: ReturnType<typeof import("./network/index.js").createFetcher>;
18
18
  records: import("./api/types.js").RecordsApi;
@@ -55,7 +55,7 @@ declare const RushDB: {
55
55
  readonly __id: string;
56
56
  readonly __label: string;
57
57
  readonly __proptypes?: import("./types/utils.js").FlattenTypes<{ [Key in import("./types/schema.js").RequiredKeysRead<S>]: S[Key]["type"]; } & { [Key_1 in import("./types/schema.js").OptionalKeysRead<S>]?: S[Key_1]["type"] | undefined; }> | undefined;
58
- } & import("./types/utils.js").FlattenTypes<import("./sdk/record.js").RecordProps<S>>>): DBRecordInstance<S>;
58
+ } & import("./types/utils.js").FlattenTypes<import("./sdk/record.js").RecordProps<S>>>): DBRecordInstance<S, import("./types/query.js").SearchQuery<S>>;
59
59
  api: ReturnType<typeof import("./api/create-api.js").createApi>;
60
60
  fetcher: ReturnType<typeof import("./network/index.js").createFetcher>;
61
61
  records: import("./api/types.js").RecordsApi;
@@ -98,7 +98,7 @@ declare const RushDB: {
98
98
  readonly __id: string;
99
99
  readonly __label: string;
100
100
  readonly __proptypes?: import("./types/utils.js").FlattenTypes<{ [Key in import("./types/schema.js").RequiredKeysRead<S>]: S[Key]["type"]; } & { [Key_1 in import("./types/schema.js").OptionalKeysRead<S>]?: S[Key_1]["type"] | undefined; }> | undefined;
101
- } & import("./types/utils.js").FlattenTypes<import("./sdk/record.js").RecordProps<S>>>): DBRecordInstance<S>;
101
+ } & import("./types/utils.js").FlattenTypes<import("./sdk/record.js").RecordProps<S>>>): DBRecordInstance<S, import("./types/query.js").SearchQuery<S>>;
102
102
  api: ReturnType<typeof import("./api/create-api.js").createApi>;
103
103
  fetcher: ReturnType<typeof import("./network/index.js").createFetcher>;
104
104
  records: import("./api/types.js").RecordsApi;
@@ -12,7 +12,7 @@ declare const RushDB: {
12
12
  readonly __id: string;
13
13
  readonly __label: string;
14
14
  readonly __proptypes?: import("./types/utils.js").FlattenTypes<{ [Key in import("./types/schema.js").RequiredKeysRead<S>]: S[Key]["type"]; } & { [Key_1 in import("./types/schema.js").OptionalKeysRead<S>]?: S[Key_1]["type"] | undefined; }> | undefined;
15
- } & import("./types/utils.js").FlattenTypes<import("./sdk/record.js").RecordProps<S>>>): DBRecordInstance<S>;
15
+ } & import("./types/utils.js").FlattenTypes<import("./sdk/record.js").RecordProps<S>>>): DBRecordInstance<S, import("./types/query.js").SearchQuery<S>>;
16
16
  api: ReturnType<typeof import("./api/create-api.js").createApi>;
17
17
  fetcher: ReturnType<typeof import("./network/index.js").createFetcher>;
18
18
  records: import("./api/types.js").RecordsApi;
@@ -55,7 +55,7 @@ declare const RushDB: {
55
55
  readonly __id: string;
56
56
  readonly __label: string;
57
57
  readonly __proptypes?: import("./types/utils.js").FlattenTypes<{ [Key in import("./types/schema.js").RequiredKeysRead<S>]: S[Key]["type"]; } & { [Key_1 in import("./types/schema.js").OptionalKeysRead<S>]?: S[Key_1]["type"] | undefined; }> | undefined;
58
- } & import("./types/utils.js").FlattenTypes<import("./sdk/record.js").RecordProps<S>>>): DBRecordInstance<S>;
58
+ } & import("./types/utils.js").FlattenTypes<import("./sdk/record.js").RecordProps<S>>>): DBRecordInstance<S, import("./types/query.js").SearchQuery<S>>;
59
59
  api: ReturnType<typeof import("./api/create-api.js").createApi>;
60
60
  fetcher: ReturnType<typeof import("./network/index.js").createFetcher>;
61
61
  records: import("./api/types.js").RecordsApi;
@@ -98,7 +98,7 @@ declare const RushDB: {
98
98
  readonly __id: string;
99
99
  readonly __label: string;
100
100
  readonly __proptypes?: import("./types/utils.js").FlattenTypes<{ [Key in import("./types/schema.js").RequiredKeysRead<S>]: S[Key]["type"]; } & { [Key_1 in import("./types/schema.js").OptionalKeysRead<S>]?: S[Key_1]["type"] | undefined; }> | undefined;
101
- } & import("./types/utils.js").FlattenTypes<import("./sdk/record.js").RecordProps<S>>>): DBRecordInstance<S>;
101
+ } & import("./types/utils.js").FlattenTypes<import("./sdk/record.js").RecordProps<S>>>): DBRecordInstance<S, import("./types/query.js").SearchQuery<S>>;
102
102
  api: ReturnType<typeof import("./api/create-api.js").createApi>;
103
103
  fetcher: ReturnType<typeof import("./network/index.js").createFetcher>;
104
104
  records: import("./api/types.js").RecordsApi;
@@ -36,21 +36,25 @@ export declare class Model<S extends Schema = any> extends RestApiProxy {
36
36
  */
37
37
  readonly recordsArrayInstance: DBRecordsArrayInstance<S>;
38
38
  getLabel(): string;
39
- find(params?: SearchQuery<S> & {
39
+ find<Q extends SearchQuery<S> = SearchQuery<S>>(params?: Q & {
40
40
  labels?: never;
41
- }, transaction?: Transaction | string): Promise<DBRecordsArrayInstance<S>>;
42
- findOne(params?: SearchQuery<S> & {
41
+ }, transaction?: Transaction | string): Promise<DBRecordsArrayInstance<S, Q>>;
42
+ findOne<Q extends SearchQuery<S> = SearchQuery<S>>(params?: Q & {
43
43
  labels?: never;
44
44
  limit?: never;
45
45
  skip?: never;
46
- }, transaction?: Transaction | string): Promise<DBRecordInstance<S>>;
47
- findById(id: string, transaction?: Transaction | string): Promise<DBRecordInstance<S>>;
48
- findUniq(params?: SearchQuery<S> & {
46
+ }, transaction?: Transaction | string): Promise<DBRecordInstance<S, Q>>;
47
+ findById(id: string, transaction?: Transaction | string): Promise<DBRecordInstance<S, {
48
+ where: {
49
+ $id: string;
50
+ };
51
+ }>>;
52
+ findUniq<Q extends SearchQuery<S> = SearchQuery<S>>(params?: Q & {
49
53
  labels?: never;
50
54
  limit?: never;
51
55
  skip?: never;
52
- }, transaction?: Transaction | string): Promise<DBRecordInstance<S>>;
53
- create(record: InferSchemaTypesWrite<S>, transaction?: Transaction | string): Promise<DBRecordInstance<S>>;
56
+ }, transaction?: Transaction | string): Promise<DBRecordInstance<S, Q>>;
57
+ create(record: InferSchemaTypesWrite<S>, transaction?: Transaction | string): Promise<DBRecordInstance<S, SearchQuery<S>>>;
54
58
  attach(sourceId: string, target: RelationTarget, options?: RelationOptions, transaction?: Transaction | string): Promise<import("../index.node.js").ApiResponse<{
55
59
  message: string;
56
60
  }, Record<string, any>>>;
@@ -58,9 +62,9 @@ export declare class Model<S extends Schema = any> extends RestApiProxy {
58
62
  message: string;
59
63
  }, Record<string, any>>>;
60
64
  private handleSetOrUpdate;
61
- set(id: string, record: InferSchemaTypesWrite<S>, transaction?: Transaction | string): Promise<DBRecordInstance<S>>;
62
- update(id: string, record: Partial<InferSchemaTypesWrite<S>>, transaction?: Transaction | string): Promise<DBRecordInstance<S>>;
63
- createMany(records: InferSchemaTypesWrite<S>[], transaction?: Transaction | string): Promise<DBRecordsArrayInstance<S>>;
65
+ set(id: string, record: InferSchemaTypesWrite<S>, transaction?: Transaction | string): Promise<DBRecordInstance<S, SearchQuery<S>>>;
66
+ update(id: string, record: Partial<InferSchemaTypesWrite<S>>, transaction?: Transaction | string): Promise<DBRecordInstance<S, SearchQuery<S>>>;
67
+ createMany(records: InferSchemaTypesWrite<S>[], transaction?: Transaction | string): Promise<DBRecordsArrayInstance<S, SearchQuery<S>>>;
64
68
  delete(searchParams: Omit<SearchQuery<S>, 'labels'>, transaction?: Transaction | string): Promise<import("../index.node.js").ApiResponse<{
65
69
  message: string;
66
70
  }, Record<string, any>>>;
@@ -1,4 +1,4 @@
1
- import type { AnyObject, PropertyType, PropertyValue, PropertyWithValue, SearchQuery, Schema, FlattenTypes, InferSchemaTypesRead, InferSchemaTypesWrite, MaybeArray, OptionalKeysRead, RequiredKeysRead } from '../types/index.js';
1
+ import type { AnyObject, ExtractAggregateFields, FlattenTypes, InferSchemaTypesRead, InferSchemaTypesWrite, MaybeArray, OptionalKeysRead, PropertyType, PropertyValue, PropertyWithValue, RequiredKeysRead, Schema, SearchQuery } from '../types/index.js';
2
2
  import type { Transaction } from './transaction.js';
3
3
  import { RestApiProxy } from '../api/rest-api-proxy.js';
4
4
  type DBRecordInternalProps<S extends Schema = Schema> = {
@@ -13,6 +13,9 @@ type DBRecordInternalProps<S extends Schema = Schema> = {
13
13
  export type RecordProps<S extends Schema = Schema> = S extends S ? InferSchemaTypesRead<S> : {
14
14
  [K in keyof S]?: S[K];
15
15
  };
16
+ export type DBRecordInferred<S extends Schema, Q extends SearchQuery<S>> = Q extends {
17
+ aggregate: infer A extends Record<string, any>;
18
+ } ? DBRecord<S> & ExtractAggregateFields<A> : DBRecord<S>;
16
19
  export type DBRecord<S extends Schema = Schema> = FlattenTypes<DBRecordInternalProps<S> & FlattenTypes<RecordProps<S>>>;
17
20
  export type DBRecordTarget = DBRecord<any> | DBRecordInstance<any> | string;
18
21
  export type RelationTarget = DBRecordsArrayInstance<any> | MaybeArray<DBRecord<any>> | MaybeArray<DBRecordInstance<any>> | MaybeArray<string>;
@@ -84,9 +87,9 @@ export declare class DBRecordDraft {
84
87
  }[] | undefined;
85
88
  };
86
89
  }
87
- export declare class DBRecordInstance<S extends Schema = Schema> extends RestApiProxy {
88
- data?: DBRecord<S>;
89
- constructor(data?: DBRecord<S>);
90
+ export declare class DBRecordInstance<S extends Schema = Schema, Q extends SearchQuery<S> = SearchQuery<S>> extends RestApiProxy {
91
+ data?: DBRecordInferred<S, Q>;
92
+ constructor(data?: DBRecordInferred<S, Q>);
90
93
  get id(): string;
91
94
  get label(): string;
92
95
  get proptypes(): FlattenTypes<FlattenTypes<{ [Key in RequiredKeysRead<S>]: S[Key]["type"]; } & { [Key_1 in OptionalKeysRead<S>]?: S[Key_1]["type"] | undefined; }>> | undefined;
@@ -95,8 +98,8 @@ export declare class DBRecordInstance<S extends Schema = Schema> extends RestApi
95
98
  delete(transaction?: Transaction | string): Promise<import("../index.node.js").ApiResponse<{
96
99
  message: string;
97
100
  }, Record<string, any>>>;
98
- update<S extends Schema = Schema>(partialData: DBRecordDraft | Partial<InferSchemaTypesWrite<S>>, transaction?: Transaction | string): Promise<DBRecordInstance<S>>;
99
- set<S extends Schema = Schema>(data: DBRecordDraft | InferSchemaTypesWrite<S>, transaction?: Transaction | string): Promise<DBRecordInstance<S>>;
101
+ update<S extends Schema = Schema>(partialData: DBRecordDraft | Partial<InferSchemaTypesWrite<S>>, transaction?: Transaction | string): Promise<DBRecordInstance<S, SearchQuery<S>>>;
102
+ set<S extends Schema = Schema>(data: DBRecordDraft | InferSchemaTypesWrite<S>, transaction?: Transaction | string): Promise<DBRecordInstance<S, SearchQuery<S>>>;
100
103
  attach(target: RelationTarget, options?: RelationOptions, transaction?: Transaction | string): Promise<import("../index.node.js").ApiResponse<{
101
104
  message: string;
102
105
  }, Record<string, any>>>;
@@ -104,10 +107,10 @@ export declare class DBRecordInstance<S extends Schema = Schema> extends RestApi
104
107
  message: string;
105
108
  }, Record<string, any>>>;
106
109
  }
107
- export declare class DBRecordsArrayInstance<S extends Schema = Schema> extends RestApiProxy {
108
- data?: DBRecord<S>[];
110
+ export declare class DBRecordsArrayInstance<S extends Schema = Schema, Q extends SearchQuery<S> = SearchQuery<S>> extends RestApiProxy {
111
+ data?: DBRecordInferred<S, Q>[];
109
112
  total: number | undefined;
110
113
  searchParams?: SearchQuery<S>;
111
- constructor(data?: DBRecord<S>[], total?: number, searchParams?: SearchQuery<S>);
114
+ constructor(data?: DBRecordInferred<S, Q>[], total?: number, searchParams?: SearchQuery<S>);
112
115
  }
113
116
  export {};
package/dist/sdk/sdk.d.ts CHANGED
@@ -14,7 +14,7 @@ export declare const initSDK: (httpClient: HttpClient) => {
14
14
  readonly __id: string;
15
15
  readonly __label: string;
16
16
  readonly __proptypes?: import("../types/utils.js").FlattenTypes<{ [Key in import("../types/schema.js").RequiredKeysRead<S>]: S[Key]["type"]; } & { [Key_1 in import("../types/schema.js").OptionalKeysRead<S>]?: S[Key_1]["type"] | undefined; }> | undefined;
17
- } & import("../types/utils.js").FlattenTypes<import("./record.js").RecordProps<S>>>): DBRecordInstance<S>;
17
+ } & import("../types/utils.js").FlattenTypes<import("./record.js").RecordProps<S>>>): DBRecordInstance<S, import("../types/query.js").SearchQuery<S>>;
18
18
  api: ReturnType<typeof import("../api/create-api.js").createApi>;
19
19
  fetcher: ReturnType<typeof import("../network/index.js").createFetcher>;
20
20
  records: import("../api/types.js").RecordsApi;
@@ -57,7 +57,7 @@ export declare const initSDK: (httpClient: HttpClient) => {
57
57
  readonly __id: string;
58
58
  readonly __label: string;
59
59
  readonly __proptypes?: import("../types/utils.js").FlattenTypes<{ [Key in import("../types/schema.js").RequiredKeysRead<S>]: S[Key]["type"]; } & { [Key_1 in import("../types/schema.js").OptionalKeysRead<S>]?: S[Key_1]["type"] | undefined; }> | undefined;
60
- } & import("../types/utils.js").FlattenTypes<import("./record.js").RecordProps<S>>>): DBRecordInstance<S>;
60
+ } & import("../types/utils.js").FlattenTypes<import("./record.js").RecordProps<S>>>): DBRecordInstance<S, import("../types/query.js").SearchQuery<S>>;
61
61
  api: ReturnType<typeof import("../api/create-api.js").createApi>;
62
62
  fetcher: ReturnType<typeof import("../network/index.js").createFetcher>;
63
63
  records: import("../api/types.js").RecordsApi;
@@ -100,7 +100,7 @@ export declare const initSDK: (httpClient: HttpClient) => {
100
100
  readonly __id: string;
101
101
  readonly __label: string;
102
102
  readonly __proptypes?: import("../types/utils.js").FlattenTypes<{ [Key in import("../types/schema.js").RequiredKeysRead<S>]: S[Key]["type"]; } & { [Key_1 in import("../types/schema.js").OptionalKeysRead<S>]?: S[Key_1]["type"] | undefined; }> | undefined;
103
- } & import("../types/utils.js").FlattenTypes<import("./record.js").RecordProps<S>>>): DBRecordInstance<S>;
103
+ } & import("../types/utils.js").FlattenTypes<import("./record.js").RecordProps<S>>>): DBRecordInstance<S, import("../types/query.js").SearchQuery<S>>;
104
104
  api: ReturnType<typeof import("../api/create-api.js").createApi>;
105
105
  fetcher: ReturnType<typeof import("../network/index.js").createFetcher>;
106
106
  records: import("../api/types.js").RecordsApi;
@@ -1,12 +1,12 @@
1
- import type { RelationOptions } from '../sdk/index.js';
2
- import type { BooleanExpression, PropertyExpression, PropertyExpressionByType, DatetimeExpression, LogicalGrouping, NullExpression, NumberExpression, StringExpression } from './expressions.js';
1
+ import type { Model, RelationOptions } from '../sdk/index.js';
2
+ import type { BooleanExpression, DatetimeExpression, LogicalGrouping, NullExpression, NumberExpression, PropertyExpression, PropertyExpressionByType, StringExpression } from './expressions.js';
3
3
  import type { Schema } from './schema.js';
4
- import type { MaybeArray, RequireAtLeastOne } from './utils.js';
5
- export type Related = {
6
- [Key in keyof Models]?: {
4
+ import type { AnyObject, MaybeArray, RequireAtLeastOne } from './utils.js';
5
+ export type Related<M extends Record<string, Model['schema']> = Models> = keyof M extends never ? AnyObject : {
6
+ [Key in keyof M]?: {
7
7
  $alias?: string;
8
8
  $relation?: RelationOptions | string;
9
- } & Where<Models[Key]>;
9
+ } & Where<M[Key]>;
10
10
  };
11
11
  export type LogicalExpressionValue<T = PropertyExpression & Related> = AndExpression<T> | NorExpression<T> | NotExpression<T> | OrExpression<T> | T | XorExpression<T>;
12
12
  export type AndExpression<T = PropertyExpression & Related> = {
@@ -79,6 +79,14 @@ export type Aggregate = {
79
79
  } | {
80
80
  [field: string]: AggregateFn | string;
81
81
  };
82
+ type InferAggregateType<T extends AggregateFn | string> = T extends string ? any : T extends {
83
+ fn: 'sum' | 'avg' | 'min' | 'max' | 'count';
84
+ } ? number : T extends {
85
+ fn: 'collect';
86
+ } ? any[] : never;
87
+ export type ExtractAggregateFields<A extends Record<string, AggregateFn>> = {
88
+ [K in keyof A]: InferAggregateType<A[K]>;
89
+ };
82
90
  export type WhereClause<S extends Schema = Schema> = {
83
91
  where?: Where<S>;
84
92
  };
package/package.json CHANGED
@@ -2,17 +2,38 @@
2
2
  "name": "@rushdb/javascript-sdk",
3
3
  "description": "RushDB Javascript SDK",
4
4
  "keywords": [
5
- "neo4j",
6
5
  "database",
7
- "firebase-alternative",
8
- "firebase",
9
- "cypher",
10
- "instant",
6
+ "graph database",
7
+ "instant database",
8
+ "instant-database",
9
+ "instantdatabase",
10
+ "instant db",
11
+ "instant-db",
11
12
  "instantdb",
13
+ "neo4j",
14
+ "cypher",
15
+ "ai",
16
+ "ai database",
17
+ "etl",
18
+ "data-pipeline",
19
+ "data science",
20
+ "data-science",
21
+ "data management",
22
+ "data-management",
23
+ "machine learning",
24
+ "machine-learning",
25
+ "persistence",
26
+ "db",
27
+ "graph",
28
+ "graphs",
29
+ "graph-database",
30
+ "self-hosted",
31
+ "rush-db",
32
+ "rush db",
12
33
  "rushdb"
13
34
  ],
14
35
  "license": "Apache-2.0",
15
- "version": "0.9.5",
36
+ "version": "0.10.0",
16
37
  "type": "module",
17
38
  "files": [
18
39
  "dist"